@javalabs/prisma-client 1.0.6 → 1.0.8

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.
@@ -0,0 +1,127 @@
1
+ import { Logger } from "@nestjs/common";
2
+ import { Pool } from "pg";
3
+
4
+ export class SequenceSynchronizer {
5
+ private readonly logger = new Logger("SequenceSynchronizer");
6
+ private readonly pool: Pool;
7
+
8
+ constructor(databaseUrl: string) {
9
+ this.pool = new Pool({
10
+ connectionString: databaseUrl,
11
+ });
12
+ }
13
+
14
+ async synchronizeSequences(): Promise<void> {
15
+ try {
16
+ this.logger.log("Iniciando sincronización de secuencias");
17
+
18
+ // Obtener todas las tablas en la base de datos
19
+ const tables = await this.getTables();
20
+ this.logger.log(`Encontradas ${tables.length} tablas para procesar`);
21
+
22
+ // Procesar cada tabla
23
+ for (const table of tables) {
24
+ await this.synchronizeTableSequences(table);
25
+ }
26
+
27
+ this.logger.log("Sincronización de secuencias completada con éxito");
28
+ } catch (error) {
29
+ this.logger.error(
30
+ `Error durante la sincronización de secuencias: ${error.message}`,
31
+ error.stack
32
+ );
33
+ throw error;
34
+ } finally {
35
+ await this.pool.end();
36
+ }
37
+ }
38
+
39
+ private async getTables(): Promise<string[]> {
40
+ const query = `
41
+ SELECT table_name
42
+ FROM information_schema.tables
43
+ WHERE table_schema = 'public'
44
+ AND table_type = 'BASE TABLE'
45
+ `;
46
+
47
+ const result = await this.pool.query(query);
48
+ return result.rows.map((row) => row.table_name);
49
+ }
50
+
51
+ private async synchronizeTableSequences(tableName: string): Promise<void> {
52
+ try {
53
+ // Verificar si la tabla tiene una columna id
54
+ const columns = await this.pool.query(
55
+ `
56
+ SELECT column_name
57
+ FROM information_schema.columns
58
+ WHERE table_name = $1
59
+ AND column_name = 'id'
60
+ `,
61
+ [tableName]
62
+ );
63
+
64
+ if (columns.rows.length === 0) {
65
+ this.logger.debug(
66
+ `La tabla ${tableName} no tiene columna id, omitiendo`
67
+ );
68
+ return;
69
+ }
70
+
71
+ // Verificar si existe una secuencia para esta tabla
72
+ const sequenceName = `${tableName}_id_seq`;
73
+ const sequences = await this.pool.query(
74
+ `
75
+ SELECT sequence_name
76
+ FROM information_schema.sequences
77
+ WHERE sequence_name = $1
78
+ `,
79
+ [sequenceName]
80
+ );
81
+
82
+ if (sequences.rows.length === 0) {
83
+ this.logger.debug(
84
+ `No se encontró secuencia para la tabla ${tableName}, omitiendo`
85
+ );
86
+ return;
87
+ }
88
+
89
+ // Obtener el máximo ID actual de la tabla
90
+ const maxResult = await this.pool.query(`
91
+ SELECT COALESCE(MAX(id), 0) as max_id FROM "${tableName}"
92
+ `);
93
+ const maxId = maxResult.rows[0].max_id;
94
+
95
+ // Obtener el valor actual de la secuencia
96
+ const currValResult = await this.pool.query(`
97
+ SELECT last_value FROM "${sequenceName}"
98
+ `);
99
+ const currVal = currValResult.rows[0].last_value;
100
+
101
+ this.logger.log(
102
+ `Tabla ${tableName}: ID Máximo = ${maxId}, Valor Actual de Secuencia = ${currVal}`
103
+ );
104
+
105
+ // Actualizar la secuencia solo si es necesario
106
+ if (currVal <= maxId) {
107
+ await this.pool.query(
108
+ `
109
+ SELECT setval($1, $2, true)
110
+ `,
111
+ [sequenceName, maxId]
112
+ );
113
+ this.logger.log(
114
+ `Actualizada secuencia para tabla ${tableName} a ${maxId}`
115
+ );
116
+ } else {
117
+ this.logger.log(
118
+ `La secuencia para la tabla ${tableName} ya está adelantada al ID máximo, no se requiere actualización`
119
+ );
120
+ }
121
+ } catch (error) {
122
+ this.logger.error(
123
+ `Error sincronizando secuencias para tabla ${tableName}: ${error.message}`
124
+ );
125
+ }
126
+ }
127
+ }
@@ -1,14 +0,0 @@
1
- /*
2
- Warnings:
3
-
4
- - You are about to drop the column `usersUser_id` on the `manual_payments` table. All the data in the column will be lost.
5
-
6
- */
7
- -- DropForeignKey
8
- ALTER TABLE "manual_payments" DROP CONSTRAINT "manual_payments_usersUser_id_fkey";
9
-
10
- -- AlterTable
11
- ALTER TABLE "manual_payments" DROP COLUMN "usersUser_id";
12
-
13
- -- AddForeignKey
14
- ALTER TABLE "manual_payments" ADD CONSTRAINT "manual_payments_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("user_id") ON DELETE RESTRICT ON UPDATE CASCADE;