orchid-orm 1.60.0 → 1.60.1

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