orchid-orm 1.55.1 → 1.56.2

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,3191 @@
1
+ import { promptSelect, getSchemaAndTableFromName, getDbTableColumnsChecks, dbColumnToAst, instantiateDbColumn, concatSchemaAndName, encodeColumnDefault, getIndexName, getExcludeName, getConstraintName, tableToAst, getDbStructureTableData, makeDomainsMap, astToMigration, createMigrationInterface, introspectDbSchema, makeStructureToAstCtx, makeFileVersion, writeMigrationFile, migrateAndClose, migrate, structureToAst, saveMigratedVersion, rakeDbCommands } from 'rake-db';
2
+ import { colors, toSnakeCase, deepCompare, emptyArray, toArray, exhaustive, toCamelCase, addCode, pluralize, codeToString, toPascalCase, getImportPath, singleQuote, quoteObjectKey, pathToLog } from 'orchid-core';
3
+ import { EnumColumn, ArrayColumn, getColumnBaseType, RawSQL, VirtualColumn, DomainColumn, UnknownColumn, defaultSchemaConfig, columnsShapeToCode, pushTableDataCode } from 'pqb';
4
+ import path from 'node:path';
5
+ import { pathToFileURL } from 'url';
6
+ import fs from 'fs/promises';
7
+ import typescript from 'typescript';
8
+ export * from 'rake-db/node-postgres';
9
+
10
+ const compareSqlExpressions = async (tableExpressions, adapter) => {
11
+ if (tableExpressions.length) {
12
+ let id = 1;
13
+ await Promise.all(
14
+ tableExpressions.map(async ({ source, compare, handle }) => {
15
+ const viewName = `orchidTmpView${id++}`;
16
+ const values = [];
17
+ let result;
18
+ try {
19
+ const results = await adapter.query(
20
+ // It is important to run `CREATE TEMPORARY VIEW` and `DROP VIEW` on the same db connection,
21
+ // that's why SQLs are combined into a single query.
22
+ [
23
+ `CREATE TEMPORARY VIEW ${viewName} AS (SELECT ${compare.map(
24
+ ({ inDb, inCode }, i) => `${inDb} AS "*inDb-${i}*", ${inCode.map(
25
+ (s, j) => `(${typeof s === "string" ? s : s.toSQL({ values })}) "*inCode-${i}-${j}*"`
26
+ ).join(", ")}`
27
+ ).join(", ")} FROM ${source})`,
28
+ `SELECT pg_get_viewdef('${viewName}') v`,
29
+ `DROP VIEW ${viewName}`
30
+ ].join("; "),
31
+ values
32
+ );
33
+ result = results[1];
34
+ } catch {
35
+ }
36
+ if (!result) {
37
+ handle();
38
+ return;
39
+ }
40
+ const match = compareSqlExpressionResult(
41
+ result.rows[0].v,
42
+ compare[0].inCode
43
+ );
44
+ handle(match);
45
+ })
46
+ );
47
+ }
48
+ };
49
+ const compareSqlExpressionResult = (resultSql, inCode) => {
50
+ let pos = 7;
51
+ const rgx = /\s+AS\s+"\*(inDb-\d+|inCode-\d+-\d+)\*",?/g;
52
+ let match;
53
+ let inDb = "";
54
+ let codeI = 0;
55
+ const matches = inCode.map(() => true);
56
+ while (match = rgx.exec(resultSql)) {
57
+ const sql = resultSql.slice(pos, rgx.lastIndex - match[0].length).trim();
58
+ const arr = match[1].split("-");
59
+ if (arr.length === 2) {
60
+ inDb = sql;
61
+ codeI = 0;
62
+ } else {
63
+ if (inDb !== sql && // Comparing `(sql) = sql` and `sql = (sql)` below.
64
+ // Could not reproduce this case in integration tests, but it was reported in #494.
65
+ !(inDb.startsWith("(") && inDb.endsWith(")") && inDb.slice(1, -1) === sql) && !(sql.startsWith("(") && sql.endsWith(")") && sql.slice(1, -1) === inDb)) {
66
+ matches[codeI] = false;
67
+ }
68
+ codeI++;
69
+ }
70
+ pos = rgx.lastIndex;
71
+ }
72
+ const firstMatching = matches.indexOf(true);
73
+ return firstMatching === -1 ? void 0 : firstMatching;
74
+ };
75
+ const promptCreateOrRename = (kind, name, drop, verifying) => {
76
+ if (verifying) throw new AbortSignal();
77
+ let hintPos = name.length + 4;
78
+ for (const from of drop) {
79
+ const value = from.length + 8 + name.length;
80
+ if (value > hintPos) hintPos = value;
81
+ }
82
+ let max = 0;
83
+ const add = name.length + 3;
84
+ for (const name2 of drop) {
85
+ if (name2.length + add > max) {
86
+ max = name2.length + add;
87
+ }
88
+ }
89
+ const renameMessage = `rename ${kind}`;
90
+ return promptSelect({
91
+ message: `Create or rename ${colors.blueBold(
92
+ name
93
+ )} ${kind} from another ${kind}?`,
94
+ options: [
95
+ `${colors.greenBold("+")} ${name} ${colors.pale(
96
+ `create ${kind}`.padStart(
97
+ hintPos + renameMessage.length - name.length - 4,
98
+ " "
99
+ )
100
+ )}`,
101
+ ...drop.map(
102
+ (d) => `${colors.yellowBold("~")} ${d} ${colors.yellowBold(
103
+ "=>"
104
+ )} ${name} ${colors.pale(
105
+ renameMessage.padStart(
106
+ hintPos + renameMessage.length - d.length - name.length - 8,
107
+ " "
108
+ )
109
+ )}`
110
+ )
111
+ ]
112
+ });
113
+ };
114
+ const checkForColumnAddOrDrop = (shape, key) => {
115
+ const item = shape[key];
116
+ if (item) {
117
+ return item && (Array.isArray(item) || item.type === "add" || item.type === "drop");
118
+ }
119
+ for (const k in shape) {
120
+ const item2 = shape[k];
121
+ if (Array.isArray(item2) ? item2.some(
122
+ (item3) => (item3.type === "add" || item3.type === "drop") && item3.item.data.name === key
123
+ ) : (item2.type === "add" || item2.type === "drop") && item2.item.data.name === key) {
124
+ return true;
125
+ }
126
+ }
127
+ return false;
128
+ };
129
+
130
+ const processSchemas = async (ast, dbStructure, {
131
+ codeItems: { schemas },
132
+ verifying,
133
+ internal: { generatorIgnore }
134
+ }) => {
135
+ const createSchemas = [];
136
+ const dropSchemas = [];
137
+ for (const schema of schemas) {
138
+ if (!dbStructure.schemas.includes(schema)) {
139
+ createSchemas.push(schema);
140
+ }
141
+ }
142
+ for (const schema of dbStructure.schemas) {
143
+ if (!schemas.has(schema) && schema !== "public" && !generatorIgnore?.schemas?.includes(schema)) {
144
+ dropSchemas.push(schema);
145
+ }
146
+ }
147
+ for (const schema of createSchemas) {
148
+ if (dropSchemas.length) {
149
+ const i = await promptCreateOrRename(
150
+ "schema",
151
+ schema,
152
+ dropSchemas,
153
+ verifying
154
+ );
155
+ if (i) {
156
+ const from = dropSchemas[i - 1];
157
+ dropSchemas.splice(i - 1, 1);
158
+ renameSchemaInStructures(dbStructure.tables, from, schema);
159
+ renameSchemaInStructures(dbStructure.views, from, schema);
160
+ renameSchemaInStructures(dbStructure.indexes, from, schema);
161
+ renameSchemaInStructures(dbStructure.excludes, from, schema);
162
+ renameSchemaInStructures(dbStructure.constraints, from, schema);
163
+ renameSchemaInStructures(dbStructure.triggers, from, schema);
164
+ renameSchemaInStructures(dbStructure.enums, from, schema);
165
+ renameSchemaInStructures(dbStructure.domains, from, schema);
166
+ renameSchemaInStructures(dbStructure.collations, from, schema);
167
+ for (const table of dbStructure.tables) {
168
+ for (const column of table.columns) {
169
+ if (column.typeSchema === from) {
170
+ column.typeSchema = schema;
171
+ }
172
+ }
173
+ }
174
+ ast.push({
175
+ type: "renameSchema",
176
+ from,
177
+ to: schema
178
+ });
179
+ continue;
180
+ }
181
+ }
182
+ ast.push({
183
+ type: "schema",
184
+ action: "create",
185
+ name: schema
186
+ });
187
+ }
188
+ for (const schema of dropSchemas) {
189
+ ast.push({
190
+ type: "schema",
191
+ action: "drop",
192
+ name: schema
193
+ });
194
+ }
195
+ };
196
+ const renameSchemaInStructures = (items, from, to) => {
197
+ for (const item of items) {
198
+ if (item.schemaName === from) {
199
+ item.schemaName = to;
200
+ }
201
+ }
202
+ };
203
+
204
+ const processExtensions = (ast, dbStructure, {
205
+ currentSchema,
206
+ internal: { extensions, generatorIgnore }
207
+ }) => {
208
+ const codeExtensions = extensions?.map((ext) => {
209
+ const [schema, name] = getSchemaAndTableFromName(ext.name);
210
+ return { schema, name, version: ext.version };
211
+ });
212
+ for (const dbExt of dbStructure.extensions) {
213
+ if (generatorIgnore?.schemas?.includes(dbExt.schemaName) || generatorIgnore?.extensions?.includes(dbExt.name)) {
214
+ continue;
215
+ }
216
+ if (codeExtensions) {
217
+ let found = false;
218
+ for (let i = 0; i < codeExtensions.length; i++) {
219
+ const codeExt = codeExtensions[i];
220
+ if (dbExt.name === codeExt.name && dbExt.schemaName === (codeExt.schema ?? currentSchema) && (!codeExt.version || codeExt.version === dbExt.version)) {
221
+ found = true;
222
+ codeExtensions.splice(i, 1);
223
+ break;
224
+ }
225
+ }
226
+ if (found) continue;
227
+ }
228
+ ast.push({
229
+ type: "extension",
230
+ action: "drop",
231
+ schema: dbExt.schemaName === currentSchema ? void 0 : dbExt.schemaName,
232
+ name: dbExt.name,
233
+ version: dbExt.version
234
+ });
235
+ }
236
+ if (codeExtensions?.length) {
237
+ ast.push(
238
+ ...codeExtensions.map((ext) => ({
239
+ type: "extension",
240
+ action: "create",
241
+ ...ext
242
+ }))
243
+ );
244
+ }
245
+ };
246
+
247
+ const processColumns = async (adapter, config, structureToAstCtx, dbStructure, domainsMap, changeTableData, ast, currentSchema, compareSql, typeCastsCache, verifying) => {
248
+ const { dbTable } = changeTableData;
249
+ const dbColumns = Object.fromEntries(
250
+ dbTable.columns.map((column) => [column.name, column])
251
+ );
252
+ const { columnsToAdd, columnsToDrop, columnsToChange } = groupColumns(
253
+ structureToAstCtx,
254
+ dbStructure,
255
+ domainsMap,
256
+ dbColumns,
257
+ changeTableData
258
+ );
259
+ await addOrRenameColumns(
260
+ config,
261
+ dbStructure,
262
+ changeTableData,
263
+ columnsToAdd,
264
+ columnsToDrop,
265
+ columnsToChange,
266
+ verifying
267
+ );
268
+ await changeColumns(
269
+ adapter,
270
+ config,
271
+ structureToAstCtx,
272
+ dbStructure,
273
+ domainsMap,
274
+ ast,
275
+ currentSchema,
276
+ dbColumns,
277
+ columnsToChange,
278
+ compareSql,
279
+ changeTableData,
280
+ typeCastsCache,
281
+ verifying
282
+ );
283
+ dropColumns(changeTableData, columnsToDrop);
284
+ };
285
+ const groupColumns = (structureToAstCtx, dbStructure, domainsMap, dbColumns, changeTableData) => {
286
+ const columnsToAdd = [];
287
+ const columnsToDrop = [];
288
+ const columnsToChange = /* @__PURE__ */ new Map();
289
+ const columnsToChangeByDbName = /* @__PURE__ */ new Map();
290
+ const { codeTable, dbTable, dbTableData } = changeTableData;
291
+ const checks = getDbTableColumnsChecks(changeTableData.dbTableData);
292
+ for (const key in codeTable.shape) {
293
+ const column = codeTable.shape[key];
294
+ if (!column.dataType) continue;
295
+ const name = column.data.name ?? key;
296
+ if (dbColumns[name]) {
297
+ columnsToChange.set(key, { key, dbName: name, column });
298
+ columnsToChangeByDbName.set(name, true);
299
+ } else {
300
+ columnsToAdd.push({ key, column });
301
+ }
302
+ }
303
+ for (const name in dbColumns) {
304
+ if (columnsToChangeByDbName.has(name)) continue;
305
+ const [key, column] = dbColumnToAst(
306
+ structureToAstCtx,
307
+ dbStructure,
308
+ domainsMap,
309
+ dbTable.name,
310
+ dbColumns[name],
311
+ dbTable,
312
+ dbTableData,
313
+ checks
314
+ );
315
+ columnsToDrop.push({ key, column });
316
+ }
317
+ return {
318
+ columnsToAdd,
319
+ columnsToDrop,
320
+ columnsToChange
321
+ };
322
+ };
323
+ const addOrRenameColumns = async (config, dbStructure, {
324
+ dbTableData,
325
+ schema,
326
+ changeTableAst: { name: tableName, shape }
327
+ }, columnsToAdd, columnsToDrop, columnsToChange, verifying) => {
328
+ for (const { key, column } of columnsToAdd) {
329
+ if (columnsToDrop.length) {
330
+ const codeName = column.data.name ?? key;
331
+ const i = await promptCreateOrRename(
332
+ "column",
333
+ codeName,
334
+ columnsToDrop.map((x) => x.key),
335
+ verifying
336
+ );
337
+ if (i) {
338
+ const drop = columnsToDrop[i - 1];
339
+ columnsToDrop.splice(i - 1, 1);
340
+ const from = drop.column.data.name ?? drop.key;
341
+ columnsToChange.set(from, {
342
+ key,
343
+ dbName: from,
344
+ column: column.name(codeName)
345
+ });
346
+ const to = config.snakeCase ? toSnakeCase(key) : key;
347
+ if (dbTableData.primaryKey) {
348
+ renameColumn(dbTableData.primaryKey.columns, from, to);
349
+ }
350
+ for (const index of dbTableData.indexes) {
351
+ for (const column2 of index.columns) {
352
+ if ("column" in column2 && column2.column === from) {
353
+ column2.column = to;
354
+ }
355
+ }
356
+ }
357
+ for (const exclude of dbTableData.excludes) {
358
+ for (const column2 of exclude.columns) {
359
+ if ("column" in column2 && column2.column === from) {
360
+ column2.column = to;
361
+ }
362
+ }
363
+ }
364
+ for (const c of dbTableData.constraints) {
365
+ if (c.check?.columns) {
366
+ renameColumn(c.check.columns, from, to);
367
+ }
368
+ if (c.references) {
369
+ renameColumn(c.references.columns, from, to);
370
+ }
371
+ }
372
+ for (const c of dbStructure.constraints) {
373
+ if (c.references && c.references.foreignSchema === schema && c.references.foreignTable === tableName) {
374
+ renameColumn(c.references.foreignColumns, from, to);
375
+ }
376
+ }
377
+ continue;
378
+ }
379
+ }
380
+ shape[key] = {
381
+ type: "add",
382
+ item: column
383
+ };
384
+ }
385
+ };
386
+ const dropColumns = ({ changeTableAst: { shape } }, columnsToDrop) => {
387
+ for (const { key, column } of columnsToDrop) {
388
+ shape[key] = {
389
+ type: "drop",
390
+ item: column
391
+ };
392
+ }
393
+ };
394
+ const changeColumns = async (adapter, config, structureToAstCtx, dbStructure, domainsMap, ast, currentSchema, dbColumns, columnsToChange, compareSql, changeTableData, typeCastsCache, verifying) => {
395
+ for (const [
396
+ key,
397
+ { key: codeKey, dbName, column: codeColumn }
398
+ ] of columnsToChange) {
399
+ const dbColumnStructure = dbColumns[dbName];
400
+ const dbColumn = instantiateDbColumn(
401
+ structureToAstCtx,
402
+ dbStructure,
403
+ domainsMap,
404
+ dbColumnStructure
405
+ );
406
+ const action = await compareColumns(
407
+ adapter,
408
+ domainsMap,
409
+ ast,
410
+ currentSchema,
411
+ compareSql,
412
+ changeTableData,
413
+ typeCastsCache,
414
+ verifying,
415
+ key,
416
+ dbName,
417
+ dbColumn,
418
+ codeColumn
419
+ );
420
+ if (action === "change") {
421
+ changeColumn(changeTableData, key, dbName, dbColumn, codeColumn);
422
+ } else if (action === "recreate") {
423
+ changeTableData.changeTableAst.shape[key] = [
424
+ {
425
+ type: "drop",
426
+ item: dbColumn
427
+ },
428
+ {
429
+ type: "add",
430
+ item: codeColumn
431
+ }
432
+ ];
433
+ } else if (action !== "recreate") {
434
+ const to = codeColumn.data.name ?? codeKey;
435
+ if (dbName !== to) {
436
+ changeTableData.changeTableAst.shape[config.snakeCase ? dbName === toSnakeCase(codeKey) ? codeKey : dbName : dbName] = {
437
+ type: "rename",
438
+ name: config.snakeCase ? to === toSnakeCase(codeKey) ? codeKey : to : to
439
+ };
440
+ }
441
+ }
442
+ }
443
+ };
444
+ const compareColumns = async (adapter, domainsMap, ast, currentSchema, compareSql, changeTableData, typeCastsCache, verifying, key, dbName, dbColumn, codeColumn) => {
445
+ if (dbColumn instanceof ArrayColumn && codeColumn instanceof ArrayColumn) {
446
+ dbColumn = dbColumn.data.item;
447
+ codeColumn = codeColumn.data.item;
448
+ }
449
+ const dbType = getColumnDbType(dbColumn, currentSchema);
450
+ const codeType = getColumnDbType(codeColumn, currentSchema);
451
+ if (dbType !== codeType) {
452
+ const typeCasts = await getTypeCasts(adapter, typeCastsCache);
453
+ const dbBaseType = getColumnBaseType(dbColumn, domainsMap, dbType);
454
+ const codeBaseType = getColumnBaseType(codeColumn, domainsMap, codeType);
455
+ if (!typeCasts.get(dbBaseType)?.has(codeBaseType)) {
456
+ if (!(dbColumn instanceof EnumColumn) || !(codeColumn instanceof EnumColumn) || !deepCompare(dbColumn.options, codeColumn.options)) {
457
+ if (verifying) throw new AbortSignal();
458
+ const tableName = concatSchemaAndName(changeTableData.changeTableAst);
459
+ const abort = await promptSelect({
460
+ message: `Cannot cast type of ${tableName}'s column ${key} from ${dbType} to ${codeType}`,
461
+ options: [
462
+ `${colors.yellowBold(
463
+ `-/+`
464
+ )} recreate the column, existing data will be ${colors.red(
465
+ "lost"
466
+ )}`,
467
+ `write migration manually`
468
+ ]
469
+ });
470
+ if (abort) {
471
+ throw new AbortSignal();
472
+ }
473
+ dbColumn.data.name = codeColumn.data.name;
474
+ return "recreate";
475
+ }
476
+ }
477
+ return "change";
478
+ }
479
+ const dbData = dbColumn.data;
480
+ const codeData = codeColumn.data;
481
+ for (const key2 of ["isNullable", "comment"]) {
482
+ if (dbData[key2] !== codeData[key2]) {
483
+ return "change";
484
+ }
485
+ }
486
+ for (const key2 of [
487
+ "maxChars",
488
+ "collation",
489
+ "compression",
490
+ "numericPrecision",
491
+ "numericScale",
492
+ "dateTimePrecision"
493
+ ]) {
494
+ if (key2 in codeData && dbData[key2] !== codeData[key2]) {
495
+ return "change";
496
+ }
497
+ }
498
+ if (dbColumn.data.isOfCustomType) {
499
+ const { typmod } = dbColumn.data;
500
+ if (typmod !== void 0 && typmod !== -1) {
501
+ const i = codeColumn.dataType.indexOf("(");
502
+ if (i === -1 || codeColumn.dataType.slice(i + 1, -1) !== `${typmod}`) {
503
+ return "change";
504
+ }
505
+ }
506
+ }
507
+ if (!deepCompare(
508
+ dbData.identity,
509
+ codeData.identity ? {
510
+ always: false,
511
+ start: 1,
512
+ increment: 1,
513
+ cache: 1,
514
+ cycle: false,
515
+ ...codeData.identity ?? {}
516
+ } : void 0
517
+ )) {
518
+ return "change";
519
+ }
520
+ if (dbData.default !== void 0 && dbData.default !== null && codeData.default !== void 0 && codeData.default !== null) {
521
+ const valuesBeforeLen = compareSql.values.length;
522
+ const dbDefault = encodeColumnDefault(
523
+ dbData.default,
524
+ compareSql.values,
525
+ dbColumn
526
+ );
527
+ const dbValues = compareSql.values.slice(valuesBeforeLen);
528
+ const codeDefault = encodeColumnDefault(
529
+ codeData.default,
530
+ compareSql.values,
531
+ codeColumn
532
+ );
533
+ const codeValues = compareSql.values.slice(valuesBeforeLen);
534
+ if (dbValues.length !== codeValues.length || dbValues.length && JSON.stringify(dbValues) !== JSON.stringify(codeValues)) {
535
+ compareSql.values.length = valuesBeforeLen;
536
+ return "change";
537
+ } else if (dbDefault !== codeDefault && dbDefault !== `(${codeDefault})`) {
538
+ compareSql.expressions.push({
539
+ inDb: dbDefault,
540
+ inCode: codeDefault,
541
+ change: () => {
542
+ changeColumn(changeTableData, key, dbName, dbColumn, codeColumn);
543
+ if (!changeTableData.pushedAst) {
544
+ changeTableData.pushedAst = true;
545
+ ast.push(changeTableData.changeTableAst);
546
+ }
547
+ }
548
+ });
549
+ }
550
+ }
551
+ return;
552
+ };
553
+ const getTypeCasts = async (adapter, typeCastsCache) => {
554
+ let typeCasts = typeCastsCache.value;
555
+ if (!typeCasts) {
556
+ const { rows } = await adapter.arrays(`SELECT s.typname, t.typname
557
+ FROM pg_cast
558
+ JOIN pg_type AS s ON s.oid = castsource
559
+ JOIN pg_type AS t ON t.oid = casttarget`);
560
+ const directTypeCasts = /* @__PURE__ */ new Map();
561
+ for (const [source, target] of rows) {
562
+ const set = directTypeCasts.get(source);
563
+ if (set) {
564
+ set.add(target);
565
+ } else {
566
+ directTypeCasts.set(source, /* @__PURE__ */ new Set([target]));
567
+ }
568
+ }
569
+ typeCasts = /* @__PURE__ */ new Map();
570
+ for (const [type, directSet] of directTypeCasts.entries()) {
571
+ const set = new Set(directSet);
572
+ typeCasts.set(type, set);
573
+ for (const subtype of directSet) {
574
+ const subset = directTypeCasts.get(subtype);
575
+ if (subset) {
576
+ for (const type2 of subset) {
577
+ set.add(type2);
578
+ }
579
+ }
580
+ }
581
+ }
582
+ typeCastsCache.value = typeCasts;
583
+ }
584
+ return typeCasts;
585
+ };
586
+ const changeColumn = (changeTableData, key, dbName, dbColumn, codeColumn) => {
587
+ dbColumn.data.as = codeColumn.data.as = void 0;
588
+ const simpleCodeColumn = Object.create(codeColumn);
589
+ simpleCodeColumn.data = {
590
+ ...codeColumn.data,
591
+ primaryKey: void 0,
592
+ indexes: void 0,
593
+ excludes: void 0,
594
+ foreignKeys: void 0,
595
+ check: void 0
596
+ };
597
+ changeTableData.changingColumns[dbName] = {
598
+ from: dbColumn,
599
+ to: simpleCodeColumn
600
+ };
601
+ changeTableData.changeTableAst.shape[key] = {
602
+ type: "change",
603
+ from: { column: dbColumn },
604
+ to: { column: simpleCodeColumn }
605
+ };
606
+ };
607
+ const getColumnDbType = (column, currentSchema) => {
608
+ if (column instanceof EnumColumn) {
609
+ const [schema = currentSchema, name] = getSchemaAndTableFromName(
610
+ column.enumName
611
+ );
612
+ return column.enumName = `${schema}.${name}`;
613
+ } else if (column instanceof ArrayColumn) {
614
+ const { item } = column.data;
615
+ let type = item instanceof EnumColumn ? item.enumName : item.dataType;
616
+ type = type.startsWith(currentSchema + ".") ? type.slice(currentSchema.length + 1) : type;
617
+ return type + "[]".repeat(column.data.arrayDims);
618
+ } else if (column.data.isOfCustomType) {
619
+ let type = column.dataType;
620
+ const i = type.indexOf("(");
621
+ if (i !== -1) {
622
+ type = type.slice(0, i);
623
+ }
624
+ return type.includes(".") ? type : currentSchema + "." + type;
625
+ } else {
626
+ return column.dataType;
627
+ }
628
+ };
629
+ const renameColumn = (columns, from, to) => {
630
+ for (let i = 0; i < columns.length; i++) {
631
+ if (columns[i] === from) {
632
+ columns[i] = to;
633
+ }
634
+ }
635
+ };
636
+
637
+ const processDomains = async (ast, adapter, domainsMap, dbStructure, {
638
+ codeItems: { domains },
639
+ structureToAstCtx,
640
+ currentSchema,
641
+ internal: { generatorIgnore }
642
+ }) => {
643
+ const codeDomains = [];
644
+ if (domains) {
645
+ for (const { schemaName, name, column } of domains) {
646
+ codeDomains.push(
647
+ makeComparableDomain(currentSchema, schemaName, name, column)
648
+ );
649
+ }
650
+ }
651
+ const tableExpressions = [];
652
+ const holdCodeDomains = /* @__PURE__ */ new Set();
653
+ for (const domain of dbStructure.domains) {
654
+ if (generatorIgnore?.schemas?.includes(domain.schemaName) || generatorIgnore?.domains?.includes(domain.name)) {
655
+ continue;
656
+ }
657
+ const dbColumn = instantiateDbColumn(
658
+ structureToAstCtx,
659
+ dbStructure,
660
+ domainsMap,
661
+ {
662
+ // not destructuring `domain` because need to ignore `numericPrecision`, `numericScale`, etc.,
663
+ // that are loaded from db, but not defined in the code
664
+ schemaName: domain.typeSchema,
665
+ tableName: "N/A",
666
+ name: domain.name,
667
+ typeSchema: domain.typeSchema,
668
+ type: domain.type,
669
+ arrayDims: domain.arrayDims,
670
+ default: domain.default,
671
+ isNullable: domain.isNullable,
672
+ collate: domain.collate,
673
+ maxChars: domain.maxChars,
674
+ typmod: -1
675
+ }
676
+ );
677
+ if (domain.checks) {
678
+ dbColumn.data.checks = domain.checks.map((check) => ({
679
+ sql: new RawSQL([[check]])
680
+ }));
681
+ }
682
+ const dbDomain = makeComparableDomain(
683
+ currentSchema,
684
+ domain.schemaName,
685
+ domain.name,
686
+ dbColumn
687
+ );
688
+ const found = codeDomains.filter(
689
+ (codeDomain) => deepCompare(dbDomain.compare, codeDomain.compare)
690
+ );
691
+ if ((domain.default || domain.checks?.length) && found.length) {
692
+ for (const codeDomain of found) {
693
+ holdCodeDomains.add(codeDomain);
694
+ }
695
+ const compare = [];
696
+ pushCompareDefault(compare, domain, found);
697
+ pushCompareChecks(compare, domain, found);
698
+ const source = `(VALUES (NULL::${getColumnDbType(
699
+ dbColumn,
700
+ currentSchema
701
+ )})) t(value)`;
702
+ tableExpressions.push({
703
+ compare,
704
+ source,
705
+ handle(i) {
706
+ const codeDomain = i === void 0 ? void 0 : found[i];
707
+ if (!codeDomain) {
708
+ ast.push(dropAst(dbDomain));
709
+ } else {
710
+ holdCodeDomains.delete(codeDomain);
711
+ }
712
+ }
713
+ });
714
+ } else if (found.length) {
715
+ let i = codeDomains.findIndex(
716
+ (codeDomain) => codeDomain.name === dbDomain.name && codeDomain.schemaName === dbDomain.schemaName
717
+ );
718
+ if (i === -1) {
719
+ i = 0;
720
+ const first = found[0];
721
+ ast.push({
722
+ type: "renameType",
723
+ kind: "DOMAIN",
724
+ fromSchema: dbDomain.schemaName,
725
+ from: dbDomain.name,
726
+ toSchema: first.schemaName,
727
+ to: first.name
728
+ });
729
+ }
730
+ codeDomains.splice(i, 1);
731
+ } else {
732
+ ast.push(dropAst(dbDomain));
733
+ }
734
+ }
735
+ for (const codeDomain of codeDomains) {
736
+ if (!holdCodeDomains.has(codeDomain)) {
737
+ ast.push(createAst(codeDomain));
738
+ }
739
+ }
740
+ if (tableExpressions.length) {
741
+ await compareSqlExpressions(tableExpressions, adapter);
742
+ if (holdCodeDomains.size) {
743
+ for (const codeDomain of holdCodeDomains.keys()) {
744
+ ast.push(createAst(codeDomain));
745
+ }
746
+ }
747
+ }
748
+ };
749
+ const makeComparableDomain = (currentSchema, schemaName, name, column) => {
750
+ let arrayDims = 0;
751
+ const isNullable = column.data.isNullable ?? false;
752
+ let inner = column;
753
+ while (inner instanceof ArrayColumn) {
754
+ inner = inner.data.item;
755
+ arrayDims++;
756
+ }
757
+ const fullType = getColumnDbType(inner, currentSchema);
758
+ const [typeSchema = "pg_catalog", type] = getSchemaAndTableFromName(fullType);
759
+ return {
760
+ schemaName,
761
+ name,
762
+ column,
763
+ compare: {
764
+ type,
765
+ typeSchema,
766
+ arrayDims,
767
+ isNullable,
768
+ maxChars: inner.data.maxChars,
769
+ numericPrecision: inner.data.numericPrecision,
770
+ numericScale: inner.data.numericScale,
771
+ dateTimePrecision: inner.data.dateTimePrecision,
772
+ collate: column.data.collate,
773
+ hasDefault: column.data.default !== void 0,
774
+ hasChecks: !!column.data.checks?.length
775
+ }
776
+ };
777
+ };
778
+ const pushCompareDefault = (compare, domain, found) => {
779
+ if (domain.default) {
780
+ compare.push({
781
+ inDb: domain.default,
782
+ inCode: found.map((codeDomain) => {
783
+ const value = codeDomain.column.data.default;
784
+ if ("sql" in value) {
785
+ return value.sql;
786
+ }
787
+ return value;
788
+ })
789
+ });
790
+ }
791
+ };
792
+ const pushCompareChecks = (compare, domain, found) => {
793
+ if (domain.checks?.length) {
794
+ const inCode = found.flatMap(
795
+ (codeDomain) => codeDomain.column.data.checks?.map(
796
+ (check) => typeof check === "string" ? check : check.sql
797
+ ) || emptyArray
798
+ );
799
+ compare.push(
800
+ ...domain.checks.map((check) => ({
801
+ inDb: check,
802
+ inCode
803
+ }))
804
+ );
805
+ }
806
+ };
807
+ const dropAst = (dbDomain) => ({
808
+ type: "domain",
809
+ action: "drop",
810
+ schema: dbDomain.schemaName,
811
+ name: dbDomain.name,
812
+ baseType: dbDomain.column
813
+ });
814
+ const createAst = (codeDomain) => ({
815
+ type: "domain",
816
+ action: "create",
817
+ schema: codeDomain.schemaName,
818
+ name: codeDomain.name,
819
+ baseType: codeDomain.column
820
+ });
821
+
822
+ const processEnums = async (ast, dbStructure, {
823
+ codeItems: { enums },
824
+ currentSchema,
825
+ verifying,
826
+ internal: { generatorIgnore }
827
+ }) => {
828
+ const createEnums = [];
829
+ const dropEnums = [];
830
+ for (const [, codeEnum] of enums) {
831
+ const { schema = currentSchema, name } = codeEnum;
832
+ const dbEnum = dbStructure.enums.find(
833
+ (x) => x.schemaName === schema && x.name === name
834
+ );
835
+ if (!dbEnum) {
836
+ createEnums.push(codeEnum);
837
+ }
838
+ }
839
+ for (const dbEnum of dbStructure.enums) {
840
+ if (generatorIgnore?.schemas?.includes(dbEnum.schemaName) || generatorIgnore?.enums?.includes(dbEnum.name)) {
841
+ continue;
842
+ }
843
+ const codeEnum = enums.get(`${dbEnum.schemaName}.${dbEnum.name}`);
844
+ if (codeEnum) {
845
+ changeEnum(ast, dbEnum, codeEnum);
846
+ continue;
847
+ }
848
+ const i = createEnums.findIndex((x) => x.name === dbEnum.name);
849
+ if (i !== -1) {
850
+ const codeEnum2 = createEnums[i];
851
+ createEnums.splice(i, 1);
852
+ const fromSchema = dbEnum.schemaName;
853
+ const toSchema = codeEnum2.schema ?? currentSchema;
854
+ renameColumnsTypeSchema(dbStructure, fromSchema, toSchema);
855
+ ast.push({
856
+ type: "renameType",
857
+ kind: "TYPE",
858
+ fromSchema,
859
+ from: dbEnum.name,
860
+ toSchema,
861
+ to: dbEnum.name
862
+ });
863
+ changeEnum(ast, dbEnum, codeEnum2);
864
+ continue;
865
+ }
866
+ dropEnums.push(dbEnum);
867
+ }
868
+ for (const codeEnum of createEnums) {
869
+ if (dropEnums.length) {
870
+ const i = await promptCreateOrRename(
871
+ "enum",
872
+ codeEnum.name,
873
+ dropEnums.map((x) => x.name),
874
+ verifying
875
+ );
876
+ if (i) {
877
+ const dbEnum = dropEnums[i - 1];
878
+ dropEnums.splice(i - 1, 1);
879
+ const fromSchema = dbEnum.schemaName;
880
+ const from = dbEnum.name;
881
+ const toSchema = codeEnum.schema ?? currentSchema;
882
+ const to = codeEnum.name;
883
+ if (fromSchema !== toSchema) {
884
+ renameColumnsTypeSchema(dbStructure, fromSchema, toSchema);
885
+ }
886
+ for (const table of dbStructure.tables) {
887
+ for (const column of table.columns) {
888
+ if (column.type === from) {
889
+ column.type = to;
890
+ }
891
+ }
892
+ }
893
+ ast.push({
894
+ type: "renameType",
895
+ kind: "TYPE",
896
+ fromSchema,
897
+ from,
898
+ toSchema,
899
+ to
900
+ });
901
+ changeEnum(ast, dbEnum, codeEnum);
902
+ continue;
903
+ }
904
+ }
905
+ ast.push({
906
+ type: "enum",
907
+ action: "create",
908
+ ...codeEnum
909
+ });
910
+ }
911
+ for (const dbEnum of dropEnums) {
912
+ ast.push({
913
+ type: "enum",
914
+ action: "drop",
915
+ schema: dbEnum.schemaName,
916
+ name: dbEnum.name,
917
+ values: dbEnum.values
918
+ });
919
+ }
920
+ };
921
+ const changeEnum = (ast, dbEnum, codeEnum) => {
922
+ const { values: dbValues } = dbEnum;
923
+ const { values: codeValues, schema, name } = codeEnum;
924
+ if (dbValues.length < codeValues.length) {
925
+ if (!dbValues.some((value) => !codeValues.includes(value))) {
926
+ ast.push({
927
+ type: "enumValues",
928
+ action: "add",
929
+ schema,
930
+ name,
931
+ values: codeValues.filter((value) => !dbValues.includes(value))
932
+ });
933
+ return;
934
+ }
935
+ } else if (dbValues.length > codeValues.length) {
936
+ if (!codeValues.some((value) => !dbValues.includes(value))) {
937
+ ast.push({
938
+ type: "enumValues",
939
+ action: "drop",
940
+ schema,
941
+ name,
942
+ values: dbValues.filter((value) => !codeValues.includes(value))
943
+ });
944
+ return;
945
+ }
946
+ } else if (!dbValues.some((value) => !codeValues.includes(value))) {
947
+ return;
948
+ }
949
+ ast.push({
950
+ type: "changeEnumValues",
951
+ schema,
952
+ name,
953
+ fromValues: dbValues,
954
+ toValues: codeValues
955
+ });
956
+ };
957
+ const renameColumnsTypeSchema = (dbStructure, from, to) => {
958
+ for (const table of dbStructure.tables) {
959
+ for (const column of table.columns) {
960
+ if (column.typeSchema === from) {
961
+ column.typeSchema = to;
962
+ }
963
+ }
964
+ }
965
+ };
966
+
967
+ const processPrimaryKey = (config, changeTableData) => {
968
+ const { codeTable } = changeTableData;
969
+ const columnsPrimaryKey = [];
970
+ for (const key in codeTable.shape) {
971
+ const column = codeTable.shape[key];
972
+ if (column.data.primaryKey) {
973
+ columnsPrimaryKey.push({ key, name: column.data.name ?? key });
974
+ }
975
+ }
976
+ changePrimaryKey(config, columnsPrimaryKey, changeTableData);
977
+ renamePrimaryKey(changeTableData);
978
+ };
979
+ const changePrimaryKey = (config, columnsPrimaryKey, {
980
+ codeTable,
981
+ dbTableData: { primaryKey: dbPrimaryKey },
982
+ changeTableAst: { shape, add, drop },
983
+ changingColumns
984
+ }) => {
985
+ const tablePrimaryKey = codeTable.internal.tableData.primaryKey;
986
+ const primaryKey = [
987
+ .../* @__PURE__ */ new Set([
988
+ ...columnsPrimaryKey,
989
+ ...(config.snakeCase ? tablePrimaryKey?.columns.map((key) => ({
990
+ key,
991
+ name: toSnakeCase(key)
992
+ })) : tablePrimaryKey?.columns.map((key) => ({ key, name: key }))) ?? []
993
+ ])
994
+ ];
995
+ if (dbPrimaryKey && primaryKey.length === dbPrimaryKey.columns.length && !primaryKey.some(
996
+ ({ name }) => !dbPrimaryKey.columns.some((dbName) => name === dbName)
997
+ )) {
998
+ if (primaryKey.length === 1) {
999
+ const { key } = primaryKey[0];
1000
+ const changes = shape[key] && toArray(shape[key]);
1001
+ if (changes) {
1002
+ for (const change of changes) {
1003
+ if (change.type !== "change") continue;
1004
+ if (change.from.column) {
1005
+ change.from.column.data.primaryKey = void 0;
1006
+ }
1007
+ if (change.to.column) {
1008
+ const column = Object.create(change.to.column);
1009
+ column.data = { ...column.data, primaryKey: void 0 };
1010
+ change.to.column = column;
1011
+ }
1012
+ }
1013
+ }
1014
+ }
1015
+ return;
1016
+ }
1017
+ const toDrop = dbPrimaryKey?.columns.filter(
1018
+ (key) => !checkForColumnAddOrDrop(shape, key)
1019
+ );
1020
+ if (toDrop?.length) {
1021
+ if (toDrop.length === 1 && changingColumns[toDrop[0]]) {
1022
+ const column = changingColumns[toDrop[0]];
1023
+ column.from.data.primaryKey = dbPrimaryKey?.name ?? true;
1024
+ } else {
1025
+ drop.primaryKey = { columns: toDrop, name: dbPrimaryKey?.name };
1026
+ }
1027
+ }
1028
+ const toAdd = primaryKey.filter(
1029
+ ({ key }) => !checkForColumnAddOrDrop(shape, key)
1030
+ );
1031
+ if (toAdd.length) {
1032
+ if (toAdd.length === 1 && changingColumns[toAdd[0].name]) {
1033
+ const column = changingColumns[toAdd[0].name];
1034
+ column.to.data.primaryKey = tablePrimaryKey?.name ?? true;
1035
+ } else {
1036
+ add.primaryKey = {
1037
+ columns: toAdd.map((c) => c.key),
1038
+ name: tablePrimaryKey?.name
1039
+ };
1040
+ }
1041
+ }
1042
+ };
1043
+ const renamePrimaryKey = ({
1044
+ codeTable,
1045
+ dbTableData: { primaryKey: dbPrimaryKey },
1046
+ schema,
1047
+ delayedAst
1048
+ }) => {
1049
+ const tablePrimaryKey = codeTable.internal.tableData.primaryKey;
1050
+ if (dbPrimaryKey && tablePrimaryKey && dbPrimaryKey?.name !== tablePrimaryKey?.name) {
1051
+ delayedAst.push({
1052
+ type: "renameTableItem",
1053
+ kind: "CONSTRAINT",
1054
+ tableSchema: schema,
1055
+ tableName: codeTable.table,
1056
+ from: dbPrimaryKey.name ?? `${codeTable.table}_pkey`,
1057
+ to: tablePrimaryKey.name ?? `${codeTable}_pkey`
1058
+ });
1059
+ }
1060
+ };
1061
+
1062
+ const processIndexesAndExcludes = (config, changeTableData, ast, compareExpressions) => {
1063
+ const codeItems = collectCodeIndexes(config, changeTableData);
1064
+ const codeComparableItems = collectCodeComparableItems(config, codeItems);
1065
+ const skipCodeItems = {
1066
+ indexes: /* @__PURE__ */ new Map(),
1067
+ excludes: /* @__PURE__ */ new Map()
1068
+ };
1069
+ const holdCodeItems = {
1070
+ indexes: /* @__PURE__ */ new Map(),
1071
+ excludes: /* @__PURE__ */ new Map()
1072
+ };
1073
+ const processParams = {
1074
+ config,
1075
+ changeTableData,
1076
+ codeComparableItems,
1077
+ codeItems,
1078
+ skipCodeItems,
1079
+ holdCodeItems,
1080
+ // counter for async SQL comparisons that are in progress
1081
+ wait: { indexes: 0, excludes: 0 },
1082
+ ast,
1083
+ compareExpressions
1084
+ };
1085
+ processItems(processParams, "indexes");
1086
+ processItems(processParams, "excludes");
1087
+ addMainItems(
1088
+ changeTableData,
1089
+ codeItems,
1090
+ skipCodeItems,
1091
+ holdCodeItems,
1092
+ "indexes"
1093
+ );
1094
+ addMainItems(
1095
+ changeTableData,
1096
+ codeItems,
1097
+ skipCodeItems,
1098
+ holdCodeItems,
1099
+ "excludes"
1100
+ );
1101
+ };
1102
+ const processItems = ({
1103
+ config,
1104
+ changeTableData,
1105
+ codeComparableItems,
1106
+ codeItems,
1107
+ skipCodeItems,
1108
+ holdCodeItems,
1109
+ wait,
1110
+ ast,
1111
+ compareExpressions
1112
+ }, key) => {
1113
+ const {
1114
+ changeTableAst: { shape }
1115
+ } = changeTableData;
1116
+ const dbItems = changeTableData.dbTableData[key];
1117
+ for (const dbItem of dbItems) {
1118
+ const hasAddedOrDroppedColumn = dbItem.columns.some(
1119
+ (column) => "column" in column && checkForColumnAddOrDrop(shape, column.column)
1120
+ );
1121
+ if (hasAddedOrDroppedColumn) continue;
1122
+ normalizeItem(dbItem);
1123
+ const { found, rename, foundAndHasSql } = findMatchingItem(
1124
+ dbItem,
1125
+ codeComparableItems,
1126
+ codeItems,
1127
+ skipCodeItems,
1128
+ changeTableData.codeTable.table,
1129
+ config,
1130
+ key
1131
+ );
1132
+ const { columns: dbColumns } = dbItem;
1133
+ if (!foundAndHasSql) {
1134
+ handleItemChange(
1135
+ changeTableData,
1136
+ dbItem,
1137
+ dbColumns,
1138
+ found[0],
1139
+ rename[0],
1140
+ key
1141
+ );
1142
+ continue;
1143
+ }
1144
+ for (const codeItem of found) {
1145
+ holdCodeItems[key].set(codeItem, true);
1146
+ }
1147
+ const compare = [];
1148
+ for (let i = 0; i < dbItem.columns.length; i++) {
1149
+ const column = dbItem.columns[i];
1150
+ if (!("expression" in column)) continue;
1151
+ compare.push({
1152
+ inDb: column.expression,
1153
+ inCode: found.map(
1154
+ (x) => x.columns[i].expression
1155
+ )
1156
+ });
1157
+ }
1158
+ if (dbItem.with) {
1159
+ compare.push({
1160
+ inDb: dbItem.with,
1161
+ inCode: found.map((x) => x.options.with)
1162
+ });
1163
+ }
1164
+ if (dbItem.where) {
1165
+ compare.push({
1166
+ inDb: dbItem.where,
1167
+ inCode: found.map((x) => x.options.where)
1168
+ });
1169
+ }
1170
+ wait[key]++;
1171
+ compareExpressions.push({
1172
+ compare,
1173
+ handle(i) {
1174
+ const codeItem = i === void 0 ? void 0 : found[i];
1175
+ handleItemChange(
1176
+ changeTableData,
1177
+ dbItem,
1178
+ dbColumns,
1179
+ codeItem,
1180
+ i === void 0 ? void 0 : rename[i],
1181
+ key
1182
+ );
1183
+ if (codeItem) {
1184
+ holdCodeItems[key].delete(codeItem);
1185
+ }
1186
+ if (!--wait[key] && holdCodeItems[key].size) {
1187
+ addItems(changeTableData, [...holdCodeItems[key].keys()], key);
1188
+ if (!changeTableData.pushedAst) {
1189
+ changeTableData.pushedAst = true;
1190
+ ast.push(changeTableData.changeTableAst);
1191
+ }
1192
+ }
1193
+ }
1194
+ });
1195
+ }
1196
+ };
1197
+ const collectCodeIndexes = (config, { codeTable, changeTableAst: { shape } }) => {
1198
+ const codeItems = { indexes: [], excludes: [] };
1199
+ for (const key in codeTable.shape) {
1200
+ const column = codeTable.shape[key];
1201
+ if (!column.data.indexes && !column.data.excludes) continue;
1202
+ const name = column.data.name ?? key;
1203
+ if (checkForColumnAddOrDrop(shape, name)) continue;
1204
+ pushCodeColumnItems(config, codeItems, key, name, column, "indexes");
1205
+ pushCodeColumnItems(config, codeItems, key, name, column, "excludes");
1206
+ }
1207
+ pushCodeCompositeItems(config, codeTable, codeItems, "indexes");
1208
+ pushCodeCompositeItems(config, codeTable, codeItems, "excludes");
1209
+ return codeItems;
1210
+ };
1211
+ const pushCodeColumnItems = (config, codeItems, columnKey, name, column, key) => {
1212
+ const items = column.data[key];
1213
+ if (!items) return;
1214
+ codeItems[key].push(
1215
+ ...items.map(
1216
+ ({
1217
+ options: { collate, opclass, order, weight, ...options },
1218
+ with: wi,
1219
+ ...index
1220
+ }) => {
1221
+ const w = key === "excludes" ? wi : void 0;
1222
+ return {
1223
+ columns: [
1224
+ {
1225
+ collate,
1226
+ opclass,
1227
+ order,
1228
+ weight,
1229
+ column: name,
1230
+ with: w
1231
+ }
1232
+ ],
1233
+ ...index,
1234
+ options: options.include ? config.snakeCase ? {
1235
+ ...options,
1236
+ include: toArray(options.include).map(toSnakeCase)
1237
+ } : options : options,
1238
+ columnKeys: [
1239
+ {
1240
+ collate,
1241
+ opclass,
1242
+ order,
1243
+ weight,
1244
+ column: columnKey,
1245
+ with: w
1246
+ }
1247
+ ],
1248
+ includeKeys: options.include
1249
+ };
1250
+ }
1251
+ )
1252
+ );
1253
+ };
1254
+ const pushCodeCompositeItems = (config, codeTable, codeItems, key) => {
1255
+ const items = codeTable.internal.tableData[key];
1256
+ if (!items) return;
1257
+ codeItems[key].push(
1258
+ ...items.map((x) => ({
1259
+ ...x,
1260
+ columns: config.snakeCase ? x.columns.map(
1261
+ (c) => "column" in c ? { ...c, column: toSnakeCase(c.column) } : c
1262
+ ) : x.columns,
1263
+ columnKeys: x.columns,
1264
+ options: x.options.include && config.snakeCase ? {
1265
+ ...x.options,
1266
+ include: toArray(x.options.include).map(toSnakeCase)
1267
+ } : x.options,
1268
+ includeKeys: x.options.include
1269
+ }))
1270
+ );
1271
+ };
1272
+ const collectCodeComparableItems = (config, codeItems) => {
1273
+ return {
1274
+ indexes: collectCodeComparableItemsType(config, codeItems, "indexes"),
1275
+ excludes: collectCodeComparableItemsType(config, codeItems, "excludes")
1276
+ };
1277
+ };
1278
+ const collectCodeComparableItemsType = (config, codeItems, key) => {
1279
+ return codeItems[key].map((codeItem) => {
1280
+ normalizeItem(codeItem.options);
1281
+ return itemToComparable({
1282
+ ...codeItem.options,
1283
+ include: codeItem.options.include === void 0 ? void 0 : config.snakeCase ? toArray(codeItem.options.include).map(toSnakeCase) : toArray(codeItem.options.include),
1284
+ columns: codeItem.columns,
1285
+ name: codeItem.name,
1286
+ columnKeys: codeItem.columnKeys,
1287
+ includeKeys: codeItem.includeKeys
1288
+ });
1289
+ });
1290
+ };
1291
+ const normalizeItem = (item) => {
1292
+ if (item.using) item.using = item.using.toLowerCase();
1293
+ if (item.using === "btree") item.using = void 0;
1294
+ if (!item.unique) item.unique = void 0;
1295
+ if (item.nullsNotDistinct === false) item.nullsNotDistinct = void 0;
1296
+ if (item.exclude) {
1297
+ for (let i = 0; i < item.columns.length; i++) {
1298
+ item.columns[i].with = item.exclude[i];
1299
+ }
1300
+ }
1301
+ };
1302
+ const itemToComparable = (index) => {
1303
+ let hasExpression = false;
1304
+ const columns = index.columns.map((column) => {
1305
+ const result = {
1306
+ ...column,
1307
+ expression: void 0,
1308
+ hasExpression: "expression" in column
1309
+ };
1310
+ if (result.hasExpression) hasExpression = true;
1311
+ return result;
1312
+ });
1313
+ return {
1314
+ ...index,
1315
+ schemaName: void 0,
1316
+ tableName: void 0,
1317
+ with: void 0,
1318
+ hasWith: !!index.with,
1319
+ where: void 0,
1320
+ hasWhere: !!index.where,
1321
+ columns,
1322
+ hasExpression
1323
+ };
1324
+ };
1325
+ const findMatchingItem = (dbItem, codeComparableItems, codeItems, skipCodeItems, tableName, config, key) => {
1326
+ const dbComparableItem = itemToComparable(
1327
+ key === "indexes" ? dbItem : {
1328
+ ...dbItem,
1329
+ exclude: void 0,
1330
+ columns: dbItem.columns.map((column, i) => ({
1331
+ ...column,
1332
+ with: dbItem.exclude[i]
1333
+ }))
1334
+ }
1335
+ );
1336
+ const { found, rename } = findMatchingItemWithoutSql(
1337
+ dbComparableItem,
1338
+ codeComparableItems,
1339
+ codeItems,
1340
+ skipCodeItems,
1341
+ tableName,
1342
+ config,
1343
+ key
1344
+ );
1345
+ const foundAndHasSql = found.length && checkIfItemHasSql(dbComparableItem);
1346
+ return { found, rename, foundAndHasSql };
1347
+ };
1348
+ const findMatchingItemWithoutSql = (dbItem, codeComparableItems, codeItems, skipCodeItems, tableName, config, key) => {
1349
+ const found = [];
1350
+ const rename = [];
1351
+ const { columns: dbColumns, ...dbItemWithoutColumns } = dbItem;
1352
+ for (let i = 0; i < codeComparableItems[key].length; i++) {
1353
+ if (skipCodeItems[key].has(i)) continue;
1354
+ const { columns: codeColumns, ...codeItem } = codeComparableItems[key][i];
1355
+ if (dbColumns.length === codeColumns.length && !dbColumns.some((dbColumn, i2) => !deepCompare(dbColumn, codeColumns[i2]))) {
1356
+ let a = dbItemWithoutColumns;
1357
+ let b = codeItem;
1358
+ const codeName = b.name ?? (key === "indexes" ? getIndexName : getExcludeName)(
1359
+ tableName,
1360
+ dbColumns
1361
+ );
1362
+ if (a.name !== b.name) {
1363
+ a = { ...a, name: void 0 };
1364
+ b = {
1365
+ ...b,
1366
+ name: void 0,
1367
+ columnKeys: void 0,
1368
+ includeKeys: void 0
1369
+ };
1370
+ if (a.language && !b.language) {
1371
+ b.language = config.language ?? "english";
1372
+ }
1373
+ if (deepCompare(a, b)) {
1374
+ found.push(codeItems[key][i]);
1375
+ rename.push(
1376
+ dbItemWithoutColumns.name !== codeName ? codeName : void 0
1377
+ );
1378
+ }
1379
+ } else {
1380
+ const {
1381
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1382
+ columnKeys,
1383
+ includeKeys,
1384
+ ...codeItemWithoutKeys
1385
+ } = codeItem;
1386
+ if (deepCompare(dbItemWithoutColumns, codeItemWithoutKeys)) {
1387
+ found.push(codeItems[key][i]);
1388
+ rename.push(void 0);
1389
+ }
1390
+ }
1391
+ if (found.length && !checkIfItemHasSql(codeItem)) {
1392
+ skipCodeItems[key].set(i, true);
1393
+ }
1394
+ }
1395
+ }
1396
+ return { found, rename };
1397
+ };
1398
+ const checkIfItemHasSql = (x) => x.hasWith || x.hasWhere || x.hasExpression;
1399
+ const handleItemChange = ({
1400
+ changeTableAst,
1401
+ schema,
1402
+ codeTable,
1403
+ changingColumns,
1404
+ delayedAst
1405
+ }, dbItem, dbColumns, found, rename, key) => {
1406
+ var _a, _b;
1407
+ if (!found) {
1408
+ const name = dbItem.name === (key === "indexes" ? getIndexName : getExcludeName)(
1409
+ changeTableAst.name,
1410
+ dbColumns
1411
+ ) ? void 0 : dbItem.name;
1412
+ if (dbColumns.length === 1 && "column" in dbColumns[0]) {
1413
+ const dbColumn = dbColumns[0];
1414
+ const column = changingColumns[dbColumn.column];
1415
+ if (column) {
1416
+ ((_a = column.from.data)[key] ?? (_a[key] = [])).push({
1417
+ options: dbItem,
1418
+ name,
1419
+ with: key === "indexes" ? void 0 : dbColumn.with
1420
+ });
1421
+ return;
1422
+ }
1423
+ }
1424
+ ((_b = changeTableAst.drop)[key] ?? (_b[key] = [])).push({
1425
+ columns: dbColumns,
1426
+ options: dbItem,
1427
+ name
1428
+ });
1429
+ } else if (rename) {
1430
+ delayedAst.push({
1431
+ type: "renameTableItem",
1432
+ kind: key === "indexes" ? "INDEX" : "CONSTRAINT",
1433
+ tableSchema: schema,
1434
+ tableName: codeTable.table,
1435
+ from: dbItem.name,
1436
+ to: rename
1437
+ });
1438
+ }
1439
+ };
1440
+ const addMainItems = (changeTableData, codeItems, skipCodeItems, holdCodeItems, key) => {
1441
+ const itemsToAdd = codeItems[key].filter(
1442
+ (item, i) => !skipCodeItems[key].has(i) && !holdCodeItems[key].has(item)
1443
+ );
1444
+ if (itemsToAdd.length) {
1445
+ addItems(
1446
+ changeTableData,
1447
+ itemsToAdd.map((x) => ({
1448
+ ...x,
1449
+ columns: x.columnKeys,
1450
+ columnNames: x.columns,
1451
+ options: x.options.include ? { ...x.options, include: x.includeKeys } : x.options
1452
+ })),
1453
+ key
1454
+ );
1455
+ }
1456
+ };
1457
+ const addItems = ({ changeTableAst, changingColumns }, add, key) => {
1458
+ var _a, _b;
1459
+ const items = (_a = changeTableAst.add)[key] ?? (_a[key] = []);
1460
+ for (const item of add) {
1461
+ if (item.columns.length === 1 && "column" in item.columns[0]) {
1462
+ const column = changingColumns[(item.columnNames || item.columns)[0].column];
1463
+ if (column) {
1464
+ ((_b = column.to.data)[key] ?? (_b[key] = [])).push(
1465
+ key === "indexes" ? item : {
1466
+ ...item,
1467
+ with: item.columns[0].with
1468
+ }
1469
+ );
1470
+ continue;
1471
+ }
1472
+ }
1473
+ items.push(item);
1474
+ }
1475
+ };
1476
+
1477
+ const mapMatchToDb = {
1478
+ FULL: "f",
1479
+ PARTIAL: "p",
1480
+ SIMPLE: "s"
1481
+ };
1482
+ const mapMatchToCode = {};
1483
+ for (const key in mapMatchToDb) {
1484
+ mapMatchToCode[mapMatchToDb[key]] = key;
1485
+ }
1486
+ const mapActionToDb = {
1487
+ "NO ACTION": "a",
1488
+ RESTRICT: "r",
1489
+ CASCADE: "c",
1490
+ "SET NULL": "n",
1491
+ "SET DEFAULT": "d"
1492
+ };
1493
+ const mapActionToCode = {};
1494
+ for (const key in mapActionToDb) {
1495
+ mapActionToCode[mapActionToDb[key]] = key;
1496
+ }
1497
+ const processForeignKeys = (config, ast, changeTables, currentSchema, tableShapes) => {
1498
+ var _a, _b;
1499
+ for (const changeTableData of changeTables) {
1500
+ const codeForeignKeys = collectCodeFkeys(
1501
+ config,
1502
+ changeTableData,
1503
+ currentSchema
1504
+ );
1505
+ const { codeTable, dbTableData, changeTableAst, schema, changingColumns } = changeTableData;
1506
+ const { shape, add, drop } = changeTableAst;
1507
+ let changed = false;
1508
+ for (const dbConstraint of dbTableData.constraints) {
1509
+ const { references: dbReferences } = dbConstraint;
1510
+ if (!dbReferences) continue;
1511
+ const hasChangedColumn = dbReferences.columns.some(
1512
+ (column) => checkForColumnAddOrDrop(shape, column)
1513
+ );
1514
+ if (hasChangedColumn) continue;
1515
+ const foreignShape = tableShapes[`${dbReferences.foreignSchema}.${dbReferences.foreignTable}`];
1516
+ const hasForeignChangedColumn = foreignShape && dbReferences.foreignColumns.some((column) => {
1517
+ const res = checkForColumnAddOrDrop(foreignShape, column);
1518
+ return res;
1519
+ });
1520
+ if (hasForeignChangedColumn) continue;
1521
+ let found = false;
1522
+ let rename;
1523
+ for (let i = 0; i < codeForeignKeys.length; i++) {
1524
+ const codeForeignKey = codeForeignKeys[i];
1525
+ const codeReferences = codeForeignKey.references;
1526
+ if (deepCompare(dbReferences, codeReferences)) {
1527
+ found = true;
1528
+ codeForeignKeys.splice(i, 1);
1529
+ const codeName = codeForeignKey.codeConstraint.name ?? getConstraintName(
1530
+ codeTable.table,
1531
+ codeForeignKey,
1532
+ config.snakeCase
1533
+ );
1534
+ if (codeName !== dbConstraint.name) {
1535
+ rename = codeName;
1536
+ }
1537
+ }
1538
+ }
1539
+ if (!found) {
1540
+ const foreignKey = dbForeignKeyToCodeForeignKey(
1541
+ config,
1542
+ dbConstraint,
1543
+ dbReferences
1544
+ );
1545
+ if (dbReferences.columns.length === 1 && changingColumns[dbReferences.columns[0]]) {
1546
+ const column = changingColumns[dbReferences.columns[0]];
1547
+ ((_a = column.from.data).foreignKeys ?? (_a.foreignKeys = [])).push({
1548
+ fnOrTable: foreignKey.references.fnOrTable,
1549
+ foreignColumns: foreignKey.references.foreignColumns,
1550
+ options: foreignKey.references.options
1551
+ });
1552
+ } else {
1553
+ (drop.constraints ?? (drop.constraints = [])).push(foreignKey);
1554
+ }
1555
+ changed = true;
1556
+ } else if (rename) {
1557
+ ast.push({
1558
+ type: "renameTableItem",
1559
+ kind: "CONSTRAINT",
1560
+ tableSchema: schema,
1561
+ tableName: codeTable.table,
1562
+ from: dbConstraint.name,
1563
+ to: rename
1564
+ });
1565
+ }
1566
+ }
1567
+ if (codeForeignKeys.length) {
1568
+ const constraints = add.constraints ?? (add.constraints = []);
1569
+ for (const { codeConstraint, references } of codeForeignKeys) {
1570
+ if (references.columns.length === 1 && changingColumns[references.columns[0]]) {
1571
+ const column = changingColumns[references.columns[0]];
1572
+ ((_b = column.to.data).foreignKeys ?? (_b.foreignKeys = [])).push({
1573
+ fnOrTable: references.foreignTable,
1574
+ foreignColumns: codeConstraint.references.foreignColumns,
1575
+ options: codeConstraint.references.options
1576
+ });
1577
+ } else {
1578
+ constraints.push(codeConstraint);
1579
+ }
1580
+ }
1581
+ changed = true;
1582
+ }
1583
+ if (changed && !changeTableData.pushedAst) {
1584
+ changeTableData.pushedAst = true;
1585
+ ast.push(changeTableData.changeTableAst);
1586
+ }
1587
+ }
1588
+ };
1589
+ const collectCodeFkeys = (config, { codeTable, changeTableAst: { shape } }, currentSchema) => {
1590
+ const codeForeignKeys = [];
1591
+ for (const key in codeTable.shape) {
1592
+ const column = codeTable.shape[key];
1593
+ if (!column.data.foreignKeys) continue;
1594
+ const name = column.data.name ?? key;
1595
+ if (checkForColumnAddOrDrop(shape, name)) continue;
1596
+ codeForeignKeys.push(
1597
+ ...column.data.foreignKeys.map((x) => {
1598
+ const columns = [name];
1599
+ const fnOrTable = fnOrTableToString(x.fnOrTable);
1600
+ return parseForeignKey(
1601
+ config,
1602
+ {
1603
+ name: x.options?.name,
1604
+ references: {
1605
+ columns: [name],
1606
+ fnOrTable,
1607
+ foreignColumns: x.foreignColumns,
1608
+ options: x.options
1609
+ }
1610
+ },
1611
+ {
1612
+ columns,
1613
+ fnOrTable,
1614
+ foreignColumns: x.foreignColumns,
1615
+ options: x.options
1616
+ },
1617
+ currentSchema
1618
+ );
1619
+ })
1620
+ );
1621
+ }
1622
+ if (codeTable.internal.tableData.constraints) {
1623
+ for (const tableConstraint of codeTable.internal.tableData.constraints) {
1624
+ const { references: refs } = tableConstraint;
1625
+ if (!refs) continue;
1626
+ const fnOrTable = fnOrTableToString(refs.fnOrTable);
1627
+ codeForeignKeys.push(
1628
+ parseForeignKey(
1629
+ config,
1630
+ {
1631
+ ...tableConstraint,
1632
+ references: {
1633
+ ...refs,
1634
+ fnOrTable
1635
+ }
1636
+ },
1637
+ {
1638
+ ...refs,
1639
+ fnOrTable,
1640
+ columns: config.snakeCase ? refs.columns.map(toSnakeCase) : refs.columns,
1641
+ foreignColumns: config.snakeCase ? refs.foreignColumns.map(toSnakeCase) : refs.foreignColumns
1642
+ },
1643
+ currentSchema
1644
+ )
1645
+ );
1646
+ }
1647
+ }
1648
+ return codeForeignKeys;
1649
+ };
1650
+ const fnOrTableToString = (fnOrTable) => {
1651
+ if (typeof fnOrTable !== "string") {
1652
+ const { schema, table } = new (fnOrTable())();
1653
+ fnOrTable = concatSchemaAndName({ schema, name: table });
1654
+ }
1655
+ return fnOrTable;
1656
+ };
1657
+ const parseForeignKey = (config, codeConstraint, references, currentSchema) => {
1658
+ const { fnOrTable, columns, foreignColumns, options } = references;
1659
+ const [schema, table] = getSchemaAndTableFromName(fnOrTable);
1660
+ return {
1661
+ references: {
1662
+ foreignSchema: schema ?? currentSchema,
1663
+ foreignTable: table,
1664
+ columns,
1665
+ foreignColumns: config.snakeCase ? foreignColumns.map(toSnakeCase) : foreignColumns,
1666
+ match: mapMatchToDb[options?.match || "SIMPLE"],
1667
+ onUpdate: mapActionToDb[options?.onUpdate || "NO ACTION"],
1668
+ onDelete: mapActionToDb[options?.onDelete || "NO ACTION"]
1669
+ },
1670
+ codeConstraint
1671
+ };
1672
+ };
1673
+ const dbForeignKeyToCodeForeignKey = (config, dbConstraint, dbReferences) => ({
1674
+ name: dbConstraint.name === getConstraintName(
1675
+ dbConstraint.tableName,
1676
+ { references: dbReferences },
1677
+ config.snakeCase
1678
+ ) ? void 0 : dbConstraint.name,
1679
+ references: {
1680
+ columns: dbReferences.columns,
1681
+ fnOrTable: `${dbReferences.foreignSchema}.${dbReferences.foreignTable}`,
1682
+ foreignColumns: dbReferences.foreignColumns,
1683
+ options: {
1684
+ match: dbReferences.match === "s" ? void 0 : mapMatchToCode[dbReferences.match],
1685
+ onUpdate: dbReferences.onUpdate === "a" ? void 0 : mapActionToCode[dbReferences.onUpdate],
1686
+ onDelete: dbReferences.onDelete === "a" ? void 0 : mapActionToCode[dbReferences.onDelete]
1687
+ }
1688
+ }
1689
+ });
1690
+
1691
+ const processChecks = (ast, changeTableData, compareExpressions) => {
1692
+ const codeChecks = collectCodeChecks(changeTableData);
1693
+ const {
1694
+ dbTableData,
1695
+ changeTableAst: { add, shape }
1696
+ } = changeTableData;
1697
+ const hasDbChecks = dbTableData.constraints.some((c) => c.check);
1698
+ if (!hasDbChecks) {
1699
+ if (codeChecks.length) {
1700
+ const constraints = add.constraints ?? (add.constraints = []);
1701
+ for (const codeCheck of codeChecks) {
1702
+ if (!codeCheck.column || !changeTableData.changingColumns[codeCheck.column]) {
1703
+ constraints.push({
1704
+ check: codeCheck.check.sql,
1705
+ name: codeCheck.name
1706
+ });
1707
+ }
1708
+ }
1709
+ }
1710
+ return;
1711
+ }
1712
+ let wait = 0;
1713
+ const foundCodeChecks = /* @__PURE__ */ new Set();
1714
+ for (const dbConstraint of dbTableData.constraints) {
1715
+ const { check: dbCheck, name } = dbConstraint;
1716
+ if (!dbCheck) continue;
1717
+ const hasChangedColumn = dbCheck.columns?.some(
1718
+ (column) => checkForColumnAddOrDrop(shape, column)
1719
+ );
1720
+ if (hasChangedColumn) continue;
1721
+ if (codeChecks.length) {
1722
+ wait++;
1723
+ compareExpressions.push({
1724
+ compare: [
1725
+ {
1726
+ inDb: dbCheck.expression,
1727
+ inCode: codeChecks.map(({ check }) => check.sql)
1728
+ }
1729
+ ],
1730
+ handle(i) {
1731
+ if (i !== void 0) {
1732
+ foundCodeChecks.add(i);
1733
+ } else {
1734
+ dropCheck(changeTableData, dbCheck, name);
1735
+ }
1736
+ if (--wait !== 0) return;
1737
+ const checksToAdd = [];
1738
+ codeChecks.forEach((check, i2) => {
1739
+ if (foundCodeChecks.has(i2)) {
1740
+ if (!check.column) return;
1741
+ const change = changeTableData.changingColumns[check.column];
1742
+ if (!change) return;
1743
+ const columnChecks = change.to.data.checks;
1744
+ if (!columnChecks) return;
1745
+ const i3 = columnChecks.indexOf(check.check);
1746
+ if (i3 !== -1) {
1747
+ columnChecks.splice(i3, 1);
1748
+ }
1749
+ return;
1750
+ }
1751
+ checksToAdd.push({
1752
+ name: check.name,
1753
+ check: check.check.sql
1754
+ });
1755
+ });
1756
+ if (checksToAdd.length) {
1757
+ (add.constraints ?? (add.constraints = [])).push(...checksToAdd);
1758
+ }
1759
+ if (!changeTableData.pushedAst && (changeTableData.changeTableAst.drop.constraints?.length || add.constraints?.length)) {
1760
+ changeTableData.pushedAst = true;
1761
+ ast.push(changeTableData.changeTableAst);
1762
+ }
1763
+ }
1764
+ });
1765
+ } else {
1766
+ dropCheck(changeTableData, dbCheck, name);
1767
+ }
1768
+ }
1769
+ };
1770
+ const collectCodeChecks = ({
1771
+ codeTable,
1772
+ changeTableAst: { shape }
1773
+ }) => {
1774
+ const names = /* @__PURE__ */ new Set();
1775
+ const codeChecks = [];
1776
+ for (const key in codeTable.shape) {
1777
+ const column = codeTable.shape[key];
1778
+ if (!column.data.checks) continue;
1779
+ const columnName = column.data.name ?? key;
1780
+ if (checkForColumnAddOrDrop(shape, columnName)) continue;
1781
+ const baseName = `${codeTable.table}_${columnName}_check`;
1782
+ codeChecks.push(
1783
+ ...column.data.checks.map((check) => {
1784
+ let name = check.name;
1785
+ if (!name) {
1786
+ name = baseName;
1787
+ let n = 0;
1788
+ while (names.has(name)) {
1789
+ name = baseName + ++n;
1790
+ }
1791
+ }
1792
+ names.add(name);
1793
+ return {
1794
+ check,
1795
+ name,
1796
+ column: columnName
1797
+ };
1798
+ })
1799
+ );
1800
+ }
1801
+ if (codeTable.internal.tableData.constraints) {
1802
+ for (const constraint of codeTable.internal.tableData.constraints) {
1803
+ const { check } = constraint;
1804
+ if (check) {
1805
+ const baseName = `${codeTable.table}_check`;
1806
+ let name = constraint.name;
1807
+ if (!name) {
1808
+ name = baseName;
1809
+ let n = 0;
1810
+ while (names.has(name)) {
1811
+ name = baseName + ++n;
1812
+ }
1813
+ }
1814
+ names.add(name);
1815
+ codeChecks.push({
1816
+ check: { sql: check, name: constraint.name },
1817
+ name
1818
+ });
1819
+ }
1820
+ }
1821
+ }
1822
+ return codeChecks;
1823
+ };
1824
+ const dropCheck = ({ changeTableAst: { drop }, changingColumns }, dbCheck, name) => {
1825
+ var _a;
1826
+ const sql = new RawSQL([
1827
+ [dbCheck.expression]
1828
+ ]);
1829
+ if (dbCheck.columns?.length === 1 && changingColumns[dbCheck.columns[0]]) {
1830
+ const column = changingColumns[dbCheck.columns[0]];
1831
+ column.from.data.name = "i_d";
1832
+ ((_a = column.from.data).checks ?? (_a.checks = [])).push({
1833
+ name,
1834
+ sql
1835
+ });
1836
+ } else {
1837
+ (drop.constraints ?? (drop.constraints = [])).push({
1838
+ name,
1839
+ check: sql
1840
+ });
1841
+ }
1842
+ };
1843
+
1844
+ const processTables = async (ast, domainsMap, adapter, dbStructure, config, {
1845
+ structureToAstCtx,
1846
+ codeItems: { tables },
1847
+ currentSchema,
1848
+ internal: { generatorIgnore },
1849
+ verifying
1850
+ }) => {
1851
+ const createTables = collectCreateTables(
1852
+ tables,
1853
+ dbStructure,
1854
+ currentSchema
1855
+ );
1856
+ const compareSql = { values: [], expressions: [] };
1857
+ const tableExpressions = [];
1858
+ const { changeTables, changeTableSchemas, dropTables, tableShapes } = collectChangeAndDropTables(
1859
+ config,
1860
+ tables,
1861
+ dbStructure,
1862
+ currentSchema,
1863
+ createTables,
1864
+ generatorIgnore
1865
+ );
1866
+ applyChangeTableSchemas(changeTableSchemas, currentSchema, ast);
1867
+ await applyCreateOrRenameTables(
1868
+ dbStructure,
1869
+ createTables,
1870
+ dropTables,
1871
+ changeTables,
1872
+ tableShapes,
1873
+ currentSchema,
1874
+ ast,
1875
+ verifying
1876
+ );
1877
+ await applyChangeTables(
1878
+ adapter,
1879
+ changeTables,
1880
+ structureToAstCtx,
1881
+ dbStructure,
1882
+ domainsMap,
1883
+ ast,
1884
+ currentSchema,
1885
+ config,
1886
+ compareSql,
1887
+ tableExpressions,
1888
+ verifying
1889
+ );
1890
+ processForeignKeys(config, ast, changeTables, currentSchema, tableShapes);
1891
+ await Promise.all([
1892
+ applyCompareSql(compareSql, adapter),
1893
+ compareSqlExpressions(tableExpressions, adapter)
1894
+ ]);
1895
+ for (const dbTable of dropTables) {
1896
+ ast.push(
1897
+ tableToAst(structureToAstCtx, dbStructure, dbTable, "drop", domainsMap)
1898
+ );
1899
+ }
1900
+ };
1901
+ const collectCreateTables = (tables, dbStructure, currentSchema) => {
1902
+ return tables.reduce((acc, codeTable) => {
1903
+ const tableSchema = codeTable.q.schema ?? currentSchema;
1904
+ const hasDbTable = dbStructure.tables.some(
1905
+ (t) => t.name === codeTable.table && t.schemaName === tableSchema
1906
+ );
1907
+ if (!hasDbTable) {
1908
+ acc.push(codeTable);
1909
+ }
1910
+ return acc;
1911
+ }, []);
1912
+ };
1913
+ const collectChangeAndDropTables = (config, tables, dbStructure, currentSchema, createTables, generatorIgnore) => {
1914
+ const changeTables = [];
1915
+ const changeTableSchemas = [];
1916
+ const dropTables = [];
1917
+ const tableShapes = {};
1918
+ const ignoreTables = generatorIgnore?.tables?.map((name) => {
1919
+ const [schema = currentSchema, table] = getSchemaAndTableFromName(name);
1920
+ return { schema, table };
1921
+ });
1922
+ for (const dbTable of dbStructure.tables) {
1923
+ if (dbTable.name === config.migrationsTable || generatorIgnore?.schemas?.includes(dbTable.schemaName) || ignoreTables?.some(
1924
+ ({ schema, table }) => table === dbTable.name && schema === dbTable.schemaName
1925
+ ))
1926
+ continue;
1927
+ const codeTable = tables.find(
1928
+ (t) => t.table === dbTable.name && (t.q.schema ?? currentSchema) === dbTable.schemaName
1929
+ );
1930
+ if (codeTable) {
1931
+ addChangeTable(
1932
+ dbStructure,
1933
+ changeTables,
1934
+ tableShapes,
1935
+ currentSchema,
1936
+ dbTable,
1937
+ codeTable
1938
+ );
1939
+ continue;
1940
+ }
1941
+ const i = createTables.findIndex((t) => t.table === dbTable.name);
1942
+ if (i !== -1) {
1943
+ const codeTable2 = createTables[i];
1944
+ createTables.splice(i, 1);
1945
+ changeTableSchemas.push({ codeTable: codeTable2, dbTable });
1946
+ continue;
1947
+ }
1948
+ dropTables.push(dbTable);
1949
+ }
1950
+ return { changeTables, changeTableSchemas, dropTables, tableShapes };
1951
+ };
1952
+ const applyChangeTableSchemas = (changeTableSchemas, currentSchema, ast) => {
1953
+ for (const { codeTable, dbTable } of changeTableSchemas) {
1954
+ const fromSchema = dbTable.schemaName;
1955
+ const toSchema = codeTable.q.schema ?? currentSchema;
1956
+ ast.push({
1957
+ type: "renameType",
1958
+ kind: "TABLE",
1959
+ fromSchema,
1960
+ from: dbTable.name,
1961
+ toSchema,
1962
+ to: dbTable.name
1963
+ });
1964
+ }
1965
+ };
1966
+ const applyChangeTables = async (adapter, changeTables, structureToAstCtx, dbStructure, domainsMap, ast, currentSchema, config, compareSql, tableExpressions, verifying) => {
1967
+ const compareExpressions = [];
1968
+ const typeCastsCache = {};
1969
+ for (const changeTableData of changeTables) {
1970
+ compareExpressions.length = 0;
1971
+ await processTableChange(
1972
+ adapter,
1973
+ structureToAstCtx,
1974
+ dbStructure,
1975
+ domainsMap,
1976
+ ast,
1977
+ currentSchema,
1978
+ config,
1979
+ changeTableData,
1980
+ compareSql,
1981
+ compareExpressions,
1982
+ typeCastsCache,
1983
+ verifying
1984
+ );
1985
+ if (compareExpressions.length) {
1986
+ const { codeTable } = changeTableData;
1987
+ const names = [];
1988
+ const types = [];
1989
+ for (const key in codeTable.shape) {
1990
+ const column = codeTable.shape[key];
1991
+ if (!column.dataType) continue;
1992
+ const name = column.data.name ?? key;
1993
+ names.push(name);
1994
+ types.push(getColumnDbType(column, currentSchema));
1995
+ }
1996
+ const tableName = codeTable.table;
1997
+ const source = `(VALUES (${types.map((x) => `NULL::${x}`).join(", ")})) "${tableName}"(${names.map((x) => `"${x}"`).join(", ")})`;
1998
+ tableExpressions.push(
1999
+ ...compareExpressions.map((x) => ({ ...x, source }))
2000
+ );
2001
+ }
2002
+ }
2003
+ };
2004
+ const applyCompareSql = async (compareSql, adapter) => {
2005
+ if (compareSql.expressions.length) {
2006
+ const {
2007
+ rows: [results]
2008
+ } = await adapter.arrays(
2009
+ "SELECT " + compareSql.expressions.map((x) => `${x.inDb} = (${x.inCode})`).join(", "),
2010
+ compareSql.values
2011
+ );
2012
+ for (let i = 0; i < results.length; i++) {
2013
+ if (!results[i]) {
2014
+ compareSql.expressions[i].change();
2015
+ }
2016
+ }
2017
+ }
2018
+ };
2019
+ const applyCreateOrRenameTables = async (dbStructure, createTables, dropTables, changeTables, tableShapes, currentSchema, ast, verifying) => {
2020
+ for (const codeTable of createTables) {
2021
+ if (dropTables.length) {
2022
+ const i = await promptCreateOrRename(
2023
+ "table",
2024
+ codeTable.table,
2025
+ dropTables.map((x) => x.name),
2026
+ verifying
2027
+ );
2028
+ if (i) {
2029
+ const dbTable = dropTables[i - 1];
2030
+ dropTables.splice(i - 1, 1);
2031
+ ast.push({
2032
+ type: "renameType",
2033
+ kind: "TABLE",
2034
+ fromSchema: dbTable.schemaName,
2035
+ from: dbTable.name,
2036
+ toSchema: codeTable.q.schema ?? currentSchema,
2037
+ to: codeTable.table
2038
+ });
2039
+ addChangeTable(
2040
+ dbStructure,
2041
+ changeTables,
2042
+ tableShapes,
2043
+ currentSchema,
2044
+ dbTable,
2045
+ codeTable
2046
+ );
2047
+ continue;
2048
+ }
2049
+ }
2050
+ ast.push(createTableAst(currentSchema, codeTable));
2051
+ }
2052
+ };
2053
+ const addChangeTable = (dbStructure, changeTables, tableShapes, currentSchema, dbTable, codeTable) => {
2054
+ const shape = {};
2055
+ const schema = codeTable.q.schema ?? currentSchema;
2056
+ changeTables.push({
2057
+ codeTable: cloneCodeTableForChange(codeTable),
2058
+ dbTable,
2059
+ dbTableData: getDbStructureTableData(dbStructure, dbTable),
2060
+ schema,
2061
+ changeTableAst: {
2062
+ type: "changeTable",
2063
+ schema,
2064
+ name: codeTable.table,
2065
+ shape,
2066
+ add: {},
2067
+ drop: {}
2068
+ },
2069
+ pushedAst: false,
2070
+ changingColumns: {},
2071
+ delayedAst: []
2072
+ });
2073
+ tableShapes[`${schema}.${codeTable.table}`] = shape;
2074
+ };
2075
+ const cloneCodeTableForChange = (codeTable) => ({
2076
+ ...codeTable,
2077
+ // codeTable is a class instance and not all props can be cloned with `...`
2078
+ table: codeTable.table,
2079
+ shape: Object.fromEntries(
2080
+ Object.entries(codeTable.shape).map(([key, column]) => {
2081
+ const cloned = Object.create(column);
2082
+ cloned.data = {
2083
+ ...cloned.data,
2084
+ checks: cloned.data.checks && [...cloned.data.checks]
2085
+ };
2086
+ return [key, cloned];
2087
+ })
2088
+ )
2089
+ });
2090
+ const createTableAst = (currentSchema, table) => {
2091
+ return {
2092
+ type: "table",
2093
+ action: "create",
2094
+ schema: table.q.schema === currentSchema ? void 0 : table.q.schema,
2095
+ comment: table.internal.comment,
2096
+ name: table.table,
2097
+ shape: makeTableShape(table),
2098
+ noPrimaryKey: table.internal.noPrimaryKey ? "ignore" : "error",
2099
+ ...table.internal.tableData
2100
+ };
2101
+ };
2102
+ const makeTableShape = (table) => {
2103
+ const shape = {};
2104
+ for (const key in table.shape) {
2105
+ const column = table.shape[key];
2106
+ if (!(column instanceof VirtualColumn)) {
2107
+ shape[key] = column;
2108
+ }
2109
+ }
2110
+ return shape;
2111
+ };
2112
+ const processTableChange = async (adapter, structureToAstCtx, dbStructure, domainsMap, ast, currentSchema, config, changeTableData, compareSql, compareExpressions, typeCastsCache, verifying) => {
2113
+ await processColumns(
2114
+ adapter,
2115
+ config,
2116
+ structureToAstCtx,
2117
+ dbStructure,
2118
+ domainsMap,
2119
+ changeTableData,
2120
+ ast,
2121
+ currentSchema,
2122
+ compareSql,
2123
+ typeCastsCache,
2124
+ verifying
2125
+ );
2126
+ processPrimaryKey(config, changeTableData);
2127
+ processIndexesAndExcludes(config, changeTableData, ast, compareExpressions);
2128
+ processChecks(ast, changeTableData, compareExpressions);
2129
+ const { changeTableAst } = changeTableData;
2130
+ if (Object.keys(changeTableAst.shape).length || Object.keys(changeTableAst.add).length || Object.keys(changeTableAst.drop).length) {
2131
+ changeTableData.pushedAst = true;
2132
+ ast.push(changeTableAst);
2133
+ }
2134
+ if (changeTableData.delayedAst.length) {
2135
+ ast.push(...changeTableData.delayedAst);
2136
+ }
2137
+ };
2138
+
2139
+ const composeMigration = async (adapter, config, ast, dbStructure, params) => {
2140
+ const { structureToAstCtx, currentSchema } = params;
2141
+ const domainsMap = makeDomainsMap(structureToAstCtx, dbStructure);
2142
+ await processSchemas(ast, dbStructure, params);
2143
+ processExtensions(ast, dbStructure, params);
2144
+ await processDomains(ast, adapter, domainsMap, dbStructure, params);
2145
+ await processEnums(ast, dbStructure, params);
2146
+ await processTables(ast, domainsMap, adapter, dbStructure, config, params);
2147
+ return astToMigration(currentSchema, config, ast);
2148
+ };
2149
+
2150
+ const rollbackErr = new Error("Rollback");
2151
+ const verifyMigration = async (adapter, config, migrationCode, generateMigrationParams) => {
2152
+ const migrationFn = new Function("change", migrationCode);
2153
+ let code;
2154
+ try {
2155
+ await adapter.transaction(void 0, async (trx) => {
2156
+ const changeFns = [];
2157
+ migrationFn((changeCb) => {
2158
+ changeFns.push(changeCb);
2159
+ });
2160
+ const { log } = config;
2161
+ config.log = false;
2162
+ const db = createMigrationInterface(trx, true, config);
2163
+ config.log = log;
2164
+ for (const changeFn of changeFns) {
2165
+ await changeFn(db, true);
2166
+ }
2167
+ const dbStructure = await introspectDbSchema(trx);
2168
+ generateMigrationParams.verifying = true;
2169
+ try {
2170
+ code = await composeMigration(
2171
+ trx,
2172
+ config,
2173
+ [],
2174
+ dbStructure,
2175
+ generateMigrationParams
2176
+ );
2177
+ } catch (err) {
2178
+ if (err instanceof AbortSignal) {
2179
+ code = false;
2180
+ throw rollbackErr;
2181
+ }
2182
+ throw err;
2183
+ }
2184
+ throw rollbackErr;
2185
+ });
2186
+ } catch (err) {
2187
+ if (err !== rollbackErr) {
2188
+ throw err;
2189
+ }
2190
+ }
2191
+ return code;
2192
+ };
2193
+
2194
+ const report = (ast, config, currentSchema) => {
2195
+ if (!config.logger) return;
2196
+ const code = [];
2197
+ let green, red, yellow, pale;
2198
+ if (typeof config.log === "object" && config.log.colors === false) {
2199
+ green = red = yellow = pale = (s) => s;
2200
+ } else {
2201
+ ({ green, red, yellow, pale } = colors);
2202
+ }
2203
+ for (const a of ast) {
2204
+ switch (a.type) {
2205
+ case "table": {
2206
+ let hasPrimaryKey = !!a.primaryKey;
2207
+ const counters = {
2208
+ column: 0,
2209
+ index: a.indexes?.length ?? 0,
2210
+ exclude: a.excludes?.length ?? 0,
2211
+ "foreign key": a.constraints?.reduce(
2212
+ (sum, c) => c.references ? sum + 1 : sum,
2213
+ 0
2214
+ ) ?? 0,
2215
+ check: a.constraints?.reduce(
2216
+ (sum, c) => c.check ? sum + 1 : sum,
2217
+ 0
2218
+ ) ?? 0
2219
+ };
2220
+ for (const key in a.shape) {
2221
+ counters.column++;
2222
+ const column = a.shape[key];
2223
+ if (column.data.primaryKey) {
2224
+ hasPrimaryKey = true;
2225
+ }
2226
+ if (column.data.indexes) {
2227
+ counters.index += column.data.indexes.length;
2228
+ }
2229
+ if (column.data.excludes) {
2230
+ counters.exclude += column.data.excludes.length;
2231
+ }
2232
+ if (column.data.foreignKeys) {
2233
+ counters["foreign key"] += column.data.foreignKeys.length;
2234
+ }
2235
+ if (column.data.checks) {
2236
+ counters.check += column.data.checks.length;
2237
+ }
2238
+ }
2239
+ const summary = [];
2240
+ for (const key in counters) {
2241
+ const value = counters[key];
2242
+ if (value || key === "column") {
2243
+ summary.push(
2244
+ `${value} ${pluralize(key, value, key === "index" ? "es" : "s")}`
2245
+ );
2246
+ }
2247
+ }
2248
+ if (!hasPrimaryKey) {
2249
+ summary.push("no primary key");
2250
+ }
2251
+ code.push(
2252
+ `${a.action === "create" ? green("+ create table") : red("- drop table")} ${dbItemName(a, currentSchema)} (${summary.join(", ")})`
2253
+ );
2254
+ break;
2255
+ }
2256
+ case "changeTable": {
2257
+ const inner = [];
2258
+ const toCodeCtx = {
2259
+ t: "t",
2260
+ table: a.name,
2261
+ currentSchema,
2262
+ migration: true,
2263
+ snakeCase: config.snakeCase
2264
+ };
2265
+ for (const key in a.shape) {
2266
+ const changes = toArray(a.shape[key]);
2267
+ for (const change of changes) {
2268
+ if (change.type === "add" || change.type === "drop") {
2269
+ const column = change.item;
2270
+ const { primaryKey, indexes, excludes, foreignKeys, checks } = column.data;
2271
+ inner.push(
2272
+ `${change.type === "add" ? green("+ add column") : red("- drop column")} ${key} ${column.data.alias ?? getColumnDbType(column, currentSchema)}${column.data.isNullable ? " nullable" : ""}${primaryKey ? " primary key" : ""}${foreignKeys ? ` references ${foreignKeys.map((fk) => {
2273
+ return `${fnOrTableToString(
2274
+ fk.fnOrTable
2275
+ )}(${fk.foreignColumns.join(", ")})`;
2276
+ }).join(", ")}` : ""}${indexes?.length ? indexes.length === 1 ? ", has index" : `, has ${indexes.length} indexes` : ""}${excludes?.length ? excludes.length === 1 ? ", has exclude" : `, has ${excludes.length} excludes` : ""}${checks?.length ? `, checks ${checks.map((check) => check.sql.toSQL({ values: [] })).join(", ")}` : ""}`
2277
+ );
2278
+ } else if (change.type === "change") {
2279
+ let name = change.from.column?.data.name ?? key;
2280
+ if (config.snakeCase) name = toCamelCase(name);
2281
+ const changes2 = [];
2282
+ inner.push(`${yellow("~ change column")} ${name}:`, changes2);
2283
+ changes2.push(`${yellow("from")}: `);
2284
+ const fromCode = change.from.column.toCode(toCodeCtx, key);
2285
+ for (const code2 of fromCode) {
2286
+ addCode(changes2, code2);
2287
+ }
2288
+ changes2.push(` ${yellow("to")}: `);
2289
+ const toCode = change.to.column.toCode(toCodeCtx, key);
2290
+ for (const code2 of toCode) {
2291
+ addCode(changes2, code2);
2292
+ }
2293
+ } else if (change.type === "rename") {
2294
+ inner.push(
2295
+ `${yellow("~ rename column")} ${config.snakeCase ? toCamelCase(key) : key} ${yellow("=>")} ${change.name}`
2296
+ );
2297
+ } else {
2298
+ exhaustive(change.type);
2299
+ }
2300
+ }
2301
+ }
2302
+ if (a.drop.primaryKey) {
2303
+ inner.push(
2304
+ `${red(`- drop primary key`)} on (${a.drop.primaryKey.columns.join(
2305
+ ", "
2306
+ )})`
2307
+ );
2308
+ }
2309
+ if (a.drop.indexes) {
2310
+ for (const index of a.drop.indexes) {
2311
+ inner.push(
2312
+ `${red(
2313
+ `- drop${index.options.unique ? " unique" : ""} index`
2314
+ )} on (${index.columns.map((c) => "column" in c ? c.column : c.expression).join(", ")})`
2315
+ );
2316
+ }
2317
+ }
2318
+ if (a.drop.excludes) {
2319
+ for (const exclude of a.drop.excludes) {
2320
+ inner.push(
2321
+ `${red(`- drop exclude`)} on (${exclude.columns.map((c) => "column" in c ? c.column : c.expression).join(", ")})`
2322
+ );
2323
+ }
2324
+ }
2325
+ if (a.drop.constraints) {
2326
+ for (const { references } of a.drop.constraints) {
2327
+ if (!references) continue;
2328
+ const [schema, name] = getSchemaAndTableFromName(
2329
+ references.fnOrTable
2330
+ );
2331
+ inner.push(
2332
+ `${red(`- drop foreign key`)} on (${references.columns.join(
2333
+ ", "
2334
+ )}) to ${dbItemName(
2335
+ {
2336
+ schema,
2337
+ name
2338
+ },
2339
+ currentSchema
2340
+ )}(${references.foreignColumns.join(", ")})`
2341
+ );
2342
+ }
2343
+ for (const { check } of a.drop.constraints) {
2344
+ if (!check) continue;
2345
+ inner.push(`${red(`- drop check`)} ${check.toSQL({ values: [] })}`);
2346
+ }
2347
+ }
2348
+ if (a.add.primaryKey) {
2349
+ inner.push(
2350
+ `${green(`+ add primary key`)} on (${a.add.primaryKey.columns.join(
2351
+ ", "
2352
+ )})`
2353
+ );
2354
+ }
2355
+ if (a.add.indexes) {
2356
+ for (const index of a.add.indexes) {
2357
+ inner.push(
2358
+ `${green(
2359
+ `+ add${index.options.unique ? " unique" : ""} index`
2360
+ )} on (${index.columns.map((c) => "column" in c ? c.column : c.expression).join(", ")})`
2361
+ );
2362
+ }
2363
+ }
2364
+ if (a.add.excludes) {
2365
+ for (const exclude of a.add.excludes) {
2366
+ inner.push(
2367
+ `${green(`+ add exclude`)} on (${exclude.columns.map((c) => "column" in c ? c.column : c.expression).join(", ")})`
2368
+ );
2369
+ }
2370
+ }
2371
+ if (a.add.constraints) {
2372
+ for (const { references } of a.add.constraints) {
2373
+ if (!references) continue;
2374
+ inner.push(
2375
+ `${green(`+ add foreign key`)} on (${references.columns.join(
2376
+ ", "
2377
+ )}) to ${references.fnOrTable}(${references.foreignColumns.join(", ")})`
2378
+ );
2379
+ }
2380
+ for (const { check } of a.add.constraints) {
2381
+ if (!check) continue;
2382
+ inner.push(
2383
+ `${green(`+ add check`)} ${check.toSQL({ values: [] })}`
2384
+ );
2385
+ }
2386
+ }
2387
+ code.push(
2388
+ `${yellow("~ change table")} ${dbItemName(a, currentSchema)}${inner.length ? ":" : ""}`
2389
+ );
2390
+ if (inner.length) {
2391
+ code.push(inner);
2392
+ }
2393
+ break;
2394
+ }
2395
+ case "schema": {
2396
+ code.push(
2397
+ `${a.action === "create" ? green("+ create schema") : red("- drop schema")} ${a.name}`
2398
+ );
2399
+ break;
2400
+ }
2401
+ case "renameSchema": {
2402
+ code.push(
2403
+ `${yellow("~ rename schema")} ${a.from} ${yellow("=>")} ${a.to}`
2404
+ );
2405
+ break;
2406
+ }
2407
+ case "renameType": {
2408
+ code.push(
2409
+ `${yellow(
2410
+ `~ ${a.fromSchema !== a.toSchema ? a.from !== a.to ? "change schema and rename" : "change schema of" : "rename"} ${a.kind.toLowerCase()}`
2411
+ )} ${dbItemName(
2412
+ {
2413
+ schema: a.fromSchema,
2414
+ name: a.from
2415
+ },
2416
+ currentSchema
2417
+ )} ${yellow("=>")} ${dbItemName(
2418
+ {
2419
+ schema: a.toSchema,
2420
+ name: a.to
2421
+ },
2422
+ currentSchema
2423
+ )}`
2424
+ );
2425
+ break;
2426
+ }
2427
+ case "extension": {
2428
+ code.push(
2429
+ `${a.action === "create" ? green("+ create extension") : red("- drop extension")} ${dbItemName(a, currentSchema)}${a.version ? ` ${pale(a.version)}` : ""}`
2430
+ );
2431
+ break;
2432
+ }
2433
+ case "enum": {
2434
+ code.push(
2435
+ `${a.action === "create" ? green("+ create enum") : red("- drop enum")} ${dbItemName(a, currentSchema)}: (${a.values.join(", ")})`
2436
+ );
2437
+ break;
2438
+ }
2439
+ case "enumValues": {
2440
+ code.push(
2441
+ `${a.action === "add" ? green("+ add values to enum") : red("- remove values from enum")} ${dbItemName(a, currentSchema)}: ${a.values.join(", ")}`
2442
+ );
2443
+ break;
2444
+ }
2445
+ case "changeEnumValues": {
2446
+ if (a.fromValues) {
2447
+ code.push(
2448
+ `${red("- remove values from enum")} ${dbItemName(
2449
+ a,
2450
+ currentSchema
2451
+ )}: ${a.fromValues.join(", ")}`
2452
+ );
2453
+ }
2454
+ if (a.toValues) {
2455
+ code.push(
2456
+ `${green("+ add values to enum")} ${dbItemName(
2457
+ a,
2458
+ currentSchema
2459
+ )}: ${a.toValues.join(", ")}`
2460
+ );
2461
+ }
2462
+ break;
2463
+ }
2464
+ case "domain": {
2465
+ code.push(
2466
+ `${a.action === "create" ? green("+ create domain") : red("- drop domain")} ${dbItemName(a, currentSchema)}`
2467
+ );
2468
+ break;
2469
+ }
2470
+ case "view":
2471
+ case "collation":
2472
+ case "renameEnumValues":
2473
+ case "constraint":
2474
+ break;
2475
+ case "renameTableItem": {
2476
+ code.push(
2477
+ `${yellow(`~ rename ${a.kind.toLowerCase()}`)} on table ${dbItemName(
2478
+ { schema: a.tableSchema, name: a.tableName },
2479
+ currentSchema
2480
+ )}: ${a.from} ${yellow("=>")} ${a.to}`
2481
+ );
2482
+ break;
2483
+ }
2484
+ default:
2485
+ exhaustive(a);
2486
+ }
2487
+ }
2488
+ const result = codeToString(code, "", " ");
2489
+ config.logger.log(result);
2490
+ };
2491
+ const dbItemName = ({ schema, name }, currentSchema) => {
2492
+ return schema && schema !== currentSchema ? `${schema}.${name}` : name;
2493
+ };
2494
+
2495
+ class AbortSignal extends Error {
2496
+ }
2497
+ const generate = async (adapters, config, args, afterPull) => {
2498
+ let { dbPath } = config;
2499
+ if (!dbPath || !config.baseTable) throw invalidConfig(config);
2500
+ if (!adapters.length) throw new Error(`Database options must not be empty`);
2501
+ if (!dbPath.endsWith(".ts")) dbPath += ".ts";
2502
+ let migrationName = args[0] ?? "generated";
2503
+ let up;
2504
+ if (migrationName === "up") {
2505
+ up = true;
2506
+ migrationName = "generated";
2507
+ } else {
2508
+ up = args[1] === "up";
2509
+ }
2510
+ if (afterPull) {
2511
+ adapters = [afterPull.adapter];
2512
+ }
2513
+ const { dbStructure } = await migrateAndPullStructures(
2514
+ adapters,
2515
+ config,
2516
+ afterPull
2517
+ );
2518
+ const [adapter] = adapters;
2519
+ const currentSchema = adapter.schema ?? "public";
2520
+ const db = await getDbFromConfig(config, dbPath);
2521
+ const { columnTypes, internal } = db.$qb;
2522
+ const codeItems = await getActualItems(
2523
+ db,
2524
+ currentSchema,
2525
+ internal,
2526
+ columnTypes
2527
+ );
2528
+ const structureToAstCtx = makeStructureToAstCtx(config, currentSchema);
2529
+ const generateMigrationParams = {
2530
+ structureToAstCtx,
2531
+ codeItems,
2532
+ currentSchema,
2533
+ internal
2534
+ };
2535
+ const ast = [];
2536
+ let migrationCode;
2537
+ try {
2538
+ migrationCode = await composeMigration(
2539
+ adapter,
2540
+ config,
2541
+ ast,
2542
+ dbStructure,
2543
+ generateMigrationParams
2544
+ );
2545
+ } catch (err) {
2546
+ if (err instanceof AbortSignal) {
2547
+ await closeAdapters(adapters);
2548
+ return;
2549
+ }
2550
+ throw err;
2551
+ }
2552
+ if (migrationCode && !afterPull) {
2553
+ const result = await verifyMigration(
2554
+ adapter,
2555
+ config,
2556
+ migrationCode,
2557
+ generateMigrationParams
2558
+ );
2559
+ if (result !== void 0) {
2560
+ throw new Error(
2561
+ `Failed to verify generated migration: some of database changes were not applied properly. This is a bug, please open an issue, attach the following migration code:
2562
+ ${migrationCode}${result === false ? "" : `
2563
+ After applying:
2564
+ ${result}`}`
2565
+ );
2566
+ }
2567
+ }
2568
+ const { logger } = config;
2569
+ if ((!up || !migrationCode) && !afterPull) await closeAdapters(adapters);
2570
+ if (!migrationCode) {
2571
+ logger?.log("No changes were detected");
2572
+ return;
2573
+ }
2574
+ const version = afterPull?.version ?? await makeFileVersion({}, config);
2575
+ const delayLog = [];
2576
+ await writeMigrationFile(
2577
+ {
2578
+ ...config,
2579
+ logger: logger ? { ...logger, log: (msg) => delayLog.push(msg) } : logger
2580
+ },
2581
+ version,
2582
+ migrationName,
2583
+ migrationCode
2584
+ );
2585
+ report(ast, config, currentSchema);
2586
+ if (logger) {
2587
+ for (const msg of delayLog) {
2588
+ logger.log(`
2589
+ ${msg}`);
2590
+ }
2591
+ }
2592
+ if (up) {
2593
+ for (const adapter2 of adapters) {
2594
+ await migrateAndClose({ adapter: adapter2, config });
2595
+ }
2596
+ } else if (!afterPull) {
2597
+ await closeAdapters(adapters);
2598
+ }
2599
+ };
2600
+ const invalidConfig = (config) => new Error(
2601
+ `\`${config.dbPath ? "baseTable" : "dbPath"}\` setting must be set in the migrations config for the generator to work`
2602
+ );
2603
+ const getDbFromConfig = async (config, dbPath) => {
2604
+ const module = await config.import(
2605
+ pathToFileURL(path.resolve(config.basePath, dbPath)).toString()
2606
+ );
2607
+ const db = module[config.dbExportedAs ?? "db"];
2608
+ if (!db?.$qb) {
2609
+ throw new Error(
2610
+ `Unable to import OrchidORM instance as ${config.dbExportedAs ?? "db"} from ${config.dbPath}`
2611
+ );
2612
+ }
2613
+ return db;
2614
+ };
2615
+ const migrateAndPullStructures = async (adapters, config, afterPull) => {
2616
+ if (afterPull) {
2617
+ return {
2618
+ dbStructure: {
2619
+ schemas: [],
2620
+ tables: [],
2621
+ views: [],
2622
+ indexes: [],
2623
+ excludes: [],
2624
+ constraints: [],
2625
+ triggers: [],
2626
+ extensions: [],
2627
+ enums: [],
2628
+ domains: [],
2629
+ collations: []
2630
+ }
2631
+ };
2632
+ }
2633
+ for (const adapter of adapters) {
2634
+ await migrate({ adapter, config });
2635
+ }
2636
+ const dbStructures = await Promise.all(
2637
+ adapters.map((adapter) => introspectDbSchema(adapter))
2638
+ );
2639
+ const dbStructure = dbStructures[0];
2640
+ for (let i = 1; i < dbStructures.length; i++) {
2641
+ compareDbStructures(dbStructure, dbStructures[i], i);
2642
+ }
2643
+ return { dbStructure };
2644
+ };
2645
+ const compareDbStructures = (a, b, i, path2) => {
2646
+ let err;
2647
+ if (typeof a !== typeof b) {
2648
+ err = true;
2649
+ }
2650
+ if (!a || typeof a !== "object") {
2651
+ if (a !== b) {
2652
+ err = true;
2653
+ }
2654
+ } else {
2655
+ if (Array.isArray(a)) {
2656
+ for (let n = 0, len = a.length; n < len; n++) {
2657
+ compareDbStructures(
2658
+ a[n],
2659
+ b[n],
2660
+ i,
2661
+ path2 ? `${path2}[${n}]` : String(n)
2662
+ );
2663
+ }
2664
+ } else {
2665
+ for (const key in a) {
2666
+ compareDbStructures(
2667
+ a[key],
2668
+ b[key],
2669
+ i,
2670
+ path2 ? `${path2}.${key}` : key
2671
+ );
2672
+ }
2673
+ }
2674
+ }
2675
+ if (err) {
2676
+ throw new Error(`${path2} in the db 0 does not match db ${i}`);
2677
+ }
2678
+ };
2679
+ const getActualItems = async (db, currentSchema, internal, columnTypes) => {
2680
+ const tableNames = /* @__PURE__ */ new Set();
2681
+ const habtmTables = /* @__PURE__ */ new Map();
2682
+ const codeItems = {
2683
+ schemas: /* @__PURE__ */ new Set(void 0),
2684
+ enums: /* @__PURE__ */ new Map(),
2685
+ tables: [],
2686
+ domains: []
2687
+ };
2688
+ const domains = /* @__PURE__ */ new Map();
2689
+ for (const key in db) {
2690
+ if (key[0] === "$") continue;
2691
+ const table = db[key];
2692
+ if (!table.table) {
2693
+ throw new Error(`Table ${key} is missing table property`);
2694
+ }
2695
+ const { schema } = table.q;
2696
+ const name = concatSchemaAndName({ schema, name: table.table });
2697
+ if (tableNames.has(name)) {
2698
+ throw new Error(`Table ${name} is defined more than once`);
2699
+ }
2700
+ tableNames.add(name);
2701
+ if (schema) codeItems.schemas.add(schema);
2702
+ codeItems.tables.push(table);
2703
+ for (const key2 in table.relations) {
2704
+ const column = table.shape[key2];
2705
+ if (column && "joinTable" in column) {
2706
+ processHasAndBelongsToManyColumn(column, habtmTables, codeItems);
2707
+ }
2708
+ }
2709
+ for (const key2 in table.shape) {
2710
+ const column = table.shape[key2];
2711
+ if (column.data.computed) {
2712
+ delete table.shape[key2];
2713
+ } else if (column instanceof DomainColumn) {
2714
+ const [schemaName = currentSchema, name2] = getSchemaAndTableFromName(
2715
+ column.dataType
2716
+ );
2717
+ domains.set(column.dataType, {
2718
+ schemaName,
2719
+ name: name2,
2720
+ column: column.data.as ?? new UnknownColumn(defaultSchemaConfig)
2721
+ });
2722
+ } else {
2723
+ const en = column.dataType === "enum" ? column : column instanceof ArrayColumn && column.data.item.dataType === "enum" ? column.data.item : void 0;
2724
+ if (en) {
2725
+ processEnumColumn(en, currentSchema, codeItems);
2726
+ }
2727
+ }
2728
+ }
2729
+ }
2730
+ if (internal.extensions) {
2731
+ for (const extension of internal.extensions) {
2732
+ const [schema] = getSchemaAndTableFromName(extension.name);
2733
+ if (schema) codeItems.schemas.add(schema);
2734
+ }
2735
+ }
2736
+ if (internal.domains) {
2737
+ for (const key in internal.domains) {
2738
+ const [schemaName = currentSchema, name] = getSchemaAndTableFromName(key);
2739
+ const column = internal.domains[key](columnTypes);
2740
+ domains.set(key, {
2741
+ schemaName,
2742
+ name,
2743
+ column
2744
+ });
2745
+ }
2746
+ }
2747
+ for (const domain of domains.values()) {
2748
+ codeItems.schemas.add(domain.schemaName);
2749
+ codeItems.domains.push(domain);
2750
+ }
2751
+ return codeItems;
2752
+ };
2753
+ const processEnumColumn = (column, currentSchema, codeItems) => {
2754
+ const { enumName, options } = column;
2755
+ const [schema, name] = getSchemaAndTableFromName(enumName);
2756
+ const enumSchema = schema ?? currentSchema;
2757
+ codeItems.enums.set(`${enumSchema}.${name}`, {
2758
+ schema: enumSchema,
2759
+ name,
2760
+ values: options
2761
+ });
2762
+ if (schema) codeItems.schemas.add(schema);
2763
+ };
2764
+ const processHasAndBelongsToManyColumn = (column, habtmTables, codeItems) => {
2765
+ const q = column.joinTable;
2766
+ const prev = habtmTables.get(q.table);
2767
+ if (prev) {
2768
+ for (const key in q.shape) {
2769
+ if (q.shape[key].dataType !== prev.shape[key]?.dataType) {
2770
+ throw new Error(
2771
+ `Column ${key} in ${q.table} in hasAndBelongsToMany relation does not match with the relation on the other side`
2772
+ );
2773
+ }
2774
+ }
2775
+ return;
2776
+ }
2777
+ habtmTables.set(q.table, q);
2778
+ const joinTable = Object.create(q);
2779
+ const shape = {};
2780
+ for (const key in joinTable.shape) {
2781
+ const column2 = Object.create(joinTable.shape[key]);
2782
+ column2.data = {
2783
+ ...column2.data,
2784
+ name: column2.data.name ?? key,
2785
+ identity: void 0,
2786
+ primaryKey: void 0,
2787
+ default: void 0
2788
+ };
2789
+ shape[toCamelCase(key)] = column2;
2790
+ }
2791
+ joinTable.shape = shape;
2792
+ joinTable.internal = {
2793
+ ...joinTable.internal,
2794
+ tableData: {
2795
+ ...joinTable.internal.tableData,
2796
+ primaryKey: {
2797
+ columns: Object.keys(shape)
2798
+ }
2799
+ },
2800
+ noPrimaryKey: false
2801
+ };
2802
+ codeItems.tables.push(joinTable);
2803
+ return;
2804
+ };
2805
+ const closeAdapters = (adapters) => {
2806
+ return Promise.all(adapters.map((x) => x.close()));
2807
+ };
2808
+
2809
+ const getTableInfosAndFKeys = (asts, config) => {
2810
+ var _a;
2811
+ const generateTableTo = config.generateTableTo ?? ((name) => `./tables/${name}.table.ts`);
2812
+ const tableInfos = {};
2813
+ const fkeys = {};
2814
+ for (const ast of asts) {
2815
+ if (ast.type === "table") {
2816
+ const tableKey = toCamelCase(ast.name);
2817
+ const dbTableName = ast.schema ? `${ast.schema}.${ast.name}` : ast.name;
2818
+ let tablePath = path.resolve(config.basePath, generateTableTo(tableKey));
2819
+ if (!tablePath.endsWith(".ts")) tablePath += ".ts";
2820
+ const name = toPascalCase(ast.name);
2821
+ const info = {
2822
+ dbTableName,
2823
+ key: tableKey,
2824
+ path: tablePath,
2825
+ name,
2826
+ className: `${name}Table`
2827
+ };
2828
+ tableInfos[dbTableName] = info;
2829
+ if (ast.constraints) {
2830
+ for (const { references } of ast.constraints) {
2831
+ if (!references) continue;
2832
+ (fkeys[_a = references.fnOrTable] ?? (fkeys[_a] = [])).push({
2833
+ table: info,
2834
+ references
2835
+ });
2836
+ }
2837
+ }
2838
+ }
2839
+ }
2840
+ return { tableInfos, fkeys };
2841
+ };
2842
+ const appCodeGenTable = (tableInfos, fkeys, ast, baseTablePath, baseTableExportedAs, currentSchema) => {
2843
+ const tableInfo = tableInfos[ast.schema ? `${ast.schema}.${ast.name}` : ast.name];
2844
+ const imports = {
2845
+ "orchid-orm": "Selectable, Insertable, Updatable",
2846
+ [getImportPath(tableInfo.path, baseTablePath)]: baseTableExportedAs
2847
+ };
2848
+ const props = [];
2849
+ if (ast.schema) {
2850
+ props.push(`schema = ${singleQuote(ast.schema)};`);
2851
+ }
2852
+ props.push(`readonly table = ${singleQuote(ast.name)};`);
2853
+ if (ast.comment) {
2854
+ props.push(`comment = ${singleQuote(ast.comment)};`);
2855
+ }
2856
+ if (ast.noPrimaryKey === "ignore") {
2857
+ props.push("noPrimaryKey = true;");
2858
+ }
2859
+ const hasTableData = Boolean(
2860
+ ast.primaryKey || ast.indexes?.length || ast.excludes?.length || ast.constraints?.length
2861
+ );
2862
+ const shapeCode = columnsShapeToCode(
2863
+ { t: "t", table: ast.name, currentSchema },
2864
+ ast.shape
2865
+ );
2866
+ props.push(
2867
+ `columns = this.setColumns(${hasTableData ? "\n " : ""}(t) => ({`,
2868
+ hasTableData ? [shapeCode] : shapeCode,
2869
+ hasTableData ? " })," : "}));"
2870
+ );
2871
+ if (hasTableData) {
2872
+ props.push(pushTableDataCode([], ast), ");");
2873
+ }
2874
+ const relations = [];
2875
+ const fullTableName = ast.schema ? `${ast.schema}.${ast.name}` : ast.name;
2876
+ const belongsTo = fkeys[fullTableName];
2877
+ if (belongsTo) {
2878
+ for (const { table, references } of belongsTo) {
2879
+ imports[getImportPath(tableInfo.path, table.path)] = table.className;
2880
+ relations.push(
2881
+ `${table.key}: this.belongsTo(() => ${table.className}, {`,
2882
+ [
2883
+ `columns: [${references.foreignColumns.map(singleQuote).join(", ")}],`,
2884
+ `references: [${references.columns.map(singleQuote).join(", ")}],`
2885
+ ],
2886
+ "}),"
2887
+ );
2888
+ }
2889
+ }
2890
+ if (ast.constraints) {
2891
+ for (const { references } of ast.constraints) {
2892
+ if (!references) continue;
2893
+ const table = tableInfos[references.fnOrTable];
2894
+ imports[getImportPath(tableInfo.path, table.path)] = table.className;
2895
+ relations.push(
2896
+ `${table.key}: this.hasMany(() => ${table.className}, {`,
2897
+ [
2898
+ `columns: [${references.columns.map(singleQuote).join(", ")}],`,
2899
+ `references: [${references.foreignColumns.map(singleQuote).join(", ")}],`
2900
+ ],
2901
+ "}),"
2902
+ );
2903
+ }
2904
+ }
2905
+ if (relations.length) {
2906
+ props.push("", "relations = {", relations, "};");
2907
+ }
2908
+ const importsCode = importsToCode(imports);
2909
+ const { name, className } = tableInfo;
2910
+ const code = [
2911
+ `export type ${name} = Selectable<${className}>;
2912
+ export type ${name}New = Insertable<${className}>;
2913
+ export type ${name}Update = Updatable<${className}>;
2914
+
2915
+ export class ${className} extends ${baseTableExportedAs} {`,
2916
+ props,
2917
+ "}\n"
2918
+ ];
2919
+ return {
2920
+ ...tableInfo,
2921
+ content: importsCode + "\n\n" + codeToString(code, "", " ")
2922
+ };
2923
+ };
2924
+ function importsToCode(imports) {
2925
+ return Object.entries(imports).map(([from, name]) => `import { ${name} } from '${from}';`).join("\n");
2926
+ }
2927
+
2928
+ const { createSourceFile, ScriptTarget, SyntaxKind } = typescript;
2929
+ const appCodeGenUpdateDbFile = async (dbPath, tables, extensions, domains, currentSchema) => {
2930
+ const content = await fs.readFile(dbPath, "utf-8");
2931
+ const statements = getTsStatements(content);
2932
+ const importName = getOrchidOrmImportName(statements);
2933
+ if (!importName) {
2934
+ throw new Error(`Main file does not contain import of orchid-orm`);
2935
+ }
2936
+ const { config, tablesList } = getOrchidOrmArgs(importName, statements);
2937
+ const changes = [];
2938
+ let replacedConfig;
2939
+ if (extensions.length || domains.length) {
2940
+ let code = content.slice(config.pos, config.end).trim();
2941
+ if (code[0] !== "{") code = `{...${code}}`;
2942
+ code = "{\n " + code.slice(1, -1).trim();
2943
+ if (!code.endsWith(",")) code += ",";
2944
+ if (extensions.length) {
2945
+ code += `
2946
+ extensions: [${extensions.map(
2947
+ (ext) => ext.version ? `{ ${quoteObjectKey(ext.name, false)}: '${ext.version}' }` : singleQuote(ext.name)
2948
+ ).join(", ")}],`;
2949
+ }
2950
+ if (domains.length) {
2951
+ code += `
2952
+ domains: {
2953
+ ${domains.sort((a, b) => a.name > b.name ? 1 : -1).map(
2954
+ (ast) => `${quoteObjectKey(
2955
+ ast.schema ? `${ast.schema}.${ast.name}` : ast.name,
2956
+ false
2957
+ )}: (t) => ${ast.baseType.toCode(
2958
+ { t: "t", table: ast.name, currentSchema },
2959
+ ast.baseType.data.name ?? ""
2960
+ )},`
2961
+ ).join("\n ")}
2962
+ },`;
2963
+ }
2964
+ replacedConfig = code + "\n}";
2965
+ }
2966
+ const tablesChanges = makeTablesListChanges(
2967
+ content,
2968
+ statements,
2969
+ tablesList,
2970
+ tables,
2971
+ dbPath
2972
+ );
2973
+ if (tablesChanges) {
2974
+ addChange(
2975
+ content,
2976
+ changes,
2977
+ tablesChanges.imports.pos,
2978
+ tablesChanges.imports.text
2979
+ );
2980
+ }
2981
+ if (replacedConfig) {
2982
+ replaceContent(content, changes, config.pos, config.end, replacedConfig);
2983
+ }
2984
+ if (tablesChanges) {
2985
+ addChange(
2986
+ content,
2987
+ changes,
2988
+ tablesChanges.tablesList.pos,
2989
+ tablesChanges.tablesList.text
2990
+ );
2991
+ }
2992
+ return applyChanges(content, changes);
2993
+ };
2994
+ const getTsStatements = (content) => {
2995
+ return createSourceFile("file.ts", content, ScriptTarget.Latest, true).statements;
2996
+ };
2997
+ const getOrchidOrmImportName = (statements) => {
2998
+ for (const node of statements) {
2999
+ if (node.kind !== SyntaxKind.ImportDeclaration) continue;
3000
+ const imp = node;
3001
+ const source = imp.moduleSpecifier.getText().slice(1, -1);
3002
+ if (source !== "orchid-orm") continue;
3003
+ if (!imp.importClause) continue;
3004
+ const elements = imp.importClause.namedBindings?.elements;
3005
+ for (const element of elements) {
3006
+ if (element.propertyName?.escapedText === "orchidORM" || element.name.escapedText === "orchidORM") {
3007
+ return element.name.escapedText.toString();
3008
+ }
3009
+ }
3010
+ }
3011
+ return;
3012
+ };
3013
+ const makeTablesListChanges = (content, statements, object, tables, dbPath) => {
3014
+ const spaces = getTablesListSpaces(content, object);
3015
+ let imports = "";
3016
+ let tablesList = "";
3017
+ const prependComma = object.properties.length && !object.properties.hasTrailingComma;
3018
+ const tablesListNewLine = content.slice(object.properties.end, object.end).includes("\n");
3019
+ const tablesArr = Object.values(tables);
3020
+ for (let i = 0; i < tablesArr.length; i++) {
3021
+ const { path, className, key } = tablesArr[i];
3022
+ const importPath = getImportPath(dbPath, path);
3023
+ imports += `
3024
+ import { ${className} } from '${importPath}';`;
3025
+ tablesList += `${i === 0 && prependComma ? "," : ""}
3026
+ ${spaces} ${key}: ${className},`;
3027
+ if (i === tablesArr.length - 1 && !tablesListNewLine) {
3028
+ tablesList += `
3029
+ ${spaces}`;
3030
+ }
3031
+ }
3032
+ if (!imports.length) return;
3033
+ let importPos = 0;
3034
+ for (const node of statements) {
3035
+ if (node.kind === SyntaxKind.ImportDeclaration) {
3036
+ importPos = node.end;
3037
+ }
3038
+ }
3039
+ return {
3040
+ imports: { pos: importPos, text: imports },
3041
+ tablesList: { pos: object.properties.end, text: tablesList }
3042
+ };
3043
+ };
3044
+ const getTablesListSpaces = (content, object) => {
3045
+ const lines = content.slice(0, object.end).split("\n");
3046
+ const last = lines[lines.length - 1];
3047
+ return last.match(/^\s+/)?.[0] || "";
3048
+ };
3049
+ const getOrchidOrmArgs = (importName, statements) => {
3050
+ for (const v of statements) {
3051
+ if (v.kind !== SyntaxKind.VariableStatement) continue;
3052
+ for (const node of v.declarationList.declarations) {
3053
+ const call = node.initializer;
3054
+ if (call?.kind !== SyntaxKind.CallExpression) continue;
3055
+ if (call.expression.getText() !== importName) continue;
3056
+ if (call.arguments.length !== 2) {
3057
+ throw new Error(
3058
+ "Invalid number of arguments when initializing orchid orm"
3059
+ );
3060
+ }
3061
+ const object = call.arguments[1];
3062
+ if (object?.kind !== SyntaxKind.ObjectLiteralExpression) {
3063
+ throw new Error(
3064
+ "Second argument of orchidORM must be an object literal"
3065
+ );
3066
+ }
3067
+ return { config: call.arguments[0], tablesList: object };
3068
+ }
3069
+ }
3070
+ throw new Error("List of tables is not found in main file");
3071
+ };
3072
+ const addChange = (content, changes, at, text, end = at) => {
3073
+ if (changes.length === 0) {
3074
+ changes.push([0, at], text, [end, content.length]);
3075
+ } else {
3076
+ const last = changes[changes.length - 1];
3077
+ last[1] = at;
3078
+ changes.push(text, [end, content.length]);
3079
+ }
3080
+ };
3081
+ const replaceContent = (content, changes, from, to, text) => {
3082
+ addChange(content, changes, from, text, to);
3083
+ };
3084
+ const applyChanges = (content, changes) => {
3085
+ return changes.length ? changes.map(
3086
+ (item) => typeof item === "string" ? item : content.slice(item[0], item[1])
3087
+ ).join("") : content;
3088
+ };
3089
+
3090
+ const pull = async (adapters, config) => {
3091
+ if (!config.dbPath || !config.baseTable) {
3092
+ throw new Error(
3093
+ `\`${config.dbPath ? "baseTable" : "dbPath"}\` setting must be set in the migrations config for pull command`
3094
+ );
3095
+ }
3096
+ const baseTablePath = config.baseTable.getFilePath();
3097
+ const baseTableExportedAs = config.baseTable.exportAs;
3098
+ const [adapter] = adapters;
3099
+ const currentSchema = adapter.schema || "public";
3100
+ const ctx = makeStructureToAstCtx(config, currentSchema);
3101
+ const asts = await structureToAst(ctx, adapter, config);
3102
+ const { tableInfos, fkeys } = getTableInfosAndFKeys(asts, config);
3103
+ const exclusiveWriteOptions = { flag: "wx" };
3104
+ const pendingFileWrites = [];
3105
+ const tables = {};
3106
+ const extensions = [];
3107
+ const domains = [];
3108
+ let firstTable;
3109
+ for (const ast of asts) {
3110
+ switch (ast.type) {
3111
+ case "table": {
3112
+ const table = appCodeGenTable(
3113
+ tableInfos,
3114
+ fkeys,
3115
+ ast,
3116
+ baseTablePath,
3117
+ baseTableExportedAs,
3118
+ currentSchema
3119
+ );
3120
+ tables[table.key] = table;
3121
+ if (!firstTable) firstTable = table;
3122
+ pendingFileWrites.push([
3123
+ table.path,
3124
+ table.content,
3125
+ exclusiveWriteOptions
3126
+ ]);
3127
+ break;
3128
+ }
3129
+ case "extension": {
3130
+ extensions.push({
3131
+ name: ast.schema ? `${ast.schema}.${ast.name}` : ast.name,
3132
+ version: ast.version
3133
+ });
3134
+ break;
3135
+ }
3136
+ case "domain": {
3137
+ domains.push(ast);
3138
+ break;
3139
+ }
3140
+ }
3141
+ }
3142
+ if (!firstTable && !extensions.length && !domains.length) {
3143
+ await adapter.close();
3144
+ return;
3145
+ }
3146
+ let dbPath = path.resolve(config.basePath, config.dbPath);
3147
+ if (!dbPath.endsWith(".ts")) dbPath += ".ts";
3148
+ const content = await appCodeGenUpdateDbFile(
3149
+ dbPath,
3150
+ tables,
3151
+ extensions,
3152
+ domains,
3153
+ currentSchema
3154
+ );
3155
+ if (content) pendingFileWrites.push([dbPath, content]);
3156
+ if (firstTable) {
3157
+ await fs.mkdir(path.dirname(firstTable.path), { recursive: true });
3158
+ }
3159
+ await Promise.all(
3160
+ pendingFileWrites.map(
3161
+ ([path2, content2, options]) => fs.writeFile(path2, content2, options).then(() => {
3162
+ config.logger?.log(`Created ${pathToLog(path2)}`);
3163
+ })
3164
+ )
3165
+ );
3166
+ const version = await makeFileVersion({}, config);
3167
+ await generate(adapters, config, ["pull"], { adapter, version });
3168
+ await Promise.all(
3169
+ adapters.map(async (adapter2) => {
3170
+ const silentAdapter = adapter2;
3171
+ silentAdapter.silentArrays = adapter2.arrays;
3172
+ await saveMigratedVersion(silentAdapter, version, "pull.ts", config);
3173
+ await adapter2.close();
3174
+ })
3175
+ );
3176
+ };
3177
+
3178
+ rakeDbCommands.g = rakeDbCommands.generate = {
3179
+ run: generate,
3180
+ help: "gen migration from OrchidORM tables",
3181
+ helpArguments: {
3182
+ "no arguments": '"generated" is a default file name',
3183
+ "migration-name": "set migration file name",
3184
+ up: "auto-apply migration",
3185
+ "migration-name up": "with a custom name and apply it"
3186
+ },
3187
+ helpAfter: "reset"
3188
+ };
3189
+ rakeDbCommands.pull.run = pull;
3190
+ rakeDbCommands.pull.help = "generate ORM tables and a migration for an existing database";
3191
+ //# sourceMappingURL=node-postgres.mjs.map