@javalabs/prisma-client 1.0.27 → 1.0.29

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.
Files changed (50) hide show
  1. package/.github/CODEOWNERS +1 -1
  2. package/README.md +269 -269
  3. package/migration-config.json +63 -63
  4. package/migration-config.json.bk +95 -95
  5. package/migrations/add_reserved_amount.sql +7 -7
  6. package/package.json +44 -44
  7. package/prisma/migrations/add_uuid_to_transactions.sql +13 -13
  8. package/prisma/schema.prisma +609 -601
  9. package/src/index.ts +23 -23
  10. package/src/prisma-factory.service.ts +40 -40
  11. package/src/prisma.module.ts +9 -9
  12. package/src/prisma.service.ts +16 -16
  13. package/src/scripts/add-uuid-to-table.ts +138 -138
  14. package/src/scripts/create-tenant-schemas.ts +145 -145
  15. package/src/scripts/data-migration/batch-migrator.ts +248 -248
  16. package/src/scripts/data-migration/data-transformer.ts +426 -426
  17. package/src/scripts/data-migration/db-connector.ts +120 -120
  18. package/src/scripts/data-migration/dependency-resolver.ts +174 -174
  19. package/src/scripts/data-migration/entity-discovery.ts +196 -196
  20. package/src/scripts/data-migration/foreign-key-manager.ts +277 -277
  21. package/src/scripts/data-migration/migration-config.json +63 -63
  22. package/src/scripts/data-migration/migration-tool.ts +509 -509
  23. package/src/scripts/data-migration/schema-utils.ts +248 -248
  24. package/src/scripts/data-migration/tenant-migrator.ts +201 -201
  25. package/src/scripts/data-migration/typecast-manager.ts +193 -193
  26. package/src/scripts/data-migration/types.ts +113 -113
  27. package/src/scripts/database-initializer.ts +49 -49
  28. package/src/scripts/drop-database.ts +104 -104
  29. package/src/scripts/dump-source-db.sh +61 -61
  30. package/src/scripts/encrypt-user-passwords.ts +36 -36
  31. package/src/scripts/error-handler.ts +117 -117
  32. package/src/scripts/fix-data-types.ts +241 -241
  33. package/src/scripts/fix-enum-values.ts +357 -357
  34. package/src/scripts/fix-schema-discrepancies.ts +317 -317
  35. package/src/scripts/fix-table-indexes.ts +601 -601
  36. package/src/scripts/migrate-schema-structure.ts +90 -90
  37. package/src/scripts/migrate-uuid.ts +76 -76
  38. package/src/scripts/post-migration-validator.ts +526 -526
  39. package/src/scripts/pre-migration-validator.ts +610 -610
  40. package/src/scripts/reset-database.ts +263 -263
  41. package/src/scripts/retry-failed-migrations.ts +416 -416
  42. package/src/scripts/run-migration.ts +707 -707
  43. package/src/scripts/schema-sync.ts +128 -128
  44. package/src/scripts/sequence-sync-cli.ts +416 -416
  45. package/src/scripts/sequence-synchronizer.ts +127 -127
  46. package/src/scripts/sync-enum-types.ts +170 -170
  47. package/src/scripts/sync-enum-values.ts +563 -563
  48. package/src/scripts/truncate-database.ts +123 -123
  49. package/src/scripts/verify-migration-setup.ts +135 -135
  50. package/tsconfig.json +17 -17
@@ -1,201 +1,201 @@
1
- import { Logger } from "@nestjs/common";
2
- import { PrismaClient } from "@prisma/client";
3
- import { SchemaUtils } from "./schema-utils";
4
- import { EntityDiscovery } from "./entity-discovery";
5
- import { BatchMigrator } from "./batch-migrator";
6
- import { DatabaseConnections } from "./types";
7
- import { DependencyResolver } from "./dependency-resolver";
8
-
9
- export class TenantMigrator {
10
- private readonly logger = new Logger("TenantMigrator");
11
- private readonly dependencyResolver: DependencyResolver;
12
-
13
- constructor(
14
- private readonly schemaUtils: SchemaUtils,
15
- private readonly entityDiscovery: EntityDiscovery,
16
- private readonly batchMigrator: BatchMigrator,
17
- private readonly connections: DatabaseConnections
18
- ) {
19
- this.dependencyResolver = new DependencyResolver(
20
- connections.sourcePool,
21
- connections.targetPool
22
- );
23
- }
24
-
25
- // Método para verificar dependencias de fase
26
- async verifyPhaseDependencies(
27
- tenantId: string,
28
- tables: string[]
29
- ): Promise<boolean> {
30
- try {
31
- for (const table of tables) {
32
- const count = await this.connections.targetPrisma.$queryRawUnsafe(
33
- `SELECT COUNT(*) FROM "${tenantId}"."${table}"`
34
- );
35
-
36
- if (!count || count[0].count === "0") {
37
- this.logger.warn(
38
- `No data found in required table ${table} for tenant ${tenantId}`
39
- );
40
- return false;
41
- }
42
- }
43
- return true;
44
- } catch (error) {
45
- this.logger.error(`Error verifying phase dependencies: ${error.message}`);
46
- return false;
47
- }
48
- }
49
-
50
- async migrateDataForTenant(
51
- tenantId: string,
52
- providerId: number,
53
- includeTables?: string[] | null,
54
- excludeTables?: string[] | null
55
- ) {
56
- this.logger.log(
57
- `Migrating data for tenant: ${tenantId} (Provider ID: ${
58
- providerId || "N/A"
59
- })`
60
- );
61
-
62
- // Verificar que el tenant existe y pertenece al provider (o no tiene provider)
63
- try {
64
- let tenantExists = false;
65
-
66
- try {
67
- // Modificar la consulta para incluir casos donde provider_id es nulo
68
- const result = await this.connections.sourcePrisma.api_keys.findFirst({
69
- where: {
70
- api_key: tenantId,
71
- OR: [{ provider_id: providerId }, { provider_id: null }],
72
- },
73
- });
74
-
75
- tenantExists = !!result;
76
- } catch (error) {
77
- this.logger.warn(
78
- `Error checking tenant existence, will assume using public schema: ${error.message}`
79
- );
80
- tenantExists = true; // Asumir que estamos usando el esquema público
81
- }
82
-
83
- if (!tenantExists) {
84
- this.logger.warn(
85
- `Tenant ${tenantId} does not exist or does not belong to provider ${
86
- providerId || "N/A"
87
- }. Using public schema as source.`
88
- );
89
- // Continuamos de todos modos, asumiendo que usaremos el esquema público
90
- }
91
-
92
- // Log para depuración
93
- this.logger.log(`Proceeding with migration for tenant ${tenantId}`);
94
- } catch (error) {
95
- this.logger.error(
96
- `Error verifying tenant ${tenantId} for provider ${
97
- providerId || "N/A"
98
- }: ${error.message}`
99
- );
100
- // Log más detallado del error
101
- this.logger.error(`Error details: ${JSON.stringify(error)}`);
102
- // Continuamos de todos modos
103
- }
104
-
105
- // Create a client for this specific tenant schema with increased timeout
106
- const tenantPrisma = new PrismaClient({
107
- datasources: {
108
- db: {
109
- url: `${process.env.DATABASE_URL}?schema=${tenantId}`,
110
- },
111
- },
112
- // Increase transaction timeout to 5 minutes (was 2 minutes)
113
- transactionOptions: {
114
- maxWait: 300000, // 5 minutes max wait time
115
- timeout: 300000, // 5 minutes timeout
116
- },
117
- log: ["query", "error", "warn"], // Añadir logging para depuración
118
- });
119
-
120
- try {
121
- // Validate that the schema exists in the target database
122
- const schemaExists = await this.schemaUtils.checkSchemaExists(tenantId);
123
- if (!schemaExists) {
124
- this.logger.error(
125
- `Schema ${tenantId} does not exist in target database. Skipping migration.`
126
- );
127
- return;
128
- }
129
-
130
- // Get all tables from the target schema
131
- const targetTables = await this.schemaUtils.getTargetTables(tenantId);
132
-
133
- // Discover entity types and their relationships automatically
134
- let entityTypes = await this.entityDiscovery.discoverEntityTypes(
135
- tenantId,
136
- targetTables
137
- );
138
-
139
- // Filtrar entidades según los parámetros includeTables y excludeTables
140
- if (includeTables) {
141
- entityTypes = entityTypes.filter((entity) =>
142
- includeTables.includes(entity.name)
143
- );
144
- this.logger.log(
145
- `Filtered to include only: ${includeTables.join(", ")}`
146
- );
147
- }
148
-
149
- if (excludeTables) {
150
- entityTypes = entityTypes.filter(
151
- (entity) => !excludeTables.includes(entity.name)
152
- );
153
- this.logger.log(`Filtered to exclude: ${excludeTables.join(", ")}`);
154
- }
155
-
156
- // Ordenar entidades basadas en dependencias
157
- // Replace dependencyManager with dependencyResolver for ordering
158
- const sortedTables = await this.dependencyResolver.analyzeDependencies();
159
- const orderedEntities = entityTypes
160
- .sort((a, b) => {
161
- const aIndex = sortedTables.indexOf(a.name);
162
- const bIndex = sortedTables.indexOf(b.name);
163
- return aIndex - bIndex;
164
- })
165
- .filter((entity) => sortedTables.includes(entity.name));
166
-
167
- this.logger.log(
168
- `Migration order: ${orderedEntities.map((e) => e.name).join(" -> ")}`
169
- );
170
-
171
- this.logger.log(
172
- `Discovered ${entityTypes.length} entity types for migration`
173
- );
174
-
175
- // Migrate each entity type separately to avoid transaction timeouts
176
- for (const entity of orderedEntities) {
177
- await this.batchMigrator.migrateEntityDataInBatches(
178
- "public", // esquema fuente
179
- tenantId, // esquema destino
180
- {
181
- type: "tenant",
182
- idField: entity.idField,
183
- sourceTable: entity.name,
184
- targetTable: entity.name,
185
- filterColumn: entity.filterColumn,
186
- via: entity.filterVia,
187
- },
188
- providerId?.toString()
189
- );
190
- }
191
-
192
- this.logger.log(`Completed migration for tenant ${tenantId}`);
193
- } catch (error) {
194
- this.logger.error(
195
- `Error migrating data for tenant ${tenantId}: ${error.message}`
196
- );
197
- } finally {
198
- await tenantPrisma.$disconnect();
199
- }
200
- }
201
- }
1
+ import { Logger } from "@nestjs/common";
2
+ import { PrismaClient } from "@prisma/client";
3
+ import { SchemaUtils } from "./schema-utils";
4
+ import { EntityDiscovery } from "./entity-discovery";
5
+ import { BatchMigrator } from "./batch-migrator";
6
+ import { DatabaseConnections } from "./types";
7
+ import { DependencyResolver } from "./dependency-resolver";
8
+
9
+ export class TenantMigrator {
10
+ private readonly logger = new Logger("TenantMigrator");
11
+ private readonly dependencyResolver: DependencyResolver;
12
+
13
+ constructor(
14
+ private readonly schemaUtils: SchemaUtils,
15
+ private readonly entityDiscovery: EntityDiscovery,
16
+ private readonly batchMigrator: BatchMigrator,
17
+ private readonly connections: DatabaseConnections
18
+ ) {
19
+ this.dependencyResolver = new DependencyResolver(
20
+ connections.sourcePool,
21
+ connections.targetPool
22
+ );
23
+ }
24
+
25
+ // Método para verificar dependencias de fase
26
+ async verifyPhaseDependencies(
27
+ tenantId: string,
28
+ tables: string[]
29
+ ): Promise<boolean> {
30
+ try {
31
+ for (const table of tables) {
32
+ const count = await this.connections.targetPrisma.$queryRawUnsafe(
33
+ `SELECT COUNT(*) FROM "${tenantId}"."${table}"`
34
+ );
35
+
36
+ if (!count || count[0].count === "0") {
37
+ this.logger.warn(
38
+ `No data found in required table ${table} for tenant ${tenantId}`
39
+ );
40
+ return false;
41
+ }
42
+ }
43
+ return true;
44
+ } catch (error) {
45
+ this.logger.error(`Error verifying phase dependencies: ${error.message}`);
46
+ return false;
47
+ }
48
+ }
49
+
50
+ async migrateDataForTenant(
51
+ tenantId: string,
52
+ providerId: number,
53
+ includeTables?: string[] | null,
54
+ excludeTables?: string[] | null
55
+ ) {
56
+ this.logger.log(
57
+ `Migrating data for tenant: ${tenantId} (Provider ID: ${
58
+ providerId || "N/A"
59
+ })`
60
+ );
61
+
62
+ // Verificar que el tenant existe y pertenece al provider (o no tiene provider)
63
+ try {
64
+ let tenantExists = false;
65
+
66
+ try {
67
+ // Modificar la consulta para incluir casos donde provider_id es nulo
68
+ const result = await this.connections.sourcePrisma.api_keys.findFirst({
69
+ where: {
70
+ api_key: tenantId,
71
+ OR: [{ provider_id: providerId }, { provider_id: null }],
72
+ },
73
+ });
74
+
75
+ tenantExists = !!result;
76
+ } catch (error) {
77
+ this.logger.warn(
78
+ `Error checking tenant existence, will assume using public schema: ${error.message}`
79
+ );
80
+ tenantExists = true; // Asumir que estamos usando el esquema público
81
+ }
82
+
83
+ if (!tenantExists) {
84
+ this.logger.warn(
85
+ `Tenant ${tenantId} does not exist or does not belong to provider ${
86
+ providerId || "N/A"
87
+ }. Using public schema as source.`
88
+ );
89
+ // Continuamos de todos modos, asumiendo que usaremos el esquema público
90
+ }
91
+
92
+ // Log para depuración
93
+ this.logger.log(`Proceeding with migration for tenant ${tenantId}`);
94
+ } catch (error) {
95
+ this.logger.error(
96
+ `Error verifying tenant ${tenantId} for provider ${
97
+ providerId || "N/A"
98
+ }: ${error.message}`
99
+ );
100
+ // Log más detallado del error
101
+ this.logger.error(`Error details: ${JSON.stringify(error)}`);
102
+ // Continuamos de todos modos
103
+ }
104
+
105
+ // Create a client for this specific tenant schema with increased timeout
106
+ const tenantPrisma = new PrismaClient({
107
+ datasources: {
108
+ db: {
109
+ url: `${process.env.DATABASE_URL}?schema=${tenantId}`,
110
+ },
111
+ },
112
+ // Increase transaction timeout to 5 minutes (was 2 minutes)
113
+ transactionOptions: {
114
+ maxWait: 300000, // 5 minutes max wait time
115
+ timeout: 300000, // 5 minutes timeout
116
+ },
117
+ log: ["query", "error", "warn"], // Añadir logging para depuración
118
+ });
119
+
120
+ try {
121
+ // Validate that the schema exists in the target database
122
+ const schemaExists = await this.schemaUtils.checkSchemaExists(tenantId);
123
+ if (!schemaExists) {
124
+ this.logger.error(
125
+ `Schema ${tenantId} does not exist in target database. Skipping migration.`
126
+ );
127
+ return;
128
+ }
129
+
130
+ // Get all tables from the target schema
131
+ const targetTables = await this.schemaUtils.getTargetTables(tenantId);
132
+
133
+ // Discover entity types and their relationships automatically
134
+ let entityTypes = await this.entityDiscovery.discoverEntityTypes(
135
+ tenantId,
136
+ targetTables
137
+ );
138
+
139
+ // Filtrar entidades según los parámetros includeTables y excludeTables
140
+ if (includeTables) {
141
+ entityTypes = entityTypes.filter((entity) =>
142
+ includeTables.includes(entity.name)
143
+ );
144
+ this.logger.log(
145
+ `Filtered to include only: ${includeTables.join(", ")}`
146
+ );
147
+ }
148
+
149
+ if (excludeTables) {
150
+ entityTypes = entityTypes.filter(
151
+ (entity) => !excludeTables.includes(entity.name)
152
+ );
153
+ this.logger.log(`Filtered to exclude: ${excludeTables.join(", ")}`);
154
+ }
155
+
156
+ // Ordenar entidades basadas en dependencias
157
+ // Replace dependencyManager with dependencyResolver for ordering
158
+ const sortedTables = await this.dependencyResolver.analyzeDependencies();
159
+ const orderedEntities = entityTypes
160
+ .sort((a, b) => {
161
+ const aIndex = sortedTables.indexOf(a.name);
162
+ const bIndex = sortedTables.indexOf(b.name);
163
+ return aIndex - bIndex;
164
+ })
165
+ .filter((entity) => sortedTables.includes(entity.name));
166
+
167
+ this.logger.log(
168
+ `Migration order: ${orderedEntities.map((e) => e.name).join(" -> ")}`
169
+ );
170
+
171
+ this.logger.log(
172
+ `Discovered ${entityTypes.length} entity types for migration`
173
+ );
174
+
175
+ // Migrate each entity type separately to avoid transaction timeouts
176
+ for (const entity of orderedEntities) {
177
+ await this.batchMigrator.migrateEntityDataInBatches(
178
+ "public", // esquema fuente
179
+ tenantId, // esquema destino
180
+ {
181
+ type: "tenant",
182
+ idField: entity.idField,
183
+ sourceTable: entity.name,
184
+ targetTable: entity.name,
185
+ filterColumn: entity.filterColumn,
186
+ via: entity.filterVia,
187
+ },
188
+ providerId?.toString()
189
+ );
190
+ }
191
+
192
+ this.logger.log(`Completed migration for tenant ${tenantId}`);
193
+ } catch (error) {
194
+ this.logger.error(
195
+ `Error migrating data for tenant ${tenantId}: ${error.message}`
196
+ );
197
+ } finally {
198
+ await tenantPrisma.$disconnect();
199
+ }
200
+ }
201
+ }