@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,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
+ });