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