@javalabs/prisma-client 1.0.30 → 1.0.31

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 (80) hide show
  1. package/.github/CODEOWNERS +1 -1
  2. package/README.md +269 -269
  3. package/dist/scripts/add-uuid-to-table.js +32 -32
  4. package/dist/scripts/data-migration/batch-migrator.js +12 -12
  5. package/dist/scripts/data-migration/data-transformer.js +14 -14
  6. package/dist/scripts/data-migration/dependency-resolver.js +23 -23
  7. package/dist/scripts/data-migration/entity-discovery.js +68 -68
  8. package/dist/scripts/data-migration/foreign-key-manager.js +23 -23
  9. package/dist/scripts/data-migration/migration-tool.js +5 -5
  10. package/dist/scripts/data-migration/schema-utils.js +74 -74
  11. package/dist/scripts/data-migration/typecast-manager.js +4 -4
  12. package/dist/scripts/database-initializer.js +5 -5
  13. package/dist/scripts/drop-database.js +5 -5
  14. package/dist/scripts/fix-data-types.js +53 -53
  15. package/dist/scripts/fix-enum-values.js +34 -34
  16. package/dist/scripts/fix-schema-discrepancies.js +40 -40
  17. package/dist/scripts/fix-table-indexes.js +81 -81
  18. package/dist/scripts/migrate-schema-structure.js +4 -4
  19. package/dist/scripts/migrate-uuid.js +19 -19
  20. package/dist/scripts/post-migration-validator.js +49 -49
  21. package/dist/scripts/pre-migration-validator.js +107 -107
  22. package/dist/scripts/reset-database.js +21 -21
  23. package/dist/scripts/retry-failed-migrations.js +28 -28
  24. package/dist/scripts/run-migration.js +5 -5
  25. package/dist/scripts/schema-sync.js +18 -18
  26. package/dist/scripts/sequence-sync-cli.js +55 -55
  27. package/dist/scripts/sequence-synchronizer.js +20 -20
  28. package/dist/scripts/sync-enum-types.js +30 -30
  29. package/dist/scripts/sync-enum-values.js +52 -52
  30. package/dist/scripts/truncate-database.js +10 -10
  31. package/dist/scripts/verify-migration-setup.js +10 -10
  32. package/dist/tsconfig.tsbuildinfo +1 -1
  33. package/migration-config.json +63 -63
  34. package/migration-config.json.bk +95 -95
  35. package/migrations/add_reserved_amount.sql +7 -7
  36. package/package.json +44 -44
  37. package/prisma/migrations/add_uuid_to_transactions.sql +13 -13
  38. package/prisma/schema.prisma +636 -609
  39. package/src/index.ts +23 -23
  40. package/src/prisma-factory.service.ts +40 -40
  41. package/src/prisma.module.ts +9 -9
  42. package/src/prisma.service.ts +16 -16
  43. package/src/scripts/add-uuid-to-table.ts +138 -138
  44. package/src/scripts/create-tenant-schemas.ts +145 -145
  45. package/src/scripts/data-migration/batch-migrator.ts +248 -248
  46. package/src/scripts/data-migration/data-transformer.ts +426 -426
  47. package/src/scripts/data-migration/db-connector.ts +120 -120
  48. package/src/scripts/data-migration/dependency-resolver.ts +174 -174
  49. package/src/scripts/data-migration/entity-discovery.ts +196 -196
  50. package/src/scripts/data-migration/foreign-key-manager.ts +277 -277
  51. package/src/scripts/data-migration/migration-config.json +63 -63
  52. package/src/scripts/data-migration/migration-tool.ts +509 -509
  53. package/src/scripts/data-migration/schema-utils.ts +248 -248
  54. package/src/scripts/data-migration/tenant-migrator.ts +201 -201
  55. package/src/scripts/data-migration/typecast-manager.ts +193 -193
  56. package/src/scripts/data-migration/types.ts +113 -113
  57. package/src/scripts/database-initializer.ts +49 -49
  58. package/src/scripts/drop-database.ts +104 -104
  59. package/src/scripts/dump-source-db.sh +61 -61
  60. package/src/scripts/encrypt-user-passwords.ts +36 -36
  61. package/src/scripts/error-handler.ts +117 -117
  62. package/src/scripts/fix-data-types.ts +241 -241
  63. package/src/scripts/fix-enum-values.ts +357 -357
  64. package/src/scripts/fix-schema-discrepancies.ts +317 -317
  65. package/src/scripts/fix-table-indexes.ts +601 -601
  66. package/src/scripts/migrate-schema-structure.ts +90 -90
  67. package/src/scripts/migrate-uuid.ts +76 -76
  68. package/src/scripts/post-migration-validator.ts +526 -526
  69. package/src/scripts/pre-migration-validator.ts +610 -610
  70. package/src/scripts/reset-database.ts +263 -263
  71. package/src/scripts/retry-failed-migrations.ts +416 -416
  72. package/src/scripts/run-migration.ts +707 -707
  73. package/src/scripts/schema-sync.ts +128 -128
  74. package/src/scripts/sequence-sync-cli.ts +416 -416
  75. package/src/scripts/sequence-synchronizer.ts +127 -127
  76. package/src/scripts/sync-enum-types.ts +170 -170
  77. package/src/scripts/sync-enum-values.ts +563 -563
  78. package/src/scripts/truncate-database.ts +123 -123
  79. package/src/scripts/verify-migration-setup.ts +135 -135
  80. package/tsconfig.json +17 -17
@@ -1,49 +1,49 @@
1
- import { PrismaClient } from "@prisma/client";
2
- import { exec } from "child_process";
3
- import { promisify } from "util";
4
-
5
- const execAsync = promisify(exec);
6
-
7
- export class DatabaseInitializer {
8
- constructor(private readonly databaseUrl: string) {}
9
-
10
- async initialize(): Promise<void> {
11
- try {
12
- console.log("Checking if database needs initialization...");
13
-
14
- const { Pool } = await import("pg");
15
- const pool = new Pool({ connectionString: this.databaseUrl });
16
-
17
- try {
18
- // Verificar si existen tablas en la base de datos
19
- const result = await pool.query(`
20
- SELECT COUNT(*)
21
- FROM information_schema.tables
22
- WHERE table_schema = 'public'
23
- AND table_type = 'BASE TABLE'
24
- `);
25
-
26
- const tableCount = parseInt(result.rows[0].count);
27
-
28
- if (tableCount === 0) {
29
- console.log(
30
- "No tables found in database. Running initial migration..."
31
- );
32
- // Ejecutar migración inicial usando Prisma
33
- await execAsync("npx prisma migrate deploy");
34
- await execAsync("npx prisma db push");
35
- console.log("Initial database migration completed successfully.");
36
- } else {
37
- console.log(
38
- `Database already contains ${tableCount} tables. Skipping initialization.`
39
- );
40
- }
41
- } finally {
42
- await pool.end();
43
- }
44
- } catch (error) {
45
- console.error("Error initializing database:", error);
46
- throw error;
47
- }
48
- }
49
- }
1
+ import { PrismaClient } from "@prisma/client";
2
+ import { exec } from "child_process";
3
+ import { promisify } from "util";
4
+
5
+ const execAsync = promisify(exec);
6
+
7
+ export class DatabaseInitializer {
8
+ constructor(private readonly databaseUrl: string) {}
9
+
10
+ async initialize(): Promise<void> {
11
+ try {
12
+ console.log("Checking if database needs initialization...");
13
+
14
+ const { Pool } = await import("pg");
15
+ const pool = new Pool({ connectionString: this.databaseUrl });
16
+
17
+ try {
18
+ // Verificar si existen tablas en la base de datos
19
+ const result = await pool.query(`
20
+ SELECT COUNT(*)
21
+ FROM information_schema.tables
22
+ WHERE table_schema = 'public'
23
+ AND table_type = 'BASE TABLE'
24
+ `);
25
+
26
+ const tableCount = parseInt(result.rows[0].count);
27
+
28
+ if (tableCount === 0) {
29
+ console.log(
30
+ "No tables found in database. Running initial migration..."
31
+ );
32
+ // Ejecutar migración inicial usando Prisma
33
+ await execAsync("npx prisma migrate deploy");
34
+ await execAsync("npx prisma db push");
35
+ console.log("Initial database migration completed successfully.");
36
+ } else {
37
+ console.log(
38
+ `Database already contains ${tableCount} tables. Skipping initialization.`
39
+ );
40
+ }
41
+ } finally {
42
+ await pool.end();
43
+ }
44
+ } catch (error) {
45
+ console.error("Error initializing database:", error);
46
+ throw error;
47
+ }
48
+ }
49
+ }
@@ -1,105 +1,105 @@
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 DatabaseDropTool {
8
- private readonly logger = new Logger("DatabaseDropTool");
9
- private readonly adminPool: pg.Pool;
10
-
11
- constructor(private readonly databaseUrl: string) {
12
- // Conexión a la base de datos postgres (admin)
13
- // Modificamos la URL para conectarnos a la base de datos postgres en lugar de la base de datos específica
14
- const adminUrl = this.databaseUrl.replace(/\/[^/]+$/, "/postgres");
15
-
16
- this.adminPool = new pg.Pool({
17
- connectionString: adminUrl,
18
- });
19
- }
20
-
21
- async dropDatabase() {
22
- try {
23
- this.logger.log("Starting database drop process");
24
-
25
- // Extraer el nombre de la base de datos de la URL
26
- const dbName = this.extractDatabaseName(this.databaseUrl);
27
-
28
- if (!dbName) {
29
- throw new Error("Could not extract database name from connection URL");
30
- }
31
-
32
- this.logger.log(`Attempting to drop database: ${dbName}`);
33
-
34
- // 1. Terminar todas las conexiones activas a la base de datos
35
- await this.terminateConnections(dbName);
36
-
37
- // 2. Eliminar la base de datos
38
- await this.adminPool.query(`DROP DATABASE IF EXISTS "${dbName}"`);
39
-
40
- this.logger.log(`Database ${dbName} has been successfully dropped`);
41
- } catch (error) {
42
- this.logger.error(
43
- `Error dropping database: ${error.message}`,
44
- error.stack
45
- );
46
- throw error;
47
- } finally {
48
- await this.cleanup();
49
- }
50
- }
51
-
52
- private extractDatabaseName(url: string): string | null {
53
- // Extraer el nombre de la base de datos de la URL de conexión
54
- const matches = url.match(/\/([^/?]+)($|\?)/);
55
- return matches ? matches[1] : null;
56
- }
57
-
58
- private async terminateConnections(dbName: string) {
59
- this.logger.log(`Terminating all connections to database: ${dbName}`);
60
-
61
- try {
62
- // PostgreSQL 9.2+
63
- await this.adminPool.query(`
64
- SELECT pg_terminate_backend(pg_stat_activity.pid)
65
- FROM pg_stat_activity
66
- WHERE pg_stat_activity.datname = $1
67
- AND pid <> pg_backend_pid()
68
- `, [dbName]);
69
-
70
- this.logger.log("All connections terminated successfully");
71
- } catch (error) {
72
- this.logger.error(`Error terminating connections: ${error.message}`);
73
- // Continuamos con el proceso incluso si hay un error aquí
74
- }
75
- }
76
-
77
- private async cleanup() {
78
- this.logger.log("Cleaning up database connections");
79
- await this.adminPool.end();
80
- }
81
- }
82
-
83
- // Script para ejecutar desde línea de comandos
84
- if (require.main === module) {
85
- const run = async () => {
86
- try {
87
- // Obtener la URL de la base de datos desde los argumentos o .env
88
- const databaseUrl = process.argv[2] || process.env.DATABASE_URL;
89
-
90
- if (!databaseUrl) {
91
- console.error("Error: No database URL provided. Please provide a database URL as an argument or set DATABASE_URL environment variable.");
92
- process.exit(1);
93
- }
94
-
95
- const dropTool = new DatabaseDropTool(databaseUrl);
96
- await dropTool.dropDatabase();
97
- process.exit(0);
98
- } catch (error) {
99
- console.error("Error:", error.message);
100
- process.exit(1);
101
- }
102
- };
103
-
104
- 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 DatabaseDropTool {
8
+ private readonly logger = new Logger("DatabaseDropTool");
9
+ private readonly adminPool: pg.Pool;
10
+
11
+ constructor(private readonly databaseUrl: string) {
12
+ // Conexión a la base de datos postgres (admin)
13
+ // Modificamos la URL para conectarnos a la base de datos postgres en lugar de la base de datos específica
14
+ const adminUrl = this.databaseUrl.replace(/\/[^/]+$/, "/postgres");
15
+
16
+ this.adminPool = new pg.Pool({
17
+ connectionString: adminUrl,
18
+ });
19
+ }
20
+
21
+ async dropDatabase() {
22
+ try {
23
+ this.logger.log("Starting database drop process");
24
+
25
+ // Extraer el nombre de la base de datos de la URL
26
+ const dbName = this.extractDatabaseName(this.databaseUrl);
27
+
28
+ if (!dbName) {
29
+ throw new Error("Could not extract database name from connection URL");
30
+ }
31
+
32
+ this.logger.log(`Attempting to drop database: ${dbName}`);
33
+
34
+ // 1. Terminar todas las conexiones activas a la base de datos
35
+ await this.terminateConnections(dbName);
36
+
37
+ // 2. Eliminar la base de datos
38
+ await this.adminPool.query(`DROP DATABASE IF EXISTS "${dbName}"`);
39
+
40
+ this.logger.log(`Database ${dbName} has been successfully dropped`);
41
+ } catch (error) {
42
+ this.logger.error(
43
+ `Error dropping database: ${error.message}`,
44
+ error.stack
45
+ );
46
+ throw error;
47
+ } finally {
48
+ await this.cleanup();
49
+ }
50
+ }
51
+
52
+ private extractDatabaseName(url: string): string | null {
53
+ // Extraer el nombre de la base de datos de la URL de conexión
54
+ const matches = url.match(/\/([^/?]+)($|\?)/);
55
+ return matches ? matches[1] : null;
56
+ }
57
+
58
+ private async terminateConnections(dbName: string) {
59
+ this.logger.log(`Terminating all connections to database: ${dbName}`);
60
+
61
+ try {
62
+ // PostgreSQL 9.2+
63
+ await this.adminPool.query(`
64
+ SELECT pg_terminate_backend(pg_stat_activity.pid)
65
+ FROM pg_stat_activity
66
+ WHERE pg_stat_activity.datname = $1
67
+ AND pid <> pg_backend_pid()
68
+ `, [dbName]);
69
+
70
+ this.logger.log("All connections terminated successfully");
71
+ } catch (error) {
72
+ this.logger.error(`Error terminating connections: ${error.message}`);
73
+ // Continuamos con el proceso incluso si hay un error aquí
74
+ }
75
+ }
76
+
77
+ private async cleanup() {
78
+ this.logger.log("Cleaning up database connections");
79
+ await this.adminPool.end();
80
+ }
81
+ }
82
+
83
+ // Script para ejecutar desde línea de comandos
84
+ if (require.main === module) {
85
+ const run = async () => {
86
+ try {
87
+ // Obtener la URL de la base de datos desde los argumentos o .env
88
+ const databaseUrl = process.argv[2] || process.env.DATABASE_URL;
89
+
90
+ if (!databaseUrl) {
91
+ console.error("Error: No database URL provided. Please provide a database URL as an argument or set DATABASE_URL environment variable.");
92
+ process.exit(1);
93
+ }
94
+
95
+ const dropTool = new DatabaseDropTool(databaseUrl);
96
+ await dropTool.dropDatabase();
97
+ process.exit(0);
98
+ } catch (error) {
99
+ console.error("Error:", error.message);
100
+ process.exit(1);
101
+ }
102
+ };
103
+
104
+ run();
105
105
  }
@@ -1,62 +1,62 @@
1
- #!/bin/bash
2
-
3
- # --- Verificar e instalar pg_dump si es necesario ---
4
- # Use explicit path to PostgreSQL 16 binaries
5
- PG16_PATH="/usr/local/opt/postgresql@16/bin"
6
- if ! command -v "${PG16_PATH}/pg_dump" &> /dev/null; then
7
- echo "PostgreSQL 16 no está instalado. Intentando instalar con Homebrew..."
8
- if ! command -v brew &> /dev/null; then
9
- echo "Error: Homebrew no está instalado."
10
- exit 1
11
- fi
12
- brew install postgresql@16
13
- fi
14
-
15
- # --- Configuración ---
16
- # Read from environment variables
17
- # Load environment variables if .env exists
18
- if [ -f "../../.env" ]; then
19
- set -o allexport
20
- source "../../.env"
21
- set +o allexport
22
- fi
23
-
24
- if [ -z "$SOURCE_DATABASE_URL" ]; then
25
- echo "Error: SOURCE_DATABASE_URL environment variable not set"
26
- exit 1
27
- fi
28
-
29
- OUTPUT_FILE="dumps/source_dump_$(date +%Y%m%d_%H%M%S).sql"
30
-
31
- # --- Version Check ---
32
- SERVER_VERSION=$(psql "$SOURCE_DATABASE_URL" -t -c "SHOW server_version_num;" | tr -d '[:space:]')
33
- LOCAL_VERSION=$(pg_dump --version | grep -oE '[0-9]+' | head -1)
34
-
35
- if [ "$SERVER_VERSION" -gt "$((LOCAL_VERSION * 10000))" ]; then
36
- echo "Warning: Server version ($SERVER_VERSION) is newer than local pg_dump ($LOCAL_VERSION)"
37
- echo "Forcing dump with basic compatibility mode..."
38
- COMPAT_FLAGS="--no-sync --no-comments"
39
- else
40
- COMPAT_FLAGS=""
41
- fi
42
-
43
- # --- Comando pg_dump ---
44
- echo "Creando dump de la base de datos desde ($SOURCE_DATABASE_URL)..."
45
-
46
- "${PG16_PATH}/pg_dump" $COMPAT_FLAGS \
47
- --dbname="$SOURCE_DATABASE_URL" \
48
- --schema=public \
49
- --data-only \
50
- --inserts \
51
- --file="$OUTPUT_FILE"
52
-
53
- # --- Resultado ---
54
- if [ $? -eq 0 ]; then
55
- echo "Dump creado exitosamente en: $OUTPUT_FILE"
56
- else
57
- echo "Error al crear el dump."
58
- exit 1
59
- fi
60
-
61
- exit 0
1
+ #!/bin/bash
2
+
3
+ # --- Verificar e instalar pg_dump si es necesario ---
4
+ # Use explicit path to PostgreSQL 16 binaries
5
+ PG16_PATH="/usr/local/opt/postgresql@16/bin"
6
+ if ! command -v "${PG16_PATH}/pg_dump" &> /dev/null; then
7
+ echo "PostgreSQL 16 no está instalado. Intentando instalar con Homebrew..."
8
+ if ! command -v brew &> /dev/null; then
9
+ echo "Error: Homebrew no está instalado."
10
+ exit 1
11
+ fi
12
+ brew install postgresql@16
13
+ fi
14
+
15
+ # --- Configuración ---
16
+ # Read from environment variables
17
+ # Load environment variables if .env exists
18
+ if [ -f "../../.env" ]; then
19
+ set -o allexport
20
+ source "../../.env"
21
+ set +o allexport
22
+ fi
23
+
24
+ if [ -z "$SOURCE_DATABASE_URL" ]; then
25
+ echo "Error: SOURCE_DATABASE_URL environment variable not set"
26
+ exit 1
27
+ fi
28
+
29
+ OUTPUT_FILE="dumps/source_dump_$(date +%Y%m%d_%H%M%S).sql"
30
+
31
+ # --- Version Check ---
32
+ SERVER_VERSION=$(psql "$SOURCE_DATABASE_URL" -t -c "SHOW server_version_num;" | tr -d '[:space:]')
33
+ LOCAL_VERSION=$(pg_dump --version | grep -oE '[0-9]+' | head -1)
34
+
35
+ if [ "$SERVER_VERSION" -gt "$((LOCAL_VERSION * 10000))" ]; then
36
+ echo "Warning: Server version ($SERVER_VERSION) is newer than local pg_dump ($LOCAL_VERSION)"
37
+ echo "Forcing dump with basic compatibility mode..."
38
+ COMPAT_FLAGS="--no-sync --no-comments"
39
+ else
40
+ COMPAT_FLAGS=""
41
+ fi
42
+
43
+ # --- Comando pg_dump ---
44
+ echo "Creando dump de la base de datos desde ($SOURCE_DATABASE_URL)..."
45
+
46
+ "${PG16_PATH}/pg_dump" $COMPAT_FLAGS \
47
+ --dbname="$SOURCE_DATABASE_URL" \
48
+ --schema=public \
49
+ --data-only \
50
+ --inserts \
51
+ --file="$OUTPUT_FILE"
52
+
53
+ # --- Resultado ---
54
+ if [ $? -eq 0 ]; then
55
+ echo "Dump creado exitosamente en: $OUTPUT_FILE"
56
+ else
57
+ echo "Error al crear el dump."
58
+ exit 1
59
+ fi
60
+
61
+ exit 0
62
62
 
@@ -1,36 +1,36 @@
1
- import { PrismaClient } from "@prisma/client";
2
- import * as bcrypt from "bcrypt";
3
-
4
- const prisma = new PrismaClient();
5
- const SALT_ROUNDS = 10;
6
- const PEPPER = process.env.PASSWORD_PEPPER || "clave-secreta-super-segura";
7
-
8
- function generateDefaultPassword(email: string): string {
9
- const randomId = Math.floor(1000 + Math.random() * 9000); // 4 dígitos
10
- return `PASS-${email}-${randomId}`;
11
- }
12
-
13
- async function encryptPasswords() {
14
- const users = await prisma.users.findMany();
15
- let updated = 0;
16
-
17
- for (const user of users) {
18
- const defaultPassword = generateDefaultPassword(user.email);
19
- const hashed = await bcrypt.hash(defaultPassword + PEPPER, SALT_ROUNDS);
20
- await prisma.users.update({
21
- where: { user_id: user.user_id },
22
- data: { password: hashed },
23
- });
24
- updated++;
25
- console.log(`Usuario: ${user.email} | Nuevo password: ${defaultPassword}`);
26
- }
27
-
28
- console.log(`Total de contraseñas generadas y cifradas: ${updated}`);
29
- await prisma.$disconnect();
30
- }
31
-
32
- encryptPasswords().catch((e) => {
33
- console.error("Error al cifrar contraseñas:", e);
34
- prisma.$disconnect();
35
- process.exit(1);
36
- });
1
+ import { PrismaClient } from "@prisma/client";
2
+ import * as bcrypt from "bcrypt";
3
+
4
+ const prisma = new PrismaClient();
5
+ const SALT_ROUNDS = 10;
6
+ const PEPPER = process.env.PASSWORD_PEPPER || "clave-secreta-super-segura";
7
+
8
+ function generateDefaultPassword(email: string): string {
9
+ const randomId = Math.floor(1000 + Math.random() * 9000); // 4 dígitos
10
+ return `PASS-${email}-${randomId}`;
11
+ }
12
+
13
+ async function encryptPasswords() {
14
+ const users = await prisma.users.findMany();
15
+ let updated = 0;
16
+
17
+ for (const user of users) {
18
+ const defaultPassword = generateDefaultPassword(user.email);
19
+ const hashed = await bcrypt.hash(defaultPassword + PEPPER, SALT_ROUNDS);
20
+ await prisma.users.update({
21
+ where: { user_id: user.user_id },
22
+ data: { password: hashed },
23
+ });
24
+ updated++;
25
+ console.log(`Usuario: ${user.email} | Nuevo password: ${defaultPassword}`);
26
+ }
27
+
28
+ console.log(`Total de contraseñas generadas y cifradas: ${updated}`);
29
+ await prisma.$disconnect();
30
+ }
31
+
32
+ encryptPasswords().catch((e) => {
33
+ console.error("Error al cifrar contraseñas:", e);
34
+ prisma.$disconnect();
35
+ process.exit(1);
36
+ });