@javalabs/prisma-client 1.0.0
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.
- package/README.md +220 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +34 -0
- package/dist/index.js.map +1 -0
- package/dist/prisma-factory.service.d.ts +9 -0
- package/dist/prisma-factory.service.js +47 -0
- package/dist/prisma-factory.service.js.map +1 -0
- package/dist/prisma.module.d.ts +2 -0
- package/dist/prisma.module.js +23 -0
- package/dist/prisma.module.js.map +1 -0
- package/dist/prisma.service.d.ts +6 -0
- package/dist/prisma.service.js +27 -0
- package/dist/prisma.service.js.map +1 -0
- package/dist/scripts/create-tenant-schemas.d.ts +1 -0
- package/dist/scripts/create-tenant-schemas.js +117 -0
- package/dist/scripts/create-tenant-schemas.js.map +1 -0
- package/dist/scripts/data-migration/batch-migrator.d.ts +25 -0
- package/dist/scripts/data-migration/batch-migrator.js +333 -0
- package/dist/scripts/data-migration/batch-migrator.js.map +1 -0
- package/dist/scripts/data-migration/data-transformer.d.ts +17 -0
- package/dist/scripts/data-migration/data-transformer.js +242 -0
- package/dist/scripts/data-migration/data-transformer.js.map +1 -0
- package/dist/scripts/data-migration/db-connector.d.ts +7 -0
- package/dist/scripts/data-migration/db-connector.js +58 -0
- package/dist/scripts/data-migration/db-connector.js.map +1 -0
- package/dist/scripts/data-migration/dependency-manager.d.ts +9 -0
- package/dist/scripts/data-migration/dependency-manager.js +86 -0
- package/dist/scripts/data-migration/dependency-manager.js.map +1 -0
- package/dist/scripts/data-migration/dependency-resolver.d.ts +18 -0
- package/dist/scripts/data-migration/dependency-resolver.js +251 -0
- package/dist/scripts/data-migration/dependency-resolver.js.map +1 -0
- package/dist/scripts/data-migration/entity-discovery.d.ts +11 -0
- package/dist/scripts/data-migration/entity-discovery.js +152 -0
- package/dist/scripts/data-migration/entity-discovery.js.map +1 -0
- package/dist/scripts/data-migration/foreign-key-manager.d.ts +17 -0
- package/dist/scripts/data-migration/foreign-key-manager.js +70 -0
- package/dist/scripts/data-migration/foreign-key-manager.js.map +1 -0
- package/dist/scripts/data-migration/migration-phases.d.ts +5 -0
- package/dist/scripts/data-migration/migration-phases.js +55 -0
- package/dist/scripts/data-migration/migration-phases.js.map +1 -0
- package/dist/scripts/data-migration/migration-tool.d.ts +29 -0
- package/dist/scripts/data-migration/migration-tool.js +250 -0
- package/dist/scripts/data-migration/migration-tool.js.map +1 -0
- package/dist/scripts/data-migration/phase-generator.d.ts +15 -0
- package/dist/scripts/data-migration/phase-generator.js +187 -0
- package/dist/scripts/data-migration/phase-generator.js.map +1 -0
- package/dist/scripts/data-migration/schema-utils.d.ts +18 -0
- package/dist/scripts/data-migration/schema-utils.js +164 -0
- package/dist/scripts/data-migration/schema-utils.js.map +1 -0
- package/dist/scripts/data-migration/tenant-migrator.d.ts +15 -0
- package/dist/scripts/data-migration/tenant-migrator.js +110 -0
- package/dist/scripts/data-migration/tenant-migrator.js.map +1 -0
- package/dist/scripts/data-migration/typecast-manager.d.ts +5 -0
- package/dist/scripts/data-migration/typecast-manager.js +35 -0
- package/dist/scripts/data-migration/typecast-manager.js.map +1 -0
- package/dist/scripts/data-migration/types.d.ts +34 -0
- package/dist/scripts/data-migration/types.js +3 -0
- package/dist/scripts/data-migration/types.js.map +1 -0
- package/dist/scripts/data-migration.d.ts +22 -0
- package/dist/scripts/data-migration.js +593 -0
- package/dist/scripts/data-migration.js.map +1 -0
- package/dist/scripts/drop-database.d.ts +10 -0
- package/dist/scripts/drop-database.js +81 -0
- package/dist/scripts/drop-database.js.map +1 -0
- package/dist/scripts/error-handler.d.ts +12 -0
- package/dist/scripts/error-handler.js +82 -0
- package/dist/scripts/error-handler.js.map +1 -0
- package/dist/scripts/fix-data-types.d.ts +10 -0
- package/dist/scripts/fix-data-types.js +185 -0
- package/dist/scripts/fix-data-types.js.map +1 -0
- package/dist/scripts/fix-enum-values.d.ts +17 -0
- package/dist/scripts/fix-enum-values.js +234 -0
- package/dist/scripts/fix-enum-values.js.map +1 -0
- package/dist/scripts/fix-schema-discrepancies.d.ts +21 -0
- package/dist/scripts/fix-schema-discrepancies.js +240 -0
- package/dist/scripts/fix-schema-discrepancies.js.map +1 -0
- package/dist/scripts/migrate-schema-structure.d.ts +1 -0
- package/dist/scripts/migrate-schema-structure.js +76 -0
- package/dist/scripts/migrate-schema-structure.js.map +1 -0
- package/dist/scripts/post-migration-validator.d.ts +21 -0
- package/dist/scripts/post-migration-validator.js +341 -0
- package/dist/scripts/post-migration-validator.js.map +1 -0
- package/dist/scripts/pre-migration-validator.d.ts +25 -0
- package/dist/scripts/pre-migration-validator.js +491 -0
- package/dist/scripts/pre-migration-validator.js.map +1 -0
- package/dist/scripts/reset-database.d.ts +17 -0
- package/dist/scripts/reset-database.js +202 -0
- package/dist/scripts/reset-database.js.map +1 -0
- package/dist/scripts/retry-failed-migrations.d.ts +14 -0
- package/dist/scripts/retry-failed-migrations.js +301 -0
- package/dist/scripts/retry-failed-migrations.js.map +1 -0
- package/dist/scripts/run-migration.d.ts +1 -0
- package/dist/scripts/run-migration.js +525 -0
- package/dist/scripts/run-migration.js.map +1 -0
- package/dist/scripts/schema-sync.d.ts +1 -0
- package/dist/scripts/schema-sync.js +85 -0
- package/dist/scripts/schema-sync.js.map +1 -0
- package/dist/scripts/sync-enum-types.d.ts +13 -0
- package/dist/scripts/sync-enum-types.js +139 -0
- package/dist/scripts/sync-enum-types.js.map +1 -0
- package/dist/scripts/sync-enum-values.d.ts +20 -0
- package/dist/scripts/sync-enum-values.js +336 -0
- package/dist/scripts/sync-enum-values.js.map +1 -0
- package/dist/scripts/truncate-database.d.ts +10 -0
- package/dist/scripts/truncate-database.js +100 -0
- package/dist/scripts/truncate-database.js.map +1 -0
- package/dist/scripts/verify-migration-setup.d.ts +11 -0
- package/dist/scripts/verify-migration-setup.js +120 -0
- package/dist/scripts/verify-migration-setup.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/migration-config-public.json +95 -0
- package/migration-config.json +95 -0
- package/package.json +33 -0
- package/prisma/migrations/migration_lock.toml +3 -0
- package/prisma/schema.prisma +360 -0
- package/src/index.ts +23 -0
- package/src/prisma-factory.service.ts +41 -0
- package/src/prisma.module.ts +10 -0
- package/src/prisma.service.ts +17 -0
- package/src/scripts/create-tenant-schemas.ts +146 -0
- package/src/scripts/data-migration/batch-migrator.ts +569 -0
- package/src/scripts/data-migration/data-transformer.ts +377 -0
- package/src/scripts/data-migration/db-connector.ts +67 -0
- package/src/scripts/data-migration/dependency-resolver.ts +319 -0
- package/src/scripts/data-migration/entity-discovery.ts +197 -0
- package/src/scripts/data-migration/foreign-key-manager.ts +95 -0
- package/src/scripts/data-migration/migration-tool.ts +357 -0
- package/src/scripts/data-migration/schema-utils.ts +186 -0
- package/src/scripts/data-migration/tenant-migrator.ts +194 -0
- package/src/scripts/data-migration/typecast-manager.ts +38 -0
- package/src/scripts/data-migration/types.ts +40 -0
- package/src/scripts/drop-database.ts +105 -0
- package/src/scripts/dump-source-db.sh +62 -0
- package/src/scripts/dumps/source_dump_20250413_112626.sql +1527 -0
- package/src/scripts/error-handler.ts +118 -0
- package/src/scripts/fix-data-types.ts +242 -0
- package/src/scripts/fix-enum-values.ts +357 -0
- package/src/scripts/fix-schema-discrepancies.ts +318 -0
- package/src/scripts/migrate-schema-structure.ts +90 -0
- package/src/scripts/post-migration-validator.ts +427 -0
- package/src/scripts/pre-migration-validator.ts +611 -0
- package/src/scripts/reset-database.ts +264 -0
- package/src/scripts/retry-failed-migrations.ts +416 -0
- package/src/scripts/run-migration.ts +691 -0
- package/src/scripts/schema-sync.ts +129 -0
- package/src/scripts/sync-enum-types.ts +171 -0
- package/src/scripts/sync-enum-values.ts +563 -0
- package/src/scripts/truncate-database.ts +124 -0
- package/src/scripts/verify-migration-setup.ts +136 -0
- package/tsconfig.json +18 -0
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { Logger } from "@nestjs/common";
|
|
2
|
+
import { PrismaClient } from "@prisma/client";
|
|
3
|
+
import { SchemaUtils } from "./schema-utils";
|
|
4
|
+
import { EntityDiscovery } from "./entity-discovery";
|
|
5
|
+
import { BatchMigrator } from "./batch-migrator";
|
|
6
|
+
import { DatabaseConnections } from "./types";
|
|
7
|
+
import { DependencyResolver } from "./dependency-resolver";
|
|
8
|
+
|
|
9
|
+
export class TenantMigrator {
|
|
10
|
+
private readonly logger = new Logger("TenantMigrator");
|
|
11
|
+
private readonly dependencyResolver: DependencyResolver;
|
|
12
|
+
|
|
13
|
+
constructor(
|
|
14
|
+
private readonly schemaUtils: SchemaUtils,
|
|
15
|
+
private readonly entityDiscovery: EntityDiscovery,
|
|
16
|
+
private readonly batchMigrator: BatchMigrator,
|
|
17
|
+
private readonly connections: DatabaseConnections
|
|
18
|
+
) {
|
|
19
|
+
this.dependencyResolver = new DependencyResolver(
|
|
20
|
+
connections.sourcePool,
|
|
21
|
+
connections.targetPool
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Método para verificar dependencias de fase
|
|
26
|
+
async verifyPhaseDependencies(
|
|
27
|
+
tenantId: string,
|
|
28
|
+
tables: string[]
|
|
29
|
+
): Promise<boolean> {
|
|
30
|
+
try {
|
|
31
|
+
for (const table of tables) {
|
|
32
|
+
const count = await this.connections.targetPrisma.$queryRawUnsafe(
|
|
33
|
+
`SELECT COUNT(*) FROM "${tenantId}"."${table}"`
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
if (!count || count[0].count === "0") {
|
|
37
|
+
this.logger.warn(
|
|
38
|
+
`No data found in required table ${table} for tenant ${tenantId}`
|
|
39
|
+
);
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return true;
|
|
44
|
+
} catch (error) {
|
|
45
|
+
this.logger.error(`Error verifying phase dependencies: ${error.message}`);
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async migrateDataForTenant(
|
|
51
|
+
tenantId: string,
|
|
52
|
+
providerId: number,
|
|
53
|
+
includeTables?: string[] | null,
|
|
54
|
+
excludeTables?: string[] | null
|
|
55
|
+
) {
|
|
56
|
+
this.logger.log(
|
|
57
|
+
`Migrating data for tenant: ${tenantId} (Provider ID: ${
|
|
58
|
+
providerId || "N/A"
|
|
59
|
+
})`
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
// Verificar que el tenant existe y pertenece al provider (o no tiene provider)
|
|
63
|
+
try {
|
|
64
|
+
let tenantExists = false;
|
|
65
|
+
|
|
66
|
+
try {
|
|
67
|
+
// Modificar la consulta para incluir casos donde provider_id es nulo
|
|
68
|
+
const result = await this.connections.sourcePrisma.api_keys.findFirst({
|
|
69
|
+
where: {
|
|
70
|
+
api_key: tenantId,
|
|
71
|
+
OR: [{ provider_id: providerId }, { provider_id: null }],
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
tenantExists = !!result;
|
|
76
|
+
} catch (error) {
|
|
77
|
+
this.logger.warn(
|
|
78
|
+
`Error checking tenant existence, will assume using public schema: ${error.message}`
|
|
79
|
+
);
|
|
80
|
+
tenantExists = true; // Asumir que estamos usando el esquema público
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (!tenantExists) {
|
|
84
|
+
this.logger.warn(
|
|
85
|
+
`Tenant ${tenantId} does not exist or does not belong to provider ${
|
|
86
|
+
providerId || "N/A"
|
|
87
|
+
}. Using public schema as source.`
|
|
88
|
+
);
|
|
89
|
+
// Continuamos de todos modos, asumiendo que usaremos el esquema público
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Log para depuración
|
|
93
|
+
this.logger.log(`Proceeding with migration for tenant ${tenantId}`);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
this.logger.error(
|
|
96
|
+
`Error verifying tenant ${tenantId} for provider ${
|
|
97
|
+
providerId || "N/A"
|
|
98
|
+
}: ${error.message}`
|
|
99
|
+
);
|
|
100
|
+
// Log más detallado del error
|
|
101
|
+
this.logger.error(`Error details: ${JSON.stringify(error)}`);
|
|
102
|
+
// Continuamos de todos modos
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Create a client for this specific tenant schema with increased timeout
|
|
106
|
+
const tenantPrisma = new PrismaClient({
|
|
107
|
+
datasources: {
|
|
108
|
+
db: {
|
|
109
|
+
url: `${process.env.DATABASE_URL}?schema=${tenantId}`,
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
// Increase transaction timeout to 5 minutes (was 2 minutes)
|
|
113
|
+
transactionOptions: {
|
|
114
|
+
maxWait: 300000, // 5 minutes max wait time
|
|
115
|
+
timeout: 300000, // 5 minutes timeout
|
|
116
|
+
},
|
|
117
|
+
log: ["query", "error", "warn"], // Añadir logging para depuración
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
try {
|
|
121
|
+
// Validate that the schema exists in the target database
|
|
122
|
+
const schemaExists = await this.schemaUtils.checkSchemaExists(tenantId);
|
|
123
|
+
if (!schemaExists) {
|
|
124
|
+
this.logger.error(
|
|
125
|
+
`Schema ${tenantId} does not exist in target database. Skipping migration.`
|
|
126
|
+
);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Get all tables from the target schema
|
|
131
|
+
const targetTables = await this.schemaUtils.getTargetTables(tenantId);
|
|
132
|
+
|
|
133
|
+
// Discover entity types and their relationships automatically
|
|
134
|
+
let entityTypes = await this.entityDiscovery.discoverEntityTypes(
|
|
135
|
+
tenantId,
|
|
136
|
+
targetTables
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
// Filtrar entidades según los parámetros includeTables y excludeTables
|
|
140
|
+
if (includeTables) {
|
|
141
|
+
entityTypes = entityTypes.filter((entity) =>
|
|
142
|
+
includeTables.includes(entity.name)
|
|
143
|
+
);
|
|
144
|
+
this.logger.log(
|
|
145
|
+
`Filtered to include only: ${includeTables.join(", ")}`
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (excludeTables) {
|
|
150
|
+
entityTypes = entityTypes.filter(
|
|
151
|
+
(entity) => !excludeTables.includes(entity.name)
|
|
152
|
+
);
|
|
153
|
+
this.logger.log(`Filtered to exclude: ${excludeTables.join(", ")}`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Ordenar entidades basadas en dependencias
|
|
157
|
+
// Replace dependencyManager with dependencyResolver for ordering
|
|
158
|
+
const sortedTables = await this.dependencyResolver.analyzeDependencies();
|
|
159
|
+
const orderedEntities = entityTypes
|
|
160
|
+
.sort((a, b) => {
|
|
161
|
+
const aIndex = sortedTables.indexOf(a.name);
|
|
162
|
+
const bIndex = sortedTables.indexOf(b.name);
|
|
163
|
+
return aIndex - bIndex;
|
|
164
|
+
})
|
|
165
|
+
.filter(entity => sortedTables.includes(entity.name));
|
|
166
|
+
|
|
167
|
+
this.logger.log(
|
|
168
|
+
`Migration order: ${orderedEntities.map((e) => e.name).join(" -> ")}`
|
|
169
|
+
);
|
|
170
|
+
|
|
171
|
+
this.logger.log(
|
|
172
|
+
`Discovered ${entityTypes.length} entity types for migration`
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
// Migrate each entity type separately to avoid transaction timeouts
|
|
176
|
+
for (const entity of orderedEntities) {
|
|
177
|
+
await this.batchMigrator.migrateEntityDataInBatches(
|
|
178
|
+
tenantPrisma,
|
|
179
|
+
entity,
|
|
180
|
+
providerId,
|
|
181
|
+
tenantId
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
this.logger.log(`Completed migration for tenant ${tenantId}`);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
this.logger.error(
|
|
188
|
+
`Error migrating data for tenant ${tenantId}: ${error.message}`
|
|
189
|
+
);
|
|
190
|
+
} finally {
|
|
191
|
+
await tenantPrisma.$disconnect();
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { ColumnSchema } from "./types";
|
|
2
|
+
|
|
3
|
+
export class TypecastManager {
|
|
4
|
+
getTypecastForColumn(column: ColumnSchema): string {
|
|
5
|
+
switch (column.data_type.toLowerCase()) {
|
|
6
|
+
case "numeric":
|
|
7
|
+
case "decimal":
|
|
8
|
+
return "::numeric";
|
|
9
|
+
case "integer":
|
|
10
|
+
return "::integer";
|
|
11
|
+
case "bigint":
|
|
12
|
+
return "::bigint";
|
|
13
|
+
case "boolean":
|
|
14
|
+
return "::boolean";
|
|
15
|
+
case "timestamp":
|
|
16
|
+
return "::timestamp";
|
|
17
|
+
case "timestamptz":
|
|
18
|
+
return "::timestamptz";
|
|
19
|
+
case "user-defined":
|
|
20
|
+
// Manejar tipos enum
|
|
21
|
+
if (column.udt_name?.startsWith("enum_")) {
|
|
22
|
+
return `::${column.udt_name}`;
|
|
23
|
+
}
|
|
24
|
+
return "";
|
|
25
|
+
default:
|
|
26
|
+
return "";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Método para generar la expresión de CAST para un tipo enum específico
|
|
31
|
+
getEnumCastExpression(
|
|
32
|
+
schemaName: string,
|
|
33
|
+
enumType: string,
|
|
34
|
+
paramIndex: number
|
|
35
|
+
): string {
|
|
36
|
+
return `CAST($${paramIndex} AS "${schemaName}".${enumType})`;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { Pool } from "pg";
|
|
2
|
+
import { PrismaClient } from "@prisma/client";
|
|
3
|
+
|
|
4
|
+
export interface DatabaseConnections {
|
|
5
|
+
sourcePool: Pool;
|
|
6
|
+
targetPool: Pool;
|
|
7
|
+
sourcePrisma: PrismaClient;
|
|
8
|
+
targetPrisma: PrismaClient;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface ColumnSchema {
|
|
12
|
+
table_name: string;
|
|
13
|
+
column_name: string;
|
|
14
|
+
data_type: string;
|
|
15
|
+
udt_name: string;
|
|
16
|
+
character_maximum_length?: number;
|
|
17
|
+
is_nullable: string;
|
|
18
|
+
column_default?: string;
|
|
19
|
+
constraint_type?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Updated EntityType to include filter configuration
|
|
23
|
+
export interface EntityType {
|
|
24
|
+
name: string; // Table name
|
|
25
|
+
idField: string; // Primary key column name
|
|
26
|
+
filterColumn?: string; // Column used for filtering (either directly or via join)
|
|
27
|
+
filterVia?: string; // Intermediate table for filtering join (if needed)
|
|
28
|
+
// Keep optional legacy fields for potential backward compatibility or specific use cases
|
|
29
|
+
foreignKey?: string;
|
|
30
|
+
joinTable?: string;
|
|
31
|
+
joinField?: string;
|
|
32
|
+
joinForeignKey?: string;
|
|
33
|
+
directQuery?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface EnumCastValue {
|
|
37
|
+
needsEnumCast: boolean;
|
|
38
|
+
value: any;
|
|
39
|
+
enumType: string;
|
|
40
|
+
}
|
|
@@ -0,0 +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();
|
|
105
|
+
}
|
|
@@ -0,0 +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
|
|
62
|
+
|