@javalabs/prisma-client 1.0.26 → 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 (170) 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 -607
  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
  51. package/dist/index.d.ts +0 -7
  52. package/dist/index.js +0 -34
  53. package/dist/index.js.map +0 -1
  54. package/dist/prisma-factory.service.d.ts +0 -9
  55. package/dist/prisma-factory.service.js +0 -47
  56. package/dist/prisma-factory.service.js.map +0 -1
  57. package/dist/prisma.module.d.ts +0 -2
  58. package/dist/prisma.module.js +0 -23
  59. package/dist/prisma.module.js.map +0 -1
  60. package/dist/prisma.service.d.ts +0 -6
  61. package/dist/prisma.service.js +0 -27
  62. package/dist/prisma.service.js.map +0 -1
  63. package/dist/scripts/add-uuid-to-table.d.ts +0 -8
  64. package/dist/scripts/add-uuid-to-table.js +0 -98
  65. package/dist/scripts/add-uuid-to-table.js.map +0 -1
  66. package/dist/scripts/create-tenant-schemas.d.ts +0 -1
  67. package/dist/scripts/create-tenant-schemas.js +0 -117
  68. package/dist/scripts/create-tenant-schemas.js.map +0 -1
  69. package/dist/scripts/data-migration/batch-migrator.d.ts +0 -20
  70. package/dist/scripts/data-migration/batch-migrator.js +0 -134
  71. package/dist/scripts/data-migration/batch-migrator.js.map +0 -1
  72. package/dist/scripts/data-migration/data-transformer.d.ts +0 -26
  73. package/dist/scripts/data-migration/data-transformer.js +0 -278
  74. package/dist/scripts/data-migration/data-transformer.js.map +0 -1
  75. package/dist/scripts/data-migration/db-connector.d.ts +0 -12
  76. package/dist/scripts/data-migration/db-connector.js +0 -94
  77. package/dist/scripts/data-migration/db-connector.js.map +0 -1
  78. package/dist/scripts/data-migration/dependency-resolver.d.ts +0 -18
  79. package/dist/scripts/data-migration/dependency-resolver.js +0 -132
  80. package/dist/scripts/data-migration/dependency-resolver.js.map +0 -1
  81. package/dist/scripts/data-migration/entity-discovery.d.ts +0 -11
  82. package/dist/scripts/data-migration/entity-discovery.js +0 -152
  83. package/dist/scripts/data-migration/entity-discovery.js.map +0 -1
  84. package/dist/scripts/data-migration/foreign-key-manager.d.ts +0 -18
  85. package/dist/scripts/data-migration/foreign-key-manager.js +0 -160
  86. package/dist/scripts/data-migration/foreign-key-manager.js.map +0 -1
  87. package/dist/scripts/data-migration/migration-tool.d.ts +0 -48
  88. package/dist/scripts/data-migration/migration-tool.js +0 -290
  89. package/dist/scripts/data-migration/migration-tool.js.map +0 -1
  90. package/dist/scripts/data-migration/schema-utils.d.ts +0 -18
  91. package/dist/scripts/data-migration/schema-utils.js +0 -207
  92. package/dist/scripts/data-migration/schema-utils.js.map +0 -1
  93. package/dist/scripts/data-migration/tenant-migrator.d.ts +0 -15
  94. package/dist/scripts/data-migration/tenant-migrator.js +0 -117
  95. package/dist/scripts/data-migration/tenant-migrator.js.map +0 -1
  96. package/dist/scripts/data-migration/typecast-manager.d.ts +0 -9
  97. package/dist/scripts/data-migration/typecast-manager.js +0 -179
  98. package/dist/scripts/data-migration/typecast-manager.js.map +0 -1
  99. package/dist/scripts/data-migration/types.d.ts +0 -100
  100. package/dist/scripts/data-migration/types.js +0 -3
  101. package/dist/scripts/data-migration/types.js.map +0 -1
  102. package/dist/scripts/database-initializer.d.ts +0 -5
  103. package/dist/scripts/database-initializer.js +0 -45
  104. package/dist/scripts/database-initializer.js.map +0 -1
  105. package/dist/scripts/drop-database.d.ts +0 -10
  106. package/dist/scripts/drop-database.js +0 -81
  107. package/dist/scripts/drop-database.js.map +0 -1
  108. package/dist/scripts/encrypt-user-passwords.d.ts +0 -1
  109. package/dist/scripts/encrypt-user-passwords.js +0 -33
  110. package/dist/scripts/encrypt-user-passwords.js.map +0 -1
  111. package/dist/scripts/error-handler.d.ts +0 -12
  112. package/dist/scripts/error-handler.js +0 -82
  113. package/dist/scripts/error-handler.js.map +0 -1
  114. package/dist/scripts/fix-data-types.d.ts +0 -10
  115. package/dist/scripts/fix-data-types.js +0 -185
  116. package/dist/scripts/fix-data-types.js.map +0 -1
  117. package/dist/scripts/fix-enum-values.d.ts +0 -17
  118. package/dist/scripts/fix-enum-values.js +0 -234
  119. package/dist/scripts/fix-enum-values.js.map +0 -1
  120. package/dist/scripts/fix-schema-discrepancies.d.ts +0 -21
  121. package/dist/scripts/fix-schema-discrepancies.js +0 -240
  122. package/dist/scripts/fix-schema-discrepancies.js.map +0 -1
  123. package/dist/scripts/fix-table-indexes.d.ts +0 -26
  124. package/dist/scripts/fix-table-indexes.js +0 -460
  125. package/dist/scripts/fix-table-indexes.js.map +0 -1
  126. package/dist/scripts/migrate-schema-structure.d.ts +0 -1
  127. package/dist/scripts/migrate-schema-structure.js +0 -76
  128. package/dist/scripts/migrate-schema-structure.js.map +0 -1
  129. package/dist/scripts/migrate-uuid.d.ts +0 -2
  130. package/dist/scripts/migrate-uuid.js +0 -57
  131. package/dist/scripts/migrate-uuid.js.map +0 -1
  132. package/dist/scripts/post-migration-validator.d.ts +0 -34
  133. package/dist/scripts/post-migration-validator.js +0 -363
  134. package/dist/scripts/post-migration-validator.js.map +0 -1
  135. package/dist/scripts/pre-migration-validator.d.ts +0 -25
  136. package/dist/scripts/pre-migration-validator.js +0 -491
  137. package/dist/scripts/pre-migration-validator.js.map +0 -1
  138. package/dist/scripts/reset-database.d.ts +0 -17
  139. package/dist/scripts/reset-database.js +0 -202
  140. package/dist/scripts/reset-database.js.map +0 -1
  141. package/dist/scripts/retry-failed-migrations.d.ts +0 -14
  142. package/dist/scripts/retry-failed-migrations.js +0 -301
  143. package/dist/scripts/retry-failed-migrations.js.map +0 -1
  144. package/dist/scripts/run-migration.d.ts +0 -1
  145. package/dist/scripts/run-migration.js +0 -512
  146. package/dist/scripts/run-migration.js.map +0 -1
  147. package/dist/scripts/schema-sync.d.ts +0 -1
  148. package/dist/scripts/schema-sync.js +0 -85
  149. package/dist/scripts/schema-sync.js.map +0 -1
  150. package/dist/scripts/sequence-sync-cli.d.ts +0 -2
  151. package/dist/scripts/sequence-sync-cli.js +0 -287
  152. package/dist/scripts/sequence-sync-cli.js.map +0 -1
  153. package/dist/scripts/sequence-synchronizer.d.ts +0 -8
  154. package/dist/scripts/sequence-synchronizer.js +0 -88
  155. package/dist/scripts/sequence-synchronizer.js.map +0 -1
  156. package/dist/scripts/sync-enum-types.d.ts +0 -13
  157. package/dist/scripts/sync-enum-types.js +0 -139
  158. package/dist/scripts/sync-enum-types.js.map +0 -1
  159. package/dist/scripts/sync-enum-values.d.ts +0 -20
  160. package/dist/scripts/sync-enum-values.js +0 -336
  161. package/dist/scripts/sync-enum-values.js.map +0 -1
  162. package/dist/scripts/truncate-database.d.ts +0 -10
  163. package/dist/scripts/truncate-database.js +0 -100
  164. package/dist/scripts/truncate-database.js.map +0 -1
  165. package/dist/scripts/verify-migration-setup.d.ts +0 -11
  166. package/dist/scripts/verify-migration-setup.js +0 -120
  167. package/dist/scripts/verify-migration-setup.js.map +0 -1
  168. package/dist/tsconfig.tsbuildinfo +0 -1
  169. package/prisma/migrations/add_athena_match_fields.sql +0 -18
  170. package/prisma/migrations/add_bank_receipt_number.sql +0 -9
@@ -1,124 +1,124 @@
1
- import * as pg from "pg";
2
- import * as dotenv from "dotenv";
3
- import { Logger } from "@nestjs/common";
4
-
5
- dotenv.config();
6
-
7
- export class DatabaseTruncateTool {
8
- private readonly logger = new Logger("DatabaseTruncateTool");
9
- private readonly pool: pg.Pool;
10
-
11
- constructor(private readonly databaseUrl: string) {
12
- this.pool = new pg.Pool({
13
- connectionString: this.databaseUrl,
14
- });
15
- }
16
-
17
- async truncateDatabase() {
18
- try {
19
- this.logger.log("Starting database truncate process");
20
-
21
- // Obtener todos los schemas excepto los del sistema
22
- const schemas = await this.getSchemas();
23
- this.logger.log(`Found ${schemas.length} schemas to process`);
24
-
25
- // Para cada schema, truncar todas sus tablas
26
- for (const schema of schemas) {
27
- await this.truncateSchema(schema);
28
- }
29
-
30
- this.logger.log("Database has been successfully truncated");
31
- } catch (error) {
32
- this.logger.error(
33
- `Error truncating database: ${error.message}`,
34
- error.stack
35
- );
36
- throw error;
37
- } finally {
38
- await this.cleanup();
39
- }
40
- }
41
-
42
- private async getSchemas(): Promise<string[]> {
43
- const result = await this.pool.query(`
44
- SELECT schema_name
45
- FROM information_schema.schemata
46
- WHERE schema_name NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
47
- AND schema_name NOT LIKE 'pg_%'
48
- `);
49
-
50
- return result.rows.map(row => row.schema_name);
51
- }
52
-
53
- private async truncateSchema(schemaName: string) {
54
- this.logger.log(`Processing schema: ${schemaName}`);
55
-
56
- try {
57
- // Obtener todas las tablas del schema
58
- const tablesResult = await this.pool.query(`
59
- SELECT table_name
60
- FROM information_schema.tables
61
- WHERE table_schema = $1
62
- AND table_type = 'BASE TABLE'
63
- `, [schemaName]);
64
-
65
- const tables = tablesResult.rows.map(row => row.table_name);
66
-
67
- if (tables.length === 0) {
68
- this.logger.log(`No tables found in schema ${schemaName}`);
69
- return;
70
- }
71
-
72
- this.logger.log(`Found ${tables.length} tables in schema ${schemaName}`);
73
-
74
- // Desactivar restricciones de clave foránea temporalmente
75
- await this.pool.query(`SET session_replication_role = 'replica'`);
76
-
77
- // Truncar cada tabla
78
- for (const table of tables) {
79
- try {
80
- await this.pool.query(`TRUNCATE TABLE "${schemaName}"."${table}" CASCADE`);
81
- this.logger.log(`Truncated table ${schemaName}.${table}`);
82
- } catch (tableError) {
83
- this.logger.error(`Error truncating table ${schemaName}.${table}: ${tableError.message}`);
84
- }
85
- }
86
-
87
- // Reactivar restricciones de clave foránea
88
- await this.pool.query(`SET session_replication_role = 'origin'`);
89
-
90
- this.logger.log(`Successfully processed schema: ${schemaName}`);
91
- } catch (error) {
92
- this.logger.error(`Error processing schema ${schemaName}: ${error.message}`);
93
- }
94
- }
95
-
96
- private async cleanup() {
97
- this.logger.log("Cleaning up database connections");
98
- await this.pool.end();
99
- }
100
- }
101
-
102
- // Script para ejecutar desde línea de comandos
103
- if (require.main === module) {
104
- const run = async () => {
105
- try {
106
- // Obtener la URL de la base de datos desde los argumentos o .env
107
- const databaseUrl = process.argv[2] || process.env.DATABASE_URL;
108
-
109
- if (!databaseUrl) {
110
- console.error("Error: No database URL provided. Please provide a database URL as an argument or set DATABASE_URL environment variable.");
111
- process.exit(1);
112
- }
113
-
114
- const truncateTool = new DatabaseTruncateTool(databaseUrl);
115
- await truncateTool.truncateDatabase();
116
- process.exit(0);
117
- } catch (error) {
118
- console.error("Error:", error.message);
119
- process.exit(1);
120
- }
121
- };
122
-
123
- run();
1
+ import * as pg from "pg";
2
+ import * as dotenv from "dotenv";
3
+ import { Logger } from "@nestjs/common";
4
+
5
+ dotenv.config();
6
+
7
+ export class DatabaseTruncateTool {
8
+ private readonly logger = new Logger("DatabaseTruncateTool");
9
+ private readonly pool: pg.Pool;
10
+
11
+ constructor(private readonly databaseUrl: string) {
12
+ this.pool = new pg.Pool({
13
+ connectionString: this.databaseUrl,
14
+ });
15
+ }
16
+
17
+ async truncateDatabase() {
18
+ try {
19
+ this.logger.log("Starting database truncate process");
20
+
21
+ // Obtener todos los schemas excepto los del sistema
22
+ const schemas = await this.getSchemas();
23
+ this.logger.log(`Found ${schemas.length} schemas to process`);
24
+
25
+ // Para cada schema, truncar todas sus tablas
26
+ for (const schema of schemas) {
27
+ await this.truncateSchema(schema);
28
+ }
29
+
30
+ this.logger.log("Database has been successfully truncated");
31
+ } catch (error) {
32
+ this.logger.error(
33
+ `Error truncating database: ${error.message}`,
34
+ error.stack
35
+ );
36
+ throw error;
37
+ } finally {
38
+ await this.cleanup();
39
+ }
40
+ }
41
+
42
+ private async getSchemas(): Promise<string[]> {
43
+ const result = await this.pool.query(`
44
+ SELECT schema_name
45
+ FROM information_schema.schemata
46
+ WHERE schema_name NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
47
+ AND schema_name NOT LIKE 'pg_%'
48
+ `);
49
+
50
+ return result.rows.map(row => row.schema_name);
51
+ }
52
+
53
+ private async truncateSchema(schemaName: string) {
54
+ this.logger.log(`Processing schema: ${schemaName}`);
55
+
56
+ try {
57
+ // Obtener todas las tablas del schema
58
+ const tablesResult = await this.pool.query(`
59
+ SELECT table_name
60
+ FROM information_schema.tables
61
+ WHERE table_schema = $1
62
+ AND table_type = 'BASE TABLE'
63
+ `, [schemaName]);
64
+
65
+ const tables = tablesResult.rows.map(row => row.table_name);
66
+
67
+ if (tables.length === 0) {
68
+ this.logger.log(`No tables found in schema ${schemaName}`);
69
+ return;
70
+ }
71
+
72
+ this.logger.log(`Found ${tables.length} tables in schema ${schemaName}`);
73
+
74
+ // Desactivar restricciones de clave foránea temporalmente
75
+ await this.pool.query(`SET session_replication_role = 'replica'`);
76
+
77
+ // Truncar cada tabla
78
+ for (const table of tables) {
79
+ try {
80
+ await this.pool.query(`TRUNCATE TABLE "${schemaName}"."${table}" CASCADE`);
81
+ this.logger.log(`Truncated table ${schemaName}.${table}`);
82
+ } catch (tableError) {
83
+ this.logger.error(`Error truncating table ${schemaName}.${table}: ${tableError.message}`);
84
+ }
85
+ }
86
+
87
+ // Reactivar restricciones de clave foránea
88
+ await this.pool.query(`SET session_replication_role = 'origin'`);
89
+
90
+ this.logger.log(`Successfully processed schema: ${schemaName}`);
91
+ } catch (error) {
92
+ this.logger.error(`Error processing schema ${schemaName}: ${error.message}`);
93
+ }
94
+ }
95
+
96
+ private async cleanup() {
97
+ this.logger.log("Cleaning up database connections");
98
+ await this.pool.end();
99
+ }
100
+ }
101
+
102
+ // Script para ejecutar desde línea de comandos
103
+ if (require.main === module) {
104
+ const run = async () => {
105
+ try {
106
+ // Obtener la URL de la base de datos desde los argumentos o .env
107
+ const databaseUrl = process.argv[2] || process.env.DATABASE_URL;
108
+
109
+ if (!databaseUrl) {
110
+ console.error("Error: No database URL provided. Please provide a database URL as an argument or set DATABASE_URL environment variable.");
111
+ process.exit(1);
112
+ }
113
+
114
+ const truncateTool = new DatabaseTruncateTool(databaseUrl);
115
+ await truncateTool.truncateDatabase();
116
+ process.exit(0);
117
+ } catch (error) {
118
+ console.error("Error:", error.message);
119
+ process.exit(1);
120
+ }
121
+ };
122
+
123
+ run();
124
124
  }
@@ -1,136 +1,136 @@
1
- import * as dotenv from 'dotenv';
2
- import * as pg from 'pg';
3
- import { Logger } from '@nestjs/common';
4
-
5
- dotenv.config();
6
-
7
- export class MigrationSetupVerifier {
8
- private readonly logger = new Logger('MigrationSetupVerifier');
9
- private readonly sourcePool: pg.Pool;
10
- private readonly targetPool: pg.Pool;
11
-
12
- constructor() {
13
- this.sourcePool = new pg.Pool({
14
- connectionString: process.env.SOURCE_DATABASE_URL,
15
- });
16
-
17
- this.targetPool = new pg.Pool({
18
- connectionString: process.env.DATABASE_URL,
19
- });
20
- }
21
-
22
- async verifySetup() {
23
- this.logger.log('Starting migration setup verification');
24
-
25
- try {
26
- // Verificar conexiones
27
- await this.verifyConnections();
28
-
29
- // Verificar tenants
30
- await this.verifyTenants();
31
-
32
- // Verificar esquemas
33
- await this.verifySchemas();
34
-
35
- this.logger.log('Migration setup verification completed');
36
- } catch (error) {
37
- this.logger.error(`Error during setup verification: ${error.message}`);
38
- } finally {
39
- await this.cleanup();
40
- }
41
- }
42
-
43
- private async verifyConnections() {
44
- this.logger.log('Verifying database connections...');
45
-
46
- try {
47
- const sourceClient = await this.sourcePool.connect();
48
- const sourceResult = await sourceClient.query('SELECT NOW() as time');
49
- sourceClient.release();
50
- this.logger.log(`Source database connection successful: ${sourceResult.rows[0].time}`);
51
- } catch (error) {
52
- this.logger.error(`Source database connection failed: ${error.message}`);
53
- throw new Error('Source database connection failed');
54
- }
55
-
56
- try {
57
- const targetClient = await this.targetPool.connect();
58
- const targetResult = await targetClient.query('SELECT NOW() as time');
59
- targetClient.release();
60
- this.logger.log(`Target database connection successful: ${targetResult.rows[0].time}`);
61
- } catch (error) {
62
- this.logger.error(`Target database connection failed: ${error.message}`);
63
- throw new Error('Target database connection failed');
64
- }
65
- }
66
-
67
- private async verifyTenants() {
68
- this.logger.log('Verifying tenants in source database...');
69
-
70
- try {
71
- const result = await this.sourcePool.query(`
72
- SELECT api_key, provider_id
73
- FROM api_keys
74
- WHERE api_key != ''
75
- AND provider_id IS NOT NULL
76
- `);
77
-
78
- this.logger.log(`Found ${result.rows.length} valid tenants in source database`);
79
-
80
- if (result.rows.length === 0) {
81
- this.logger.warn('No valid tenants found in source database!');
82
- this.logger.log('Will use "public" schema as default source for migration');
83
- } else {
84
- // Mostrar algunos ejemplos
85
- const examples = result.rows.slice(0, 5);
86
- this.logger.log(`Sample tenants: ${JSON.stringify(examples)}`);
87
- }
88
- } catch (error) {
89
- this.logger.error(`Error verifying tenants: ${error.message}`);
90
- this.logger.log('Will use "public" schema as default source for migration');
91
- }
92
- }
93
-
94
- private async verifySchemas() {
95
- this.logger.log('Verifying schemas in target database...');
96
-
97
- try {
98
- const result = await this.targetPool.query(`
99
- SELECT schema_name
100
- FROM information_schema.schemata
101
- WHERE schema_name NOT IN ('public', 'information_schema', 'pg_catalog', 'pg_toast')
102
- AND schema_name NOT LIKE 'pg_%'
103
- `);
104
-
105
- this.logger.log(`Found ${result.rows.length} schemas in target database`);
106
-
107
- if (result.rows.length === 0) {
108
- this.logger.warn('No tenant schemas found in target database!');
109
- } else {
110
- // Mostrar algunos ejemplos
111
- const examples = result.rows.slice(0, 5);
112
- this.logger.log(`Sample schemas: ${JSON.stringify(examples)}`);
113
- }
114
- } catch (error) {
115
- this.logger.error(`Error verifying schemas: ${error.message}`);
116
- }
117
- }
118
-
119
- private async cleanup() {
120
- try {
121
- await this.sourcePool.end();
122
- await this.targetPool.end();
123
- } catch (error) {
124
- this.logger.error(`Error during cleanup: ${error.message}`);
125
- }
126
- }
127
- }
128
-
129
- // Ejecutar la verificación si este archivo se ejecuta directamente
130
- if (require.main === module) {
131
- const verifier = new MigrationSetupVerifier();
132
- verifier.verifySetup().catch(error => {
133
- console.error('Verification failed:', error);
134
- process.exit(1);
135
- });
1
+ import * as dotenv from 'dotenv';
2
+ import * as pg from 'pg';
3
+ import { Logger } from '@nestjs/common';
4
+
5
+ dotenv.config();
6
+
7
+ export class MigrationSetupVerifier {
8
+ private readonly logger = new Logger('MigrationSetupVerifier');
9
+ private readonly sourcePool: pg.Pool;
10
+ private readonly targetPool: pg.Pool;
11
+
12
+ constructor() {
13
+ this.sourcePool = new pg.Pool({
14
+ connectionString: process.env.SOURCE_DATABASE_URL,
15
+ });
16
+
17
+ this.targetPool = new pg.Pool({
18
+ connectionString: process.env.DATABASE_URL,
19
+ });
20
+ }
21
+
22
+ async verifySetup() {
23
+ this.logger.log('Starting migration setup verification');
24
+
25
+ try {
26
+ // Verificar conexiones
27
+ await this.verifyConnections();
28
+
29
+ // Verificar tenants
30
+ await this.verifyTenants();
31
+
32
+ // Verificar esquemas
33
+ await this.verifySchemas();
34
+
35
+ this.logger.log('Migration setup verification completed');
36
+ } catch (error) {
37
+ this.logger.error(`Error during setup verification: ${error.message}`);
38
+ } finally {
39
+ await this.cleanup();
40
+ }
41
+ }
42
+
43
+ private async verifyConnections() {
44
+ this.logger.log('Verifying database connections...');
45
+
46
+ try {
47
+ const sourceClient = await this.sourcePool.connect();
48
+ const sourceResult = await sourceClient.query('SELECT NOW() as time');
49
+ sourceClient.release();
50
+ this.logger.log(`Source database connection successful: ${sourceResult.rows[0].time}`);
51
+ } catch (error) {
52
+ this.logger.error(`Source database connection failed: ${error.message}`);
53
+ throw new Error('Source database connection failed');
54
+ }
55
+
56
+ try {
57
+ const targetClient = await this.targetPool.connect();
58
+ const targetResult = await targetClient.query('SELECT NOW() as time');
59
+ targetClient.release();
60
+ this.logger.log(`Target database connection successful: ${targetResult.rows[0].time}`);
61
+ } catch (error) {
62
+ this.logger.error(`Target database connection failed: ${error.message}`);
63
+ throw new Error('Target database connection failed');
64
+ }
65
+ }
66
+
67
+ private async verifyTenants() {
68
+ this.logger.log('Verifying tenants in source database...');
69
+
70
+ try {
71
+ const result = await this.sourcePool.query(`
72
+ SELECT api_key, provider_id
73
+ FROM api_keys
74
+ WHERE api_key != ''
75
+ AND provider_id IS NOT NULL
76
+ `);
77
+
78
+ this.logger.log(`Found ${result.rows.length} valid tenants in source database`);
79
+
80
+ if (result.rows.length === 0) {
81
+ this.logger.warn('No valid tenants found in source database!');
82
+ this.logger.log('Will use "public" schema as default source for migration');
83
+ } else {
84
+ // Mostrar algunos ejemplos
85
+ const examples = result.rows.slice(0, 5);
86
+ this.logger.log(`Sample tenants: ${JSON.stringify(examples)}`);
87
+ }
88
+ } catch (error) {
89
+ this.logger.error(`Error verifying tenants: ${error.message}`);
90
+ this.logger.log('Will use "public" schema as default source for migration');
91
+ }
92
+ }
93
+
94
+ private async verifySchemas() {
95
+ this.logger.log('Verifying schemas in target database...');
96
+
97
+ try {
98
+ const result = await this.targetPool.query(`
99
+ SELECT schema_name
100
+ FROM information_schema.schemata
101
+ WHERE schema_name NOT IN ('public', 'information_schema', 'pg_catalog', 'pg_toast')
102
+ AND schema_name NOT LIKE 'pg_%'
103
+ `);
104
+
105
+ this.logger.log(`Found ${result.rows.length} schemas in target database`);
106
+
107
+ if (result.rows.length === 0) {
108
+ this.logger.warn('No tenant schemas found in target database!');
109
+ } else {
110
+ // Mostrar algunos ejemplos
111
+ const examples = result.rows.slice(0, 5);
112
+ this.logger.log(`Sample schemas: ${JSON.stringify(examples)}`);
113
+ }
114
+ } catch (error) {
115
+ this.logger.error(`Error verifying schemas: ${error.message}`);
116
+ }
117
+ }
118
+
119
+ private async cleanup() {
120
+ try {
121
+ await this.sourcePool.end();
122
+ await this.targetPool.end();
123
+ } catch (error) {
124
+ this.logger.error(`Error during cleanup: ${error.message}`);
125
+ }
126
+ }
127
+ }
128
+
129
+ // Ejecutar la verificación si este archivo se ejecuta directamente
130
+ if (require.main === module) {
131
+ const verifier = new MigrationSetupVerifier();
132
+ verifier.verifySetup().catch(error => {
133
+ console.error('Verification failed:', error);
134
+ process.exit(1);
135
+ });
136
136
  }
package/tsconfig.json CHANGED
@@ -1,18 +1,18 @@
1
- {
2
- "compilerOptions": {
3
- "module": "commonjs",
4
- "declaration": true,
5
- "removeComments": true,
6
- "emitDecoratorMetadata": true,
7
- "experimentalDecorators": true,
8
- "allowSyntheticDefaultImports": true,
9
- "target": "es2017",
10
- "sourceMap": true,
11
- "outDir": "./dist",
12
- "baseUrl": "./",
13
- "incremental": true,
14
- "skipLibCheck": true
15
- },
16
- "include": ["src/**/*"],
17
- "exclude": ["node_modules", "dist"]
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "declaration": true,
5
+ "removeComments": true,
6
+ "emitDecoratorMetadata": true,
7
+ "experimentalDecorators": true,
8
+ "allowSyntheticDefaultImports": true,
9
+ "target": "es2017",
10
+ "sourceMap": true,
11
+ "outDir": "./dist",
12
+ "baseUrl": "./",
13
+ "incremental": true,
14
+ "skipLibCheck": true
15
+ },
16
+ "include": ["src/**/*"],
17
+ "exclude": ["node_modules", "dist"]
18
18
  }
package/dist/index.d.ts DELETED
@@ -1,7 +0,0 @@
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
- export declare const prisma: PrismaClient<import(".prisma/client").Prisma.PrismaClientOptions, import(".prisma/client").Prisma.LogLevel, import("@prisma/client/runtime/library").DefaultArgs>;
6
- export { PrismaModule, PrismaService, PrismaFactoryService };
7
- export * from "@prisma/client";
package/dist/index.js DELETED
@@ -1,34 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- var _a;
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.PrismaFactoryService = exports.PrismaService = exports.PrismaModule = exports.prisma = void 0;
19
- const client_1 = require("@prisma/client");
20
- const prisma_module_1 = require("./prisma.module");
21
- Object.defineProperty(exports, "PrismaModule", { enumerable: true, get: function () { return prisma_module_1.PrismaModule; } });
22
- const prisma_service_1 = require("./prisma.service");
23
- Object.defineProperty(exports, "PrismaService", { enumerable: true, get: function () { return prisma_service_1.PrismaService; } });
24
- const prisma_factory_service_1 = require("./prisma-factory.service");
25
- Object.defineProperty(exports, "PrismaFactoryService", { enumerable: true, get: function () { return prisma_factory_service_1.PrismaFactoryService; } });
26
- const prismaClientSingleton = () => {
27
- return new client_1.PrismaClient();
28
- };
29
- const globalForPrisma = globalThis;
30
- exports.prisma = (_a = globalForPrisma.prisma) !== null && _a !== void 0 ? _a : prismaClientSingleton();
31
- if (process.env.NODE_ENV !== "production")
32
- globalForPrisma.prisma = exports.prisma;
33
- __exportStar(require("@prisma/client"), exports);
34
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,2CAA8C;AAC9C,mDAA+C;AAoBtC,6FApBA,4BAAY,OAoBA;AAnBrB,qDAAiD;AAmB1B,8FAnBd,8BAAa,OAmBc;AAlBpC,qEAAgE;AAkB1B,qGAlB7B,6CAAoB,OAkB6B;AAf1D,MAAM,qBAAqB,GAAG,GAAG,EAAE;IACjC,OAAO,IAAI,qBAAY,EAAE,CAAC;AAC5B,CAAC,CAAC;AAIF,MAAM,eAAe,GAAG,UAEvB,CAAC;AAEW,QAAA,MAAM,GAAG,MAAA,eAAe,CAAC,MAAM,mCAAI,qBAAqB,EAAE,CAAC;AAExE,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;IAAE,eAAe,CAAC,MAAM,GAAG,cAAM,CAAC;AAI3E,iDAA+B"}
@@ -1,9 +0,0 @@
1
- import { OnModuleDestroy } from '@nestjs/common';
2
- import { PrismaClient } from '@prisma/client';
3
- export declare class PrismaFactoryService implements OnModuleDestroy {
4
- private clients;
5
- private readonly logger;
6
- getClient(tenantId: string): PrismaClient;
7
- getMasterClient(): PrismaClient;
8
- onModuleDestroy(): Promise<void>;
9
- }
@@ -1,47 +0,0 @@
1
- "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var PrismaFactoryService_1;
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.PrismaFactoryService = void 0;
11
- const common_1 = require("@nestjs/common");
12
- const client_1 = require("@prisma/client");
13
- let PrismaFactoryService = PrismaFactoryService_1 = class PrismaFactoryService {
14
- constructor() {
15
- this.clients = new Map();
16
- this.logger = new common_1.Logger(PrismaFactoryService_1.name);
17
- }
18
- getClient(tenantId) {
19
- if (!this.clients.has(tenantId)) {
20
- this.logger.log(`Creating new Prisma client for tenant: ${tenantId}`);
21
- const client = new client_1.PrismaClient({
22
- datasources: {
23
- db: {
24
- url: `${process.env.DATABASE_URL}?schema=${tenantId}`,
25
- },
26
- },
27
- });
28
- this.clients.set(tenantId, client);
29
- }
30
- return this.clients.get(tenantId);
31
- }
32
- getMasterClient() {
33
- return this.getClient('public');
34
- }
35
- async onModuleDestroy() {
36
- this.logger.log('Disconnecting all Prisma clients');
37
- for (const [tenantId, client] of this.clients.entries()) {
38
- this.logger.log(`Disconnecting client for tenant: ${tenantId}`);
39
- await client.$disconnect();
40
- }
41
- }
42
- };
43
- exports.PrismaFactoryService = PrismaFactoryService;
44
- exports.PrismaFactoryService = PrismaFactoryService = PrismaFactoryService_1 = __decorate([
45
- (0, common_1.Injectable)()
46
- ], PrismaFactoryService);
47
- //# sourceMappingURL=prisma-factory.service.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"prisma-factory.service.js","sourceRoot":"","sources":["../src/prisma-factory.service.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,2CAAqE;AACrE,2CAA8C;AAGvC,IAAM,oBAAoB,4BAA1B,MAAM,oBAAoB;IAA1B;QACG,YAAO,GAA8B,IAAI,GAAG,EAAE,CAAC;QACtC,WAAM,GAAG,IAAI,eAAM,CAAC,sBAAoB,CAAC,IAAI,CAAC,CAAC;IAkClE,CAAC;IAhCC,SAAS,CAAC,QAAgB;QACxB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;YAChC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,0CAA0C,QAAQ,EAAE,CAAC,CAAC;YAGtE,MAAM,MAAM,GAAG,IAAI,qBAAY,CAAC;gBAC9B,WAAW,EAAE;oBACX,EAAE,EAAE;wBACF,GAAG,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,WAAW,QAAQ,EAAE;qBACtD;iBACF;aACF,CAAC,CAAC;YAEH,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QACrC,CAAC;QAED,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACpC,CAAC;IAGD,eAAe;QACb,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAClC,CAAC;IAED,KAAK,CAAC,eAAe;QACnB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;QAEpD,KAAK,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;YACxD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,oCAAoC,QAAQ,EAAE,CAAC,CAAC;YAChE,MAAM,MAAM,CAAC,WAAW,EAAE,CAAC;QAC7B,CAAC;IACH,CAAC;CACF,CAAA;AApCY,oDAAoB;+BAApB,oBAAoB;IADhC,IAAA,mBAAU,GAAE;GACA,oBAAoB,CAoChC"}