@javalabs/prisma-client 1.0.0

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 (150) hide show
  1. package/README.md +220 -0
  2. package/dist/index.d.ts +7 -0
  3. package/dist/index.js +34 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/prisma-factory.service.d.ts +9 -0
  6. package/dist/prisma-factory.service.js +47 -0
  7. package/dist/prisma-factory.service.js.map +1 -0
  8. package/dist/prisma.module.d.ts +2 -0
  9. package/dist/prisma.module.js +23 -0
  10. package/dist/prisma.module.js.map +1 -0
  11. package/dist/prisma.service.d.ts +6 -0
  12. package/dist/prisma.service.js +27 -0
  13. package/dist/prisma.service.js.map +1 -0
  14. package/dist/scripts/create-tenant-schemas.d.ts +1 -0
  15. package/dist/scripts/create-tenant-schemas.js +117 -0
  16. package/dist/scripts/create-tenant-schemas.js.map +1 -0
  17. package/dist/scripts/data-migration/batch-migrator.d.ts +25 -0
  18. package/dist/scripts/data-migration/batch-migrator.js +333 -0
  19. package/dist/scripts/data-migration/batch-migrator.js.map +1 -0
  20. package/dist/scripts/data-migration/data-transformer.d.ts +17 -0
  21. package/dist/scripts/data-migration/data-transformer.js +242 -0
  22. package/dist/scripts/data-migration/data-transformer.js.map +1 -0
  23. package/dist/scripts/data-migration/db-connector.d.ts +7 -0
  24. package/dist/scripts/data-migration/db-connector.js +58 -0
  25. package/dist/scripts/data-migration/db-connector.js.map +1 -0
  26. package/dist/scripts/data-migration/dependency-manager.d.ts +9 -0
  27. package/dist/scripts/data-migration/dependency-manager.js +86 -0
  28. package/dist/scripts/data-migration/dependency-manager.js.map +1 -0
  29. package/dist/scripts/data-migration/dependency-resolver.d.ts +18 -0
  30. package/dist/scripts/data-migration/dependency-resolver.js +251 -0
  31. package/dist/scripts/data-migration/dependency-resolver.js.map +1 -0
  32. package/dist/scripts/data-migration/entity-discovery.d.ts +11 -0
  33. package/dist/scripts/data-migration/entity-discovery.js +152 -0
  34. package/dist/scripts/data-migration/entity-discovery.js.map +1 -0
  35. package/dist/scripts/data-migration/foreign-key-manager.d.ts +17 -0
  36. package/dist/scripts/data-migration/foreign-key-manager.js +70 -0
  37. package/dist/scripts/data-migration/foreign-key-manager.js.map +1 -0
  38. package/dist/scripts/data-migration/migration-phases.d.ts +5 -0
  39. package/dist/scripts/data-migration/migration-phases.js +55 -0
  40. package/dist/scripts/data-migration/migration-phases.js.map +1 -0
  41. package/dist/scripts/data-migration/migration-tool.d.ts +29 -0
  42. package/dist/scripts/data-migration/migration-tool.js +250 -0
  43. package/dist/scripts/data-migration/migration-tool.js.map +1 -0
  44. package/dist/scripts/data-migration/phase-generator.d.ts +15 -0
  45. package/dist/scripts/data-migration/phase-generator.js +187 -0
  46. package/dist/scripts/data-migration/phase-generator.js.map +1 -0
  47. package/dist/scripts/data-migration/schema-utils.d.ts +18 -0
  48. package/dist/scripts/data-migration/schema-utils.js +164 -0
  49. package/dist/scripts/data-migration/schema-utils.js.map +1 -0
  50. package/dist/scripts/data-migration/tenant-migrator.d.ts +15 -0
  51. package/dist/scripts/data-migration/tenant-migrator.js +110 -0
  52. package/dist/scripts/data-migration/tenant-migrator.js.map +1 -0
  53. package/dist/scripts/data-migration/typecast-manager.d.ts +5 -0
  54. package/dist/scripts/data-migration/typecast-manager.js +35 -0
  55. package/dist/scripts/data-migration/typecast-manager.js.map +1 -0
  56. package/dist/scripts/data-migration/types.d.ts +34 -0
  57. package/dist/scripts/data-migration/types.js +3 -0
  58. package/dist/scripts/data-migration/types.js.map +1 -0
  59. package/dist/scripts/data-migration.d.ts +22 -0
  60. package/dist/scripts/data-migration.js +593 -0
  61. package/dist/scripts/data-migration.js.map +1 -0
  62. package/dist/scripts/drop-database.d.ts +10 -0
  63. package/dist/scripts/drop-database.js +81 -0
  64. package/dist/scripts/drop-database.js.map +1 -0
  65. package/dist/scripts/error-handler.d.ts +12 -0
  66. package/dist/scripts/error-handler.js +82 -0
  67. package/dist/scripts/error-handler.js.map +1 -0
  68. package/dist/scripts/fix-data-types.d.ts +10 -0
  69. package/dist/scripts/fix-data-types.js +185 -0
  70. package/dist/scripts/fix-data-types.js.map +1 -0
  71. package/dist/scripts/fix-enum-values.d.ts +17 -0
  72. package/dist/scripts/fix-enum-values.js +234 -0
  73. package/dist/scripts/fix-enum-values.js.map +1 -0
  74. package/dist/scripts/fix-schema-discrepancies.d.ts +21 -0
  75. package/dist/scripts/fix-schema-discrepancies.js +240 -0
  76. package/dist/scripts/fix-schema-discrepancies.js.map +1 -0
  77. package/dist/scripts/migrate-schema-structure.d.ts +1 -0
  78. package/dist/scripts/migrate-schema-structure.js +76 -0
  79. package/dist/scripts/migrate-schema-structure.js.map +1 -0
  80. package/dist/scripts/post-migration-validator.d.ts +21 -0
  81. package/dist/scripts/post-migration-validator.js +341 -0
  82. package/dist/scripts/post-migration-validator.js.map +1 -0
  83. package/dist/scripts/pre-migration-validator.d.ts +25 -0
  84. package/dist/scripts/pre-migration-validator.js +491 -0
  85. package/dist/scripts/pre-migration-validator.js.map +1 -0
  86. package/dist/scripts/reset-database.d.ts +17 -0
  87. package/dist/scripts/reset-database.js +202 -0
  88. package/dist/scripts/reset-database.js.map +1 -0
  89. package/dist/scripts/retry-failed-migrations.d.ts +14 -0
  90. package/dist/scripts/retry-failed-migrations.js +301 -0
  91. package/dist/scripts/retry-failed-migrations.js.map +1 -0
  92. package/dist/scripts/run-migration.d.ts +1 -0
  93. package/dist/scripts/run-migration.js +525 -0
  94. package/dist/scripts/run-migration.js.map +1 -0
  95. package/dist/scripts/schema-sync.d.ts +1 -0
  96. package/dist/scripts/schema-sync.js +85 -0
  97. package/dist/scripts/schema-sync.js.map +1 -0
  98. package/dist/scripts/sync-enum-types.d.ts +13 -0
  99. package/dist/scripts/sync-enum-types.js +139 -0
  100. package/dist/scripts/sync-enum-types.js.map +1 -0
  101. package/dist/scripts/sync-enum-values.d.ts +20 -0
  102. package/dist/scripts/sync-enum-values.js +336 -0
  103. package/dist/scripts/sync-enum-values.js.map +1 -0
  104. package/dist/scripts/truncate-database.d.ts +10 -0
  105. package/dist/scripts/truncate-database.js +100 -0
  106. package/dist/scripts/truncate-database.js.map +1 -0
  107. package/dist/scripts/verify-migration-setup.d.ts +11 -0
  108. package/dist/scripts/verify-migration-setup.js +120 -0
  109. package/dist/scripts/verify-migration-setup.js.map +1 -0
  110. package/dist/tsconfig.tsbuildinfo +1 -0
  111. package/migration-config-public.json +95 -0
  112. package/migration-config.json +95 -0
  113. package/package.json +33 -0
  114. package/prisma/migrations/migration_lock.toml +3 -0
  115. package/prisma/schema.prisma +360 -0
  116. package/src/index.ts +23 -0
  117. package/src/prisma-factory.service.ts +41 -0
  118. package/src/prisma.module.ts +10 -0
  119. package/src/prisma.service.ts +17 -0
  120. package/src/scripts/create-tenant-schemas.ts +146 -0
  121. package/src/scripts/data-migration/batch-migrator.ts +569 -0
  122. package/src/scripts/data-migration/data-transformer.ts +377 -0
  123. package/src/scripts/data-migration/db-connector.ts +67 -0
  124. package/src/scripts/data-migration/dependency-resolver.ts +319 -0
  125. package/src/scripts/data-migration/entity-discovery.ts +197 -0
  126. package/src/scripts/data-migration/foreign-key-manager.ts +95 -0
  127. package/src/scripts/data-migration/migration-tool.ts +357 -0
  128. package/src/scripts/data-migration/schema-utils.ts +186 -0
  129. package/src/scripts/data-migration/tenant-migrator.ts +194 -0
  130. package/src/scripts/data-migration/typecast-manager.ts +38 -0
  131. package/src/scripts/data-migration/types.ts +40 -0
  132. package/src/scripts/drop-database.ts +105 -0
  133. package/src/scripts/dump-source-db.sh +62 -0
  134. package/src/scripts/dumps/source_dump_20250413_112626.sql +1527 -0
  135. package/src/scripts/error-handler.ts +118 -0
  136. package/src/scripts/fix-data-types.ts +242 -0
  137. package/src/scripts/fix-enum-values.ts +357 -0
  138. package/src/scripts/fix-schema-discrepancies.ts +318 -0
  139. package/src/scripts/migrate-schema-structure.ts +90 -0
  140. package/src/scripts/post-migration-validator.ts +427 -0
  141. package/src/scripts/pre-migration-validator.ts +611 -0
  142. package/src/scripts/reset-database.ts +264 -0
  143. package/src/scripts/retry-failed-migrations.ts +416 -0
  144. package/src/scripts/run-migration.ts +691 -0
  145. package/src/scripts/schema-sync.ts +129 -0
  146. package/src/scripts/sync-enum-types.ts +171 -0
  147. package/src/scripts/sync-enum-values.ts +563 -0
  148. package/src/scripts/truncate-database.ts +124 -0
  149. package/src/scripts/verify-migration-setup.ts +136 -0
  150. package/tsconfig.json +18 -0
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ForeignKeyManager = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ class ForeignKeyManager {
6
+ constructor(connections) {
7
+ this.connections = connections;
8
+ this.logger = new common_1.Logger("ForeignKeyManager");
9
+ }
10
+ async getForeignKeyDependencies(schemaName, tableName) {
11
+ try {
12
+ const query = `
13
+ SELECT
14
+ kcu.column_name,
15
+ ccu.table_name AS foreign_table_name,
16
+ ccu.column_name AS foreign_column_name
17
+ FROM
18
+ information_schema.table_constraints tc
19
+ JOIN information_schema.key_column_usage kcu
20
+ ON tc.constraint_name = kcu.constraint_name
21
+ AND tc.table_schema = kcu.table_schema
22
+ JOIN information_schema.constraint_column_usage ccu
23
+ ON ccu.constraint_name = tc.constraint_name
24
+ AND ccu.table_schema = tc.table_schema
25
+ WHERE
26
+ tc.constraint_type = 'FOREIGN KEY'
27
+ AND tc.table_schema = $1
28
+ AND tc.table_name = $2;
29
+ `;
30
+ const { rows } = await this.connections.targetPool.query(query, [
31
+ schemaName,
32
+ tableName,
33
+ ]);
34
+ return rows.map((row) => ({
35
+ column: row.column_name,
36
+ foreignTable: row.foreign_table_name,
37
+ foreignColumn: row.foreign_column_name,
38
+ }));
39
+ }
40
+ catch (error) {
41
+ this.logger.error(`Error getting foreign key dependencies for ${tableName}: ${error.message}`);
42
+ return [];
43
+ }
44
+ }
45
+ async checkForeignKeyDependencies(prisma, schemaName, row, dependencies) {
46
+ const missingDependencies = [];
47
+ for (const dep of dependencies) {
48
+ if (row[dep.column] !== null) {
49
+ const query = `
50
+ SELECT 1 FROM "${schemaName}"."${dep.foreignTable}"
51
+ WHERE "${dep.foreignColumn}" = $1
52
+ LIMIT 1
53
+ `;
54
+ try {
55
+ const result = await prisma.$queryRawUnsafe(query, row[dep.column]);
56
+ if (!result || (Array.isArray(result) && result.length === 0)) {
57
+ missingDependencies.push(`${dep.foreignTable}.${dep.foreignColumn}=${row[dep.column]}`);
58
+ }
59
+ }
60
+ catch (error) {
61
+ this.logger.error(`Error checking dependency ${dep.foreignTable}.${dep.foreignColumn}: ${error.message}`);
62
+ missingDependencies.push(`${dep.foreignTable}.${dep.foreignColumn}=${row[dep.column]} (error)`);
63
+ }
64
+ }
65
+ }
66
+ return missingDependencies;
67
+ }
68
+ }
69
+ exports.ForeignKeyManager = ForeignKeyManager;
70
+ //# sourceMappingURL=foreign-key-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"foreign-key-manager.js","sourceRoot":"","sources":["../../../src/scripts/data-migration/foreign-key-manager.ts"],"names":[],"mappings":";;;AAAA,2CAAwC;AAIxC,MAAa,iBAAiB;IAG5B,YAA6B,WAAgC;QAAhC,gBAAW,GAAX,WAAW,CAAqB;QAF5C,WAAM,GAAG,IAAI,eAAM,CAAC,mBAAmB,CAAC,CAAC;IAEM,CAAC;IAEjE,KAAK,CAAC,yBAAyB,CAC7B,UAAkB,EAClB,SAAiB;QAIjB,IAAI,CAAC;YACH,MAAM,KAAK,GAAG;;;;;;;;;;;;;;;;;OAiBb,CAAC;YAEF,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK,EAAE;gBAC9D,UAAU;gBACV,SAAS;aACV,CAAC,CAAC;YACH,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;gBACxB,MAAM,EAAE,GAAG,CAAC,WAAW;gBACvB,YA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C,IAAI,CACtB,GAAG,GAAG,CAAC,YAAY,IAAI,GAAG,CAAC,aAAa,IACtC,GAAG,CAAC,GAAG,CAAC,MAAM,CAChB,UAAU,CACX,CAAC;gBACJ,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,mBAAmB,CAAC;IAC7B,CAAC;CACF;AA1FD,8CA0FC"}
@@ -0,0 +1,5 @@
1
+ import { MigrationPhase } from './types';
2
+ import { PrismaClient } from '@prisma/client';
3
+ export declare const defaultMigrationPhases: MigrationPhase[];
4
+ export declare function generateMigrationPhases(prisma: PrismaClient): Promise<MigrationPhase[]>;
5
+ export declare const migrationPhases: MigrationPhase[];
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.migrationPhases = exports.defaultMigrationPhases = void 0;
4
+ exports.generateMigrationPhases = generateMigrationPhases;
5
+ const phase_generator_1 = require("./phase-generator");
6
+ exports.defaultMigrationPhases = [
7
+ {
8
+ name: "Base Tables",
9
+ tables: ["users", "providers", "companies", "countries"],
10
+ required: true,
11
+ },
12
+ {
13
+ name: "Core Financial",
14
+ tables: ["balances", "banks"],
15
+ required: true,
16
+ },
17
+ {
18
+ name: "Transactions",
19
+ tables: ["transactions", "global_user_transactions"],
20
+ required: true,
21
+ },
22
+ {
23
+ name: "Transaction Related",
24
+ tables: ["transaction_updates", "daily_logs", "invoices"],
25
+ required: true,
26
+ },
27
+ {
28
+ name: "Customer Data",
29
+ tables: ["customers", "charges", "credit_requests"],
30
+ required: true,
31
+ },
32
+ {
33
+ name: "Supporting Data",
34
+ tables: [
35
+ "notifications",
36
+ "api_keys",
37
+ "api_request_logs",
38
+ "pending_references",
39
+ "toku",
40
+ ],
41
+ required: false,
42
+ },
43
+ ];
44
+ async function generateMigrationPhases(prisma) {
45
+ const phaseGenerator = new phase_generator_1.PhaseGenerator(prisma);
46
+ try {
47
+ return await phaseGenerator.generatePhases();
48
+ }
49
+ catch (error) {
50
+ console.error('Error generando fases de migración:', error);
51
+ return exports.defaultMigrationPhases;
52
+ }
53
+ }
54
+ exports.migrationPhases = exports.defaultMigrationPhases;
55
+ //# sourceMappingURL=migration-phases.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-phases.js","sourceRoot":"","sources":["../../../src/scripts/data-migration/migration-phases.ts"],"names":[],"mappings":";;;AA6CA,0DAQC;AApDD,uDAAmD;AAItC,QAAA,sBAAsB,GAAqB;IACtD;QACE,IAAI,EAAE,aAAa;QACnB,MAAM,EAAE,CAAC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,CAAC;QACxD,QAAQ,EAAE,IAAI;KACf;IACD;QACE,IAAI,EAAE,gBAAgB;QACtB,MAAM,EAAE,CAAC,UAAU,EAAE,OAAO,CAAC;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD;QACE,IAAI,EAAE,cAAc;QACpB,MAAM,EAAE,CAAC,cAAc,EAAE,0BAA0B,CAAC;QACpD,QAAQ,EAAE,IAAI;KACf;IACD;QACE,IAAI,EAAE,qBAAqB;QAC3B,MAAM,EAAE,CAAC,qBAAqB,EAAE,YAAY,EAAE,UAAU,CAAC;QACzD,QAAQ,EAAE,IAAI;KACf;IACD;QACE,IAAI,EAAE,eAAe;QACrB,MAAM,EAAE,CAAC,WAAW,EAAE,SAAS,EAAE,iBAAiB,CAAC;QACnD,QAAQ,EAAE,IAAI;KACf;IACD;QACE,IAAI,EAAE,iBAAiB;QACvB,MAAM,EAAE;YACN,eAAe;YACf,UAAU;YACV,kBAAkB;YAClB,oBAAoB;YACpB,MAAM;SACP;QACD,QAAQ,EAAE,KAAK;KAChB;CACF,CAAC;AAGK,KAAK,UAAU,uBAAuB,CAAC,MAAoB;IAChE,MAAM,cAAc,GAAG,IAAI,gCAAc,CAAC,MAAM,CAAC,CAAC;IAClD,IAAI,CAAC;QACH,OAAO,MAAM,cAAc,CAAC,cAAc,EAAE,CAAC;IAC/C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAC5D,OAAO,8BAAsB,CAAC;IAChC,CAAC;AACH,CAAC;AAGY,QAAA,eAAe,GAAG,8BAAsB,CAAC"}
@@ -0,0 +1,29 @@
1
+ import { DatabaseConnections } from "./types";
2
+ interface MigrationOptions {
3
+ publicOnly?: boolean;
4
+ multiTenant?: boolean;
5
+ sourceSchema?: string;
6
+ targetSchema?: string;
7
+ forceSingleTenant?: boolean;
8
+ configPath?: string;
9
+ }
10
+ export declare class DataMigrationTool {
11
+ private readonly connections;
12
+ private readonly logger;
13
+ private readonly schemaUtils;
14
+ private readonly dataTransformer;
15
+ private readonly foreignKeyManager;
16
+ private readonly batchMigrator;
17
+ private readonly dependencyResolver;
18
+ private migrationConfig;
19
+ private schemaCache;
20
+ private targetSchemaCache;
21
+ constructor(connections: DatabaseConnections);
22
+ private loadConfig;
23
+ migrateData(options?: MigrationOptions): Promise<void>;
24
+ private migratePublicTablesOnly;
25
+ private validateSourceData;
26
+ private migrateMultiTenantWithConfig;
27
+ private verifyMigration;
28
+ }
29
+ export {};
@@ -0,0 +1,250 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DataMigrationTool = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const fs = require("fs");
6
+ const path = require("path");
7
+ const schema_utils_1 = require("./schema-utils");
8
+ const data_transformer_1 = require("./data-transformer");
9
+ const batch_migrator_1 = require("./batch-migrator");
10
+ const foreign_key_manager_1 = require("./foreign-key-manager");
11
+ const dependency_resolver_1 = require("./dependency-resolver");
12
+ class DataMigrationTool {
13
+ constructor(connections) {
14
+ this.connections = connections;
15
+ this.logger = new common_1.Logger("DataMigrationTool");
16
+ this.schemaCache = {};
17
+ this.targetSchemaCache = {};
18
+ this.schemaUtils = new schema_utils_1.SchemaUtils(connections.sourcePool, connections.targetPool);
19
+ this.dataTransformer = new data_transformer_1.DataTransformer(this.schemaUtils);
20
+ this.foreignKeyManager = new foreign_key_manager_1.ForeignKeyManager(connections);
21
+ this.dependencyResolver = new dependency_resolver_1.DependencyResolver(connections.sourcePool, connections.targetPool);
22
+ this.batchMigrator = new batch_migrator_1.BatchMigrator(this.dataTransformer, this.schemaUtils, connections, this.dependencyResolver, this.schemaCache, this.targetSchemaCache);
23
+ }
24
+ loadConfig(configPath = 'migration-config.json') {
25
+ const fullPath = path.resolve(process.cwd(), configPath);
26
+ if (!fs.existsSync(fullPath)) {
27
+ throw new Error(`Migration config file not found at: ${fullPath}`);
28
+ }
29
+ try {
30
+ const fileContent = fs.readFileSync(fullPath, 'utf-8');
31
+ this.migrationConfig = JSON.parse(fileContent);
32
+ this.logger.log(`Loaded migration config from: ${fullPath}`);
33
+ }
34
+ catch (error) {
35
+ throw new Error(`Error reading or parsing migration config file: ${error.message}`);
36
+ }
37
+ if (!this.migrationConfig.commonSchema || !this.migrationConfig.tables || !this.migrationConfig.tenantInfo) {
38
+ throw new Error('Invalid migration config structure.');
39
+ }
40
+ }
41
+ async migrateData(options = {}) {
42
+ try {
43
+ this.logger.log("Starting data migration process");
44
+ this.loadConfig(options.configPath);
45
+ if (options.forceSingleTenant || options.publicOnly) {
46
+ this.logger.log("Public-only migration requested. Migrating only 'public' type tables...");
47
+ await this.migratePublicTablesOnly();
48
+ }
49
+ else {
50
+ this.logger.log("Multi-tenant migration requested based on config...");
51
+ await this.migrateMultiTenantWithConfig();
52
+ }
53
+ }
54
+ catch (error) {
55
+ this.logger.error(`Migration failed: ${error.message}`);
56
+ console.error(error);
57
+ throw error;
58
+ }
59
+ }
60
+ async migratePublicTablesOnly() {
61
+ const { commonSchema, tables: tablesConfig } = this.migrationConfig;
62
+ const allTablesInOrder = await this.dependencyResolver.analyzeDependencies();
63
+ const publicTablesToMigrate = allTablesInOrder.filter(t => { var _a; return ((_a = tablesConfig[t]) === null || _a === void 0 ? void 0 : _a.type) === 'public'; });
64
+ this.logger.log(`Migrating public tables to '${commonSchema}' schema: ${publicTablesToMigrate.join(", ")}`);
65
+ if (publicTablesToMigrate.length === 0) {
66
+ this.logger.warn("No tables configured as 'public'. Public-only migration will not process any tables.");
67
+ return;
68
+ }
69
+ await this.connections.targetPool.query(`SET session_replication_role = 'replica';`);
70
+ for (const tableName of publicTablesToMigrate) {
71
+ const config = tablesConfig[tableName];
72
+ if (!config) {
73
+ this.logger.warn(`Config not found for public table ${tableName}, skipping.`);
74
+ continue;
75
+ }
76
+ try {
77
+ await this.batchMigrator.migrateEntityDataInBatches(this.connections.targetPrisma, { name: tableName, idField: config.idField }, null, commonSchema);
78
+ }
79
+ catch (error) {
80
+ this.logger.error(`Error migrating public table ${tableName}: ${error.message}`);
81
+ throw error;
82
+ }
83
+ }
84
+ await this.connections.targetPool.query(`SET session_replication_role = 'origin';`);
85
+ this.logger.log("Finished migrating public tables.");
86
+ }
87
+ async validateSourceData() {
88
+ this.logger.log("Validating source data...");
89
+ try {
90
+ const { sourceTable, providerIdColumn } = this.migrationConfig.tenantInfo;
91
+ const tablesConfig = this.migrationConfig.tables;
92
+ let transactionTableKey = 'transactions';
93
+ let providerTableKey = 'providers';
94
+ let transactionProviderFk = providerIdColumn;
95
+ for (const key in tablesConfig) {
96
+ if (tablesConfig[key].type === 'filteredPublic' && tablesConfig[key].filterColumn === providerIdColumn && !tablesConfig[key].via) {
97
+ transactionTableKey = key;
98
+ transactionProviderFk = tablesConfig[key].filterColumn;
99
+ }
100
+ if (tablesConfig[key].type === 'public' && tablesConfig[key].idField === providerIdColumn) {
101
+ providerTableKey = key;
102
+ }
103
+ }
104
+ this.logger.debug(`Validation check: Using ${transactionTableKey}.${transactionProviderFk} referencing ${providerTableKey}.${providerIdColumn}`);
105
+ const query = `
106
+ SELECT t."${tablesConfig[transactionTableKey].idField}" AS transaction_id, t."${transactionProviderFk}"
107
+ FROM "${transactionTableKey}" t
108
+ LEFT JOIN "${providerTableKey}" p ON t."${transactionProviderFk}" = p."${providerIdColumn}"
109
+ WHERE t."${transactionProviderFk}" IS NOT NULL AND p."${providerIdColumn}" IS NULL;
110
+ `;
111
+ const invalidTransactions = (await this.connections.sourcePrisma.$queryRawUnsafe(query));
112
+ if (invalidTransactions.length > 0) {
113
+ this.logger.error(`${invalidTransactions.length} records found in ${transactionTableKey} with invalid foreign key reference to ${providerTableKey}.${providerIdColumn}`);
114
+ console.error("Invalid records (limit 10):", invalidTransactions.slice(0, 10));
115
+ throw new Error("Source data validation failed: Invalid foreign key references found. Please check the configuration or fix the source data.");
116
+ }
117
+ else {
118
+ this.logger.log(`Source data validation passed: All ${transactionTableKey}.${transactionProviderFk} references are valid.`);
119
+ }
120
+ }
121
+ catch (error) {
122
+ this.logger.error("Error during source data validation:");
123
+ console.error(error);
124
+ throw error;
125
+ }
126
+ }
127
+ async migrateMultiTenantWithConfig() {
128
+ var _a, _b;
129
+ await this.validateSourceData();
130
+ const { commonSchema, tables: tablesConfig, tenantInfo } = this.migrationConfig;
131
+ const allTablesInOrder = await this.dependencyResolver.analyzeDependencies();
132
+ this.logger.log(`Migrating public tables to '${commonSchema}' schema...`);
133
+ await this.connections.targetPool.query(`SET session_replication_role = 'replica';`);
134
+ const publicTables = allTablesInOrder.filter(t => { var _a; return ((_a = tablesConfig[t]) === null || _a === void 0 ? void 0 : _a.type) === 'public'; });
135
+ for (const tableName of publicTables) {
136
+ const config = tablesConfig[tableName];
137
+ if (!config) {
138
+ this.logger.warn(`Skipping migration for table ${tableName}: Not found in config.`);
139
+ continue;
140
+ }
141
+ try {
142
+ await this.batchMigrator.migrateEntityDataInBatches(this.connections.targetPrisma, { name: tableName, idField: config.idField }, null, commonSchema);
143
+ }
144
+ catch (error) {
145
+ this.logger.error(`Error migrating public table ${tableName}: ${error.message}`);
146
+ throw error;
147
+ }
148
+ }
149
+ await this.connections.targetPool.query(`SET session_replication_role = 'origin';`);
150
+ this.logger.log("Finished migrating public tables.");
151
+ this.logger.log(`Fetching tenant info from source table '${tenantInfo.sourceTable}'...`);
152
+ const tenants = await this.connections.sourcePrisma[tenantInfo.sourceTable].findMany({
153
+ select: {
154
+ [tenantInfo.tenantIdColumn]: true,
155
+ [tenantInfo.providerIdColumn]: true,
156
+ }
157
+ });
158
+ this.logger.log(`Found ${tenants.length} potential tenants.`);
159
+ const validTenants = new Map();
160
+ this.logger.log("Ensuring tenant schemas exist (if strategy requires them)...");
161
+ let requiresTenantSchemas = Object.values(tablesConfig).some(t => t.type === 'tenant');
162
+ if (requiresTenantSchemas) {
163
+ this.logger.log('Tenant-specific schemas are required by config.');
164
+ for (const tenant of tenants) {
165
+ const tenantId = tenant[tenantInfo.tenantIdColumn];
166
+ const providerId = (_a = tenant[tenantInfo.providerIdColumn]) !== null && _a !== void 0 ? _a : null;
167
+ if (tenantId && typeof tenantId === 'string' && tenantId !== commonSchema) {
168
+ await this.schemaUtils.createSchema(tenantId);
169
+ validTenants.set(tenantId, providerId);
170
+ this.logger.log(`Ensured schema exists for tenant: ${tenantId}`);
171
+ }
172
+ else {
173
+ this.logger.warn(`Skipping invalid/public tenant ID: ${tenantId}`);
174
+ }
175
+ }
176
+ }
177
+ else {
178
+ this.logger.log('No tables configured with type "tenant". Tenant schema creation skipped.');
179
+ for (const tenant of tenants) {
180
+ const tenantId = tenant[tenantInfo.tenantIdColumn];
181
+ const providerId = (_b = tenant[tenantInfo.providerIdColumn]) !== null && _b !== void 0 ? _b : null;
182
+ if (tenantId && typeof tenantId === 'string') {
183
+ validTenants.set(tenantId, providerId);
184
+ }
185
+ }
186
+ }
187
+ this.logger.log(`Prepared ${validTenants.size} valid tenants for migration.`);
188
+ const tablesToMigratePerTenant = allTablesInOrder.filter(t => { var _a, _b; return ((_a = tablesConfig[t]) === null || _a === void 0 ? void 0 : _a.type) === 'filteredPublic' || ((_b = tablesConfig[t]) === null || _b === void 0 ? void 0 : _b.type) === 'tenant'; });
189
+ this.logger.log(`Migrating filtered/tenant tables: ${tablesToMigratePerTenant.join(", ")}`);
190
+ for (const [tenantId, providerId] of validTenants.entries()) {
191
+ this.logger.log(`Starting migration pass related to tenant: ${tenantId} (Filtering by Provider ID: ${providerId !== null && providerId !== void 0 ? providerId : 'N/A'})`);
192
+ await this.connections.targetPool.query(`SET session_replication_role = 'replica';`);
193
+ for (const tableName of tablesToMigratePerTenant) {
194
+ const config = tablesConfig[tableName];
195
+ if (!config) {
196
+ this.logger.warn(`Skipping migration for table ${tableName} for tenant ${tenantId}: Not found in config.`);
197
+ continue;
198
+ }
199
+ const targetSchemaForTable = config.type === 'tenant' ? tenantId : commonSchema;
200
+ try {
201
+ const entity = {
202
+ name: tableName,
203
+ idField: config.idField,
204
+ filterColumn: config.filterColumn,
205
+ filterVia: config.via
206
+ };
207
+ await this.batchMigrator.migrateEntityDataInBatches(this.connections.targetPrisma, entity, providerId, targetSchemaForTable);
208
+ }
209
+ catch (error) {
210
+ this.logger.error(`Error migrating table ${tableName} into schema ${targetSchemaForTable} (related to tenant ${tenantId}): ${error.message}`);
211
+ }
212
+ }
213
+ await this.connections.targetPool.query(`SET session_replication_role = 'origin';`);
214
+ this.logger.log(`Finished migration pass related to tenant: ${tenantId}`);
215
+ }
216
+ this.logger.log("Data migration process completed.");
217
+ }
218
+ async verifyMigration(tenantIds) {
219
+ this.logger.log("Verifying migrated data...");
220
+ try {
221
+ const publicResult = await this.connections.targetPool.query(`SELECT tablename, n_live_tup FROM pg_stat_user_tables WHERE schemaname = $1`, [this.migrationConfig.commonSchema]);
222
+ this.logger.log(`Verification for schema '${this.migrationConfig.commonSchema}':`);
223
+ publicResult.rows.forEach(row => this.logger.log(` Table: ${row.tablename}, Rows: ${row.n_live_tup}`));
224
+ }
225
+ catch (err) {
226
+ this.logger.error(`Error verifying public schema: ${err.message}`);
227
+ }
228
+ let requiresTenantSchemas = Object.values(this.migrationConfig.tables).some(t => t.type === 'tenant');
229
+ if (requiresTenantSchemas) {
230
+ for (const tenantId of tenantIds) {
231
+ try {
232
+ const tenantResult = await this.connections.targetPool.query(`SELECT tablename, n_live_tup FROM pg_stat_user_tables WHERE schemaname = $1`, [tenantId]);
233
+ this.logger.log(`Verification for tenant schema '${tenantId}':`);
234
+ if (tenantResult.rows.length === 0) {
235
+ this.logger.warn(` Schema ${tenantId} has no tables (or pg_stat_user_tables is empty).`);
236
+ }
237
+ else {
238
+ tenantResult.rows.forEach(row => this.logger.log(` Table: ${row.tablename}, Rows: ${row.n_live_tup}`));
239
+ }
240
+ }
241
+ catch (err) {
242
+ this.logger.error(`Error verifying tenant schema ${tenantId}: ${err.message}`);
243
+ }
244
+ }
245
+ }
246
+ this.logger.log("Verification finished.");
247
+ }
248
+ }
249
+ exports.DataMigrationTool = DataMigrationTool;
250
+ //# sourceMappingURL=migration-tool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-tool.js","sourceRoot":"","sources":["../../../src/scripts/data-migration/migration-tool.ts"],"names":[],"mappings":";;;AAAA,2CAAwC;AACxC,yBAAyB;AACzB,6BAA6B;AAC7B,iDAA6C;AAC7C,yDAAqD;AAErD,qDAAiD;AACjD,+DAA0D;AAC1D,+DAA2D;AA8B3D,MAAa,iBAAiB;IAa5B,YAA6B,WAAgC;QAAhC,gBAAW,GAAX,WAAW,CAAqB;QAZ5C,WAAM,GAAG,IAAI,eAAM,CAAC,mBAAmB,CAAC,CAAC;QAQlD,gBAAW,GAAmC,EAAE,CAAC;QACjD,sBAAiB,GAAmC,EAAE,CAAC;QAI7D,IAAI,CAAC,WAAW,GAAG,IAAI,0BAAW,CAChC,WAAW,CAAC,UAAU,EACtB,WAAW,CAAC,UAAU,CACvB,CAAC;QACF,IAAI,CAAC,eAAe,GAAG,IAAI,kCAAe,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAC7D,IAAI,CAAC,iBAAiB,GAAG,IAAI,uCAAiB,CAAC,WAAW,CAAC,CAAC;QAC5D,IAAI,CAAC,kBAAkB,GAAG,IAAI,wCAAkB,CAC9C,WAAW,CAAC,UAAU,EACtB,WAAW,CAAC,UAAU,CACvB,CAAC;QACF,IAAI,CAAC,aAAa,GAAG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,qBAAqB,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;QACtG,IAAI,qBAAqB,EAAE,CAAC;YACxB,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;gBAC/B,IAAI,CAAC;oBACD,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,KAAK,CAC5D,6EAA6E,EAC7E,CAAC,QAAQ,CAAC,CACT,CAAC;oBACF,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,mCAAmC,QAAQ,IAAI,CAAC,CAAC;oBACjE,IAAI,YAAY,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;wBACjC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,YAAY,QAAQ,mDAAmD,CAAC,CAAC;oBAC9F,CAAC;yBAAM,CAAC;wBACJ,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,YAAY,GAAG,CAAC,SAAS,WAAW,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;oBAC5G,CAAC;gBACL,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACX,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,iCAAiC,QAAQ,KAAK,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC;gBACnF,CAAC;YACL,CAAC;QACL,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;IAC9C,CAAC;CACJ;AA9TD,8CA8TC"}
@@ -0,0 +1,15 @@
1
+ import { PrismaClient } from "@prisma/client";
2
+ import { MigrationPhase } from "./types";
3
+ export declare class PhaseGenerator {
4
+ private readonly logger;
5
+ private readonly prisma;
6
+ private readonly schemaPath;
7
+ constructor(prisma: PrismaClient);
8
+ generatePhases(): Promise<MigrationPhase[]>;
9
+ private runPrismaGenerate;
10
+ private extractRelations;
11
+ private buildDependencyGraph;
12
+ private createOrderedPhases;
13
+ private getPhaseDescription;
14
+ private getDefaultPhases;
15
+ }
@@ -0,0 +1,187 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PhaseGenerator = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const fs = require("fs");
6
+ const path = require("path");
7
+ const child_process_1 = require("child_process");
8
+ class PhaseGenerator {
9
+ constructor(prisma) {
10
+ this.logger = new common_1.Logger("PhaseGenerator");
11
+ this.prisma = prisma;
12
+ this.schemaPath = path.resolve(process.cwd(), "prisma/schema.prisma");
13
+ }
14
+ async generatePhases() {
15
+ try {
16
+ this.logger.log("Actualizando cliente Prisma...");
17
+ this.runPrismaGenerate();
18
+ this.logger.log("Analizando esquema de Prisma...");
19
+ const relations = await this.extractRelations();
20
+ const dependencyGraph = this.buildDependencyGraph(relations);
21
+ const orderedPhases = this.createOrderedPhases(dependencyGraph);
22
+ this.logger.log(`Generadas ${orderedPhases.length} fases de migración`);
23
+ return orderedPhases;
24
+ }
25
+ catch (error) {
26
+ this.logger.error(`Error generando fases: ${error.message}`);
27
+ return this.getDefaultPhases();
28
+ }
29
+ }
30
+ runPrismaGenerate() {
31
+ try {
32
+ (0, child_process_1.execSync)("npx prisma generate", { stdio: "inherit" });
33
+ }
34
+ catch (error) {
35
+ this.logger.warn("Error ejecutando prisma generate, usando cliente existente");
36
+ }
37
+ }
38
+ async extractRelations() {
39
+ const relations = new Map();
40
+ try {
41
+ const schemaContent = fs.readFileSync(this.schemaPath, "utf8");
42
+ const modelRegex = /model\s+(\w+)\s+{([^}]*)}/g;
43
+ const relationRegex = /@relation\(fields:\s*\[([^\]]+)\],\s*references:\s*\[([^\]]+)\]/g;
44
+ let modelMatch;
45
+ while ((modelMatch = modelRegex.exec(schemaContent)) !== null) {
46
+ const modelName = modelMatch[1].toLowerCase();
47
+ const modelBody = modelMatch[2];
48
+ if (!relations.has(modelName)) {
49
+ relations.set(modelName, new Set());
50
+ }
51
+ let relationMatch;
52
+ while ((relationMatch = relationRegex.exec(modelBody)) !== null) {
53
+ const referencedModelRegex = /(\w+)\s+(\w+)(\?)?\s+@relation/;
54
+ const lines = modelBody.split("\n");
55
+ for (const line of lines) {
56
+ if (line.includes("@relation") && line.includes(relationMatch[0])) {
57
+ const typeMatch = referencedModelRegex.exec(line);
58
+ if (typeMatch) {
59
+ const referencedModel = typeMatch[1].toLowerCase();
60
+ relations.get(modelName).add(referencedModel);
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }
66
+ return relations;
67
+ }
68
+ catch (error) {
69
+ this.logger.error(`Error extrayendo relaciones: ${error.message}`);
70
+ return new Map();
71
+ }
72
+ }
73
+ buildDependencyGraph(relations) {
74
+ const graph = new Map();
75
+ for (const [model, _] of relations) {
76
+ if (!graph.has(model)) {
77
+ graph.set(model, new Set());
78
+ }
79
+ }
80
+ for (const [model, dependencies] of relations) {
81
+ for (const dependency of dependencies) {
82
+ if (!graph.has(dependency)) {
83
+ graph.set(dependency, new Set());
84
+ }
85
+ graph.get(dependency).add(model);
86
+ }
87
+ }
88
+ return graph;
89
+ }
90
+ createOrderedPhases(graph) {
91
+ const phases = [];
92
+ const visited = new Set();
93
+ const findBaseTables = () => {
94
+ const baseTables = [];
95
+ for (const [table, dependencies] of graph) {
96
+ if (!visited.has(table) && dependencies.size === 0) {
97
+ baseTables.push(table);
98
+ }
99
+ }
100
+ return baseTables;
101
+ };
102
+ let phaseNumber = 1;
103
+ let currentPhaseTables = findBaseTables();
104
+ while (currentPhaseTables.length > 0) {
105
+ for (const table of currentPhaseTables) {
106
+ visited.add(table);
107
+ }
108
+ phases.push({
109
+ name: `Phase ${phaseNumber}: ${this.getPhaseDescription(phaseNumber, currentPhaseTables)}`,
110
+ tables: currentPhaseTables,
111
+ required: phaseNumber <= 3
112
+ });
113
+ for (const [table, dependencies] of graph) {
114
+ for (const dependency of [...dependencies]) {
115
+ if (visited.has(dependency)) {
116
+ dependencies.delete(dependency);
117
+ }
118
+ }
119
+ }
120
+ currentPhaseTables = findBaseTables();
121
+ phaseNumber++;
122
+ }
123
+ const remainingTables = [...graph.keys()].filter(table => !visited.has(table));
124
+ if (remainingTables.length > 0) {
125
+ this.logger.warn(`Tablas con dependencias circulares: ${remainingTables.join(", ")}`);
126
+ phases.push({
127
+ name: `Phase ${phaseNumber}: Circular Dependencies`,
128
+ tables: remainingTables,
129
+ required: false
130
+ });
131
+ }
132
+ return phases;
133
+ }
134
+ getPhaseDescription(phaseNumber, tables) {
135
+ if (phaseNumber === 1)
136
+ return "Base Tables";
137
+ if (tables.some(t => t.includes("transaction")))
138
+ return "Transactions";
139
+ if (tables.some(t => t.includes("user")))
140
+ return "User Data";
141
+ if (tables.some(t => t.includes("balance") || t.includes("bank")))
142
+ return "Financial";
143
+ return "Supporting Data";
144
+ }
145
+ getDefaultPhases() {
146
+ return [
147
+ {
148
+ name: "Base Tables",
149
+ tables: ["users", "providers", "companies", "countries"],
150
+ required: true,
151
+ },
152
+ {
153
+ name: "Core Financial",
154
+ tables: ["balances", "banks"],
155
+ required: true,
156
+ },
157
+ {
158
+ name: "Transactions",
159
+ tables: ["transactions", "global_user_transactions"],
160
+ required: true,
161
+ },
162
+ {
163
+ name: "Transaction Related",
164
+ tables: ["transaction_updates", "daily_logs", "invoices"],
165
+ required: true,
166
+ },
167
+ {
168
+ name: "Customer Data",
169
+ tables: ["customers", "charges", "credit_requests"],
170
+ required: true,
171
+ },
172
+ {
173
+ name: "Supporting Data",
174
+ tables: [
175
+ "notifications",
176
+ "api_keys",
177
+ "api_request_logs",
178
+ "pending_references",
179
+ "toku",
180
+ ],
181
+ required: false,
182
+ },
183
+ ];
184
+ }
185
+ }
186
+ exports.PhaseGenerator = PhaseGenerator;
187
+ //# sourceMappingURL=phase-generator.js.map