@javalabs/prisma-client 1.0.27 → 1.0.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.github/CODEOWNERS +1 -1
  2. package/README.md +269 -269
  3. package/migration-config.json +63 -63
  4. package/migration-config.json.bk +95 -95
  5. package/migrations/add_reserved_amount.sql +7 -7
  6. package/package.json +44 -44
  7. package/prisma/migrations/add_uuid_to_transactions.sql +13 -13
  8. package/prisma/schema.prisma +609 -601
  9. package/src/index.ts +23 -23
  10. package/src/prisma-factory.service.ts +40 -40
  11. package/src/prisma.module.ts +9 -9
  12. package/src/prisma.service.ts +16 -16
  13. package/src/scripts/add-uuid-to-table.ts +138 -138
  14. package/src/scripts/create-tenant-schemas.ts +145 -145
  15. package/src/scripts/data-migration/batch-migrator.ts +248 -248
  16. package/src/scripts/data-migration/data-transformer.ts +426 -426
  17. package/src/scripts/data-migration/db-connector.ts +120 -120
  18. package/src/scripts/data-migration/dependency-resolver.ts +174 -174
  19. package/src/scripts/data-migration/entity-discovery.ts +196 -196
  20. package/src/scripts/data-migration/foreign-key-manager.ts +277 -277
  21. package/src/scripts/data-migration/migration-config.json +63 -63
  22. package/src/scripts/data-migration/migration-tool.ts +509 -509
  23. package/src/scripts/data-migration/schema-utils.ts +248 -248
  24. package/src/scripts/data-migration/tenant-migrator.ts +201 -201
  25. package/src/scripts/data-migration/typecast-manager.ts +193 -193
  26. package/src/scripts/data-migration/types.ts +113 -113
  27. package/src/scripts/database-initializer.ts +49 -49
  28. package/src/scripts/drop-database.ts +104 -104
  29. package/src/scripts/dump-source-db.sh +61 -61
  30. package/src/scripts/encrypt-user-passwords.ts +36 -36
  31. package/src/scripts/error-handler.ts +117 -117
  32. package/src/scripts/fix-data-types.ts +241 -241
  33. package/src/scripts/fix-enum-values.ts +357 -357
  34. package/src/scripts/fix-schema-discrepancies.ts +317 -317
  35. package/src/scripts/fix-table-indexes.ts +601 -601
  36. package/src/scripts/migrate-schema-structure.ts +90 -90
  37. package/src/scripts/migrate-uuid.ts +76 -76
  38. package/src/scripts/post-migration-validator.ts +526 -526
  39. package/src/scripts/pre-migration-validator.ts +610 -610
  40. package/src/scripts/reset-database.ts +263 -263
  41. package/src/scripts/retry-failed-migrations.ts +416 -416
  42. package/src/scripts/run-migration.ts +707 -707
  43. package/src/scripts/schema-sync.ts +128 -128
  44. package/src/scripts/sequence-sync-cli.ts +416 -416
  45. package/src/scripts/sequence-synchronizer.ts +127 -127
  46. package/src/scripts/sync-enum-types.ts +170 -170
  47. package/src/scripts/sync-enum-values.ts +563 -563
  48. package/src/scripts/truncate-database.ts +123 -123
  49. package/src/scripts/verify-migration-setup.ts +135 -135
  50. package/tsconfig.json +17 -17
@@ -1,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
  }