@javalabs/prisma-client 1.0.18 → 1.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.dockerignore +14 -0
- package/Dockerfile +23 -0
- package/README.md +269 -269
- package/dist/index.d.ts +1 -1
- package/dist/prisma.service.d.ts +1 -1
- package/dist/scripts/add-uuid-to-table.js +32 -32
- package/dist/scripts/data-migration/batch-migrator.js +12 -12
- package/dist/scripts/data-migration/data-transformer.js +14 -14
- package/dist/scripts/data-migration/dependency-resolver.js +23 -23
- package/dist/scripts/data-migration/entity-discovery.js +68 -68
- package/dist/scripts/data-migration/foreign-key-manager.js +23 -23
- package/dist/scripts/data-migration/migration-tool.js +5 -5
- package/dist/scripts/data-migration/schema-utils.js +74 -74
- package/dist/scripts/data-migration/typecast-manager.js +4 -4
- package/dist/scripts/database-initializer.js +5 -5
- package/dist/scripts/drop-database.js +5 -5
- package/dist/scripts/fix-data-types.js +53 -53
- package/dist/scripts/fix-enum-values.js +34 -34
- package/dist/scripts/fix-schema-discrepancies.js +40 -40
- package/dist/scripts/fix-table-indexes.js +81 -81
- package/dist/scripts/migrate-schema-structure.js +4 -4
- package/dist/scripts/migrate-uuid.js +19 -19
- package/dist/scripts/post-migration-validator.js +49 -49
- package/dist/scripts/pre-migration-validator.js +107 -107
- package/dist/scripts/reset-database.js +21 -21
- package/dist/scripts/retry-failed-migrations.js +28 -28
- package/dist/scripts/run-migration.js +5 -5
- package/dist/scripts/schema-sync.js +18 -18
- package/dist/scripts/sequence-sync-cli.js +55 -55
- package/dist/scripts/sequence-synchronizer.js +20 -20
- package/dist/scripts/sync-enum-types.js +30 -30
- package/dist/scripts/sync-enum-values.js +52 -52
- package/dist/scripts/truncate-database.js +10 -10
- package/dist/scripts/verify-migration-setup.js +10 -10
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/migration-config.json +63 -63
- package/migration-config.json.bk +95 -95
- package/package.json +44 -44
- package/prisma/migrations/add_accepts_partial_payments_to_users.sql +19 -0
- package/prisma/migrations/add_amount_received_to_manual_payments.sql +19 -0
- package/prisma/migrations/add_commission_fields.sql +33 -0
- package/prisma/migrations/add_uuid_to_transactions.sql +13 -13
- package/prisma/migrations/complete_partial_payments_migration.sql +53 -0
- package/prisma/migrations/create_settlements_table.sql +60 -0
- package/prisma/schema.prisma +47 -1
- package/src/index.ts +23 -23
- package/src/prisma-factory.service.ts +40 -40
- package/src/prisma.module.ts +9 -9
- package/src/prisma.service.ts +16 -16
- package/src/scripts/add-uuid-to-table.ts +138 -138
- package/src/scripts/create-tenant-schemas.ts +145 -145
- package/src/scripts/data-migration/batch-migrator.ts +248 -248
- package/src/scripts/data-migration/data-transformer.ts +426 -426
- package/src/scripts/data-migration/db-connector.ts +120 -120
- package/src/scripts/data-migration/dependency-resolver.ts +174 -174
- package/src/scripts/data-migration/entity-discovery.ts +196 -196
- package/src/scripts/data-migration/foreign-key-manager.ts +277 -277
- package/src/scripts/data-migration/migration-config.json +63 -63
- package/src/scripts/data-migration/migration-tool.ts +509 -509
- package/src/scripts/data-migration/schema-utils.ts +248 -248
- package/src/scripts/data-migration/tenant-migrator.ts +201 -201
- package/src/scripts/data-migration/typecast-manager.ts +193 -193
- package/src/scripts/data-migration/types.ts +113 -113
- package/src/scripts/database-initializer.ts +49 -49
- package/src/scripts/drop-database.ts +104 -104
- package/src/scripts/dump-source-db.sh +61 -61
- package/src/scripts/encrypt-user-passwords.ts +36 -36
- package/src/scripts/error-handler.ts +117 -117
- package/src/scripts/fix-data-types.ts +241 -241
- package/src/scripts/fix-enum-values.ts +357 -357
- package/src/scripts/fix-schema-discrepancies.ts +317 -317
- package/src/scripts/fix-table-indexes.ts +601 -601
- package/src/scripts/migrate-schema-structure.ts +90 -90
- package/src/scripts/migrate-uuid.ts +76 -76
- package/src/scripts/post-migration-validator.ts +526 -526
- package/src/scripts/pre-migration-validator.ts +610 -610
- package/src/scripts/reset-database.ts +263 -263
- package/src/scripts/retry-failed-migrations.ts +416 -416
- package/src/scripts/run-migration.ts +707 -707
- package/src/scripts/schema-sync.ts +128 -128
- package/src/scripts/sequence-sync-cli.ts +416 -416
- package/src/scripts/sequence-synchronizer.ts +127 -127
- package/src/scripts/sync-enum-types.ts +170 -170
- package/src/scripts/sync-enum-values.ts +563 -563
- package/src/scripts/truncate-database.ts +123 -123
- package/src/scripts/verify-migration-setup.ts +135 -135
- package/tsconfig.json +17 -17
- package/dist/scripts/data-migration/dependency-manager.d.ts +0 -9
- package/dist/scripts/data-migration/dependency-manager.js +0 -86
- package/dist/scripts/data-migration/dependency-manager.js.map +0 -1
- package/dist/scripts/data-migration/migration-config.json +0 -63
- package/dist/scripts/data-migration/migration-phases.d.ts +0 -5
- package/dist/scripts/data-migration/migration-phases.js +0 -55
- package/dist/scripts/data-migration/migration-phases.js.map +0 -1
- package/dist/scripts/data-migration/multi-source-migrator.d.ts +0 -17
- package/dist/scripts/data-migration/multi-source-migrator.js +0 -130
- package/dist/scripts/data-migration/multi-source-migrator.js.map +0 -1
- package/dist/scripts/data-migration/phase-generator.d.ts +0 -15
- package/dist/scripts/data-migration/phase-generator.js +0 -187
- package/dist/scripts/data-migration/phase-generator.js.map +0 -1
- package/dist/scripts/data-migration.d.ts +0 -22
- package/dist/scripts/data-migration.js +0 -593
- package/dist/scripts/data-migration.js.map +0 -1
- package/dist/scripts/multi-db-migration.d.ts +0 -1
- package/dist/scripts/multi-db-migration.js +0 -55
- package/dist/scripts/multi-db-migration.js.map +0 -1
package/prisma/schema.prisma
CHANGED
|
@@ -238,6 +238,7 @@ model manual_payments {
|
|
|
238
238
|
id Int @id @default(autoincrement())
|
|
239
239
|
user_id Int
|
|
240
240
|
amount Decimal @db.Decimal(10, 2)
|
|
241
|
+
amount_received Decimal? @db.Decimal(10, 2)
|
|
241
242
|
currency String @db.VarChar(10)
|
|
242
243
|
bank_transaction_id Int?
|
|
243
244
|
receipt_image_url String? @db.Text
|
|
@@ -391,7 +392,11 @@ model transactions {
|
|
|
391
392
|
updatedAt DateTime @db.Timestamptz(6)
|
|
392
393
|
bank_name String? @db.VarChar(100)
|
|
393
394
|
account_number String? @db.VarChar(50)
|
|
394
|
-
custom_id
|
|
395
|
+
custom_id String? @db.VarChar(255)
|
|
396
|
+
commission Decimal? @default(0) @db.Decimal(10, 2)
|
|
397
|
+
fixed_fee Decimal? @default(0) @db.Decimal(10, 2)
|
|
398
|
+
total_commission_fee Decimal? @default(0) @db.Decimal(10, 2)
|
|
399
|
+
total_operation Decimal? @default(0) @db.Decimal(10, 2)
|
|
395
400
|
toku toku?
|
|
396
401
|
account_type enum_account_type?
|
|
397
402
|
daily_logs daily_logs[]
|
|
@@ -426,6 +431,10 @@ model users {
|
|
|
426
431
|
payOutWebhookUrl String?
|
|
427
432
|
payInRedirectUrl String?
|
|
428
433
|
payOutRedirectUrl String?
|
|
434
|
+
payin_commission_percent Decimal? @default(0) @db.Decimal(5, 2)
|
|
435
|
+
payin_fixed_fee Decimal? @default(0) @db.Decimal(10, 2)
|
|
436
|
+
payout_fixed_fee Decimal? @default(0) @db.Decimal(10, 2)
|
|
437
|
+
accepts_partial_payments Boolean? @default(false)
|
|
429
438
|
api_keys api_keys[]
|
|
430
439
|
balances balances[]
|
|
431
440
|
credit_requests credit_requests[]
|
|
@@ -436,6 +445,7 @@ model users {
|
|
|
436
445
|
notifications notifications[]
|
|
437
446
|
pending_references pending_references[]
|
|
438
447
|
transactions transactions[]
|
|
448
|
+
settlements settlements[]
|
|
439
449
|
countries countries @relation(fields: [country_id], references: [id], onDelete: Cascade)
|
|
440
450
|
isDeleted Boolean @default(false)
|
|
441
451
|
deletedAt DateTime? @db.Timestamptz(6)
|
|
@@ -552,3 +562,39 @@ enum enum_transactions_user_type_account {
|
|
|
552
562
|
checking
|
|
553
563
|
savings
|
|
554
564
|
}
|
|
565
|
+
|
|
566
|
+
enum enum_settlements_status {
|
|
567
|
+
pending
|
|
568
|
+
completed
|
|
569
|
+
cancelled
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
model settlements {
|
|
573
|
+
id Int @id @default(autoincrement())
|
|
574
|
+
user_id Int
|
|
575
|
+
settlement_date DateTime @db.Timestamptz(6)
|
|
576
|
+
period_start DateTime @db.Timestamptz(6)
|
|
577
|
+
period_end DateTime @db.Timestamptz(6)
|
|
578
|
+
payin_count Int @default(0)
|
|
579
|
+
payin_total_amount Decimal @default(0) @db.Decimal(15, 2)
|
|
580
|
+
payin_total_commission Decimal @default(0) @db.Decimal(15, 2)
|
|
581
|
+
payin_net_amount Decimal @default(0) @db.Decimal(15, 2)
|
|
582
|
+
payout_count Int @default(0)
|
|
583
|
+
payout_total_amount Decimal @default(0) @db.Decimal(15, 2)
|
|
584
|
+
payout_total_commission Decimal @default(0) @db.Decimal(15, 2)
|
|
585
|
+
payout_total_with_commission Decimal @default(0) @db.Decimal(15, 2)
|
|
586
|
+
total_commission Decimal @default(0) @db.Decimal(15, 2)
|
|
587
|
+
balance_before Decimal @default(0) @db.Decimal(15, 2)
|
|
588
|
+
settlement_amount Decimal @default(0) @db.Decimal(15, 2)
|
|
589
|
+
balance_after Decimal @default(0) @db.Decimal(15, 2)
|
|
590
|
+
status enum_settlements_status @default(pending)
|
|
591
|
+
notes String? @db.Text
|
|
592
|
+
currency String @default("USD") @db.VarChar(3)
|
|
593
|
+
created_at DateTime @default(now()) @db.Timestamptz(6)
|
|
594
|
+
updated_at DateTime @updatedAt @db.Timestamptz(6)
|
|
595
|
+
users users @relation(fields: [user_id], references: [user_id], onDelete: Cascade)
|
|
596
|
+
|
|
597
|
+
@@index([user_id], map: "idx_settlements_user_id")
|
|
598
|
+
@@index([period_start, period_end], map: "idx_settlements_period")
|
|
599
|
+
@@index([settlement_date], map: "idx_settlements_date")
|
|
600
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import { PrismaClient } from "@prisma/client";
|
|
2
|
-
import { PrismaModule } from "./prisma.module";
|
|
3
|
-
import { PrismaService } from "./prisma.service";
|
|
4
|
-
import { PrismaFactoryService } from "./prisma-factory.service";
|
|
5
|
-
|
|
6
|
-
// Create a singleton instance of the PrismaClient
|
|
7
|
-
const prismaClientSingleton = () => {
|
|
8
|
-
return new PrismaClient();
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton>;
|
|
12
|
-
|
|
13
|
-
const globalForPrisma = globalThis as unknown as {
|
|
14
|
-
prisma: PrismaClientSingleton | undefined;
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
export const prisma = globalForPrisma.prisma ?? prismaClientSingleton();
|
|
18
|
-
|
|
19
|
-
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
|
20
|
-
|
|
21
|
-
// Explicitly export the modules and services
|
|
22
|
-
export { PrismaModule, PrismaService, PrismaFactoryService };
|
|
23
|
-
export * from "@prisma/client";
|
|
1
|
+
import { PrismaClient } from "@prisma/client";
|
|
2
|
+
import { PrismaModule } from "./prisma.module";
|
|
3
|
+
import { PrismaService } from "./prisma.service";
|
|
4
|
+
import { PrismaFactoryService } from "./prisma-factory.service";
|
|
5
|
+
|
|
6
|
+
// Create a singleton instance of the PrismaClient
|
|
7
|
+
const prismaClientSingleton = () => {
|
|
8
|
+
return new PrismaClient();
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton>;
|
|
12
|
+
|
|
13
|
+
const globalForPrisma = globalThis as unknown as {
|
|
14
|
+
prisma: PrismaClientSingleton | undefined;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const prisma = globalForPrisma.prisma ?? prismaClientSingleton();
|
|
18
|
+
|
|
19
|
+
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
|
20
|
+
|
|
21
|
+
// Explicitly export the modules and services
|
|
22
|
+
export { PrismaModule, PrismaService, PrismaFactoryService };
|
|
23
|
+
export * from "@prisma/client";
|
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
import { Injectable, OnModuleDestroy, Logger } from '@nestjs/common';
|
|
2
|
-
import { PrismaClient } from '@prisma/client';
|
|
3
|
-
|
|
4
|
-
@Injectable()
|
|
5
|
-
export class PrismaFactoryService implements OnModuleDestroy {
|
|
6
|
-
private clients: Map<string, PrismaClient> = new Map();
|
|
7
|
-
private readonly logger = new Logger(PrismaFactoryService.name);
|
|
8
|
-
|
|
9
|
-
getClient(tenantId: string): PrismaClient {
|
|
10
|
-
if (!this.clients.has(tenantId)) {
|
|
11
|
-
this.logger.log(`Creating new Prisma client for tenant: ${tenantId}`);
|
|
12
|
-
|
|
13
|
-
// Crear un nuevo cliente con el schema específico
|
|
14
|
-
const client = new PrismaClient({
|
|
15
|
-
datasources: {
|
|
16
|
-
db: {
|
|
17
|
-
url: `${process.env.DATABASE_URL}?schema=${tenantId}`,
|
|
18
|
-
},
|
|
19
|
-
},
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
this.clients.set(tenantId, client);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
return this.clients.get(tenantId);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// Cliente para el schema público/master
|
|
29
|
-
getMasterClient(): PrismaClient {
|
|
30
|
-
return this.getClient('public');
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
async onModuleDestroy() {
|
|
34
|
-
this.logger.log('Disconnecting all Prisma clients');
|
|
35
|
-
// Desconectar todos los clientes al finalizar
|
|
36
|
-
for (const [tenantId, client] of this.clients.entries()) {
|
|
37
|
-
this.logger.log(`Disconnecting client for tenant: ${tenantId}`);
|
|
38
|
-
await client.$disconnect();
|
|
39
|
-
}
|
|
40
|
-
}
|
|
1
|
+
import { Injectable, OnModuleDestroy, Logger } from '@nestjs/common';
|
|
2
|
+
import { PrismaClient } from '@prisma/client';
|
|
3
|
+
|
|
4
|
+
@Injectable()
|
|
5
|
+
export class PrismaFactoryService implements OnModuleDestroy {
|
|
6
|
+
private clients: Map<string, PrismaClient> = new Map();
|
|
7
|
+
private readonly logger = new Logger(PrismaFactoryService.name);
|
|
8
|
+
|
|
9
|
+
getClient(tenantId: string): PrismaClient {
|
|
10
|
+
if (!this.clients.has(tenantId)) {
|
|
11
|
+
this.logger.log(`Creating new Prisma client for tenant: ${tenantId}`);
|
|
12
|
+
|
|
13
|
+
// Crear un nuevo cliente con el schema específico
|
|
14
|
+
const client = new PrismaClient({
|
|
15
|
+
datasources: {
|
|
16
|
+
db: {
|
|
17
|
+
url: `${process.env.DATABASE_URL}?schema=${tenantId}`,
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
this.clients.set(tenantId, client);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return this.clients.get(tenantId);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Cliente para el schema público/master
|
|
29
|
+
getMasterClient(): PrismaClient {
|
|
30
|
+
return this.getClient('public');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async onModuleDestroy() {
|
|
34
|
+
this.logger.log('Disconnecting all Prisma clients');
|
|
35
|
+
// Desconectar todos los clientes al finalizar
|
|
36
|
+
for (const [tenantId, client] of this.clients.entries()) {
|
|
37
|
+
this.logger.log(`Disconnecting client for tenant: ${tenantId}`);
|
|
38
|
+
await client.$disconnect();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
41
|
}
|
package/src/prisma.module.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { Module, Global } from '@nestjs/common';
|
|
2
|
-
import { PrismaService } from './prisma.service';
|
|
3
|
-
import { PrismaFactoryService } from './prisma-factory.service';
|
|
4
|
-
|
|
5
|
-
@Global()
|
|
6
|
-
@Module({
|
|
7
|
-
providers: [PrismaService, PrismaFactoryService],
|
|
8
|
-
exports: [PrismaService, PrismaFactoryService],
|
|
9
|
-
})
|
|
1
|
+
import { Module, Global } from '@nestjs/common';
|
|
2
|
+
import { PrismaService } from './prisma.service';
|
|
3
|
+
import { PrismaFactoryService } from './prisma-factory.service';
|
|
4
|
+
|
|
5
|
+
@Global()
|
|
6
|
+
@Module({
|
|
7
|
+
providers: [PrismaService, PrismaFactoryService],
|
|
8
|
+
exports: [PrismaService, PrismaFactoryService],
|
|
9
|
+
})
|
|
10
10
|
export class PrismaModule {}
|
package/src/prisma.service.ts
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
|
2
|
-
import { prisma } from './index';
|
|
3
|
-
|
|
4
|
-
@Injectable()
|
|
5
|
-
export class PrismaService implements OnModuleInit, OnModuleDestroy {
|
|
6
|
-
async onModuleInit() {
|
|
7
|
-
await prisma.$connect();
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
async onModuleDestroy() {
|
|
11
|
-
await prisma.$disconnect();
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
get client() {
|
|
15
|
-
return prisma;
|
|
16
|
-
}
|
|
1
|
+
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
|
2
|
+
import { prisma } from './index';
|
|
3
|
+
|
|
4
|
+
@Injectable()
|
|
5
|
+
export class PrismaService implements OnModuleInit, OnModuleDestroy {
|
|
6
|
+
async onModuleInit() {
|
|
7
|
+
await prisma.$connect();
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
async onModuleDestroy() {
|
|
11
|
+
await prisma.$disconnect();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
get client() {
|
|
15
|
+
return prisma;
|
|
16
|
+
}
|
|
17
17
|
}
|
|
@@ -1,138 +1,138 @@
|
|
|
1
|
-
import { PrismaClient } from "@prisma/client";
|
|
2
|
-
import { exec } from "child_process";
|
|
3
|
-
import { promisify } from "util";
|
|
4
|
-
|
|
5
|
-
const execAsync = promisify(exec);
|
|
6
|
-
const prisma = new PrismaClient();
|
|
7
|
-
|
|
8
|
-
interface AddUuidOptions {
|
|
9
|
-
tableName: string;
|
|
10
|
-
columnName?: string;
|
|
11
|
-
makeRequired?: boolean;
|
|
12
|
-
addDefault?: boolean;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
async function addUuidToTable({
|
|
16
|
-
tableName,
|
|
17
|
-
columnName = "uuid",
|
|
18
|
-
makeRequired = false,
|
|
19
|
-
addDefault = false,
|
|
20
|
-
}: AddUuidOptions) {
|
|
21
|
-
try {
|
|
22
|
-
console.log(
|
|
23
|
-
`🚀 Iniciando proceso de añadir UUID a la tabla ${tableName}...`
|
|
24
|
-
);
|
|
25
|
-
|
|
26
|
-
// 1. Verificar si la tabla existe
|
|
27
|
-
const tableExists = await prisma.$queryRaw`
|
|
28
|
-
SELECT EXISTS (
|
|
29
|
-
SELECT FROM information_schema.tables
|
|
30
|
-
WHERE table_name = ${tableName}
|
|
31
|
-
);
|
|
32
|
-
`;
|
|
33
|
-
|
|
34
|
-
if (!tableExists[0].exists) {
|
|
35
|
-
throw new Error(`La tabla ${tableName} no existe`);
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// 2. Verificar si la columna ya existe
|
|
39
|
-
const columnExists = await prisma.$queryRaw`
|
|
40
|
-
SELECT EXISTS (
|
|
41
|
-
SELECT FROM information_schema.columns
|
|
42
|
-
WHERE table_name = ${tableName}
|
|
43
|
-
AND column_name = ${columnName}
|
|
44
|
-
);
|
|
45
|
-
`;
|
|
46
|
-
|
|
47
|
-
if (columnExists[0].exists) {
|
|
48
|
-
console.log(
|
|
49
|
-
`⚠️ La columna ${columnName} ya existe en la tabla ${tableName}`
|
|
50
|
-
);
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// 3. Habilitar la extensión uuid-ossp si no está habilitada
|
|
55
|
-
console.log("📦 Habilitando extensión uuid-ossp...");
|
|
56
|
-
await prisma.$executeRaw`CREATE EXTENSION IF NOT EXISTS "uuid-ossp";`;
|
|
57
|
-
|
|
58
|
-
// 4. Añadir la columna UUID
|
|
59
|
-
console.log(`📝 Añadiendo columna ${columnName}...`);
|
|
60
|
-
await prisma.$executeRaw`
|
|
61
|
-
ALTER TABLE ${tableName}
|
|
62
|
-
ADD COLUMN ${columnName} VARCHAR(255);
|
|
63
|
-
`;
|
|
64
|
-
|
|
65
|
-
// 5. Actualizar registros existentes con UUIDs
|
|
66
|
-
console.log("🔄 Actualizando registros existentes con UUIDs...");
|
|
67
|
-
await prisma.$executeRaw`
|
|
68
|
-
UPDATE ${tableName}
|
|
69
|
-
SET ${columnName} = uuid_generate_v4()
|
|
70
|
-
WHERE ${columnName} IS NULL;
|
|
71
|
-
`;
|
|
72
|
-
|
|
73
|
-
// 6. Crear índice
|
|
74
|
-
console.log("📊 Creando índice...");
|
|
75
|
-
await prisma.$executeRaw`
|
|
76
|
-
CREATE INDEX idx_${tableName}_${columnName}
|
|
77
|
-
ON ${tableName}(${columnName});
|
|
78
|
-
`;
|
|
79
|
-
|
|
80
|
-
// 7. Añadir restricción unique
|
|
81
|
-
console.log("🔒 Añadiendo restricción unique...");
|
|
82
|
-
await prisma.$executeRaw`
|
|
83
|
-
ALTER TABLE ${tableName}
|
|
84
|
-
ADD CONSTRAINT ${tableName}_${columnName}_key
|
|
85
|
-
UNIQUE (${columnName});
|
|
86
|
-
`;
|
|
87
|
-
|
|
88
|
-
// 8. Si se requiere, hacer la columna NOT NULL
|
|
89
|
-
if (makeRequired) {
|
|
90
|
-
console.log("⚠️ Haciendo la columna NOT NULL...");
|
|
91
|
-
await prisma.$executeRaw`
|
|
92
|
-
ALTER TABLE ${tableName}
|
|
93
|
-
ALTER COLUMN ${columnName} SET NOT NULL;
|
|
94
|
-
`;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// 9. Si se requiere, añadir valor por defecto
|
|
98
|
-
if (addDefault) {
|
|
99
|
-
console.log("⚡ Añadiendo valor por defecto...");
|
|
100
|
-
await prisma.$executeRaw`
|
|
101
|
-
ALTER TABLE ${tableName}
|
|
102
|
-
ALTER COLUMN ${columnName}
|
|
103
|
-
SET DEFAULT uuid_generate_v4();
|
|
104
|
-
`;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
console.log(
|
|
108
|
-
`✅ Proceso completado exitosamente para la tabla ${tableName}`
|
|
109
|
-
);
|
|
110
|
-
} catch (error) {
|
|
111
|
-
console.error("❌ Error durante el proceso:", error);
|
|
112
|
-
throw error;
|
|
113
|
-
} finally {
|
|
114
|
-
await prisma.$disconnect();
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
// Ejemplo de uso
|
|
119
|
-
async function main() {
|
|
120
|
-
try {
|
|
121
|
-
await addUuidToTable({
|
|
122
|
-
tableName: "transactions",
|
|
123
|
-
columnName: "uuid",
|
|
124
|
-
makeRequired: false, // Primero lo dejamos como opcional
|
|
125
|
-
addDefault: false, // No añadimos valor por defecto inicialmente
|
|
126
|
-
});
|
|
127
|
-
} catch (error) {
|
|
128
|
-
console.error("Error en el proceso principal:", error);
|
|
129
|
-
process.exit(1);
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// Ejecutar el script
|
|
134
|
-
if (require.main === module) {
|
|
135
|
-
main();
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
export { addUuidToTable };
|
|
1
|
+
import { PrismaClient } from "@prisma/client";
|
|
2
|
+
import { exec } from "child_process";
|
|
3
|
+
import { promisify } from "util";
|
|
4
|
+
|
|
5
|
+
const execAsync = promisify(exec);
|
|
6
|
+
const prisma = new PrismaClient();
|
|
7
|
+
|
|
8
|
+
interface AddUuidOptions {
|
|
9
|
+
tableName: string;
|
|
10
|
+
columnName?: string;
|
|
11
|
+
makeRequired?: boolean;
|
|
12
|
+
addDefault?: boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function addUuidToTable({
|
|
16
|
+
tableName,
|
|
17
|
+
columnName = "uuid",
|
|
18
|
+
makeRequired = false,
|
|
19
|
+
addDefault = false,
|
|
20
|
+
}: AddUuidOptions) {
|
|
21
|
+
try {
|
|
22
|
+
console.log(
|
|
23
|
+
`🚀 Iniciando proceso de añadir UUID a la tabla ${tableName}...`
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
// 1. Verificar si la tabla existe
|
|
27
|
+
const tableExists = await prisma.$queryRaw`
|
|
28
|
+
SELECT EXISTS (
|
|
29
|
+
SELECT FROM information_schema.tables
|
|
30
|
+
WHERE table_name = ${tableName}
|
|
31
|
+
);
|
|
32
|
+
`;
|
|
33
|
+
|
|
34
|
+
if (!tableExists[0].exists) {
|
|
35
|
+
throw new Error(`La tabla ${tableName} no existe`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// 2. Verificar si la columna ya existe
|
|
39
|
+
const columnExists = await prisma.$queryRaw`
|
|
40
|
+
SELECT EXISTS (
|
|
41
|
+
SELECT FROM information_schema.columns
|
|
42
|
+
WHERE table_name = ${tableName}
|
|
43
|
+
AND column_name = ${columnName}
|
|
44
|
+
);
|
|
45
|
+
`;
|
|
46
|
+
|
|
47
|
+
if (columnExists[0].exists) {
|
|
48
|
+
console.log(
|
|
49
|
+
`⚠️ La columna ${columnName} ya existe en la tabla ${tableName}`
|
|
50
|
+
);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// 3. Habilitar la extensión uuid-ossp si no está habilitada
|
|
55
|
+
console.log("📦 Habilitando extensión uuid-ossp...");
|
|
56
|
+
await prisma.$executeRaw`CREATE EXTENSION IF NOT EXISTS "uuid-ossp";`;
|
|
57
|
+
|
|
58
|
+
// 4. Añadir la columna UUID
|
|
59
|
+
console.log(`📝 Añadiendo columna ${columnName}...`);
|
|
60
|
+
await prisma.$executeRaw`
|
|
61
|
+
ALTER TABLE ${tableName}
|
|
62
|
+
ADD COLUMN ${columnName} VARCHAR(255);
|
|
63
|
+
`;
|
|
64
|
+
|
|
65
|
+
// 5. Actualizar registros existentes con UUIDs
|
|
66
|
+
console.log("🔄 Actualizando registros existentes con UUIDs...");
|
|
67
|
+
await prisma.$executeRaw`
|
|
68
|
+
UPDATE ${tableName}
|
|
69
|
+
SET ${columnName} = uuid_generate_v4()
|
|
70
|
+
WHERE ${columnName} IS NULL;
|
|
71
|
+
`;
|
|
72
|
+
|
|
73
|
+
// 6. Crear índice
|
|
74
|
+
console.log("📊 Creando índice...");
|
|
75
|
+
await prisma.$executeRaw`
|
|
76
|
+
CREATE INDEX idx_${tableName}_${columnName}
|
|
77
|
+
ON ${tableName}(${columnName});
|
|
78
|
+
`;
|
|
79
|
+
|
|
80
|
+
// 7. Añadir restricción unique
|
|
81
|
+
console.log("🔒 Añadiendo restricción unique...");
|
|
82
|
+
await prisma.$executeRaw`
|
|
83
|
+
ALTER TABLE ${tableName}
|
|
84
|
+
ADD CONSTRAINT ${tableName}_${columnName}_key
|
|
85
|
+
UNIQUE (${columnName});
|
|
86
|
+
`;
|
|
87
|
+
|
|
88
|
+
// 8. Si se requiere, hacer la columna NOT NULL
|
|
89
|
+
if (makeRequired) {
|
|
90
|
+
console.log("⚠️ Haciendo la columna NOT NULL...");
|
|
91
|
+
await prisma.$executeRaw`
|
|
92
|
+
ALTER TABLE ${tableName}
|
|
93
|
+
ALTER COLUMN ${columnName} SET NOT NULL;
|
|
94
|
+
`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// 9. Si se requiere, añadir valor por defecto
|
|
98
|
+
if (addDefault) {
|
|
99
|
+
console.log("⚡ Añadiendo valor por defecto...");
|
|
100
|
+
await prisma.$executeRaw`
|
|
101
|
+
ALTER TABLE ${tableName}
|
|
102
|
+
ALTER COLUMN ${columnName}
|
|
103
|
+
SET DEFAULT uuid_generate_v4();
|
|
104
|
+
`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
console.log(
|
|
108
|
+
`✅ Proceso completado exitosamente para la tabla ${tableName}`
|
|
109
|
+
);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
console.error("❌ Error durante el proceso:", error);
|
|
112
|
+
throw error;
|
|
113
|
+
} finally {
|
|
114
|
+
await prisma.$disconnect();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Ejemplo de uso
|
|
119
|
+
async function main() {
|
|
120
|
+
try {
|
|
121
|
+
await addUuidToTable({
|
|
122
|
+
tableName: "transactions",
|
|
123
|
+
columnName: "uuid",
|
|
124
|
+
makeRequired: false, // Primero lo dejamos como opcional
|
|
125
|
+
addDefault: false, // No añadimos valor por defecto inicialmente
|
|
126
|
+
});
|
|
127
|
+
} catch (error) {
|
|
128
|
+
console.error("Error en el proceso principal:", error);
|
|
129
|
+
process.exit(1);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Ejecutar el script
|
|
134
|
+
if (require.main === module) {
|
|
135
|
+
main();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export { addUuidToTable };
|