orchid-orm 1.60.0 → 1.60.1

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