@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,427 @@
1
+ import * as pg from 'pg';
2
+ import * as dotenv from 'dotenv';
3
+ import { Logger } from '@nestjs/common';
4
+ import * as fs from 'fs';
5
+ import * as path from 'path';
6
+
7
+ dotenv.config();
8
+
9
+ export class PostMigrationValidator {
10
+ private readonly logger = new Logger('PostMigrationValidator');
11
+ private readonly sourcePool: pg.Pool;
12
+ private readonly targetPool: pg.Pool;
13
+ private readonly reportPath: string;
14
+ private issues: any[] = [];
15
+
16
+ constructor(
17
+ private readonly sourceUrl: string = process.env.SOURCE_DATABASE_URL,
18
+ private readonly targetUrl: string = process.env.DATABASE_URL
19
+ ) {
20
+ this.sourcePool = new pg.Pool({
21
+ connectionString: this.sourceUrl,
22
+ });
23
+
24
+ this.targetPool = new pg.Pool({
25
+ connectionString: this.targetUrl,
26
+ });
27
+
28
+ // Crear directorio para reportes si no existe
29
+ const reportsDir = path.join(process.cwd(), 'migration-logs');
30
+ if (!fs.existsSync(reportsDir)) {
31
+ fs.mkdirSync(reportsDir, { recursive: true });
32
+ }
33
+
34
+ // Archivo para guardar el reporte
35
+ const timestamp = new Date().toISOString().replace(/:/g, '-').replace(/\..+/, '');
36
+ this.reportPath = path.join(reportsDir, `post-migration-report-${timestamp}.json`);
37
+ }
38
+
39
+ async validate() {
40
+ try {
41
+ this.logger.log('Starting post-migration validation');
42
+
43
+ // Obtener todos los API keys para determinar los schemas de tenant
44
+ const apiKeysResult = await this.sourcePool.query(`
45
+ SELECT api_key, provider_id
46
+ FROM api_keys
47
+ `);
48
+
49
+ this.logger.log(`Found ${apiKeysResult.rows.length} API keys to validate`);
50
+
51
+ // Para cada API key (tenant), validar los datos migrados
52
+ for (const apiKey of apiKeysResult.rows) {
53
+ const tenantId = apiKey.api_key;
54
+ const providerId = apiKey.provider_id;
55
+
56
+ await this.validateTenantData(tenantId, providerId);
57
+ }
58
+
59
+ // Guardar el reporte
60
+ this.saveReport();
61
+
62
+ // Mostrar resumen
63
+ this.logger.log(`Validation completed with ${this.issues.length} issues found`);
64
+ if (this.issues.length > 0) {
65
+ this.logger.log(`Check the full report at: ${this.reportPath}`);
66
+
67
+ // Mostrar los primeros 5 problemas como ejemplo
68
+ this.logger.log('Sample issues:');
69
+ for (let i = 0; i < Math.min(5, this.issues.length); i++) {
70
+ const issue = this.issues[i];
71
+ this.logger.log(`- ${issue.type}: ${issue.message}`);
72
+ }
73
+ } else {
74
+ this.logger.log('No issues found. Migration was successful.');
75
+ }
76
+
77
+ return {
78
+ success: this.issues.length === 0,
79
+ issueCount: this.issues.length,
80
+ reportPath: this.reportPath
81
+ };
82
+ } catch (error) {
83
+ this.logger.error(`Error during validation: ${error.message}`, error.stack);
84
+ this.issues.push({
85
+ type: 'VALIDATION_ERROR',
86
+ message: `Validation process failed: ${error.message}`,
87
+ details: error.stack
88
+ });
89
+ this.saveReport();
90
+ return {
91
+ success: false,
92
+ issueCount: this.issues.length,
93
+ reportPath: this.reportPath
94
+ };
95
+ } finally {
96
+ await this.cleanup();
97
+ }
98
+ }
99
+
100
+ private async validateTenantData(tenantId: string, providerId: number) {
101
+ this.logger.log(`Validating data for tenant: ${tenantId} (Provider ID: ${providerId})`);
102
+
103
+ try {
104
+ // Verificar si el schema existe en la base de datos de destino
105
+ const schemaExistsResult = await this.targetPool.query(`
106
+ SELECT 1
107
+ FROM information_schema.schemata
108
+ WHERE schema_name = $1
109
+ LIMIT 1
110
+ `, [tenantId]);
111
+
112
+ if (schemaExistsResult.rows.length === 0) {
113
+ this.logger.warn(`Schema ${tenantId} does not exist in target database`);
114
+ this.issues.push({
115
+ type: 'MISSING_SCHEMA',
116
+ tenantId,
117
+ providerId,
118
+ message: `Schema ${tenantId} does not exist in target database. Migration failed for this tenant.`
119
+ });
120
+ return;
121
+ }
122
+
123
+ // Obtener todas las tablas de la base de datos de origen
124
+ const tablesResult = await this.sourcePool.query(`
125
+ SELECT table_name
126
+ FROM information_schema.tables
127
+ WHERE table_schema = 'public'
128
+ AND table_type = 'BASE TABLE'
129
+ AND table_name NOT IN ('_prisma_migrations', 'api_keys')
130
+ `);
131
+
132
+ // Para cada tabla, comparar el número de registros
133
+ for (const tableRow of tablesResult.rows) {
134
+ const tableName = tableRow.table_name;
135
+ await this.validateTableData(tenantId, tableName, providerId);
136
+ }
137
+ } catch (error) {
138
+ this.logger.error(`Error validating tenant ${tenantId}: ${error.message}`);
139
+ this.issues.push({
140
+ type: 'TENANT_VALIDATION_ERROR',
141
+ tenantId,
142
+ providerId,
143
+ message: `Error validating tenant ${tenantId}: ${error.message}`
144
+ });
145
+ }
146
+ }
147
+
148
+ private async validateTableData(tenantId: string, tableName: string, providerId: number) {
149
+ try {
150
+ // Contar registros en la base de datos de origen
151
+ let sourceCountQuery = `SELECT COUNT(*) as count FROM ${tableName}`;
152
+
153
+ // Añadir filtro por provider_id si la tabla tiene esa columna
154
+ const hasProviderIdResult = await this.sourcePool.query(`
155
+ SELECT 1
156
+ FROM information_schema.columns
157
+ WHERE table_schema = 'public'
158
+ AND table_name = $1
159
+ AND column_name = 'provider_id'
160
+ LIMIT 1
161
+ `, [tableName]);
162
+
163
+ if (hasProviderIdResult.rows.length > 0) {
164
+ sourceCountQuery += ` WHERE provider_id = ${providerId}`;
165
+ }
166
+
167
+ const sourceCountResult = await this.sourcePool.query(sourceCountQuery);
168
+ const sourceCount = parseInt(sourceCountResult.rows[0].count);
169
+
170
+ // Contar registros en la base de datos de destino
171
+ const targetCountQuery = `SELECT COUNT(*) as count FROM "${tenantId}"."${tableName}"`;
172
+ const targetCountResult = await this.targetPool.query(targetCountQuery);
173
+ const targetCount = parseInt(targetCountResult.rows[0].count);
174
+
175
+ // Calcular el porcentaje de migración
176
+ const migrationPercentage = sourceCount > 0 ? (targetCount / sourceCount) * 100 : 100;
177
+
178
+ this.logger.log(`Table ${tableName} for tenant ${tenantId}: ${targetCount}/${sourceCount} records migrated (${migrationPercentage.toFixed(2)}%)`);
179
+
180
+ // Si hay una discrepancia significativa, registrarla como un problema
181
+ if (migrationPercentage < 95) {
182
+ this.issues.push({
183
+ type: 'DATA_MISMATCH',
184
+ tenantId,
185
+ tableName,
186
+ sourceCount,
187
+ targetCount,
188
+ migrationPercentage: parseFloat(migrationPercentage.toFixed(2)),
189
+ message: `Table ${tableName} for tenant ${tenantId}: Only ${migrationPercentage.toFixed(2)}% of records were migrated (${targetCount}/${sourceCount})`
190
+ });
191
+ }
192
+
193
+ // Si hay más registros en el destino que en el origen, también es un problema
194
+ if (targetCount > sourceCount) {
195
+ this.issues.push({
196
+ type: 'EXCESS_DATA',
197
+ tenantId,
198
+ tableName,
199
+ sourceCount,
200
+ targetCount,
201
+ message: `Table ${tableName} for tenant ${tenantId}: Target has more records (${targetCount}) than source (${sourceCount})`
202
+ });
203
+ }
204
+
205
+ // Validar algunos registros aleatorios para verificar la integridad de los datos
206
+ if (sourceCount > 0 && targetCount > 0) {
207
+ await this.validateRandomRecords(tenantId, tableName, providerId);
208
+ }
209
+ } catch (error) {
210
+ this.logger.error(`Error validating table ${tableName} for tenant ${tenantId}: ${error.message}`);
211
+ this.issues.push({
212
+ type: 'TABLE_VALIDATION_ERROR',
213
+ tenantId,
214
+ tableName,
215
+ message: `Error validating table ${tableName} for tenant ${tenantId}: ${error.message}`
216
+ });
217
+ }
218
+ }
219
+
220
+ private async validateRandomRecords(tenantId: string, tableName: string, providerId: number) {
221
+ try {
222
+ // Obtener la clave primaria de la tabla
223
+ const primaryKeyResult = await this.sourcePool.query(`
224
+ SELECT kcu.column_name
225
+ FROM information_schema.table_constraints tc
226
+ JOIN information_schema.key_column_usage kcu
227
+ ON tc.constraint_name = kcu.constraint_name
228
+ AND tc.table_schema = kcu.table_schema
229
+ WHERE tc.constraint_type = 'PRIMARY KEY'
230
+ AND tc.table_schema = 'public'
231
+ AND tc.table_name = $1
232
+ LIMIT 1
233
+ `, [tableName]);
234
+
235
+ if (primaryKeyResult.rows.length === 0) {
236
+ this.logger.warn(`No primary key found for table ${tableName}`);
237
+ return;
238
+ }
239
+
240
+ const primaryKeyColumn = primaryKeyResult.rows[0].column_name;
241
+
242
+ // Obtener hasta 5 registros aleatorios de la base de datos de origen
243
+ let randomRecordsQuery = `
244
+ SELECT *
245
+ FROM ${tableName}
246
+ `;
247
+
248
+ // Añadir filtro por provider_id si la tabla tiene esa columna
249
+ const hasProviderIdResult = await this.sourcePool.query(`
250
+ SELECT 1
251
+ FROM information_schema.columns
252
+ WHERE table_schema = 'public'
253
+ AND table_name = $1
254
+ AND column_name = 'provider_id'
255
+ LIMIT 1
256
+ `, [tableName]);
257
+
258
+ if (hasProviderIdResult.rows.length > 0) {
259
+ randomRecordsQuery += ` WHERE provider_id = ${providerId}`;
260
+ }
261
+
262
+ randomRecordsQuery += `
263
+ ORDER BY RANDOM()
264
+ LIMIT 5
265
+ `;
266
+
267
+ const randomRecordsResult = await this.sourcePool.query(randomRecordsQuery);
268
+
269
+ // Para cada registro aleatorio, verificar si existe en la base de datos de destino
270
+ for (const sourceRecord of randomRecordsResult.rows) {
271
+ const primaryKeyValue = sourceRecord[primaryKeyColumn];
272
+
273
+ const targetRecordResult = await this.targetPool.query(`
274
+ SELECT *
275
+ FROM "${tenantId}"."${tableName}"
276
+ WHERE "${primaryKeyColumn}" = $1
277
+ LIMIT 1
278
+ `, [primaryKeyValue]);
279
+
280
+ if (targetRecordResult.rows.length === 0) {
281
+ this.issues.push({
282
+ type: 'MISSING_RECORD',
283
+ tenantId,
284
+ tableName,
285
+ recordId: primaryKeyValue,
286
+ message: `Record with ID ${primaryKeyValue} in table ${tableName} for tenant ${tenantId} was not migrated`
287
+ });
288
+ continue;
289
+ }
290
+
291
+ const targetRecord = targetRecordResult.rows[0];
292
+
293
+ // Comparar los valores de las columnas
294
+ for (const columnName in sourceRecord) {
295
+ // Ignorar columnas específicas de la base de datos de origen
296
+ if (columnName === 'provider_id') {
297
+ continue;
298
+ }
299
+
300
+ // Verificar si la columna existe en el registro de destino
301
+ if (!(columnName in targetRecord)) {
302
+ this.issues.push({
303
+ type: 'MISSING_COLUMN',
304
+ tenantId,
305
+ tableName,
306
+ recordId: primaryKeyValue,
307
+ columnName,
308
+ message: `Column ${columnName} is missing in record with ID ${primaryKeyValue} in table ${tableName} for tenant ${tenantId}`
309
+ });
310
+ continue;
311
+ }
312
+
313
+ // Comparar los valores (con manejo especial para tipos de datos específicos)
314
+ const sourceValue = sourceRecord[columnName];
315
+ const targetValue = targetRecord[columnName];
316
+
317
+ if (this.areValuesDifferent(sourceValue, targetValue)) {
318
+ this.issues.push({
319
+ type: 'VALUE_MISMATCH',
320
+ tenantId,
321
+ tableName,
322
+ recordId: primaryKeyValue,
323
+ columnName,
324
+ sourceValue,
325
+ targetValue,
326
+ message: `Value mismatch for column ${columnName} in record with ID ${primaryKeyValue} in table ${tableName} for tenant ${tenantId}: ${sourceValue} (source) vs ${targetValue} (target)`
327
+ });
328
+ }
329
+ }
330
+ }
331
+ } catch (error) {
332
+ this.logger.error(`Error validating random records for table ${tableName} in tenant ${tenantId}: ${error.message}`);
333
+ this.issues.push({
334
+ type: 'RECORD_VALIDATION_ERROR',
335
+ tenantId,
336
+ tableName,
337
+ message: `Error validating random records for table ${tableName} in tenant ${tenantId}: ${error.message}`
338
+ });
339
+ }
340
+ }
341
+
342
+ private areValuesDifferent(sourceValue: any, targetValue: any): boolean {
343
+ // Si ambos son null o undefined, son iguales
344
+ if (sourceValue == null && targetValue == null) {
345
+ return false;
346
+ }
347
+
348
+ // Si uno es null y el otro no, son diferentes
349
+ if (sourceValue == null || targetValue == null) {
350
+ return true;
351
+ }
352
+
353
+ // Para fechas, comparar como strings ISO
354
+ if (sourceValue instanceof Date && targetValue instanceof Date) {
355
+ return sourceValue.toISOString() !== targetValue.toISOString();
356
+ }
357
+
358
+ // Para números, comparar con tolerancia para punto flotante
359
+ if (typeof sourceValue === 'number' && typeof targetValue === 'number') {
360
+ const epsilon = 0.0001;
361
+ return Math.abs(sourceValue - targetValue) > epsilon;
362
+ }
363
+
364
+ // Para strings, comparar directamente
365
+ if (typeof sourceValue === 'string' && typeof targetValue === 'string') {
366
+ return sourceValue !== targetValue;
367
+ }
368
+
369
+ // Para booleanos, comparar directamente
370
+ if (typeof sourceValue === 'boolean' && typeof targetValue === 'boolean') {
371
+ return sourceValue !== targetValue;
372
+ }
373
+
374
+ // Para otros tipos, convertir a string y comparar
375
+ return String(sourceValue) !== String(targetValue);
376
+ }
377
+
378
+ private saveReport() {
379
+ try {
380
+ const report = {
381
+ timestamp: new Date().toISOString(),
382
+ sourceDatabase: this.sourceUrl,
383
+ targetDatabase: this.targetUrl,
384
+ issueCount: this.issues.length,
385
+ issues: this.issues
386
+ };
387
+
388
+ fs.writeFileSync(
389
+ this.reportPath,
390
+ JSON.stringify(report, null, 2),
391
+ 'utf8'
392
+ );
393
+ } catch (error) {
394
+ this.logger.error(`Error saving validation report: ${error.message}`);
395
+ }
396
+ }
397
+
398
+ private async cleanup() {
399
+ this.logger.log('Cleaning up database connections');
400
+ await this.sourcePool.end();
401
+ await this.targetPool.end();
402
+ }
403
+ }
404
+
405
+ // Script para ejecutar desde línea de comandos
406
+ if (require.main === module) {
407
+ const run = async () => {
408
+ try {
409
+ const validator = new PostMigrationValidator();
410
+ const result = await validator.validate();
411
+
412
+ if (result.success) {
413
+ console.log('Post-migration validation successful! No issues found.');
414
+ process.exit(0);
415
+ } else {
416
+ console.log(`Post-migration validation completed with ${result.issueCount} issues found.`);
417
+ console.log(`Check the full report at: ${result.reportPath}`);
418
+ process.exit(1);
419
+ }
420
+ } catch (error) {
421
+ console.error('Error:', error.message);
422
+ process.exit(1);
423
+ }
424
+ };
425
+
426
+ run();
427
+ }