@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,319 @@
|
|
|
1
|
+
import { Logger } from "@nestjs/common";
|
|
2
|
+
import { Pool } from "pg";
|
|
3
|
+
|
|
4
|
+
interface TableDependency {
|
|
5
|
+
table: string;
|
|
6
|
+
dependencies: string[];
|
|
7
|
+
level?: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class DependencyResolver {
|
|
11
|
+
private readonly logger = new Logger("DependencyResolver");
|
|
12
|
+
private dependencyGraph: Map<string, TableDependency> = new Map();
|
|
13
|
+
|
|
14
|
+
constructor(
|
|
15
|
+
private readonly sourcePool: Pool,
|
|
16
|
+
private readonly targetPool: Pool
|
|
17
|
+
) {}
|
|
18
|
+
|
|
19
|
+
async analyzeDependencies(): Promise<string[]> {
|
|
20
|
+
try {
|
|
21
|
+
// Get all tables
|
|
22
|
+
const tables = await this.getTables();
|
|
23
|
+
|
|
24
|
+
// Build dependency graph
|
|
25
|
+
for (const table of tables) {
|
|
26
|
+
const foreignKeys = await this.getForeignKeys(table);
|
|
27
|
+
|
|
28
|
+
// Add manual dependencies for specific cases
|
|
29
|
+
const manualDependencies = this.getManualDependencies(table);
|
|
30
|
+
const allDependencies = [
|
|
31
|
+
...new Set([...foreignKeys, ...manualDependencies]),
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
this.dependencyGraph.set(table, {
|
|
35
|
+
table,
|
|
36
|
+
dependencies: allDependencies,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Assign levels to tables based on dependencies
|
|
41
|
+
this.assignLevels();
|
|
42
|
+
|
|
43
|
+
// Sort tables by dependency level
|
|
44
|
+
const sortedTables = Array.from(this.dependencyGraph.values())
|
|
45
|
+
.sort((a, b) => (a.level || 0) - (b.level || 0))
|
|
46
|
+
.map((dep) => dep.table);
|
|
47
|
+
|
|
48
|
+
this.logger.log(`Migration order: ${sortedTables.join(" -> ")}`);
|
|
49
|
+
return sortedTables;
|
|
50
|
+
} catch (error) {
|
|
51
|
+
this.logger.error(`Error analyzing dependencies: ${error.message}`);
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private getManualDependencies(tableName: string): string[] {
|
|
57
|
+
// Define manual dependencies for specific cases
|
|
58
|
+
const manualDependencyMap: Record<string, string[]> = {
|
|
59
|
+
api_keys: ["users", "providers"],
|
|
60
|
+
balances: ["users"],
|
|
61
|
+
customers: ["users"],
|
|
62
|
+
global_user_transactions: ["users", "providers", "transactions"],
|
|
63
|
+
invoices: ["transactions"],
|
|
64
|
+
credit_requests: ["users", "invoices"],
|
|
65
|
+
notifications: ["users", "transactions"],
|
|
66
|
+
pending_references: ["users", "providers"],
|
|
67
|
+
daily_logs: ["transactions"],
|
|
68
|
+
transaction_updates: ["transactions"],
|
|
69
|
+
toku: ["transactions"],
|
|
70
|
+
providers: ["countries"],
|
|
71
|
+
users: ["countries"],
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
return manualDependencyMap[tableName] || [];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
private async getTables(): Promise<string[]> {
|
|
78
|
+
const query = `
|
|
79
|
+
SELECT table_name
|
|
80
|
+
FROM information_schema.tables
|
|
81
|
+
WHERE table_schema = 'public'
|
|
82
|
+
AND table_type = 'BASE TABLE'
|
|
83
|
+
AND table_name NOT IN ('_prisma_migrations', 'schema_migrations')
|
|
84
|
+
`;
|
|
85
|
+
|
|
86
|
+
const result = await this.sourcePool.query(query);
|
|
87
|
+
return result.rows.map((row) => row.table_name);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private async getForeignKeys(tableName: string): Promise<string[]> {
|
|
91
|
+
try {
|
|
92
|
+
// Get explicit foreign keys (mantener el query existente)
|
|
93
|
+
const foreignKeyQuery = `
|
|
94
|
+
SELECT DISTINCT
|
|
95
|
+
ccu.table_name AS foreign_table_name,
|
|
96
|
+
kcu.column_name AS column_name
|
|
97
|
+
FROM
|
|
98
|
+
information_schema.table_constraints AS tc
|
|
99
|
+
JOIN information_schema.constraint_column_usage AS ccu
|
|
100
|
+
ON ccu.constraint_name = tc.constraint_name
|
|
101
|
+
JOIN information_schema.key_column_usage AS kcu
|
|
102
|
+
ON kcu.constraint_name = tc.constraint_name
|
|
103
|
+
WHERE
|
|
104
|
+
tc.constraint_type = 'FOREIGN KEY'
|
|
105
|
+
AND tc.table_name = $1
|
|
106
|
+
AND tc.table_schema = 'public'
|
|
107
|
+
`;
|
|
108
|
+
|
|
109
|
+
// Expanded implicit dependencies patterns
|
|
110
|
+
const implicitDependencyQuery = `
|
|
111
|
+
SELECT DISTINCT
|
|
112
|
+
c.column_name,
|
|
113
|
+
c.udt_name,
|
|
114
|
+
c.column_default,
|
|
115
|
+
c.data_type
|
|
116
|
+
FROM
|
|
117
|
+
information_schema.columns c
|
|
118
|
+
WHERE
|
|
119
|
+
c.table_schema = 'public'
|
|
120
|
+
AND c.table_name = $1
|
|
121
|
+
AND (
|
|
122
|
+
-- Common ID patterns
|
|
123
|
+
c.column_name LIKE '%_id'
|
|
124
|
+
OR c.column_name LIKE '%_ids'
|
|
125
|
+
OR c.column_name LIKE 'id_%'
|
|
126
|
+
-- Reference patterns
|
|
127
|
+
OR c.column_name LIKE '%_ref%'
|
|
128
|
+
OR c.column_name LIKE '%_key'
|
|
129
|
+
OR c.column_name LIKE '%_code'
|
|
130
|
+
-- Relationship patterns
|
|
131
|
+
OR c.column_name LIKE '%_by'
|
|
132
|
+
OR c.column_name LIKE '%_to'
|
|
133
|
+
OR c.column_name LIKE '%_from'
|
|
134
|
+
OR c.column_name LIKE 'parent_%'
|
|
135
|
+
OR c.column_name LIKE 'child_%'
|
|
136
|
+
-- JSON/JSONB columns that might contain references
|
|
137
|
+
OR (c.data_type IN ('json', 'jsonb') AND c.column_name LIKE '%_data')
|
|
138
|
+
-- Array columns that might contain IDs
|
|
139
|
+
OR (c.data_type = 'ARRAY' AND c.column_name LIKE '%_ids')
|
|
140
|
+
-- Enum columns that might indicate relationships
|
|
141
|
+
OR (c.udt_name LIKE 'enum_%' AND c.column_name LIKE '%_type')
|
|
142
|
+
)
|
|
143
|
+
`;
|
|
144
|
+
|
|
145
|
+
// Get referenced tables through column comments or descriptions
|
|
146
|
+
const referencedTablesQuery = `
|
|
147
|
+
SELECT DISTINCT
|
|
148
|
+
obj_description(c.table_name::regclass, 'pg_class') as table_comment
|
|
149
|
+
FROM
|
|
150
|
+
information_schema.columns c
|
|
151
|
+
WHERE
|
|
152
|
+
c.table_schema = 'public'
|
|
153
|
+
AND c.table_name = $1
|
|
154
|
+
`;
|
|
155
|
+
|
|
156
|
+
const [fkResult, implicitResult, referencedResult] = await Promise.all([
|
|
157
|
+
this.sourcePool.query(foreignKeyQuery, [tableName]),
|
|
158
|
+
this.sourcePool.query(implicitDependencyQuery, [tableName]),
|
|
159
|
+
this.sourcePool.query(referencedTablesQuery, [tableName]),
|
|
160
|
+
]);
|
|
161
|
+
|
|
162
|
+
const allDependencies = new Set<string>();
|
|
163
|
+
|
|
164
|
+
// Add explicit foreign key dependencies
|
|
165
|
+
fkResult.rows.forEach((row) =>
|
|
166
|
+
allDependencies.add(row.foreign_table_name)
|
|
167
|
+
);
|
|
168
|
+
|
|
169
|
+
// Add implicit dependencies
|
|
170
|
+
implicitResult.rows.forEach((row) => {
|
|
171
|
+
const columnName = row.column_name;
|
|
172
|
+
// Convert column name to potential table name (e.g., user_id -> users)
|
|
173
|
+
const potentialTable = this.inferTableNameFromColumn(columnName);
|
|
174
|
+
if (potentialTable) {
|
|
175
|
+
allDependencies.add(potentialTable);
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
// Parse table comments for additional dependencies
|
|
180
|
+
referencedResult.rows.forEach((row) => {
|
|
181
|
+
if (row.table_comment) {
|
|
182
|
+
const referencedTables = this.parseTableComment(row.table_comment);
|
|
183
|
+
referencedTables.forEach((table) => allDependencies.add(table));
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
// Añadir lógica adicional para procesar los resultados
|
|
188
|
+
implicitResult.rows.forEach((row) => {
|
|
189
|
+
// Procesar columnas JSON/JSONB
|
|
190
|
+
if (row.data_type === "json" || row.data_type === "jsonb") {
|
|
191
|
+
const potentialRefs = this.extractJsonReferences(row.column_name);
|
|
192
|
+
potentialRefs.forEach((ref) => allDependencies.add(ref));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Procesar columnas de tipo enum
|
|
196
|
+
if (row.udt_name?.startsWith("enum_")) {
|
|
197
|
+
const enumTable = this.inferTableFromEnum(row.udt_name);
|
|
198
|
+
if (enumTable) allDependencies.add(enumTable);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Procesar arrays
|
|
202
|
+
if (row.data_type === "ARRAY") {
|
|
203
|
+
const arrayTable = this.inferTableFromArrayColumn(row.column_name);
|
|
204
|
+
if (arrayTable) allDependencies.add(arrayTable);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
return Array.from(allDependencies);
|
|
209
|
+
} catch (error) {
|
|
210
|
+
this.logger.error(
|
|
211
|
+
`Error getting dependencies for ${tableName}: ${error.message}`
|
|
212
|
+
);
|
|
213
|
+
return [];
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
private inferTableFromEnum(enumType: string): string | null {
|
|
218
|
+
// enum_transaction_status -> transactions
|
|
219
|
+
const parts = enumType.split("_");
|
|
220
|
+
if (parts.length > 1) {
|
|
221
|
+
return parts[1];
|
|
222
|
+
}
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
private inferTableFromArrayColumn(columnName: string): string | null {
|
|
227
|
+
// user_ids -> users
|
|
228
|
+
if (columnName.endsWith("_ids")) {
|
|
229
|
+
return columnName.slice(0, -4) + "s";
|
|
230
|
+
}
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
private extractJsonReferences(columnName: string): string[] {
|
|
235
|
+
// metadata_data -> buscar referencias en el nombre
|
|
236
|
+
const refs: string[] = [];
|
|
237
|
+
const parts = columnName.split("_");
|
|
238
|
+
if (parts.length > 1) {
|
|
239
|
+
const potentialTable = parts[0] + "s";
|
|
240
|
+
refs.push(potentialTable);
|
|
241
|
+
}
|
|
242
|
+
return refs;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
private inferTableNameFromColumn(columnName: string): string | null {
|
|
246
|
+
// Remove common suffixes
|
|
247
|
+
const suffixes = ["_id", "_by", "_ref", "_fk"];
|
|
248
|
+
let tableName = columnName;
|
|
249
|
+
|
|
250
|
+
for (const suffix of suffixes) {
|
|
251
|
+
if (tableName.endsWith(suffix)) {
|
|
252
|
+
tableName = tableName.slice(0, -suffix.length);
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Convert to plural form (simple conversion)
|
|
258
|
+
if (!tableName.endsWith("s")) {
|
|
259
|
+
tableName += "s";
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return tableName;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
private parseTableComment(comment: string): string[] {
|
|
266
|
+
// Extract table references from comments
|
|
267
|
+
// Example comment format: "References: users, transactions"
|
|
268
|
+
const referencesMatch = comment.match(/References:\s*([^;]+)/i);
|
|
269
|
+
if (referencesMatch) {
|
|
270
|
+
return referencesMatch[1]
|
|
271
|
+
.split(",")
|
|
272
|
+
.map((table) => table.trim())
|
|
273
|
+
.filter((table) => table.length > 0);
|
|
274
|
+
}
|
|
275
|
+
return [];
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private assignLevels(): void {
|
|
279
|
+
const visited = new Set<string>();
|
|
280
|
+
const visiting = new Set<string>();
|
|
281
|
+
|
|
282
|
+
const visit = (tableName: string, level = 0): number => {
|
|
283
|
+
if (visiting.has(tableName)) {
|
|
284
|
+
this.logger.warn(
|
|
285
|
+
`Circular dependency detected involving table: ${tableName}`
|
|
286
|
+
);
|
|
287
|
+
return level;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (visited.has(tableName)) {
|
|
291
|
+
return this.dependencyGraph.get(tableName)?.level || 0;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
visiting.add(tableName);
|
|
295
|
+
|
|
296
|
+
const node = this.dependencyGraph.get(tableName);
|
|
297
|
+
if (!node) return level;
|
|
298
|
+
|
|
299
|
+
let maxDepLevel = level;
|
|
300
|
+
for (const dep of node.dependencies) {
|
|
301
|
+
const depLevel = visit(dep, level + 1);
|
|
302
|
+
maxDepLevel = Math.max(maxDepLevel, depLevel + 1);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
node.level = maxDepLevel;
|
|
306
|
+
visited.add(tableName);
|
|
307
|
+
visiting.delete(tableName);
|
|
308
|
+
|
|
309
|
+
return maxDepLevel;
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
// Start with all tables
|
|
313
|
+
for (const tableName of this.dependencyGraph.keys()) {
|
|
314
|
+
if (!visited.has(tableName)) {
|
|
315
|
+
visit(tableName);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { Logger } from "@nestjs/common";
|
|
2
|
+
import { Pool } from "pg";
|
|
3
|
+
import { EntityType } from "./types";
|
|
4
|
+
|
|
5
|
+
export class EntityDiscovery {
|
|
6
|
+
private readonly logger = new Logger("EntityDiscovery");
|
|
7
|
+
|
|
8
|
+
constructor(private readonly targetPool: Pool) {}
|
|
9
|
+
|
|
10
|
+
async discoverEntityTypes(
|
|
11
|
+
schemaName: string,
|
|
12
|
+
tables: string[]
|
|
13
|
+
): Promise<EntityType[]> {
|
|
14
|
+
try {
|
|
15
|
+
const entityTypes: EntityType[] = [];
|
|
16
|
+
|
|
17
|
+
for (const tableName of tables) {
|
|
18
|
+
// Obtener la clave primaria de la tabla
|
|
19
|
+
const primaryKey = await this.getPrimaryKey(schemaName, tableName);
|
|
20
|
+
|
|
21
|
+
if (!primaryKey) {
|
|
22
|
+
this.logger.warn(`No primary key found for table ${tableName}, skipping`);
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Obtener las claves foráneas que podrían conectar con un proveedor
|
|
27
|
+
const foreignKeys = await this.getForeignKeys(schemaName, tableName);
|
|
28
|
+
|
|
29
|
+
// Buscar una clave foránea que podría ser provider_id
|
|
30
|
+
const providerForeignKey = foreignKeys.find(fk =>
|
|
31
|
+
fk.column_name.includes('provider_id') ||
|
|
32
|
+
fk.foreign_table_name === 'providers'
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
// Crear la entidad
|
|
36
|
+
const entity: EntityType = {
|
|
37
|
+
name: tableName,
|
|
38
|
+
idField: primaryKey,
|
|
39
|
+
foreignKey: providerForeignKey?.column_name,
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// Si no hay una clave foránea directa a providers, buscar relaciones indirectas
|
|
43
|
+
if (!entity.foreignKey) {
|
|
44
|
+
// Buscar tablas de unión que podrían conectar esta tabla con providers
|
|
45
|
+
const joinTables = await this.findJoinTables(
|
|
46
|
+
schemaName,
|
|
47
|
+
tableName,
|
|
48
|
+
'providers'
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
if (joinTables.length > 0) {
|
|
52
|
+
const joinTable = joinTables[0];
|
|
53
|
+
entity.joinTable = joinTable.join_table;
|
|
54
|
+
entity.joinField = joinTable.source_column;
|
|
55
|
+
entity.joinForeignKey = joinTable.target_column;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
entityTypes.push(entity);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return entityTypes;
|
|
63
|
+
} catch (error) {
|
|
64
|
+
this.logger.error(`Error discovering entity types: ${error.message}`);
|
|
65
|
+
return [];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private async getPrimaryKey(
|
|
70
|
+
schemaName: string,
|
|
71
|
+
tableName: string
|
|
72
|
+
): Promise<string | null> {
|
|
73
|
+
const query = `
|
|
74
|
+
SELECT a.attname
|
|
75
|
+
FROM pg_index i
|
|
76
|
+
JOIN pg_attribute a ON a.attrelid = i.indrelid
|
|
77
|
+
AND a.attnum = ANY(i.indkey)
|
|
78
|
+
WHERE i.indrelid = '"${schemaName}"."${tableName}"'::regclass
|
|
79
|
+
AND i.indisprimary;
|
|
80
|
+
`;
|
|
81
|
+
|
|
82
|
+
try {
|
|
83
|
+
const { rows } = await this.targetPool.query(query);
|
|
84
|
+
return rows.length > 0 ? rows[0].attname : null;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
this.logger.error(`Error getting primary key for ${tableName}: ${error.message}`);
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private async getForeignKeys(
|
|
92
|
+
schemaName: string,
|
|
93
|
+
tableName: string
|
|
94
|
+
): Promise<Array<{
|
|
95
|
+
column_name: string;
|
|
96
|
+
foreign_table_name: string;
|
|
97
|
+
foreign_column_name: string;
|
|
98
|
+
}>> {
|
|
99
|
+
const query = `
|
|
100
|
+
SELECT
|
|
101
|
+
kcu.column_name,
|
|
102
|
+
ccu.table_name AS foreign_table_name,
|
|
103
|
+
ccu.column_name AS foreign_column_name
|
|
104
|
+
FROM
|
|
105
|
+
information_schema.table_constraints tc
|
|
106
|
+
JOIN information_schema.key_column_usage kcu
|
|
107
|
+
ON tc.constraint_name = kcu.constraint_name
|
|
108
|
+
AND tc.table_schema = kcu.table_schema
|
|
109
|
+
JOIN information_schema.constraint_column_usage ccu
|
|
110
|
+
ON ccu.constraint_name = tc.constraint_name
|
|
111
|
+
AND ccu.table_schema = tc.table_schema
|
|
112
|
+
WHERE
|
|
113
|
+
tc.constraint_type = 'FOREIGN KEY'
|
|
114
|
+
AND tc.table_schema = $1
|
|
115
|
+
AND tc.table_name = $2;
|
|
116
|
+
`;
|
|
117
|
+
|
|
118
|
+
try {
|
|
119
|
+
const { rows } = await this.targetPool.query(query, [schemaName, tableName]);
|
|
120
|
+
return rows;
|
|
121
|
+
} catch (error) {
|
|
122
|
+
this.logger.error(`Error getting foreign keys for ${tableName}: ${error.message}`);
|
|
123
|
+
return [];
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private async findJoinTables(
|
|
128
|
+
schemaName: string,
|
|
129
|
+
sourceTable: string,
|
|
130
|
+
targetTable: string
|
|
131
|
+
): Promise<Array<{
|
|
132
|
+
join_table: string;
|
|
133
|
+
source_column: string;
|
|
134
|
+
target_column: string;
|
|
135
|
+
}>> {
|
|
136
|
+
// Buscar tablas que tienen claves foráneas tanto a sourceTable como a targetTable
|
|
137
|
+
const query = `
|
|
138
|
+
WITH source_fks AS (
|
|
139
|
+
SELECT
|
|
140
|
+
tc.table_name,
|
|
141
|
+
kcu.column_name,
|
|
142
|
+
ccu.table_name AS referenced_table
|
|
143
|
+
FROM
|
|
144
|
+
information_schema.table_constraints tc
|
|
145
|
+
JOIN information_schema.key_column_usage kcu
|
|
146
|
+
ON tc.constraint_name = kcu.constraint_name
|
|
147
|
+
AND tc.table_schema = kcu.table_schema
|
|
148
|
+
JOIN information_schema.constraint_column_usage ccu
|
|
149
|
+
ON ccu.constraint_name = tc.constraint_name
|
|
150
|
+
AND ccu.table_schema = tc.table_schema
|
|
151
|
+
WHERE
|
|
152
|
+
tc.constraint_type = 'FOREIGN KEY'
|
|
153
|
+
AND tc.table_schema = $1
|
|
154
|
+
AND ccu.table_name = $2
|
|
155
|
+
),
|
|
156
|
+
target_fks AS (
|
|
157
|
+
SELECT
|
|
158
|
+
tc.table_name,
|
|
159
|
+
kcu.column_name,
|
|
160
|
+
ccu.table_name AS referenced_table
|
|
161
|
+
FROM
|
|
162
|
+
information_schema.table_constraints tc
|
|
163
|
+
JOIN information_schema.key_column_usage kcu
|
|
164
|
+
ON tc.constraint_name = kcu.constraint_name
|
|
165
|
+
AND tc.table_schema = kcu.table_schema
|
|
166
|
+
JOIN information_schema.constraint_column_usage ccu
|
|
167
|
+
ON ccu.constraint_name = tc.constraint_name
|
|
168
|
+
AND ccu.table_schema = tc.table_schema
|
|
169
|
+
WHERE
|
|
170
|
+
tc.constraint_type = 'FOREIGN KEY'
|
|
171
|
+
AND tc.table_schema = $1
|
|
172
|
+
AND ccu.table_name = $3
|
|
173
|
+
)
|
|
174
|
+
SELECT
|
|
175
|
+
s.table_name AS join_table,
|
|
176
|
+
s.column_name AS source_column,
|
|
177
|
+
t.column_name AS target_column
|
|
178
|
+
FROM
|
|
179
|
+
source_fks s
|
|
180
|
+
JOIN target_fks t ON s.table_name = t.table_name
|
|
181
|
+
`;
|
|
182
|
+
|
|
183
|
+
try {
|
|
184
|
+
const { rows } = await this.targetPool.query(query, [
|
|
185
|
+
schemaName,
|
|
186
|
+
sourceTable,
|
|
187
|
+
targetTable,
|
|
188
|
+
]);
|
|
189
|
+
return rows;
|
|
190
|
+
} catch (error) {
|
|
191
|
+
this.logger.error(
|
|
192
|
+
`Error finding join tables between ${sourceTable} and ${targetTable}: ${error.message}`
|
|
193
|
+
);
|
|
194
|
+
return [];
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { Logger } from "@nestjs/common";
|
|
2
|
+
import { PrismaClient } from "@prisma/client";
|
|
3
|
+
import { DatabaseConnections } from "./types";
|
|
4
|
+
|
|
5
|
+
export class ForeignKeyManager {
|
|
6
|
+
private readonly logger = new Logger("ForeignKeyManager");
|
|
7
|
+
|
|
8
|
+
constructor(private readonly connections: DatabaseConnections) {}
|
|
9
|
+
|
|
10
|
+
async getForeignKeyDependencies(
|
|
11
|
+
schemaName: string,
|
|
12
|
+
tableName: string
|
|
13
|
+
): Promise<
|
|
14
|
+
Array<{ column: string; foreignTable: string; foreignColumn: string }>
|
|
15
|
+
> {
|
|
16
|
+
try {
|
|
17
|
+
const query = `
|
|
18
|
+
SELECT
|
|
19
|
+
kcu.column_name,
|
|
20
|
+
ccu.table_name AS foreign_table_name,
|
|
21
|
+
ccu.column_name AS foreign_column_name
|
|
22
|
+
FROM
|
|
23
|
+
information_schema.table_constraints tc
|
|
24
|
+
JOIN information_schema.key_column_usage kcu
|
|
25
|
+
ON tc.constraint_name = kcu.constraint_name
|
|
26
|
+
AND tc.table_schema = kcu.table_schema
|
|
27
|
+
JOIN information_schema.constraint_column_usage ccu
|
|
28
|
+
ON ccu.constraint_name = tc.constraint_name
|
|
29
|
+
AND ccu.table_schema = tc.table_schema
|
|
30
|
+
WHERE
|
|
31
|
+
tc.constraint_type = 'FOREIGN KEY'
|
|
32
|
+
AND tc.table_schema = $1
|
|
33
|
+
AND tc.table_name = $2;
|
|
34
|
+
`;
|
|
35
|
+
|
|
36
|
+
const { rows } = await this.connections.targetPool.query(query, [
|
|
37
|
+
schemaName,
|
|
38
|
+
tableName,
|
|
39
|
+
]);
|
|
40
|
+
return rows.map((row) => ({
|
|
41
|
+
column: row.column_name,
|
|
42
|
+
foreignTable: row.foreign_table_name,
|
|
43
|
+
foreignColumn: row.foreign_column_name,
|
|
44
|
+
}));
|
|
45
|
+
} catch (error) {
|
|
46
|
+
this.logger.error(
|
|
47
|
+
`Error getting foreign key dependencies for ${tableName}: ${error.message}`
|
|
48
|
+
);
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async checkForeignKeyDependencies(
|
|
54
|
+
prisma: PrismaClient,
|
|
55
|
+
schemaName: string,
|
|
56
|
+
row: any,
|
|
57
|
+
dependencies: Array<{
|
|
58
|
+
column: string;
|
|
59
|
+
foreignTable: string;
|
|
60
|
+
foreignColumn: string;
|
|
61
|
+
}>
|
|
62
|
+
): Promise<string[]> {
|
|
63
|
+
const missingDependencies: string[] = [];
|
|
64
|
+
|
|
65
|
+
for (const dep of dependencies) {
|
|
66
|
+
if (row[dep.column] !== null) {
|
|
67
|
+
const query = `
|
|
68
|
+
SELECT 1 FROM "${schemaName}"."${dep.foreignTable}"
|
|
69
|
+
WHERE "${dep.foreignColumn}" = $1
|
|
70
|
+
LIMIT 1
|
|
71
|
+
`;
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
const result = await prisma.$queryRawUnsafe(query, row[dep.column]);
|
|
75
|
+
if (!result || (Array.isArray(result) && result.length === 0)) {
|
|
76
|
+
missingDependencies.push(
|
|
77
|
+
`${dep.foreignTable}.${dep.foreignColumn}=${row[dep.column]}`
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
} catch (error) {
|
|
81
|
+
this.logger.error(
|
|
82
|
+
`Error checking dependency ${dep.foreignTable}.${dep.foreignColumn}: ${error.message}`
|
|
83
|
+
);
|
|
84
|
+
missingDependencies.push(
|
|
85
|
+
`${dep.foreignTable}.${dep.foreignColumn}=${
|
|
86
|
+
row[dep.column]
|
|
87
|
+
} (error)`
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return missingDependencies;
|
|
94
|
+
}
|
|
95
|
+
}
|