rake-db 2.17.8 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,8 +5,6 @@ var orchidCore = require('orchid-core');
5
5
  var path = require('path');
6
6
  var node_url = require('node:url');
7
7
  var fs = require('fs/promises');
8
- var prompts = require('prompts');
9
- var rakeDb$1 = require('rake-db');
10
8
 
11
9
  const getFirstWordAndRest = (input) => {
12
10
  const index = input.search(/(?=[A-Z])|[-_]/);
@@ -35,6 +33,12 @@ const getTextAfterTo = (input) => {
35
33
  const getTextAfterFrom = (input) => {
36
34
  return getTextAfterRegExp(input, /(From|-from|_from)[A-Z-_]/, 4);
37
35
  };
36
+ const joinWords = (...words) => {
37
+ return words.slice(1).reduce(
38
+ (acc, word) => acc + word[0].toUpperCase() + word.slice(1),
39
+ words[0]
40
+ );
41
+ };
38
42
  const joinColumns = (columns) => {
39
43
  return columns.map((column) => `"${column}"`).join(", ");
40
44
  };
@@ -50,11 +54,14 @@ const getSchemaAndTableFromName = (name) => {
50
54
  const quoteNameFromString = (string) => {
51
55
  return quoteTable(...getSchemaAndTableFromName(string));
52
56
  };
53
- const quoteSchemaTable = ({
57
+ const quoteSchemaTable = (arg) => {
58
+ return orchidCore.singleQuote(concatSchemaAndName(arg));
59
+ };
60
+ const concatSchemaAndName = ({
54
61
  schema,
55
62
  name
56
63
  }) => {
57
- return orchidCore.singleQuote(schema ? `${schema}.${name}` : name);
64
+ return schema ? `${schema}.${name}` : name;
58
65
  };
59
66
  const makePopulateEnumQuery = (item) => {
60
67
  const [schema, name] = getSchemaAndTableFromName(item.enumName);
@@ -66,13 +73,18 @@ const makePopulateEnumQuery = (item) => {
66
73
  };
67
74
  };
68
75
  const begin = {
69
- text: "BEGIN",
70
- values: orchidCore.emptyArray
76
+ text: "BEGIN"
71
77
  };
72
78
  const transaction = (adapter, fn) => {
73
79
  return adapter.transaction(begin, fn);
74
80
  };
75
81
  const queryLock = (trx) => trx.query(`SELECT pg_advisory_xact_lock('${RAKE_DB_LOCK_KEY}')`);
82
+ const exhaustive = (_) => {
83
+ throw new Error("Condition was not exhaustive");
84
+ };
85
+ const pluralize = (w, count, append = "s") => {
86
+ return count === 1 ? w : w + append;
87
+ };
76
88
 
77
89
  let currentChanges = [];
78
90
  const clearChanges = () => {
@@ -81,28 +93,28 @@ const clearChanges = () => {
81
93
  const getCurrentChanges = () => currentChanges;
82
94
  const pushChange = (fn) => currentChanges.push(fn);
83
95
 
84
- var __defProp$a = Object.defineProperty;
96
+ var __defProp$9 = Object.defineProperty;
85
97
  var __defProps$7 = Object.defineProperties;
86
98
  var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
87
- var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
88
- var __hasOwnProp$a = Object.prototype.hasOwnProperty;
89
- var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
90
- var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
91
- var __spreadValues$a = (a, b) => {
99
+ var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
100
+ var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
101
+ var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
102
+ var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
103
+ var __spreadValues$9 = (a, b) => {
92
104
  for (var prop in b || (b = {}))
93
- if (__hasOwnProp$a.call(b, prop))
94
- __defNormalProp$a(a, prop, b[prop]);
95
- if (__getOwnPropSymbols$a)
96
- for (var prop of __getOwnPropSymbols$a(b)) {
97
- if (__propIsEnum$a.call(b, prop))
98
- __defNormalProp$a(a, prop, b[prop]);
105
+ if (__hasOwnProp$9.call(b, prop))
106
+ __defNormalProp$9(a, prop, b[prop]);
107
+ if (__getOwnPropSymbols$9)
108
+ for (var prop of __getOwnPropSymbols$9(b)) {
109
+ if (__propIsEnum$9.call(b, prop))
110
+ __defNormalProp$9(a, prop, b[prop]);
99
111
  }
100
112
  return a;
101
113
  };
102
114
  var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
103
115
  const versionToString = (config, version) => config.migrationId === "serial" ? `${version}`.padStart(4, "0") : `${version}`;
104
116
  const columnTypeToSql = (item) => {
105
- return item.data.isOfCustomType ? `"${item.toSQL()}"` : item.toSQL();
117
+ return item.data.isOfCustomType ? quoteNameFromString(item.toSQL()) : item.toSQL();
106
118
  };
107
119
  const getColumnName = (item, key, snakeCase) => {
108
120
  return item.data.name || (snakeCase ? orchidCore.toSnakeCase(key) : key);
@@ -122,13 +134,16 @@ const columnToSql = (name, item, values, hasMultiplePrimaryKeys, snakeCase) => {
122
134
  `GENERATED ALWAYS AS (${item.data.generated.toSQL({ values })}) STORED`
123
135
  );
124
136
  }
125
- if (item.data.isPrimaryKey && !hasMultiplePrimaryKeys) {
137
+ if (item.data.primaryKey && !hasMultiplePrimaryKeys) {
138
+ if (item.data.primaryKey !== true) {
139
+ line.push(`CONSTRAINT "${item.data.primaryKey}"`);
140
+ }
126
141
  line.push("PRIMARY KEY");
127
142
  } else if (!item.data.isNullable) {
128
143
  line.push("NOT NULL");
129
144
  }
130
145
  if (item.data.check) {
131
- line.push(checkToSql(item.data.check, values));
146
+ line.push(checkToSql(item.data.check.sql, values));
132
147
  }
133
148
  const def = encodeColumnDefault(item.data.default, values, item);
134
149
  if (def !== null)
@@ -172,14 +187,14 @@ const sequenceOptionsToSql = (item) => {
172
187
  const line = [];
173
188
  if (item.dataType)
174
189
  line.push(`AS ${item.dataType}`);
175
- if (item.incrementBy !== void 0)
176
- line.push(`INCREMENT BY ${item.incrementBy}`);
190
+ if (item.increment !== void 0)
191
+ line.push(`INCREMENT BY ${item.increment}`);
177
192
  if (item.min !== void 0)
178
193
  line.push(`MINVALUE ${item.min}`);
179
194
  if (item.max !== void 0)
180
195
  line.push(`MAXVALUE ${item.max}`);
181
- if (item.startWith !== void 0)
182
- line.push(`START WITH ${item.startWith}`);
196
+ if (item.start !== void 0)
197
+ line.push(`START WITH ${item.start}`);
183
198
  if (item.cache !== void 0)
184
199
  line.push(`CACHE ${item.cache}`);
185
200
  if (item.cycle)
@@ -194,7 +209,7 @@ const addColumnIndex = (indexes, name, item) => {
194
209
  if (item.data.indexes) {
195
210
  indexes.push(
196
211
  ...item.data.indexes.map((index) => ({
197
- columns: [__spreadProps$7(__spreadValues$a({}, index), { column: name })],
212
+ columns: [__spreadProps$7(__spreadValues$9({}, index), { column: name })],
198
213
  options: index
199
214
  }))
200
215
  );
@@ -217,6 +232,8 @@ const getConstraintName = (table, constraint) => {
217
232
  return `${table}_${constraint.references.columns.join("_")}_fkey`;
218
233
  if (constraint.check)
219
234
  return `${table}_check`;
235
+ if (constraint.identity)
236
+ return `${table}_identity`;
220
237
  return `${table}_constraint`;
221
238
  };
222
239
  const constraintToSql = ({ name }, up, constraint, values, snakeCase) => {
@@ -263,12 +280,7 @@ const referencesToSql = (references, snakeCase) => {
263
280
  return sql.join(" ");
264
281
  };
265
282
  const getIndexName = (table, columns) => {
266
- return `${table}_${columns.map(
267
- (it) => {
268
- var _a;
269
- return "column" in it ? it.column : ((_a = it.expression.match(/\w+/g)) == null ? void 0 : _a.join("_")) || "expression";
270
- }
271
- ).join("_")}_idx`;
283
+ return `${table}_${columns.map((it) => "column" in it ? it.column : "expression").join("_")}_idx`;
272
284
  };
273
285
  const indexesToQuery = (up, { schema, name }, indexes, language) => {
274
286
  return indexes.map(({ columns, options }) => {
@@ -285,12 +297,12 @@ const indexesToQuery = (up, { schema, name }, indexes, language) => {
285
297
  sql.push("UNIQUE");
286
298
  }
287
299
  sql.push(`INDEX "${indexName}" ON ${quoteTable(schema, name)}`);
288
- const using = options.using || options.tsVector && "GIN";
289
- if (using) {
290
- sql.push(`USING ${using}`);
300
+ const u = options.using || options.tsVector && "GIN";
301
+ if (u) {
302
+ sql.push(`USING ${u}`);
291
303
  }
292
304
  const columnsSql = [];
293
- const lang = options.tsVector && options.languageColumn ? `"${options.languageColumn}"` : options.language ? typeof options.language === "string" ? `'${options.language}'` : options.language.toSQL({ values }) : `'${language || "english"}'`;
305
+ const lang = options.tsVector && options.languageColumn ? `"${options.languageColumn}"` : options.language ? `'${options.language}'` : `'${language || "english"}'`;
294
306
  let hasWeight = options.tsVector && columns.some((column) => !!column.weight);
295
307
  for (const column of columns) {
296
308
  const columnSql = [
@@ -315,11 +327,13 @@ const indexesToQuery = (up, { schema, name }, indexes, language) => {
315
327
  }
316
328
  columnsSql.push(sql2);
317
329
  }
318
- let columnList = columnsSql.join(hasWeight ? " || " : ", ");
319
- if (!hasWeight && options.tsVector) {
320
- if (columnsSql.length > 1)
321
- columnList = `concat_ws(' ', ${columnList})`;
322
- columnList = `to_tsvector(${lang}, ${columnList})`;
330
+ let columnList;
331
+ if (hasWeight) {
332
+ columnList = `(${columnsSql.join(" || ")})`;
333
+ } else if (options.tsVector) {
334
+ columnList = `to_tsvector(${lang}, ${columnsSql.join(" || ' ' || ")})`;
335
+ } else {
336
+ columnList = columnsSql.join(", ");
323
337
  }
324
338
  sql.push(`(${columnList})`);
325
339
  if (options.include) {
@@ -376,38 +390,38 @@ class RakeDbError extends Error {
376
390
  class NoPrimaryKey extends RakeDbError {
377
391
  }
378
392
 
379
- var __defProp$9 = Object.defineProperty;
393
+ var __defProp$8 = Object.defineProperty;
380
394
  var __defProps$6 = Object.defineProperties;
381
395
  var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
382
- var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
383
- var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
384
- var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
385
- var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
386
- var __spreadValues$9 = (a, b) => {
396
+ var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
397
+ var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
398
+ var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
399
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
400
+ var __spreadValues$8 = (a, b) => {
387
401
  for (var prop in b || (b = {}))
388
- if (__hasOwnProp$9.call(b, prop))
389
- __defNormalProp$9(a, prop, b[prop]);
390
- if (__getOwnPropSymbols$9)
391
- for (var prop of __getOwnPropSymbols$9(b)) {
392
- if (__propIsEnum$9.call(b, prop))
393
- __defNormalProp$9(a, prop, b[prop]);
402
+ if (__hasOwnProp$8.call(b, prop))
403
+ __defNormalProp$8(a, prop, b[prop]);
404
+ if (__getOwnPropSymbols$8)
405
+ for (var prop of __getOwnPropSymbols$8(b)) {
406
+ if (__propIsEnum$8.call(b, prop))
407
+ __defNormalProp$8(a, prop, b[prop]);
394
408
  }
395
409
  return a;
396
410
  };
397
411
  var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
398
- var __objRest$1 = (source, exclude) => {
412
+ var __objRest = (source, exclude) => {
399
413
  var target = {};
400
414
  for (var prop in source)
401
- if (__hasOwnProp$9.call(source, prop) && exclude.indexOf(prop) < 0)
415
+ if (__hasOwnProp$8.call(source, prop) && exclude.indexOf(prop) < 0)
402
416
  target[prop] = source[prop];
403
- if (source != null && __getOwnPropSymbols$9)
404
- for (var prop of __getOwnPropSymbols$9(source)) {
405
- if (exclude.indexOf(prop) < 0 && __propIsEnum$9.call(source, prop))
417
+ if (source != null && __getOwnPropSymbols$8)
418
+ for (var prop of __getOwnPropSymbols$8(source)) {
419
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$8.call(source, prop))
406
420
  target[prop] = source[prop];
407
421
  }
408
422
  return target;
409
423
  };
410
- const createTable$1 = async (migration, up, tableName, options, fn) => {
424
+ const createTable = async (migration, up, tableName, options, fn) => {
411
425
  var _a;
412
426
  const snakeCase = "snakeCase" in options ? options.snakeCase : migration.options.snakeCase;
413
427
  const language = "language" in options ? options.language : migration.options.language;
@@ -416,8 +430,19 @@ const createTable$1 = async (migration, up, tableName, options, fn) => {
416
430
  tableMethods
417
431
  );
418
432
  types[orchidCore.snakeCaseKey] = snakeCase;
419
- const shape = !fn ? orchidCore.emptyObject : pqb.getColumnTypes(types, fn, (_a = migration.options.baseTable) == null ? void 0 : _a.nowSQL, language);
420
- const tableData = pqb.getTableData();
433
+ let shape;
434
+ let tableData;
435
+ if (fn) {
436
+ shape = pqb.getColumnTypes(
437
+ types,
438
+ fn,
439
+ (_a = migration.options.baseTable) == null ? void 0 : _a.nowSQL,
440
+ language
441
+ );
442
+ tableData = pqb.getTableData();
443
+ } else {
444
+ shape = tableData = orchidCore.emptyObject;
445
+ }
421
446
  const ast = makeAst$2(
422
447
  up,
423
448
  tableName,
@@ -429,11 +454,10 @@ const createTable$1 = async (migration, up, tableName, options, fn) => {
429
454
  fn && validatePrimaryKey(ast);
430
455
  const queries = astToQueries$1(ast, snakeCase, language);
431
456
  for (const _b of queries) {
432
- const _c = _b, { then } = _c, query = __objRest$1(_c, ["then"]);
457
+ const _c = _b, { then } = _c, query = __objRest(_c, ["then"]);
433
458
  const result = await migration.adapter.arrays(query);
434
459
  then == null ? void 0 : then(result);
435
460
  }
436
- migration.migratedAsts.push(ast);
437
461
  let table;
438
462
  return {
439
463
  get table() {
@@ -448,20 +472,20 @@ const makeAst$2 = (up, tableName, shape, tableData, options, noPrimaryKey) => {
448
472
  const shapePKeys = [];
449
473
  for (const key in shape) {
450
474
  const column = shape[key];
451
- if (column.data.isPrimaryKey) {
475
+ if (column.data.primaryKey) {
452
476
  shapePKeys.push(key);
453
477
  }
454
478
  }
455
479
  const { primaryKey } = tableData;
456
480
  const [schema, table] = getSchemaAndTableFromName(tableName);
457
- return __spreadProps$6(__spreadValues$9(__spreadProps$6(__spreadValues$9({
481
+ return __spreadProps$6(__spreadValues$8(__spreadProps$6(__spreadValues$8({
458
482
  type: "table",
459
483
  action: up ? "create" : "drop",
460
484
  schema,
461
485
  name: table,
462
486
  shape
463
487
  }, tableData), {
464
- primaryKey: shapePKeys.length <= 1 ? primaryKey : primaryKey ? __spreadProps$6(__spreadValues$9({}, primaryKey), { columns: [...shapePKeys, ...primaryKey.columns] }) : { columns: shapePKeys }
488
+ primaryKey: shapePKeys.length <= 1 ? primaryKey : primaryKey ? __spreadProps$6(__spreadValues$8({}, primaryKey), { columns: [...shapePKeys, ...primaryKey.columns] }) : { columns: shapePKeys }
465
489
  }), options), {
466
490
  noPrimaryKey: options.noPrimaryKey ? "ignore" : noPrimaryKey || "error"
467
491
  });
@@ -472,7 +496,7 @@ const validatePrimaryKey = (ast) => {
472
496
  let hasPrimaryKey = !!((_b = (_a = ast.primaryKey) == null ? void 0 : _a.columns) == null ? void 0 : _b.length);
473
497
  if (!hasPrimaryKey) {
474
498
  for (const key in ast.shape) {
475
- if (ast.shape[key].data.isPrimaryKey) {
499
+ if (ast.shape[key].data.primaryKey) {
476
500
  hasPrimaryKey = true;
477
501
  break;
478
502
  }
@@ -538,8 +562,8 @@ const astToQueries$1 = (ast, snakeCase, language) => {
538
562
  ${constraintToSql(
539
563
  ast,
540
564
  true,
541
- __spreadProps$6(__spreadValues$9({}, item), {
542
- references: item.references ? __spreadProps$6(__spreadValues$9({}, item.references), {
565
+ __spreadProps$6(__spreadValues$8({}, item), {
566
+ references: item.references ? __spreadProps$6(__spreadValues$8({}, item.references), {
543
567
  columns: item.references.columns.map(
544
568
  (column) => getColumnName(shape[column], column, snakeCase)
545
569
  )
@@ -551,8 +575,8 @@ const astToQueries$1 = (ast, snakeCase, language) => {
551
575
  );
552
576
  });
553
577
  indexes.push(
554
- ...((_b = ast.indexes) == null ? void 0 : _b.map((index) => __spreadProps$6(__spreadValues$9({}, index), {
555
- columns: index.columns.map((item) => __spreadValues$9(__spreadValues$9({}, item), "column" in item ? {
578
+ ...((_b = ast.indexes) == null ? void 0 : _b.map((index) => __spreadProps$6(__spreadValues$8({}, index), {
579
+ columns: index.columns.map((item) => __spreadValues$8(__spreadValues$8({}, item), "column" in item ? {
556
580
  column: getColumnName(shape[item.column], item.column, snakeCase)
557
581
  } : {}))
558
582
  }))) || []
@@ -574,21 +598,21 @@ const astToQueries$1 = (ast, snakeCase, language) => {
574
598
  return queries;
575
599
  };
576
600
 
577
- var __defProp$8 = Object.defineProperty;
601
+ var __defProp$7 = Object.defineProperty;
578
602
  var __defProps$5 = Object.defineProperties;
579
603
  var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
580
- var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
581
- var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
582
- var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
583
- var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
584
- var __spreadValues$8 = (a, b) => {
604
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
605
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
606
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
607
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
608
+ var __spreadValues$7 = (a, b) => {
585
609
  for (var prop in b || (b = {}))
586
- if (__hasOwnProp$8.call(b, prop))
587
- __defNormalProp$8(a, prop, b[prop]);
588
- if (__getOwnPropSymbols$8)
589
- for (var prop of __getOwnPropSymbols$8(b)) {
590
- if (__propIsEnum$8.call(b, prop))
591
- __defNormalProp$8(a, prop, b[prop]);
610
+ if (__hasOwnProp$7.call(b, prop))
611
+ __defNormalProp$7(a, prop, b[prop]);
612
+ if (__getOwnPropSymbols$7)
613
+ for (var prop of __getOwnPropSymbols$7(b)) {
614
+ if (__propIsEnum$7.call(b, prop))
615
+ __defNormalProp$7(a, prop, b[prop]);
592
616
  }
593
617
  return a;
594
618
  };
@@ -608,16 +632,21 @@ const mergeTableData = (a, b) => {
608
632
  } else {
609
633
  a.primaryKey = {
610
634
  columns: [...a.primaryKey.columns, ...b.primaryKey.columns],
611
- options: __spreadValues$8(__spreadValues$8({}, a.primaryKey.options), b.primaryKey.options)
635
+ options: __spreadValues$7(__spreadValues$7({}, a.primaryKey.options), b.primaryKey.options)
612
636
  };
613
637
  }
614
638
  }
615
639
  a.indexes = [...a.indexes || [], ...b.indexes || []];
616
640
  a.constraints = [...a.constraints || [], ...b.constraints || []];
617
641
  };
642
+ const addOrDropChanges = [];
618
643
  function add(item, options) {
619
644
  if (item instanceof pqb.ColumnType) {
620
- return addOrDrop("add", item, options);
645
+ const result = addOrDrop("add", item, options);
646
+ if (result.type === "change")
647
+ return result;
648
+ addOrDropChanges.push(result);
649
+ return addOrDropChanges.length - 1;
621
650
  } else if (item === orchidCore.emptyObject) {
622
651
  mergeTableData(changeTableData.add, pqb.getTableData());
623
652
  pqb.resetTableData();
@@ -636,7 +665,11 @@ function add(item, options) {
636
665
  }
637
666
  const drop = function(item, options) {
638
667
  if (item instanceof pqb.ColumnType) {
639
- return addOrDrop("drop", item, options);
668
+ const result = addOrDrop("drop", item, options);
669
+ if (result.type === "change")
670
+ return result;
671
+ addOrDropChanges.push(result);
672
+ return addOrDropChanges.length - 1;
640
673
  } else if (item === orchidCore.emptyObject) {
641
674
  mergeTableData(changeTableData.drop, pqb.getTableData());
642
675
  pqb.resetTableData();
@@ -671,7 +704,7 @@ const addOrDrop = (type, item, options) => {
671
704
  check: item.data.check
672
705
  }
673
706
  });
674
- return __spreadValues$8({
707
+ return __spreadValues$7({
675
708
  type: "change",
676
709
  from: type === "add" ? empty : add2,
677
710
  to: type === "add" ? add2 : empty
@@ -689,19 +722,19 @@ const columnTypeToColumnChange = (item) => {
689
722
  if (foreignKeys == null ? void 0 : foreignKeys.some((it) => "fn" in it)) {
690
723
  throw new Error("Callback in foreignKey is not allowed in migration");
691
724
  }
692
- return __spreadProps$5(__spreadValues$8({
725
+ return __spreadProps$5(__spreadValues$7({
693
726
  column: item,
694
727
  type: item.toSQL(),
695
- nullable: item.data.isNullable,
696
- primaryKey: item.data.isPrimaryKey
728
+ nullable: item.data.isNullable
697
729
  }, item.data), {
730
+ primaryKey: item.data.primaryKey === void 0 ? void 0 : true,
698
731
  foreignKeys
699
732
  });
700
733
  }
701
734
  return item.to;
702
735
  };
703
736
  const nameKey = Symbol("name");
704
- const tableChangeMethods = __spreadProps$5(__spreadValues$8({}, tableMethods), {
737
+ const tableChangeMethods = __spreadProps$5(__spreadValues$7({}, tableMethods), {
705
738
  name(name) {
706
739
  orchidCore.setCurrentColumnName(name);
707
740
  const types = Object.create(this);
@@ -710,13 +743,14 @@ const tableChangeMethods = __spreadProps$5(__spreadValues$8({}, tableMethods), {
710
743
  },
711
744
  add,
712
745
  drop,
713
- change(from, to, options) {
714
- return __spreadValues$8({
746
+ change(from, to, using) {
747
+ return {
715
748
  type: "change",
716
- name: this[nameKey],
749
+ name: orchidCore.consumeColumnName(),
717
750
  from: columnTypeToColumnChange(from),
718
- to: columnTypeToColumnChange(to)
719
- }, options);
751
+ to: columnTypeToColumnChange(to),
752
+ using
753
+ };
720
754
  },
721
755
  default(value) {
722
756
  return { type: "change", from: { default: null }, to: { default: value } };
@@ -754,6 +788,7 @@ const changeTable = async (migration, up, tableName, options, fn) => {
754
788
  );
755
789
  Object.assign(tableChanger, tableChangeMethods);
756
790
  tableChanger[orchidCore.snakeCaseKey] = snakeCase;
791
+ addOrDropChanges.length = 0;
757
792
  const changeData = (fn == null ? void 0 : fn(tableChanger)) || {};
758
793
  const ast = makeAst$1(up, tableName, changeData, changeTableData, options);
759
794
  const queries = astToQueries(ast, snakeCase, language);
@@ -761,30 +796,54 @@ const changeTable = async (migration, up, tableName, options, fn) => {
761
796
  const result = await migration.adapter.arrays(query);
762
797
  (_a = query.then) == null ? void 0 : _a.call(query, result);
763
798
  }
764
- migration.migratedAsts.push(ast);
765
799
  };
766
800
  const makeAst$1 = (up, name, changeData, changeTableData2, options) => {
767
801
  const { comment } = options;
768
802
  const shape = {};
803
+ const consumedChanges = {};
769
804
  for (const key in changeData) {
770
805
  let item = changeData[key];
771
- if (item instanceof orchidCore.ColumnTypeBase) {
772
- item = add(item);
806
+ if (typeof item === "number") {
807
+ consumedChanges[item] = true;
808
+ item = addOrDropChanges[item];
809
+ } else if (item instanceof pqb.ColumnType) {
810
+ item = addOrDrop("add", item);
773
811
  }
774
812
  if ("type" in item) {
775
813
  if (up) {
776
- shape[key] = item.type === "change" && item.usingUp ? __spreadProps$5(__spreadValues$8({}, item), { using: item.usingUp }) : item;
814
+ shape[key] = item;
777
815
  } else {
778
816
  if (item.type === "rename") {
779
- shape[item.name] = __spreadProps$5(__spreadValues$8({}, item), { name: key });
817
+ shape[item.name] = __spreadProps$5(__spreadValues$7({}, item), { name: key });
780
818
  } else {
781
- shape[key] = item.type === "add" ? __spreadProps$5(__spreadValues$8({}, item), { type: "drop" }) : item.type === "drop" ? __spreadProps$5(__spreadValues$8({}, item), { type: "add" }) : item.type === "change" ? __spreadProps$5(__spreadValues$8({}, item), { from: item.to, to: item.from, using: item.usingDown }) : item;
819
+ shape[key] = item.type === "add" ? __spreadProps$5(__spreadValues$7({}, item), { type: "drop" }) : item.type === "drop" ? __spreadProps$5(__spreadValues$7({}, item), { type: "add" }) : item.type === "change" ? __spreadProps$5(__spreadValues$7({}, item), {
820
+ from: item.to,
821
+ to: item.from,
822
+ using: item.using && {
823
+ usingUp: item.using.usingDown,
824
+ usingDown: item.using.usingUp
825
+ }
826
+ }) : item;
782
827
  }
783
828
  }
784
829
  }
785
830
  }
831
+ for (let i = 0; i < addOrDropChanges.length; i++) {
832
+ if (consumedChanges[i])
833
+ continue;
834
+ const change = addOrDropChanges[i];
835
+ const name2 = change.item.data.name;
836
+ if (!name2) {
837
+ throw new Error(`Column in ...t.${change.type}() must have a name`);
838
+ }
839
+ const arr = shape[name2] ? orchidCore.toArray(shape[name2]) : [];
840
+ arr[up ? "push" : "unshift"](
841
+ up ? change : __spreadProps$5(__spreadValues$7({}, change), { type: change.type === "add" ? "drop" : "add" })
842
+ );
843
+ shape[name2] = arr;
844
+ }
786
845
  const [schema, table] = getSchemaAndTableFromName(name);
787
- return __spreadValues$8({
846
+ return __spreadValues$7({
788
847
  type: "changeTable",
789
848
  schema,
790
849
  name: table,
@@ -793,7 +852,7 @@ const makeAst$1 = (up, name, changeData, changeTableData2, options) => {
793
852
  }, up ? changeTableData2 : { add: changeTableData2.drop, drop: changeTableData2.add });
794
853
  };
795
854
  const astToQueries = (ast, snakeCase, language) => {
796
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
855
+ var _a;
797
856
  const queries = [];
798
857
  if (ast.comment !== void 0) {
799
858
  queries.push({
@@ -808,39 +867,26 @@ const astToQueries = (ast, snakeCase, language) => {
808
867
  };
809
868
  for (const key in ast.shape) {
810
869
  const item = ast.shape[key];
811
- if ("item" in item) {
812
- const { item: column } = item;
813
- if (column instanceof pqb.EnumColumn) {
814
- queries.push(makePopulateEnumQuery(column));
815
- }
816
- }
817
- if (item.type === "add") {
818
- if (item.item.data.isPrimaryKey) {
819
- addPrimaryKeys.columns.push(getColumnName(item.item, key, snakeCase));
820
- }
821
- } else if (item.type === "drop") {
822
- if (item.item.data.isPrimaryKey) {
823
- dropPrimaryKeys.columns.push(getColumnName(item.item, key, snakeCase));
824
- }
825
- } else if (item.type === "change") {
826
- if (item.from.column instanceof pqb.EnumColumn) {
827
- queries.push(makePopulateEnumQuery(item.from.column));
828
- }
829
- if (item.to.column instanceof pqb.EnumColumn) {
830
- queries.push(makePopulateEnumQuery(item.to.column));
831
- }
832
- if (item.from.primaryKey) {
833
- dropPrimaryKeys.columns.push(
834
- item.from.column ? getColumnName(item.from.column, key, snakeCase) : snakeCase ? orchidCore.toSnakeCase(key) : key
835
- );
836
- dropPrimaryKeys.change = true;
837
- }
838
- if (item.to.primaryKey) {
839
- addPrimaryKeys.columns.push(
840
- item.to.column ? getColumnName(item.to.column, key, snakeCase) : snakeCase ? orchidCore.toSnakeCase(key) : key
870
+ if (Array.isArray(item)) {
871
+ for (const it of item) {
872
+ handlePrerequisitesForTableItem(
873
+ key,
874
+ it,
875
+ queries,
876
+ addPrimaryKeys,
877
+ dropPrimaryKeys,
878
+ snakeCase
841
879
  );
842
- addPrimaryKeys.change = true;
843
880
  }
881
+ } else {
882
+ handlePrerequisitesForTableItem(
883
+ key,
884
+ item,
885
+ queries,
886
+ addPrimaryKeys,
887
+ dropPrimaryKeys,
888
+ snakeCase
889
+ );
844
890
  }
845
891
  }
846
892
  if (ast.add.primaryKey) {
@@ -852,6 +898,7 @@ const astToQueries = (ast, snakeCase, language) => {
852
898
  dropPrimaryKeys.columns.push(...ast.drop.primaryKey.columns);
853
899
  }
854
900
  const alterTable = [];
901
+ const renameItems = [];
855
902
  const values = [];
856
903
  const addIndexes = mapIndexesForSnakeCase(ast.add.indexes, snakeCase);
857
904
  const dropIndexes = mapIndexesForSnakeCase(ast.drop.indexes, snakeCase);
@@ -866,149 +913,45 @@ const astToQueries = (ast, snakeCase, language) => {
866
913
  const comments = [];
867
914
  for (const key in ast.shape) {
868
915
  const item = ast.shape[key];
869
- if (item.type === "add") {
870
- const column = item.item;
871
- const name = getColumnName(column, key, snakeCase);
872
- addColumnIndex(addIndexes, name, column);
873
- addColumnComment(comments, name, column);
874
- alterTable.push(
875
- `ADD COLUMN ${columnToSql(
876
- name,
877
- column,
916
+ if (Array.isArray(item)) {
917
+ for (const it of item) {
918
+ handleTableItemChange(
919
+ key,
920
+ it,
921
+ ast,
922
+ alterTable,
923
+ renameItems,
878
924
  values,
879
- addPrimaryKeys.columns.length > 1,
925
+ addPrimaryKeys,
926
+ addIndexes,
927
+ dropIndexes,
928
+ addConstraints,
929
+ dropConstraints,
930
+ comments,
880
931
  snakeCase
881
- )}`
882
- );
883
- } else if (item.type === "drop") {
884
- const name = getColumnName(item.item, key, snakeCase);
885
- alterTable.push(
886
- `DROP COLUMN "${name}"${item.dropMode ? ` ${item.dropMode}` : ""}`
887
- );
888
- } else if (item.type === "change") {
889
- const { from, to } = item;
890
- const name = getChangeColumnName(item, key, snakeCase);
891
- let changeType = false;
892
- if (to.type && (from.type !== to.type || from.collate !== to.collate)) {
893
- changeType = true;
894
- const type = !to.column || to.column.data.isOfCustomType ? `"${to.type}"` : to.type;
895
- alterTable.push(
896
- `ALTER COLUMN "${name}" TYPE ${type}${to.collate ? ` COLLATE ${quoteNameFromString(to.collate)}` : ""}${item.using ? ` USING ${item.using.toSQL({ values })}` : ""}`
897
- );
898
- }
899
- if (typeof from.identity !== typeof to.identity || !orchidCore.deepCompare(from.identity, to.identity)) {
900
- alterTable.push(
901
- `ALTER COLUMN "${name}" ${to.identity ? `ADD ${identityToSql(to.identity)}` : `DROP IDENTITY`}`
902
- );
903
- }
904
- if (from.default !== to.default) {
905
- const value = encodeColumnDefault(to.default, values, to.column);
906
- if (changeType && value !== null) {
907
- alterTable.push(`ALTER COLUMN "${name}" DROP DEFAULT`);
908
- }
909
- const expr = value === null ? "DROP DEFAULT" : `SET DEFAULT ${value}`;
910
- alterTable.push(`ALTER COLUMN "${name}" ${expr}`);
911
- }
912
- if (from.nullable !== to.nullable) {
913
- alterTable.push(
914
- `ALTER COLUMN "${name}" ${to.nullable ? "DROP" : "SET"} NOT NULL`
915
- );
916
- }
917
- if (from.compression !== to.compression) {
918
- alterTable.push(
919
- `ALTER COLUMN "${name}" SET COMPRESSION ${to.compression || "DEFAULT"}`
920
932
  );
921
933
  }
922
- if (from.check !== to.check) {
923
- const checkName = `${ast.name}_${name}_check`;
924
- if (from.check) {
925
- alterTable.push(`DROP CONSTRAINT "${checkName}"`);
926
- }
927
- if (to.check) {
928
- alterTable.push(
929
- `ADD CONSTRAINT "${checkName}"
930
- CHECK (${to.check.toSQL({
931
- values
932
- })})`
933
- );
934
- }
935
- }
936
- const foreignKeysLen = Math.max(
937
- ((_a = from.foreignKeys) == null ? void 0 : _a.length) || 0,
938
- ((_b = to.foreignKeys) == null ? void 0 : _b.length) || 0
939
- );
940
- for (let i = 0; i < foreignKeysLen; i++) {
941
- const fromFkey = (_c = from.foreignKeys) == null ? void 0 : _c[i];
942
- const toFkey = (_d = to.foreignKeys) == null ? void 0 : _d[i];
943
- if ((fromFkey || toFkey) && (!fromFkey || !toFkey || fromFkey.name !== toFkey.name || fromFkey.match !== toFkey.match || fromFkey.onUpdate !== toFkey.onUpdate || fromFkey.onDelete !== toFkey.onDelete || fromFkey.dropMode !== toFkey.dropMode || fromFkey.table !== toFkey.table || fromFkey.columns.join(",") !== toFkey.columns.join(","))) {
944
- if (fromFkey) {
945
- dropConstraints.push({
946
- name: fromFkey.name,
947
- dropMode: fromFkey.dropMode,
948
- references: {
949
- columns: [name],
950
- fnOrTable: fromFkey.table,
951
- foreignColumns: snakeCase ? fromFkey.columns.map(orchidCore.toSnakeCase) : fromFkey.columns,
952
- options: fromFkey
953
- }
954
- });
955
- }
956
- if (toFkey) {
957
- addConstraints.push({
958
- name: toFkey.name,
959
- dropMode: toFkey.dropMode,
960
- references: {
961
- columns: [name],
962
- fnOrTable: toFkey.table,
963
- foreignColumns: snakeCase ? toFkey.columns.map(orchidCore.toSnakeCase) : toFkey.columns,
964
- options: toFkey
965
- }
966
- });
967
- }
968
- }
969
- }
970
- const indexesLen = Math.max(
971
- ((_e = from.indexes) == null ? void 0 : _e.length) || 0,
972
- ((_f = to.indexes) == null ? void 0 : _f.length) || 0
973
- );
974
- for (let i = 0; i < indexesLen; i++) {
975
- const fromIndex = (_g = from.indexes) == null ? void 0 : _g[i];
976
- const toIndex = (_h = to.indexes) == null ? void 0 : _h[i];
977
- if ((fromIndex || toIndex) && (!fromIndex || !toIndex || fromIndex.collate !== toIndex.collate || fromIndex.opclass !== toIndex.opclass || fromIndex.order !== toIndex.order || fromIndex.name !== toIndex.name || fromIndex.unique !== toIndex.unique || fromIndex.using !== toIndex.using || fromIndex.include !== toIndex.include || Array.isArray(fromIndex.include) && Array.isArray(toIndex.include) && fromIndex.include.join(",") !== toIndex.include.join(",") || fromIndex.with !== toIndex.with || fromIndex.tablespace !== toIndex.tablespace || fromIndex.where !== toIndex.where || fromIndex.dropMode !== toIndex.dropMode)) {
978
- if (fromIndex) {
979
- dropIndexes.push({
980
- columns: [
981
- __spreadValues$8({
982
- column: name
983
- }, fromIndex)
984
- ],
985
- options: fromIndex
986
- });
987
- }
988
- if (toIndex) {
989
- addIndexes.push({
990
- columns: [
991
- __spreadValues$8({
992
- column: name
993
- }, toIndex)
994
- ],
995
- options: toIndex
996
- });
997
- }
998
- }
999
- }
1000
- if (from.comment !== to.comment) {
1001
- comments.push({ column: name, comment: to.comment || null });
1002
- }
1003
- } else if (item.type === "rename") {
1004
- alterTable.push(
1005
- `RENAME COLUMN "${snakeCase ? orchidCore.toSnakeCase(key) : key}" TO "${snakeCase ? orchidCore.toSnakeCase(item.name) : item.name}"`
934
+ } else {
935
+ handleTableItemChange(
936
+ key,
937
+ item,
938
+ ast,
939
+ alterTable,
940
+ renameItems,
941
+ values,
942
+ addPrimaryKeys,
943
+ addIndexes,
944
+ dropIndexes,
945
+ addConstraints,
946
+ dropConstraints,
947
+ comments,
948
+ snakeCase
1006
949
  );
1007
950
  }
1008
951
  }
1009
952
  const prependAlterTable = [];
1010
953
  if (ast.drop.primaryKey || dropPrimaryKeys.change || dropPrimaryKeys.columns.length > 1) {
1011
- const name = ((_i = dropPrimaryKeys.options) == null ? void 0 : _i.name) || `${ast.name}_pkey`;
954
+ const name = ((_a = dropPrimaryKeys.options) == null ? void 0 : _a.name) || `${ast.name}_pkey`;
1012
955
  prependAlterTable.push(`DROP CONSTRAINT "${name}"`);
1013
956
  }
1014
957
  prependAlterTable.push(
@@ -1034,42 +977,237 @@ const astToQueries = (ast, snakeCase, language) => {
1034
977
  ADD ${constraintToSql(ast, true, foreignKey, values, snakeCase)}`
1035
978
  )
1036
979
  );
980
+ const tableName = quoteWithSchema(ast);
981
+ if (renameItems.length) {
982
+ queries.push(alterTableSql(tableName, renameItems, values));
983
+ }
1037
984
  if (alterTable.length) {
1038
- queries.push({
1039
- text: `ALTER TABLE ${quoteWithSchema(ast)}
1040
- ${alterTable.join(",\n ")}`,
1041
- values
1042
- });
985
+ queries.push(alterTableSql(tableName, alterTable, values));
1043
986
  }
1044
987
  queries.push(...indexesToQuery(false, ast, dropIndexes, language));
1045
988
  queries.push(...indexesToQuery(true, ast, addIndexes, language));
1046
989
  queries.push(...commentsToQuery(ast, comments));
1047
990
  return queries;
1048
991
  };
1049
- const getChangeColumnName = (change, key, snakeCase) => {
1050
- return change.name || (change.to.column ? getColumnName(change.to.column, key, snakeCase) : snakeCase ? orchidCore.toSnakeCase(key) : key);
992
+ const alterTableSql = (tableName, lines, values) => ({
993
+ text: `ALTER TABLE ${tableName}
994
+ ${lines.join(",\n ")}`,
995
+ values
996
+ });
997
+ const handlePrerequisitesForTableItem = (key, item, queries, addPrimaryKeys, dropPrimaryKeys, snakeCase) => {
998
+ if ("item" in item) {
999
+ const { item: column } = item;
1000
+ if (column instanceof pqb.EnumColumn) {
1001
+ queries.push(makePopulateEnumQuery(column));
1002
+ }
1003
+ }
1004
+ if (item.type === "add") {
1005
+ if (item.item.data.primaryKey) {
1006
+ addPrimaryKeys.columns.push(getColumnName(item.item, key, snakeCase));
1007
+ }
1008
+ } else if (item.type === "drop") {
1009
+ if (item.item.data.primaryKey) {
1010
+ dropPrimaryKeys.columns.push(getColumnName(item.item, key, snakeCase));
1011
+ }
1012
+ } else if (item.type === "change") {
1013
+ if (item.from.column instanceof pqb.EnumColumn) {
1014
+ queries.push(makePopulateEnumQuery(item.from.column));
1015
+ }
1016
+ if (item.to.column instanceof pqb.EnumColumn) {
1017
+ queries.push(makePopulateEnumQuery(item.to.column));
1018
+ }
1019
+ if (item.from.primaryKey) {
1020
+ dropPrimaryKeys.columns.push(
1021
+ item.from.column ? getColumnName(item.from.column, key, snakeCase) : snakeCase ? orchidCore.toSnakeCase(key) : key
1022
+ );
1023
+ dropPrimaryKeys.change = true;
1024
+ }
1025
+ if (item.to.primaryKey) {
1026
+ addPrimaryKeys.columns.push(
1027
+ item.to.column ? getColumnName(item.to.column, key, snakeCase) : snakeCase ? orchidCore.toSnakeCase(key) : key
1028
+ );
1029
+ addPrimaryKeys.change = true;
1030
+ }
1031
+ }
1032
+ };
1033
+ const handleTableItemChange = (key, item, ast, alterTable, renameItems, values, addPrimaryKeys, addIndexes, dropIndexes, addConstraints, dropConstraints, comments, snakeCase) => {
1034
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1035
+ if (item.type === "add") {
1036
+ const column = item.item;
1037
+ const name = getColumnName(column, key, snakeCase);
1038
+ addColumnIndex(addIndexes, name, column);
1039
+ addColumnComment(comments, name, column);
1040
+ alterTable.push(
1041
+ `ADD COLUMN ${columnToSql(
1042
+ name,
1043
+ column,
1044
+ values,
1045
+ addPrimaryKeys.columns.length > 1,
1046
+ snakeCase
1047
+ )}`
1048
+ );
1049
+ } else if (item.type === "drop") {
1050
+ const name = getColumnName(item.item, key, snakeCase);
1051
+ alterTable.push(
1052
+ `DROP COLUMN "${name}"${item.dropMode ? ` ${item.dropMode}` : ""}`
1053
+ );
1054
+ } else if (item.type === "change") {
1055
+ const { from, to } = item;
1056
+ const name = getChangeColumnName("to", item, key, snakeCase);
1057
+ const fromName = getChangeColumnName("from", item, key, snakeCase);
1058
+ if (fromName !== name) {
1059
+ renameItems.push(renameColumnSql(fromName, name, snakeCase));
1060
+ }
1061
+ let changeType = false;
1062
+ if (to.type && (from.type !== to.type || from.collate !== to.collate)) {
1063
+ changeType = true;
1064
+ const type = !to.column || to.column.data.isOfCustomType ? quoteNameFromString(to.type) : to.type;
1065
+ alterTable.push(
1066
+ `ALTER COLUMN "${name}" TYPE ${type}${to.collate ? ` COLLATE ${quoteNameFromString(to.collate)}` : ""}${((_a = item.using) == null ? void 0 : _a.usingUp) ? ` USING ${item.using.usingUp.toSQL({ values })}` : to.column instanceof pqb.EnumColumn ? ` USING "${name}"::text::${type}` : ""}`
1067
+ );
1068
+ }
1069
+ if (typeof from.identity !== typeof to.identity || !orchidCore.deepCompare(from.identity, to.identity)) {
1070
+ if (from.identity) {
1071
+ alterTable.push(`ALTER COLUMN "${name}" DROP IDENTITY`);
1072
+ }
1073
+ if (to.identity) {
1074
+ alterTable.push(
1075
+ `ALTER COLUMN "${name}" ADD ${identityToSql(to.identity)}`
1076
+ );
1077
+ }
1078
+ }
1079
+ if (from.default !== to.default) {
1080
+ const value = encodeColumnDefault(to.default, values, to.column);
1081
+ if (changeType && value !== null) {
1082
+ alterTable.push(`ALTER COLUMN "${name}" DROP DEFAULT`);
1083
+ }
1084
+ const expr = value === null ? "DROP DEFAULT" : `SET DEFAULT ${value}`;
1085
+ alterTable.push(`ALTER COLUMN "${name}" ${expr}`);
1086
+ }
1087
+ if (from.nullable !== to.nullable) {
1088
+ alterTable.push(
1089
+ `ALTER COLUMN "${name}" ${to.nullable ? "DROP" : "SET"} NOT NULL`
1090
+ );
1091
+ }
1092
+ if (from.compression !== to.compression) {
1093
+ alterTable.push(
1094
+ `ALTER COLUMN "${name}" SET COMPRESSION ${to.compression || "DEFAULT"}`
1095
+ );
1096
+ }
1097
+ if (from.check !== to.check) {
1098
+ const checkName = `${ast.name}_${name}_check`;
1099
+ if (from.check) {
1100
+ alterTable.push(`DROP CONSTRAINT "${checkName}"`);
1101
+ }
1102
+ if (to.check) {
1103
+ alterTable.push(
1104
+ `ADD CONSTRAINT "${checkName}"
1105
+ CHECK (${to.check.sql.toSQL({
1106
+ values
1107
+ })})`
1108
+ );
1109
+ }
1110
+ }
1111
+ const foreignKeysLen = Math.max(
1112
+ ((_b = from.foreignKeys) == null ? void 0 : _b.length) || 0,
1113
+ ((_c = to.foreignKeys) == null ? void 0 : _c.length) || 0
1114
+ );
1115
+ for (let i = 0; i < foreignKeysLen; i++) {
1116
+ const fromFkey = (_d = from.foreignKeys) == null ? void 0 : _d[i];
1117
+ const toFkey = (_e = to.foreignKeys) == null ? void 0 : _e[i];
1118
+ if ((fromFkey || toFkey) && (!fromFkey || !toFkey || fromFkey.name !== toFkey.name || fromFkey.match !== toFkey.match || fromFkey.onUpdate !== toFkey.onUpdate || fromFkey.onDelete !== toFkey.onDelete || fromFkey.dropMode !== toFkey.dropMode || fromFkey.table !== toFkey.table || fromFkey.columns.join(",") !== toFkey.columns.join(","))) {
1119
+ if (fromFkey) {
1120
+ dropConstraints.push({
1121
+ name: fromFkey.name,
1122
+ dropMode: fromFkey.dropMode,
1123
+ references: {
1124
+ columns: [name],
1125
+ fnOrTable: fromFkey.table,
1126
+ foreignColumns: snakeCase ? fromFkey.columns.map(orchidCore.toSnakeCase) : fromFkey.columns,
1127
+ options: fromFkey
1128
+ }
1129
+ });
1130
+ }
1131
+ if (toFkey) {
1132
+ addConstraints.push({
1133
+ name: toFkey.name,
1134
+ dropMode: toFkey.dropMode,
1135
+ references: {
1136
+ columns: [name],
1137
+ fnOrTable: toFkey.table,
1138
+ foreignColumns: snakeCase ? toFkey.columns.map(orchidCore.toSnakeCase) : toFkey.columns,
1139
+ options: toFkey
1140
+ }
1141
+ });
1142
+ }
1143
+ }
1144
+ }
1145
+ const indexesLen = Math.max(
1146
+ ((_f = from.indexes) == null ? void 0 : _f.length) || 0,
1147
+ ((_g = to.indexes) == null ? void 0 : _g.length) || 0
1148
+ );
1149
+ for (let i = 0; i < indexesLen; i++) {
1150
+ const fromIndex = (_h = from.indexes) == null ? void 0 : _h[i];
1151
+ const toIndex = (_i = to.indexes) == null ? void 0 : _i[i];
1152
+ if ((fromIndex || toIndex) && (!fromIndex || !toIndex || fromIndex.collate !== toIndex.collate || fromIndex.opclass !== toIndex.opclass || fromIndex.order !== toIndex.order || fromIndex.name !== toIndex.name || fromIndex.unique !== toIndex.unique || fromIndex.using !== toIndex.using || fromIndex.include !== toIndex.include || Array.isArray(fromIndex.include) && Array.isArray(toIndex.include) && fromIndex.include.join(",") !== toIndex.include.join(",") || fromIndex.with !== toIndex.with || fromIndex.tablespace !== toIndex.tablespace || fromIndex.where !== toIndex.where || fromIndex.dropMode !== toIndex.dropMode)) {
1153
+ if (fromIndex) {
1154
+ dropIndexes.push({
1155
+ columns: [
1156
+ __spreadValues$7({
1157
+ column: name
1158
+ }, fromIndex)
1159
+ ],
1160
+ options: fromIndex
1161
+ });
1162
+ }
1163
+ if (toIndex) {
1164
+ addIndexes.push({
1165
+ columns: [
1166
+ __spreadValues$7({
1167
+ column: name
1168
+ }, toIndex)
1169
+ ],
1170
+ options: toIndex
1171
+ });
1172
+ }
1173
+ }
1174
+ }
1175
+ if (from.comment !== to.comment) {
1176
+ comments.push({ column: name, comment: to.comment || null });
1177
+ }
1178
+ } else if (item.type === "rename") {
1179
+ renameItems.push(renameColumnSql(key, item.name, snakeCase));
1180
+ }
1181
+ };
1182
+ const getChangeColumnName = (what, change, key, snakeCase) => {
1183
+ return change.name || (change[what].column ? (
1184
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1185
+ getColumnName(change[what].column, key, snakeCase)
1186
+ ) : snakeCase ? orchidCore.toSnakeCase(key) : key);
1187
+ };
1188
+ const renameColumnSql = (from, to, snakeCase) => {
1189
+ return `RENAME COLUMN "${snakeCase ? orchidCore.toSnakeCase(from) : from}" TO "${snakeCase ? orchidCore.toSnakeCase(to) : to}"`;
1051
1190
  };
1052
1191
  const mapIndexesForSnakeCase = (indexes, snakeCase) => {
1053
1192
  return (indexes == null ? void 0 : indexes.map((index) => ({
1054
1193
  options: index.options,
1055
1194
  columns: snakeCase ? index.columns.map(
1056
- (item) => "column" in item ? __spreadProps$5(__spreadValues$8({}, item), { column: orchidCore.toSnakeCase(item.column) }) : item
1195
+ (item) => "column" in item ? __spreadProps$5(__spreadValues$7({}, item), { column: orchidCore.toSnakeCase(item.column) }) : item
1057
1196
  ) : index.columns
1058
1197
  }))) || [];
1059
1198
  };
1060
1199
  const mapConstraintsToSnakeCase = (foreignKeys, snakeCase) => {
1061
- return (foreignKeys == null ? void 0 : foreignKeys.map((item) => __spreadProps$5(__spreadValues$8({}, item), {
1062
- references: item.references ? snakeCase ? __spreadProps$5(__spreadValues$8({}, item.references), {
1200
+ return (foreignKeys == null ? void 0 : foreignKeys.map((item) => __spreadProps$5(__spreadValues$7({}, item), {
1201
+ references: item.references ? snakeCase ? __spreadProps$5(__spreadValues$7({}, item.references), {
1063
1202
  columns: item.references.columns.map(orchidCore.toSnakeCase)
1064
1203
  }) : item.references : void 0
1065
1204
  }))) || [];
1066
1205
  };
1067
1206
 
1068
- const createView$1 = async (migration, up, name, options, sql) => {
1207
+ const createView = async (migration, up, name, options, sql) => {
1069
1208
  const ast = makeAst(up, name, options, sql);
1070
1209
  const query = astToQuery(ast);
1071
1210
  await migration.adapter.query(query);
1072
- migration.migratedAsts.push(ast);
1073
1211
  };
1074
1212
  const makeAst = (up, name, options, sql) => {
1075
1213
  if (typeof sql === "string") {
@@ -1081,7 +1219,8 @@ const makeAst = (up, name, options, sql) => {
1081
1219
  name,
1082
1220
  shape: {},
1083
1221
  sql,
1084
- options
1222
+ options,
1223
+ deps: []
1085
1224
  };
1086
1225
  };
1087
1226
  const astToQuery = (ast) => {
@@ -1127,26 +1266,26 @@ const astToQuery = (ast) => {
1127
1266
  };
1128
1267
  };
1129
1268
 
1130
- var __defProp$7 = Object.defineProperty;
1269
+ var __defProp$6 = Object.defineProperty;
1131
1270
  var __defProps$4 = Object.defineProperties;
1132
1271
  var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
1133
- var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
1134
- var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
1135
- var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
1136
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1137
- var __spreadValues$7 = (a, b) => {
1272
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
1273
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
1274
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
1275
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1276
+ var __spreadValues$6 = (a, b) => {
1138
1277
  for (var prop in b || (b = {}))
1139
- if (__hasOwnProp$7.call(b, prop))
1140
- __defNormalProp$7(a, prop, b[prop]);
1141
- if (__getOwnPropSymbols$7)
1142
- for (var prop of __getOwnPropSymbols$7(b)) {
1143
- if (__propIsEnum$7.call(b, prop))
1144
- __defNormalProp$7(a, prop, b[prop]);
1278
+ if (__hasOwnProp$6.call(b, prop))
1279
+ __defNormalProp$6(a, prop, b[prop]);
1280
+ if (__getOwnPropSymbols$6)
1281
+ for (var prop of __getOwnPropSymbols$6(b)) {
1282
+ if (__propIsEnum$6.call(b, prop))
1283
+ __defNormalProp$6(a, prop, b[prop]);
1145
1284
  }
1146
1285
  return a;
1147
1286
  };
1148
1287
  var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
1149
- const createMigrationInterface = (tx, up, config, asts) => {
1288
+ const createMigrationInterface = (tx, up, config) => {
1150
1289
  var _a;
1151
1290
  const adapter = new pqb.TransactionAdapter(
1152
1291
  tx,
@@ -1171,7 +1310,6 @@ const createMigrationInterface = (tx, up, config, asts) => {
1171
1310
  for (const key of Object.getOwnPropertyNames(proto)) {
1172
1311
  db[key] = proto[key];
1173
1312
  }
1174
- db.migratedAsts = asts;
1175
1313
  return Object.assign(db, {
1176
1314
  adapter,
1177
1315
  log,
@@ -1183,12 +1321,12 @@ class Migration {
1183
1321
  createTable(tableName, cbOrOptions, cb) {
1184
1322
  const options = !cbOrOptions || typeof cbOrOptions === "function" ? {} : cbOrOptions;
1185
1323
  const fn = typeof cbOrOptions === "function" ? cbOrOptions : cb;
1186
- return createTable$1(this, this.up, tableName, options, fn);
1324
+ return createTable(this, this.up, tableName, options, fn);
1187
1325
  }
1188
1326
  dropTable(tableName, cbOrOptions, cb) {
1189
1327
  const options = !cbOrOptions || typeof cbOrOptions === "function" ? {} : cbOrOptions;
1190
1328
  const fn = typeof cbOrOptions === "function" ? cbOrOptions : cb;
1191
- return createTable$1(this, !this.up, tableName, options, fn);
1329
+ return createTable(this, !this.up, tableName, options, fn);
1192
1330
  }
1193
1331
  changeTable(tableName, cbOrOptions, cb) {
1194
1332
  const [fn, options] = typeof cbOrOptions === "function" ? [cbOrOptions, {}] : [cb, cbOrOptions];
@@ -1219,7 +1357,7 @@ class Migration {
1219
1357
  * @param to - rename the table to
1220
1358
  */
1221
1359
  renameTable(from, to) {
1222
- return renameType(this, from, to, true);
1360
+ return renameType(this, from, to, "TABLE");
1223
1361
  }
1224
1362
  /**
1225
1363
  * Set a different schema to the table:
@@ -1309,6 +1447,25 @@ class Migration {
1309
1447
  dropIndex(tableName, columns, options) {
1310
1448
  return addIndex(this, !this.up, tableName, columns, options);
1311
1449
  }
1450
+ /**
1451
+ * Rename index:
1452
+ *
1453
+ * ```ts
1454
+ * import { change } from '../dbScript';
1455
+ *
1456
+ * change(async (db) => {
1457
+ * // tableName can be prefixed with a schema
1458
+ * await db.renameIndex('tableName', 'oldIndexName', 'newIndexName');
1459
+ * });
1460
+ * ```
1461
+ *
1462
+ * @param tableName - table which this index belongs to
1463
+ * @param from - rename the index from
1464
+ * @param to - rename the index to
1465
+ */
1466
+ renameIndex(tableName, from, to) {
1467
+ return renameTableItem(this, tableName, from, to, "INDEX");
1468
+ }
1312
1469
  /**
1313
1470
  * Add a foreign key to a table on migrating, and remove it on rollback.
1314
1471
  *
@@ -1476,6 +1633,28 @@ class Migration {
1476
1633
  dropConstraint(tableName, constraint) {
1477
1634
  return addConstraint(this, !this.up, tableName, constraint);
1478
1635
  }
1636
+ /**
1637
+ * Rename a table constraint, such as primary key, or check.
1638
+ *
1639
+ * ```ts
1640
+ * import { change } from '../dbScript';
1641
+ *
1642
+ * change(async (db) => {
1643
+ * await db.renameConstraint(
1644
+ * 'tableName', // may include schema: 'schema.table'
1645
+ * 'oldConstraintName',
1646
+ * 'newConstraintName',
1647
+ * );
1648
+ * });
1649
+ * ```
1650
+ *
1651
+ * @param tableName - name of the table containing the constraint, may include schema name, may include schema name
1652
+ * @param from - current name of the constraint
1653
+ * @param to - desired name
1654
+ */
1655
+ renameConstraint(tableName, from, to) {
1656
+ return renameTableItem(this, tableName, from, to, "CONSTRAINT");
1657
+ }
1479
1658
  /**
1480
1659
  * Rename a column:
1481
1660
  *
@@ -1512,17 +1691,36 @@ class Migration {
1512
1691
  * @param schemaName - name of the schema
1513
1692
  */
1514
1693
  createSchema(schemaName) {
1515
- return createSchema$1(this, this.up, schemaName);
1694
+ return createSchema(this, this.up, schemaName);
1516
1695
  }
1517
1696
  /**
1518
- * Drop the schema, create it on rollback. See {@link createSchema}.
1697
+ * Renames a database schema, renames it backwards on roll back.
1519
1698
  *
1520
- * @param schemaName - name of the schema
1521
- */
1522
- dropSchema(schemaName) {
1523
- return createSchema$1(this, !this.up, schemaName);
1524
- }
1525
- /**
1699
+ * ```ts
1700
+ * import { change } from '../dbScript';
1701
+ *
1702
+ * change(async (db) => {
1703
+ * await db.renameSchema('from', 'to');
1704
+ * });
1705
+ * ```
1706
+ *
1707
+ * @param from - existing schema to rename
1708
+ * @param to - desired schema name
1709
+ */
1710
+ async renameSchema(from, to) {
1711
+ await this.adapter.query(
1712
+ `ALTER SCHEMA "${this.up ? from : to}" RENAME TO "${this.up ? to : from}"`
1713
+ );
1714
+ }
1715
+ /**
1716
+ * Drop the schema, create it on rollback. See {@link createSchema}.
1717
+ *
1718
+ * @param schemaName - name of the schema
1719
+ */
1720
+ dropSchema(schemaName) {
1721
+ return createSchema(this, !this.up, schemaName);
1722
+ }
1723
+ /**
1526
1724
  * `createExtension` creates a database extension, and removes it on rollback.
1527
1725
  *
1528
1726
  * `dropExtension` takes the same arguments, removes the extension on migrate, and adds it on rollback.
@@ -1538,8 +1736,8 @@ class Migration {
1538
1736
  * @param name - name of the extension
1539
1737
  * @param options - extension options
1540
1738
  */
1541
- createExtension(name, options = {}) {
1542
- return createExtension$1(this, this.up, name, options);
1739
+ createExtension(name, options) {
1740
+ return createExtension(this, this.up, name, options);
1543
1741
  }
1544
1742
  /**
1545
1743
  * Drop the extension, create it on rollback. See {@link createExtension}.
@@ -1547,8 +1745,8 @@ class Migration {
1547
1745
  * @param name - name of the extension
1548
1746
  * @param options - extension options
1549
1747
  */
1550
- dropExtension(name, options = {}) {
1551
- return createExtension$1(this, !this.up, name, options);
1748
+ dropExtension(name, options) {
1749
+ return createExtension(this, !this.up, name, options);
1552
1750
  }
1553
1751
  /**
1554
1752
  * `createEnum` creates an enum on migrate, drops it on rollback.
@@ -1577,7 +1775,7 @@ class Migration {
1577
1775
  * @param options - enum options
1578
1776
  */
1579
1777
  createEnum(name, values, options) {
1580
- return createEnum$1(this, this.up, name, values, options);
1778
+ return createEnum(this, this.up, name, values, options);
1581
1779
  }
1582
1780
  /**
1583
1781
  * Drop the enum, create it on rollback. See {@link createEnum}.
@@ -1587,7 +1785,7 @@ class Migration {
1587
1785
  * @param options - enum options
1588
1786
  */
1589
1787
  dropEnum(name, values, options) {
1590
- return createEnum$1(this, !this.up, name, values, options);
1788
+ return createEnum(this, !this.up, name, values, options);
1591
1789
  }
1592
1790
  /**
1593
1791
  * Use these methods to add or drop one or multiple values from an existing enum.
@@ -1731,7 +1929,7 @@ class Migration {
1731
1929
  * @param to - rename the type to
1732
1930
  */
1733
1931
  renameType(from, to) {
1734
- return renameType(this, from, to, false);
1932
+ return renameType(this, from, to, "TYPE");
1735
1933
  }
1736
1934
  /**
1737
1935
  * Set a different schema to the type (such as enum):
@@ -1752,48 +1950,67 @@ class Migration {
1752
1950
  return this.renameType(`${from}.${name}`, `${to}.${name}`);
1753
1951
  }
1754
1952
  /**
1755
- * Domain is a custom database type that allows to predefine a `NOT NULL` and a `CHECK` (see [postgres tutorial](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-user-defined-data-types/)).
1953
+ * Domain is a custom database type that is based on other type and can include `NOT NULL` and a `CHECK` (see [postgres tutorial](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-user-defined-data-types/)).
1756
1954
  *
1757
- * `createDomain` and `dropDomain` take a domain name as first argument, callback returning inner column type as a second, and optional object with parameters as third.
1955
+ * Construct a column type in the function as the second argument.
1956
+ *
1957
+ * Specifiers [nullable](/guide/common-column-methods.html#nullable), [default](/guide/common-column-methods.html#default), [check](/guide/migration-column-methods.html#check), [collate](/guide/migration-column-methods.html#collate)
1958
+ * will be saved to the domain type on database level.
1758
1959
  *
1759
1960
  * ```ts
1760
1961
  * import { change } from '../dbScript';
1761
1962
  *
1762
1963
  * change(async (db) => {
1763
- * await db.createDomain('domainName', (t) => t.integer(), {
1764
- * check: db.sql`value = 42`,
1765
- * });
1964
+ * await db.createDomain('domainName', (t) =>
1965
+ * t.integer().check(db.sql`value = 42`),
1966
+ * );
1766
1967
  *
1767
1968
  * // use `schemaName.domainName` format to specify a schema
1768
- * await db.createDomain('schemaName.domainName', (t) => t.text(), {
1769
- * // unlike columns, domain is nullable by default, use notNull when needed:
1770
- * notNull: true,
1771
- * collation: 'C',
1772
- * default: db.sql`'default text'`,
1773
- * check: db.sql`length(value) > 10`,
1774
- *
1775
- * // cascade is used when dropping domain
1776
- * cascade: true,
1777
- * });
1969
+ * await db.createDomain('schemaName.domainName', (t) =>
1970
+ * t
1971
+ * .text()
1972
+ * .nullable()
1973
+ * .collate('C')
1974
+ * .default('default text')
1975
+ * .check(db.sql`length(value) > 10`),
1976
+ * );
1778
1977
  * });
1779
1978
  * ```
1780
1979
  *
1781
1980
  * @param name - name of the domain
1782
- * @param fn - function returning a column type for the domain
1783
- * @param options - domain options
1981
+ * @param fn - function returning a column type. Options `nullable`, `collate`, `default`, `check` will be applied to domain
1784
1982
  */
1785
- createDomain(name, fn, options) {
1786
- return createDomain$1(this, this.up, name, fn, options);
1983
+ createDomain(name, fn) {
1984
+ return createDomain(this, this.up, name, fn);
1787
1985
  }
1788
1986
  /**
1789
1987
  * Drop the domain, create it on rollback. See {@link dropDomain}.
1790
1988
  *
1791
1989
  * @param name - name of the domain
1792
- * @param fn - function returning a column type for the domain
1793
- * @param options - domain options
1990
+ * @param fn - function returning a column type. Options `nullable`, `collate`, `default`, `check` will be applied to domain
1991
+ */
1992
+ dropDomain(name, fn) {
1993
+ return createDomain(this, !this.up, name, fn);
1994
+ }
1995
+ /**
1996
+ * To rename a domain:
1997
+ *
1998
+ * ```ts
1999
+ * import { change } from '../dbScript';
2000
+ *
2001
+ * change(async (db) => {
2002
+ * await db.renameDomain('oldName', 'newName');
2003
+ *
2004
+ * // to move domain to a different schema
2005
+ * await db.renameDomain('oldSchema.domain', 'newSchema.domain');
2006
+ * });
2007
+ * ```
2008
+ *
2009
+ * @param from - old domain name (can include schema)
2010
+ * @param to - new domain name (can include schema)
1794
2011
  */
1795
- dropDomain(name, fn, options) {
1796
- return createDomain$1(this, !this.up, name, fn, options);
2012
+ renameDomain(from, to) {
2013
+ return renameType(this, from, to, "DOMAIN");
1797
2014
  }
1798
2015
  /**
1799
2016
  * Create and drop a database collation, (see [Postgres docs](https://www.postgresql.org/docs/current/sql-createcollation.html)).
@@ -1860,7 +2077,7 @@ class Migration {
1860
2077
  * @param options - options to create and drop the collation.
1861
2078
  */
1862
2079
  createCollation(name, options) {
1863
- return createCollation$1(this, this.up, name, options);
2080
+ return createCollation(this, this.up, name, options);
1864
2081
  }
1865
2082
  /**
1866
2083
  * Drop the collation, create it on rollback. See {@link createCollation}.
@@ -1869,11 +2086,11 @@ class Migration {
1869
2086
  * @param options - options to create and drop the collation.
1870
2087
  */
1871
2088
  dropCollation(name, options) {
1872
- return createCollation$1(this, !this.up, name, options);
2089
+ return createCollation(this, !this.up, name, options);
1873
2090
  }
1874
2091
  createView(name, ...args) {
1875
2092
  const [options, sql] = args.length === 2 ? args : [orchidCore.emptyObject, args[0]];
1876
- return createView$1(
2093
+ return createView(
1877
2094
  this,
1878
2095
  this.up,
1879
2096
  name,
@@ -1883,7 +2100,7 @@ class Migration {
1883
2100
  }
1884
2101
  dropView(name, ...args) {
1885
2102
  const [options, sql] = args.length === 2 ? args : [orchidCore.emptyObject, args[0]];
1886
- return createView$1(
2103
+ return createView(
1887
2104
  this,
1888
2105
  !this.up,
1889
2106
  name,
@@ -1962,7 +2179,7 @@ const wrapWithLog = async (log, query, fn) => {
1962
2179
  if (!log) {
1963
2180
  return fn();
1964
2181
  } else {
1965
- const sql = typeof query === "string" ? { text: query, values: [] } : query.values ? query : __spreadProps$4(__spreadValues$7({}, query), { values: [] });
2182
+ const sql = typeof query === "string" ? { text: query, values: [] } : query.values ? query : __spreadProps$4(__spreadValues$6({}, query), { values: [] });
1966
2183
  const logData = log.beforeQuery(sql);
1967
2184
  try {
1968
2185
  const result = await fn();
@@ -1980,21 +2197,21 @@ const addColumn = (migration, up, tableName, columnName, fn) => {
1980
2197
  }));
1981
2198
  };
1982
2199
  const addIndex = (migration, up, tableName, columns, options) => {
1983
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$7({}, t.add(t.index(columns, options))));
2200
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$6({}, t.add(t.index(columns, options))));
1984
2201
  };
1985
2202
  const addForeignKey = (migration, up, tableName, columns, foreignTable, foreignColumns, options) => {
1986
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$7({}, t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))));
2203
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$6({}, t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))));
1987
2204
  };
1988
2205
  const addPrimaryKey = (migration, up, tableName, columns, options) => {
1989
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$7({}, t.add(t.primaryKey(columns, options))));
2206
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$6({}, t.add(t.primaryKey(columns, options))));
1990
2207
  };
1991
2208
  const addCheck = (migration, up, tableName, check) => {
1992
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$7({}, t.add(t.check(check))));
2209
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$6({}, t.add(t.check(check))));
1993
2210
  };
1994
2211
  const addConstraint = (migration, up, tableName, constraint) => {
1995
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$7({}, t.add(t.constraint(constraint))));
2212
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$6({}, t.add(t.constraint(constraint))));
1996
2213
  };
1997
- const createSchema$1 = async (migration, up, name) => {
2214
+ const createSchema = async (migration, up, name) => {
1998
2215
  const ast = {
1999
2216
  type: "schema",
2000
2217
  action: up ? "create" : "drop",
@@ -2003,12 +2220,13 @@ const createSchema$1 = async (migration, up, name) => {
2003
2220
  await migration.adapter.query(
2004
2221
  `${ast.action === "create" ? "CREATE" : "DROP"} SCHEMA "${name}"`
2005
2222
  );
2006
- migration.migratedAsts.push(ast);
2007
2223
  };
2008
- const createExtension$1 = async (migration, up, name, options) => {
2009
- const ast = __spreadValues$7({
2224
+ const createExtension = async (migration, up, fullName, options) => {
2225
+ const [schema, name] = getSchemaAndTableFromName(fullName);
2226
+ const ast = __spreadValues$6({
2010
2227
  type: "extension",
2011
2228
  action: up ? "create" : "drop",
2229
+ schema,
2012
2230
  name
2013
2231
  }, options);
2014
2232
  let query;
@@ -2018,11 +2236,10 @@ const createExtension$1 = async (migration, up, name, options) => {
2018
2236
  query = `CREATE EXTENSION${ast.createIfNotExists ? " IF NOT EXISTS" : ""} "${ast.name}"${ast.schema ? ` SCHEMA "${ast.schema}"` : ""}${ast.version ? ` VERSION '${ast.version}'` : ""}${ast.cascade ? " CASCADE" : ""}`;
2019
2237
  }
2020
2238
  await migration.adapter.query(query);
2021
- migration.migratedAsts.push(ast);
2022
2239
  };
2023
- const createEnum$1 = async (migration, up, name, values, options = {}) => {
2240
+ const createEnum = async (migration, up, name, values, options = {}) => {
2024
2241
  const [schema, enumName] = getSchemaAndTableFromName(name);
2025
- const ast = __spreadValues$7({
2242
+ const ast = __spreadValues$6({
2026
2243
  type: "enum",
2027
2244
  action: up ? "create" : "drop",
2028
2245
  schema,
@@ -2037,39 +2254,38 @@ const createEnum$1 = async (migration, up, name, values, options = {}) => {
2037
2254
  query = `DROP TYPE${ast.dropIfExists ? " IF EXISTS" : ""} ${quotedName}${ast.cascade ? " CASCADE" : ""}`;
2038
2255
  }
2039
2256
  await migration.adapter.query(query);
2040
- migration.migratedAsts.push(ast);
2041
2257
  };
2042
- const createDomain$1 = async (migration, up, name, fn, options) => {
2258
+ const createDomain = async (migration, up, name, fn) => {
2043
2259
  const [schema, domainName] = getSchemaAndTableFromName(name);
2044
- const ast = __spreadValues$7({
2260
+ const ast = {
2045
2261
  type: "domain",
2046
2262
  action: up ? "create" : "drop",
2047
2263
  schema,
2048
2264
  name: domainName,
2049
2265
  baseType: fn(migration.columnTypes)
2050
- }, options);
2266
+ };
2051
2267
  let query;
2052
2268
  const values = [];
2053
2269
  const quotedName = quoteWithSchema(ast);
2054
2270
  if (ast.action === "create") {
2055
- query = `CREATE DOMAIN ${quotedName} AS ${columnTypeToSql(ast.baseType)}${ast.collation ? `
2056
- COLLATION ${orchidCore.singleQuote(ast.collation)}` : ""}${ast.default ? `
2057
- DEFAULT ${ast.default.toSQL({ values })}` : ""}${ast.notNull || ast.check ? "\n" : ""}${[
2058
- ast.notNull && "NOT NULL",
2059
- ast.check && `CHECK ${ast.check.toSQL({ values })}`
2271
+ const column = ast.baseType;
2272
+ query = `CREATE DOMAIN ${quotedName} AS ${columnTypeToSql(column)}${column.data.collate ? `
2273
+ COLLATE "${column.data.collate}"` : ""}${column.data.default !== void 0 ? `
2274
+ DEFAULT ${encodeColumnDefault(column.data.default, values)}` : ""}${!column.data.isNullable || column.data.check ? "\n" : ""}${[
2275
+ !column.data.isNullable && "NOT NULL",
2276
+ column.data.check && `CHECK (${column.data.check.sql.toSQL({ values })})`
2060
2277
  ].filter(Boolean).join(" ")}`;
2061
2278
  } else {
2062
- query = `DROP DOMAIN ${quotedName}${ast.cascade ? " CASCADE" : ""}`;
2279
+ query = `DROP DOMAIN ${quotedName}`;
2063
2280
  }
2064
2281
  await migration.adapter.query({
2065
2282
  text: query,
2066
2283
  values
2067
2284
  });
2068
- migration.migratedAsts.push(ast);
2069
2285
  };
2070
- const createCollation$1 = async (migration, up, name, options) => {
2286
+ const createCollation = async (migration, up, name, options) => {
2071
2287
  const [schema, collationName] = getSchemaAndTableFromName(name);
2072
- const ast = __spreadValues$7({
2288
+ const ast = __spreadValues$6({
2073
2289
  type: "collation",
2074
2290
  action: up ? "create" : "drop",
2075
2291
  schema,
@@ -2105,35 +2321,42 @@ const createCollation$1 = async (migration, up, name, options) => {
2105
2321
  await migration.adapter.query({
2106
2322
  text: query
2107
2323
  });
2108
- migration.migratedAsts.push(ast);
2109
2324
  };
2110
2325
  const queryExists = (db, sql) => {
2111
2326
  return db.adapter.query(sql).then(({ rowCount }) => rowCount > 0);
2112
2327
  };
2113
- const renameType = async (migration, from, to, table) => {
2328
+ const renameType = async (migration, from, to, kind) => {
2114
2329
  var _a;
2115
2330
  const [fromSchema, f] = getSchemaAndTableFromName(migration.up ? from : to);
2116
2331
  const [toSchema, t] = getSchemaAndTableFromName(migration.up ? to : from);
2117
2332
  const ast = {
2118
2333
  type: "renameType",
2119
- table,
2334
+ kind,
2120
2335
  fromSchema,
2121
2336
  from: f,
2122
2337
  toSchema,
2123
2338
  to: t
2124
2339
  };
2125
- const sqlKind = ast.table ? "TABLE" : "TYPE";
2126
2340
  if (ast.from !== ast.to) {
2127
2341
  await migration.adapter.query(
2128
- `ALTER ${sqlKind} ${quoteTable(ast.fromSchema, ast.from)} RENAME TO "${ast.to}"`
2342
+ `ALTER ${ast.kind} ${quoteTable(ast.fromSchema, ast.from)} RENAME TO "${ast.to}"`
2129
2343
  );
2130
2344
  }
2131
2345
  if (ast.fromSchema !== ast.toSchema) {
2132
2346
  await migration.adapter.query(
2133
- `ALTER ${sqlKind} ${quoteTable(ast.fromSchema, ast.to)} SET SCHEMA "${(_a = ast.toSchema) != null ? _a : migration.adapter.schema}"`
2347
+ `ALTER ${ast.kind} ${quoteTable(ast.fromSchema, ast.to)} SET SCHEMA "${(_a = ast.toSchema) != null ? _a : migration.adapter.schema}"`
2134
2348
  );
2135
2349
  }
2136
- migration.migratedAsts.push(ast);
2350
+ };
2351
+ const renameTableItem = async (migration, tableName, from, to, kind) => {
2352
+ const [schema, table] = getSchemaAndTableFromName(tableName);
2353
+ const [f, t] = migration.up ? [from, to] : [to, from];
2354
+ await migration.adapter.query(
2355
+ kind === "INDEX" ? `ALTER INDEX ${quoteTable(schema, f)} RENAME TO "${t}"` : `ALTER TABLE ${quoteTable(
2356
+ schema,
2357
+ table
2358
+ )} RENAME CONSTRAINT "${f}" TO "${t}"`
2359
+ );
2137
2360
  };
2138
2361
  const addOrDropEnumValues = async (migration, up, enumName, values, options) => {
2139
2362
  var _a;
@@ -2238,7 +2461,7 @@ GROUP BY n.nspname, c.relname`
2238
2461
  }
2239
2462
  };
2240
2463
 
2241
- const writeMigrationFile = async (config, version, name, content) => {
2464
+ const writeMigrationFile = async (config, version, name, migrationCode) => {
2242
2465
  var _a;
2243
2466
  await fs.mkdir(config.migrationsPath, { recursive: true });
2244
2467
  const filePath = path.resolve(config.migrationsPath, `${version}_${name}.ts`);
@@ -2246,14 +2469,18 @@ const writeMigrationFile = async (config, version, name, content) => {
2246
2469
  filePath,
2247
2470
  path.join(config.basePath, config.dbScript)
2248
2471
  );
2249
- await fs.writeFile(filePath, content(importPath, name));
2472
+ await fs.writeFile(
2473
+ filePath,
2474
+ `import { change } from '${importPath}';
2475
+ ${migrationCode}`
2476
+ );
2250
2477
  (_a = config.logger) == null ? void 0 : _a.log(`Created ${orchidCore.pathToLog(filePath)}`);
2251
2478
  };
2252
- const generate = async (config, [name]) => {
2479
+ const newMigration = async (config, [name]) => {
2253
2480
  if (!name)
2254
2481
  throw new Error("Migration name is missing");
2255
2482
  const version = await makeFileVersion({}, config);
2256
- await writeMigrationFile(config, version, name, makeContent);
2483
+ await writeMigrationFile(config, version, name, makeContent(name));
2257
2484
  };
2258
2485
  const makeFileVersion = async (ctx, config) => {
2259
2486
  if (config.migrationId === "timestamp") {
@@ -2276,9 +2503,8 @@ const generateTimeStamp = () => {
2276
2503
  now.getUTCSeconds()
2277
2504
  ].map((value) => value < 10 ? `0${value}` : value).join("");
2278
2505
  };
2279
- const makeContent = (importPath, name) => {
2280
- let content = `import { change } from '${importPath}';
2281
-
2506
+ const makeContent = (name) => {
2507
+ let content = `
2282
2508
  change(async (db) => {`;
2283
2509
  const [first, rest] = getFirstWordAndRest(name);
2284
2510
  if (rest) {
@@ -2386,28 +2612,28 @@ const renameMigrationVersionsInDb = async (config, adapter, values) => {
2386
2612
  });
2387
2613
  };
2388
2614
 
2389
- var __defProp$6 = Object.defineProperty;
2615
+ var __defProp$5 = Object.defineProperty;
2390
2616
  var __defProps$3 = Object.defineProperties;
2391
2617
  var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
2392
- var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
2393
- var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
2394
- var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
2395
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2396
- var __spreadValues$6 = (a, b) => {
2618
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
2619
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
2620
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
2621
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2622
+ var __spreadValues$5 = (a, b) => {
2397
2623
  for (var prop in b || (b = {}))
2398
- if (__hasOwnProp$6.call(b, prop))
2399
- __defNormalProp$6(a, prop, b[prop]);
2400
- if (__getOwnPropSymbols$6)
2401
- for (var prop of __getOwnPropSymbols$6(b)) {
2402
- if (__propIsEnum$6.call(b, prop))
2403
- __defNormalProp$6(a, prop, b[prop]);
2624
+ if (__hasOwnProp$5.call(b, prop))
2625
+ __defNormalProp$5(a, prop, b[prop]);
2626
+ if (__getOwnPropSymbols$5)
2627
+ for (var prop of __getOwnPropSymbols$5(b)) {
2628
+ if (__propIsEnum$5.call(b, prop))
2629
+ __defNormalProp$5(a, prop, b[prop]);
2404
2630
  }
2405
2631
  return a;
2406
2632
  };
2407
2633
  var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
2408
2634
  const getMigrations = async (ctx, config, up, allowDuplicates) => {
2409
2635
  var _a;
2410
- return ((_a = ctx.migrationsPromise) != null ? _a : ctx.migrationsPromise = config.migrations ? getMigrationsFromConfig(__spreadProps$3(__spreadValues$6({}, config), { migrations: config.migrations })) : getMigrationsFromFiles(config, allowDuplicates)).then(
2636
+ return ((_a = ctx.migrationsPromise) != null ? _a : ctx.migrationsPromise = config.migrations ? getMigrationsFromConfig(__spreadProps$3(__spreadValues$5({}, config), { migrations: config.migrations })) : getMigrationsFromFiles(config, allowDuplicates)).then(
2411
2637
  (data) => up ? data : { renameTo: data.renameTo, migrations: [...data.migrations].reverse() }
2412
2638
  );
2413
2639
  };
@@ -2663,25 +2889,9 @@ const createMigrationsTable = async (db, config) => {
2663
2889
  }
2664
2890
  };
2665
2891
 
2666
- var __defProp$5 = Object.defineProperty;
2667
- var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
2668
- var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
2669
- var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
2670
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2671
- var __spreadValues$5 = (a, b) => {
2672
- for (var prop in b || (b = {}))
2673
- if (__hasOwnProp$5.call(b, prop))
2674
- __defNormalProp$5(a, prop, b[prop]);
2675
- if (__getOwnPropSymbols$5)
2676
- for (var prop of __getOwnPropSymbols$5(b)) {
2677
- if (__propIsEnum$5.call(b, prop))
2678
- __defNormalProp$5(a, prop, b[prop]);
2679
- }
2680
- return a;
2681
- };
2682
2892
  const RAKE_DB_LOCK_KEY = "8582141715823621641";
2683
2893
  function makeMigrateFn(defaultCount, up, fn) {
2684
- return async (ctx, options, config, args = []) => {
2894
+ return async (ctx, options, config, args = [], adapters = options.map((opts) => new pqb.Adapter(opts)), dontClose) => {
2685
2895
  var _a;
2686
2896
  const set = await getMigrations(ctx, config, up);
2687
2897
  const arg = args[0];
@@ -2694,13 +2904,11 @@ function makeMigrateFn(defaultCount, up, fn) {
2694
2904
  const num = arg === "all" ? Infinity : parseInt(arg);
2695
2905
  count = isNaN(num) ? void 0 : num;
2696
2906
  }
2697
- const conf = prepareConfig(config, args, count === void 0 || force);
2698
- const asts = [];
2699
- const appCodeUpdaterCache = {};
2700
- const { appCodeUpdater } = conf;
2701
- let localAsts = asts;
2702
- for (const opts of options) {
2703
- const adapter = new pqb.Adapter(opts);
2907
+ const conf = config;
2908
+ const length = options.length;
2909
+ for (let i = 0; i < length; i++) {
2910
+ const opts = options[i];
2911
+ const adapter = adapters[i];
2704
2912
  try {
2705
2913
  await transaction(adapter, async (trx) => {
2706
2914
  const versions = await getMigratedVersionsMap(
@@ -2715,7 +2923,6 @@ function makeMigrateFn(defaultCount, up, fn) {
2715
2923
  set,
2716
2924
  versions,
2717
2925
  count != null ? count : defaultCount,
2718
- localAsts,
2719
2926
  force
2720
2927
  );
2721
2928
  });
@@ -2730,83 +2937,40 @@ function makeMigrateFn(defaultCount, up, fn) {
2730
2937
  config2,
2731
2938
  set.renameTo
2732
2939
  );
2733
- await fn(
2734
- trx,
2735
- config2,
2736
- set,
2737
- versions,
2738
- count != null ? count : defaultCount,
2739
- localAsts,
2740
- force
2741
- );
2940
+ await fn(trx, config2, set, versions, count != null ? count : defaultCount, force);
2742
2941
  });
2743
2942
  } else {
2744
2943
  throw err;
2745
2944
  }
2746
2945
  } finally {
2747
- await adapter.close();
2946
+ if (!dontClose)
2947
+ await adapter.close();
2748
2948
  }
2749
- localAsts = [];
2750
2949
  (_a = config.afterChangeCommit) == null ? void 0 : _a.call(config, {
2751
2950
  options: opts,
2752
2951
  up,
2753
2952
  migrations: set.migrations
2754
2953
  });
2755
2954
  }
2756
- await runCodeUpdaterAfterAll(
2757
- options[0],
2758
- config,
2759
- appCodeUpdater,
2760
- asts,
2761
- appCodeUpdaterCache
2762
- );
2955
+ return adapters;
2763
2956
  };
2764
2957
  }
2765
2958
  const migrate = makeMigrateFn(
2766
2959
  Infinity,
2767
2960
  true,
2768
- (trx, config, set, versions, count, asts, force) => migrateOrRollback(
2769
- trx,
2770
- config,
2771
- set,
2772
- versions,
2773
- count,
2774
- asts,
2775
- true,
2776
- false,
2777
- force
2778
- )
2961
+ (trx, config, set, versions, count, force) => migrateOrRollback(trx, config, set, versions, count, true, false, force)
2779
2962
  );
2780
2963
  const rollback = makeMigrateFn(
2781
2964
  1,
2782
2965
  false,
2783
- (trx, config, set, versions, count, asts, force) => migrateOrRollback(
2784
- trx,
2785
- config,
2786
- set,
2787
- versions,
2788
- count,
2789
- asts,
2790
- false,
2791
- false,
2792
- force
2793
- )
2966
+ (trx, config, set, versions, count, force) => migrateOrRollback(trx, config, set, versions, count, false, false, force)
2794
2967
  );
2795
2968
  const redo = makeMigrateFn(
2796
2969
  1,
2797
2970
  true,
2798
- async (trx, config, set, versions, count, asts, force) => {
2971
+ async (trx, config, set, versions, count, force) => {
2799
2972
  set.migrations.reverse();
2800
- await migrateOrRollback(
2801
- trx,
2802
- config,
2803
- set,
2804
- versions,
2805
- count,
2806
- asts,
2807
- false,
2808
- true
2809
- );
2973
+ await migrateOrRollback(trx, config, set, versions, count, false, true);
2810
2974
  set.migrations.reverse();
2811
2975
  await migrateOrRollback(
2812
2976
  trx,
@@ -2814,7 +2978,6 @@ const redo = makeMigrateFn(
2814
2978
  set,
2815
2979
  versions,
2816
2980
  count,
2817
- asts,
2818
2981
  true,
2819
2982
  true,
2820
2983
  force,
@@ -2823,19 +2986,8 @@ const redo = makeMigrateFn(
2823
2986
  }
2824
2987
  );
2825
2988
  const getDb = (adapter) => pqb.createDb({ adapter });
2826
- function prepareConfig(config, args, hasArg) {
2827
- config = __spreadValues$5({}, config);
2828
- const i = hasArg ? 0 : 1;
2829
- const arg = args[i];
2830
- if (arg === "--code") {
2831
- config.useCodeUpdater = args[i + 1] !== "false";
2832
- }
2833
- if (!config.useCodeUpdater)
2834
- delete config.appCodeUpdater;
2835
- return config;
2836
- }
2837
- const migrateOrRollback = async (trx, config, set, versions, count, asts, up, redo2, force, skipLock) => {
2838
- var _a, _b, _c;
2989
+ const migrateOrRollback = async (trx, config, set, versions, count, up, redo2, force, skipLock) => {
2990
+ var _a, _b, _c, _d;
2839
2991
  const { sequence, map: versionsMap } = versions;
2840
2992
  if (up) {
2841
2993
  const rollbackTo = checkMigrationOrder(config, set, versions, force);
@@ -2856,7 +3008,6 @@ const migrateOrRollback = async (trx, config, set, versions, count, asts, up, re
2856
3008
  set,
2857
3009
  versions,
2858
3010
  sequence.length - i,
2859
- asts,
2860
3011
  false,
2861
3012
  redo2
2862
3013
  );
@@ -2873,13 +3024,21 @@ const migrateOrRollback = async (trx, config, set, versions, count, asts, up, re
2873
3024
  await (beforeMigrate == null ? void 0 : beforeMigrate({ db, migrations }));
2874
3025
  await ((_a = config.beforeChange) == null ? void 0 : _a.call(config, { db, migrations, up, redo: redo2 }));
2875
3026
  }
3027
+ let loggedAboutStarting = false;
2876
3028
  for (const file of set.migrations) {
2877
3029
  if (up && versionsMap[file.version] || !up && !versionsMap[file.version]) {
2878
3030
  continue;
2879
3031
  }
2880
3032
  if (count-- <= 0)
2881
3033
  break;
2882
- await runMigration(trx, up, file, config, asts);
3034
+ if (!loggedAboutStarting && (!redo2 || !up)) {
3035
+ loggedAboutStarting = true;
3036
+ (_b = config.logger) == null ? void 0 : _b.log(
3037
+ `${redo2 ? "Reapplying migrations for" : up ? "Migrating" : "Rolling back"} database ${trx.config.connectionString ? new URL(trx.config.connectionString).pathname.slice(1) : trx.config.database}
3038
+ `
3039
+ );
3040
+ }
3041
+ await runMigration(trx, up, file, config);
2883
3042
  if (up) {
2884
3043
  const name = path.basename(file.path);
2885
3044
  versionsMap[file.version] = name;
@@ -2888,15 +3047,16 @@ const migrateOrRollback = async (trx, config, set, versions, count, asts, up, re
2888
3047
  versionsMap[file.version] = void 0;
2889
3048
  sequence.pop();
2890
3049
  }
2891
- (_b = config.logger) == null ? void 0 : _b.log(
2892
- `${up ? "Migrated" : "Rolled back"} ${orchidCore.pathToLog(file.path)}`
3050
+ (_c = config.logger) == null ? void 0 : _c.log(
3051
+ `${up ? "Migrated" : "Rolled back"} ${orchidCore.pathToLog(file.path)}
3052
+ `
2893
3053
  );
2894
3054
  }
2895
3055
  const afterMigrate = config[up ? "afterMigrate" : "afterRollback"];
2896
3056
  if (config.afterChange || afterMigrate) {
2897
3057
  db != null ? db : db = getDb(trx);
2898
3058
  const { migrations } = set;
2899
- await ((_c = config.afterChange) == null ? void 0 : _c.call(config, { db, up, redo: redo2, migrations }));
3059
+ await ((_d = config.afterChange) == null ? void 0 : _d.call(config, { db, up, redo: redo2, migrations }));
2900
3060
  await (afterMigrate == null ? void 0 : afterMigrate({ db, migrations }));
2901
3061
  }
2902
3062
  };
@@ -2920,31 +3080,8 @@ Run \`**db command** up force\` to rollback the above migrations and migrate all
2920
3080
  }
2921
3081
  return;
2922
3082
  };
2923
- async function runCodeUpdaterAfterAll(options, config, appCodeUpdater, asts, cache) {
2924
- for (const ast of asts) {
2925
- await (appCodeUpdater == null ? void 0 : appCodeUpdater.process({
2926
- ast,
2927
- options,
2928
- basePath: config.basePath,
2929
- cache,
2930
- logger: config.logger,
2931
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2932
- baseTable: config.baseTable,
2933
- import: config.import
2934
- }));
2935
- }
2936
- await (appCodeUpdater == null ? void 0 : appCodeUpdater.afterAll({
2937
- options,
2938
- basePath: config.basePath,
2939
- cache,
2940
- logger: config.logger,
2941
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2942
- baseTable: config.baseTable,
2943
- import: config.import
2944
- }));
2945
- }
2946
3083
  const changeCache = {};
2947
- const runMigration = async (trx, up, file, config, asts) => {
3084
+ const runMigration = async (trx, up, file, config) => {
2948
3085
  clearChanges();
2949
3086
  let changes = changeCache[file.path];
2950
3087
  if (!changes) {
@@ -2958,7 +3095,7 @@ const runMigration = async (trx, up, file, config, asts) => {
2958
3095
  changes = exported || getCurrentChanges();
2959
3096
  changeCache[file.path] = changes;
2960
3097
  }
2961
- const db = createMigrationInterface(trx, up, config, asts);
3098
+ const db = createMigrationInterface(trx, up, config);
2962
3099
  if (changes.length) {
2963
3100
  const from = up ? 0 : changes.length - 1;
2964
3101
  const to = up ? changes.length : -1;
@@ -3008,8 +3145,7 @@ const migrationConfigDefaults = {
3008
3145
  });
3009
3146
  },
3010
3147
  log: true,
3011
- logger: console,
3012
- useCodeUpdater: true
3148
+ logger: console
3013
3149
  };
3014
3150
  const processRakeDbConfig = (config) => {
3015
3151
  var _a, _b;
@@ -3017,11 +3153,6 @@ const processRakeDbConfig = (config) => {
3017
3153
  if (!result.recurrentPath) {
3018
3154
  result.recurrentPath = path.join(result.migrationsPath, "recurrent");
3019
3155
  }
3020
- if (config.appCodeUpdater && (!("baseTable" in config) || !config.baseTable)) {
3021
- throw new Error(
3022
- "`baseTable` option is required in `rakeDb` for `appCodeUpdater`"
3023
- );
3024
- }
3025
3156
  if (!result.log) {
3026
3157
  delete result.logger;
3027
3158
  }
@@ -3083,6 +3214,204 @@ const getDatabaseAndUserFromOptions = (options) => {
3083
3214
  }
3084
3215
  };
3085
3216
 
3217
+ const colors = {
3218
+ yellow: (s) => `\x1B[33m${s}\x1B[0m`,
3219
+ green: (s) => `\x1B[32m${s}\x1B[0m`,
3220
+ red: (s) => `\x1B[31m${s}\x1B[0m`,
3221
+ blue: (s) => `\x1B[34m${s}\x1B[0m`,
3222
+ bright: (s) => `\x1B[1m${s}\x1B[0m`,
3223
+ blueBold: (s) => `\x1B[1m\x1B[34m${s}\x1B[0m`,
3224
+ yellowBold: (s) => `\x1B[1m\x1B[33m${s}\x1B[0m`,
3225
+ greenBold: (s) => `\x1B[1m\x1B[32m${s}\x1B[0m`,
3226
+ pale: (s) => `\x1B[2m${s}\x1B[0m`
3227
+ };
3228
+
3229
+ const ESC = "\x1B";
3230
+ const CSI = `${ESC}[`;
3231
+ const cursorShow = `${CSI}?25h`;
3232
+ const cursorHide = `${CSI}?25l`;
3233
+ const { stdin, stdout } = process;
3234
+ const visibleChars = (s) => s.replace(
3235
+ // eslint-disable-next-line no-control-regex
3236
+ /[\u001B\u009B][[\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\d\/#&.:=?%@~_]+)*|[a-zA-Z\d]+(?:;[-a-zA-Z\d\/#&.:=?%@~_]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PRZcf-ntqry=><~]))/g,
3237
+ ""
3238
+ ).length;
3239
+ const clear = (text) => {
3240
+ const rows = text.split(/\r?\n/).reduce(
3241
+ (rows2, line) => rows2 + 1 + Math.floor(Math.max(visibleChars(line) - 1, 0) / stdout.columns),
3242
+ 0
3243
+ );
3244
+ let clear2 = "";
3245
+ for (let i = 0; i < rows; i++) {
3246
+ clear2 += `${CSI}2K`;
3247
+ if (i < rows - 1) {
3248
+ clear2 += `${CSI}${i < rows - 1 ? "1A" : "G"}`;
3249
+ }
3250
+ }
3251
+ return clear2;
3252
+ };
3253
+ const prompt = async ({
3254
+ render,
3255
+ onKeyPress,
3256
+ validate,
3257
+ value,
3258
+ cursor: showCursor
3259
+ }) => {
3260
+ stdin.resume();
3261
+ if (stdin.isTTY)
3262
+ stdin.setRawMode(true);
3263
+ stdin.setEncoding("utf-8");
3264
+ if (!showCursor)
3265
+ stdout.write(cursorHide);
3266
+ return new Promise((res) => {
3267
+ let prevText;
3268
+ const ctx = {
3269
+ value,
3270
+ submitted: false,
3271
+ render() {
3272
+ let text = (ctx.submitted ? colors.greenBold("\u2714") : colors.yellowBold("?")) + " " + render(ctx);
3273
+ if (ctx.submitted)
3274
+ text += "\n";
3275
+ stdout.write(prevText ? clear(prevText) + "\r" + text : text);
3276
+ prevText = text;
3277
+ },
3278
+ submit(value2) {
3279
+ if (value2 !== void 0)
3280
+ ctx.value = value2;
3281
+ if (ctx.value === void 0 || validate && !(validate == null ? void 0 : validate(ctx)))
3282
+ return;
3283
+ ctx.submitted = true;
3284
+ ctx.render();
3285
+ close();
3286
+ res(ctx.value);
3287
+ }
3288
+ };
3289
+ const close = () => {
3290
+ if (!showCursor)
3291
+ stdout.write(cursorShow);
3292
+ if (stdin.isTTY)
3293
+ stdin.setRawMode(false);
3294
+ stdin.off("data", keypress);
3295
+ stdin.pause();
3296
+ };
3297
+ const keypress = (s) => {
3298
+ if (s === "" || s === "") {
3299
+ close == null ? void 0 : close();
3300
+ process.exit(0);
3301
+ }
3302
+ if (s === "\r" || s === "\n" || s === "\r\n") {
3303
+ ctx.submit();
3304
+ } else {
3305
+ onKeyPress(ctx, s);
3306
+ }
3307
+ };
3308
+ stdin.on("data", keypress);
3309
+ ctx.render();
3310
+ });
3311
+ };
3312
+ const defaultActive = (s) => `${colors.blueBold("\u276F")} ${s}`;
3313
+ const defaultInactive = (s) => ` ${s}`;
3314
+ const promptSelect = ({
3315
+ message,
3316
+ options,
3317
+ active = defaultActive,
3318
+ inactive = defaultInactive
3319
+ }) => prompt({
3320
+ value: 0,
3321
+ render(ctx) {
3322
+ let text = `${message} ${colors.pale(
3323
+ "Use arrows or jk. Press enter to submit."
3324
+ )}
3325
+ `;
3326
+ for (let i = 0; i < options.length; i++) {
3327
+ text += (ctx.value === i ? active : inactive)(options[i]) + "\n";
3328
+ }
3329
+ return text;
3330
+ },
3331
+ onKeyPress(ctx, s) {
3332
+ ctx.value = s === "\x1B[H" ? 0 : s === "\x1B[F" ? options.length - 1 : s === "\x1B[A" || s === "k" ? ctx.value === 0 ? options.length - 1 : ctx.value - 1 : s === "\x1B[B" || s === "j" || s === " " ? ctx.value === options.length - 1 ? 0 : ctx.value + 1 : ctx.value;
3333
+ ctx.render();
3334
+ }
3335
+ });
3336
+ const promptConfirm = ({
3337
+ message
3338
+ }) => prompt({
3339
+ value: true,
3340
+ render(ctx) {
3341
+ return `${colors.bright(message)}
3342
+ ${ctx.submitted ? `> ${ctx.value ? colors.greenBold("Yes") : colors.yellowBold("No")}` : colors.pale(`> (Y/n)`)}
3343
+ `;
3344
+ },
3345
+ onKeyPress(ctx, s) {
3346
+ let ok;
3347
+ if (s === "y" || s === "Y")
3348
+ ok = true;
3349
+ else if (s === "n" || s === "N")
3350
+ ok = false;
3351
+ if (ok !== void 0) {
3352
+ ctx.submit(ok);
3353
+ }
3354
+ }
3355
+ });
3356
+ const promptText = ({
3357
+ message,
3358
+ default: def = "",
3359
+ password,
3360
+ min
3361
+ }) => {
3362
+ let showDefault = true;
3363
+ let x = 0;
3364
+ const renderValue = (ctx) => password ? "*".repeat(ctx.value.length) : ctx.value;
3365
+ return prompt({
3366
+ value: def,
3367
+ cursor: true,
3368
+ validate: (ctx) => !min || ctx.value.length >= min,
3369
+ render(ctx) {
3370
+ let text = `${colors.bright(message)}
3371
+ > ${ctx.submitted ? renderValue(ctx) : showDefault ? colors.pale(def) + "\b".repeat(def.length) : ctx.value}`;
3372
+ if (ctx.submitted)
3373
+ text += "\n";
3374
+ return text;
3375
+ },
3376
+ onKeyPress(ctx, s) {
3377
+ let value = showDefault ? "" : ctx.value;
3378
+ if (s === "\x1B[D" && x > 0) {
3379
+ x--;
3380
+ stdout.write("\b");
3381
+ } else if (s === "\x1B[C" && x < value.length) {
3382
+ stdout.write(value[x]);
3383
+ x++;
3384
+ }
3385
+ if (s !== "\x7F" && s !== "\x1B[3~" && !visibleChars(s))
3386
+ return;
3387
+ if (showDefault) {
3388
+ showDefault = false;
3389
+ stdout.write(" ".repeat(def.length) + "\b".repeat(def.length));
3390
+ }
3391
+ const prev = value;
3392
+ const prevX = x;
3393
+ if (s === "\x7F") {
3394
+ if (x > 0) {
3395
+ value = value.slice(0, x - 1) + value.slice(x);
3396
+ x--;
3397
+ }
3398
+ } else if (s === "\x1B[3~") {
3399
+ if (x < value.length) {
3400
+ value = value.slice(0, x) + value.slice(x + 1);
3401
+ }
3402
+ } else {
3403
+ value = value.slice(0, x) + s + value.slice(x);
3404
+ x++;
3405
+ }
3406
+ ctx.value = value;
3407
+ const spaces = prev.length - value.length;
3408
+ stdout.write(
3409
+ "\b".repeat(prevX) + renderValue(ctx) + (spaces > 0 ? " ".repeat(spaces) + "\b".repeat(spaces) : "") + "\b".repeat(value.length - x)
3410
+ );
3411
+ }
3412
+ });
3413
+ };
3414
+
3086
3415
  var __defProp$3 = Object.defineProperty;
3087
3416
  var __defProps$2 = Object.defineProperties;
3088
3417
  var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
@@ -3120,34 +3449,25 @@ const setAdapterOptions = (options, set) => {
3120
3449
  }
3121
3450
  };
3122
3451
  const setAdminCredentialsToOptions = async (options, create) => {
3123
- const confirm = await prompts([
3124
- {
3125
- message: `Would you like to share admin credentials to ${create ? "create" : "drop"} a database`,
3126
- type: "confirm",
3127
- name: "confirm",
3128
- initial: true
3129
- }
3130
- ]);
3131
- if (!confirm.confirm) {
3452
+ const ok = await promptConfirm({
3453
+ message: `Would you like to share admin credentials to ${create ? "create" : "drop"} a database?`
3454
+ });
3455
+ if (!ok) {
3132
3456
  return;
3133
3457
  }
3134
- const values = await prompts([
3135
- {
3136
- message: "Enter admin user:",
3137
- type: "text",
3138
- name: "user",
3139
- initial: "postgres",
3140
- min: 1
3141
- },
3142
- {
3143
- message: "Enter admin password:",
3144
- type: "password",
3145
- name: "password"
3146
- }
3147
- ]);
3148
- return setAdapterOptions(options, __spreadProps$2(__spreadValues$3({}, values), {
3149
- password: values.password || void 0
3150
- }));
3458
+ const user = await promptText({
3459
+ message: "Enter admin user:",
3460
+ default: "postgres",
3461
+ min: 1
3462
+ });
3463
+ const password = await promptText({
3464
+ message: "Enter admin password:",
3465
+ password: true
3466
+ });
3467
+ return setAdapterOptions(options, {
3468
+ user,
3469
+ password: password || void 0
3470
+ });
3151
3471
  };
3152
3472
 
3153
3473
  const execute = async (options, sql) => {
@@ -3279,14 +3599,14 @@ const columnsSql = ({
3279
3599
  information_schema._pg_datetime_precision(
3280
3600
  information_schema._pg_truetypid(a, t),
3281
3601
  information_schema._pg_truetypmod(a, t)
3282
- ) AS "datetimePrecision",
3602
+ ) AS "dateTimePrecision",
3283
3603
  CAST(
3284
3604
  CASE WHEN a.attgenerated = ''
3285
3605
  THEN pg_get_expr(ad.adbin, ad.adrelid)
3286
3606
  END AS information_schema.character_data
3287
3607
  ) AS "default",
3288
3608
  NOT (a.attnotnull OR (t.typtype = 'd' AND t.typnotnull)) AS "isNullable",
3289
- co.collname AS "collation",
3609
+ co.collname AS "collate",
3290
3610
  NULLIF(a.attcompression, '') AS compression,
3291
3611
  pgd.description AS "comment",
3292
3612
  (
@@ -3353,6 +3673,19 @@ ORDER BY relname`;
3353
3673
  const viewsSql = `SELECT
3354
3674
  nc.nspname AS "schemaName",
3355
3675
  c.relname AS "name",
3676
+ (
3677
+ SELECT COALESCE(json_agg(t.*), '[]')
3678
+ FROM (
3679
+ SELECT
3680
+ ns.nspname AS "schemaName",
3681
+ obj.relname AS "name"
3682
+ FROM pg_class obj
3683
+ JOIN pg_depend dep ON dep.refobjid = obj.oid
3684
+ JOIN pg_rewrite rew ON rew.oid = dep.objid
3685
+ JOIN pg_namespace ns ON ns.oid = obj.relnamespace
3686
+ WHERE rew.ev_class = c.oid AND obj.oid <> c.oid
3687
+ ) t
3688
+ ) "deps",
3356
3689
  right(substring(r.ev_action from ':hasRecursive w'), 1)::bool AS "isRecursive",
3357
3690
  array_to_json(c.reloptions) AS "with",
3358
3691
  (SELECT coalesce(json_agg(t), '[]') FROM (${columnsSql({
@@ -3374,7 +3707,7 @@ const indexesSql = `SELECT
3374
3707
  t.relname "tableName",
3375
3708
  ic.relname "name",
3376
3709
  am.amname AS "using",
3377
- i.indisunique "isUnique",
3710
+ i.indisunique "unique",
3378
3711
  (
3379
3712
  SELECT json_agg(
3380
3713
  (
@@ -3554,7 +3887,7 @@ JOIN pg_catalog.pg_namespace n ON n.oid = extnamespace
3554
3887
  const enumsSql = `SELECT
3555
3888
  n.nspname as "schemaName",
3556
3889
  t.typname as name,
3557
- json_agg(e.enumlabel) as values
3890
+ json_agg(e.enumlabel ORDER BY e.enumsortorder) as values
3558
3891
  FROM pg_type t
3559
3892
  JOIN pg_enum e ON t.oid = e.enumtypid
3560
3893
  JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
@@ -3565,15 +3898,15 @@ const domainsSql = `SELECT
3565
3898
  d.typname AS "name",
3566
3899
  t.typname AS "type",
3567
3900
  s.nspname AS "typeSchema",
3568
- d.typnotnull AS "notNull",
3901
+ NOT d.typnotnull AS "isNullable",
3569
3902
  d.typcategory = 'A' AS "isArray",
3570
3903
  character_maximum_length AS "maxChars",
3571
3904
  numeric_precision AS "numericPrecision",
3572
3905
  numeric_scale AS "numericScale",
3573
3906
  datetime_precision AS "dateTimePrecision",
3574
- collation_name AS "collation",
3907
+ collation_name AS "collate",
3575
3908
  domain_default AS "default",
3576
- pg_get_expr(conbin, conrelid) AS "expression"
3909
+ pg_get_expr(conbin, conrelid) AS "check"
3577
3910
  FROM pg_catalog.pg_type d
3578
3911
  JOIN pg_catalog.pg_namespace n ON n.oid = d.typnamespace
3579
3912
  JOIN information_schema.domains i
@@ -3590,7 +3923,7 @@ JOIN pg_catalog.pg_namespace s ON s.oid = t.typnamespace
3590
3923
  LEFT JOIN pg_catalog.pg_constraint c ON c.contypid = d.oid
3591
3924
  WHERE d.typtype = 'd' AND ${filterSchema("n.nspname")}`;
3592
3925
  const collationsSql = `SELECT
3593
- nspname "schema",
3926
+ nspname "schemaName",
3594
3927
  collname "name",
3595
3928
  CASE WHEN collprovider = 'i' THEN 'icu' WHEN collprovider = 'c' THEN 'libc' ELSE collprovider::text END "provider",
3596
3929
  collisdeterministic "deterministic",
@@ -3615,9 +3948,93 @@ const sql = `SELECT (${schemasSql}) AS "schemas", ${jsonAgg(
3615
3948
  "collations"
3616
3949
  )}`;
3617
3950
  async function introspectDbSchema(db) {
3951
+ var _a;
3618
3952
  const data = await db.query(sql);
3619
- return data.rows[0];
3953
+ const result = data.rows[0];
3954
+ for (const domain of result.domains) {
3955
+ nullsToUndefined(domain);
3956
+ }
3957
+ for (const table of result.tables) {
3958
+ for (const column of table.columns) {
3959
+ nullsToUndefined(column);
3960
+ if (column.identity)
3961
+ nullsToUndefined(column.identity);
3962
+ if (column.compression) {
3963
+ column.compression = column.compression === "p" ? "pglz" : "lz4";
3964
+ }
3965
+ }
3966
+ }
3967
+ for (const index of result.indexes) {
3968
+ nullsToUndefined(index);
3969
+ for (const column of index.columns) {
3970
+ if (!("expression" in column))
3971
+ continue;
3972
+ const s = column.expression;
3973
+ const columnR = `"?\\w+"?`;
3974
+ const langR = `(${columnR}|'\\w+'::regconfig)`;
3975
+ const firstColumnR = `[(]*${columnR}`;
3976
+ const concatR = `\\|\\|`;
3977
+ const restColumnR = ` ${concatR} ' '::text\\) ${concatR} ${columnR}\\)`;
3978
+ const coalesceColumn = `COALESCE\\(${columnR}, ''::text\\)`;
3979
+ const tsVectorR = `to_tsvector\\(${langR}, (${firstColumnR}|${restColumnR}|${coalesceColumn})+\\)`;
3980
+ const weightR = `'\\w'::"char"`;
3981
+ const setWeightR = `setweight\\(${tsVectorR}, ${weightR}\\)`;
3982
+ const setWeightOrTsVectorR = `(${setWeightR}|${tsVectorR})`;
3983
+ const match = s.match(
3984
+ new RegExp(`^([\\(]*${setWeightOrTsVectorR}[\\)]*( ${concatR} )?)+$`)
3985
+ );
3986
+ if (!match)
3987
+ continue;
3988
+ let language;
3989
+ let languageColumn;
3990
+ const tokens = (_a = match[0].match(
3991
+ new RegExp(
3992
+ `setweight\\(|to_tsvector\\(${langR}|[:']?${columnR}\\(?`,
3993
+ "g"
3994
+ )
3995
+ )) == null ? void 0 : _a.reduce((acc, token) => {
3996
+ if (token === "setweight(" || token === "COALESCE(" || token[0] === ":")
3997
+ return acc;
3998
+ if (token.startsWith("to_tsvector(")) {
3999
+ if (token[12] === "'") {
4000
+ language = token.slice(13, -12);
4001
+ } else {
4002
+ languageColumn = token.slice(12);
4003
+ }
4004
+ } else if (token[0] === "'") {
4005
+ acc.push({ kind: "weight", value: token[1] });
4006
+ } else {
4007
+ if (token[0] === '"')
4008
+ token = token.slice(1, -1);
4009
+ acc.push({ kind: "column", value: token });
4010
+ }
4011
+ return acc;
4012
+ }, []);
4013
+ if (!tokens)
4014
+ continue;
4015
+ index.language = language;
4016
+ index.languageColumn = languageColumn;
4017
+ index.tsVector = true;
4018
+ index.columns = [];
4019
+ for (const token of tokens) {
4020
+ if (token.kind === "column") {
4021
+ index.columns.push({
4022
+ column: token.value
4023
+ });
4024
+ } else if (token.kind === "weight") {
4025
+ index.columns[index.columns.length - 1].weight = token.value;
4026
+ }
4027
+ }
4028
+ }
4029
+ }
4030
+ return result;
3620
4031
  }
4032
+ const nullsToUndefined = (obj) => {
4033
+ for (const key in obj) {
4034
+ if (obj[key] === null)
4035
+ obj[key] = void 0;
4036
+ }
4037
+ };
3621
4038
 
3622
4039
  var __defProp$2 = Object.defineProperty;
3623
4040
  var __defProps$1 = Object.defineProperties;
@@ -3638,18 +4055,6 @@ var __spreadValues$2 = (a, b) => {
3638
4055
  return a;
3639
4056
  };
3640
4057
  var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
3641
- var __objRest = (source, exclude) => {
3642
- var target = {};
3643
- for (var prop in source)
3644
- if (__hasOwnProp$2.call(source, prop) && exclude.indexOf(prop) < 0)
3645
- target[prop] = source[prop];
3646
- if (source != null && __getOwnPropSymbols$2)
3647
- for (var prop of __getOwnPropSymbols$2(source)) {
3648
- if (exclude.indexOf(prop) < 0 && __propIsEnum$2.call(source, prop))
3649
- target[prop] = source[prop];
3650
- }
3651
- return target;
3652
- };
3653
4058
  const matchMap = {
3654
4059
  s: void 0,
3655
4060
  f: "FULL",
@@ -3663,6 +4068,13 @@ const fkeyActionMap = {
3663
4068
  n: "SET NULL",
3664
4069
  d: "SET DEFAULT"
3665
4070
  };
4071
+ const makeStructureToAstCtx = (config, currentSchema) => ({
4072
+ snakeCase: config.snakeCase,
4073
+ unsupportedTypes: {},
4074
+ currentSchema,
4075
+ columnSchemaConfig: config.schemaConfig,
4076
+ columnsByType: pqb.makeColumnsByType(config.schemaConfig)
4077
+ });
3666
4078
  const structureToAst = async (ctx, adapter) => {
3667
4079
  const ast = [];
3668
4080
  const data = await introspectDbSchema(adapter);
@@ -3680,42 +4092,15 @@ const structureToAst = async (ctx, adapter) => {
3680
4092
  type: "collation",
3681
4093
  action: "create"
3682
4094
  }, it), {
3683
- schema: it.schema === ctx.currentSchema ? void 0 : it.schema
4095
+ schema: it.schemaName === ctx.currentSchema ? void 0 : it.schemaName
3684
4096
  }));
3685
4097
  }
3686
- const pendingTables = {};
4098
+ const domains = makeDomainsMap(ctx, data);
3687
4099
  for (const table of data.tables) {
3688
- const key = `${table.schemaName}.${table.name}`;
3689
- const dependsOn = /* @__PURE__ */ new Set();
3690
- for (const fk of data.constraints) {
3691
- const { references } = fk;
3692
- if (!references || fk.schemaName !== table.schemaName || fk.tableName !== table.name)
3693
- continue;
3694
- const otherKey = `${references.foreignSchema}.${references.foreignTable}`;
3695
- if (otherKey !== key) {
3696
- dependsOn.add(otherKey);
3697
- }
3698
- }
3699
- pendingTables[key] = { table, dependsOn };
3700
- }
3701
- const domains = {};
3702
- for (const it of data.domains) {
3703
- domains[`${it.schemaName}.${it.name}`] = getColumn(ctx, data, domains, {
3704
- schemaName: it.schemaName,
3705
- name: it.name,
3706
- type: it.type,
3707
- typeSchema: it.typeSchema,
3708
- isArray: it.isArray,
3709
- isSerial: false
3710
- });
3711
- }
3712
- for (const key in pendingTables) {
3713
- const { table, dependsOn } = pendingTables[key];
3714
- if (!dependsOn.size) {
3715
- pushTableAst(ctx, ast, data, domains, table, pendingTables);
3716
- }
4100
+ if (table.name === "schemaMigrations")
4101
+ continue;
4102
+ ast.push(tableToAst(ctx, data, table, "create", domains));
3717
4103
  }
3718
- const outerConstraints = [];
3719
4104
  for (const it of data.extensions) {
3720
4105
  ast.push({
3721
4106
  type: "extension",
@@ -3740,51 +4125,50 @@ const structureToAst = async (ctx, adapter) => {
3740
4125
  action: "create",
3741
4126
  schema: it.schemaName === ctx.currentSchema ? void 0 : it.schemaName,
3742
4127
  name: it.name,
3743
- baseType: domains[`${it.schemaName}.${it.name}`],
3744
- notNull: it.notNull,
3745
- collation: it.collation,
3746
- default: pqb.simplifyColumnDefault(it.default),
3747
- check: it.check ? pqb.raw({ raw: it.check }) : void 0
4128
+ baseType: domains[`${it.schemaName}.${it.name}`]
3748
4129
  });
3749
4130
  }
3750
- for (const key in pendingTables) {
3751
- const innerConstraints = [];
3752
- const { table } = pendingTables[key];
4131
+ for (const table of data.tables) {
3753
4132
  for (const fkey of data.constraints) {
3754
- if (fkey.schemaName !== table.schemaName || fkey.tableName !== table.name)
3755
- continue;
3756
- const otherKey = fkey.references && `${fkey.references.foreignSchema}.${fkey.references.foreignTable}`;
3757
- if (!otherKey || !pendingTables[otherKey] || otherKey === key) {
3758
- innerConstraints.push(fkey);
3759
- } else {
3760
- outerConstraints.push([fkey, table]);
4133
+ if (fkey.references && fkey.tableName === table.name && fkey.schemaName === table.schemaName && checkIfIsOuterRecursiveFkey(data, table, fkey.references)) {
4134
+ ast.push(__spreadProps$1(__spreadValues$2({}, constraintToAst(ctx, fkey)), {
4135
+ type: "constraint",
4136
+ action: "create",
4137
+ tableSchema: table.schemaName === ctx.currentSchema ? void 0 : table.schemaName,
4138
+ tableName: fkey.tableName
4139
+ }));
3761
4140
  }
3762
4141
  }
3763
- pushTableAst(
3764
- ctx,
3765
- ast,
3766
- data,
3767
- domains,
3768
- table,
3769
- pendingTables,
3770
- innerConstraints
3771
- );
3772
- }
3773
- for (const [fkey, table] of outerConstraints) {
3774
- ast.push(__spreadProps$1(__spreadValues$2({}, constraintToAst(ctx, fkey)), {
3775
- type: "constraint",
3776
- action: "create",
3777
- tableSchema: table.schemaName === ctx.currentSchema ? void 0 : table.schemaName,
3778
- tableName: fkey.tableName
3779
- }));
3780
4142
  }
3781
4143
  for (const view of data.views) {
3782
4144
  ast.push(viewToAst(ctx, data, domains, view));
3783
4145
  }
3784
4146
  return ast;
3785
4147
  };
3786
- const makeBelongsToTable = (schema, table) => (item) => item.schemaName === schema && item.tableName === table;
3787
- const getIsSerial = (item) => {
4148
+ const makeDomainsMap = (ctx, data) => {
4149
+ const domains = {};
4150
+ for (const it of data.domains) {
4151
+ const column = instantiateDbColumn(ctx, data, domains, {
4152
+ schemaName: it.schemaName,
4153
+ name: it.name,
4154
+ type: it.type,
4155
+ typeSchema: it.typeSchema,
4156
+ isArray: it.isArray,
4157
+ tableName: "",
4158
+ isNullable: it.isNullable,
4159
+ collate: it.collate,
4160
+ default: it.default
4161
+ });
4162
+ if (it.check) {
4163
+ column.data.check = {
4164
+ sql: new pqb.RawSQL([[it.check]])
4165
+ };
4166
+ }
4167
+ domains[`${it.schemaName}.${it.name}`] = column;
4168
+ }
4169
+ return domains;
4170
+ };
4171
+ const getDbColumnIsSerial = (item) => {
3788
4172
  if (item.type === "int2" || item.type === "int4" || item.type === "int8") {
3789
4173
  const { default: def, schemaName, tableName, name } = item;
3790
4174
  const seq = `${tableName}_${name}_seq`;
@@ -3794,166 +4178,104 @@ const getIsSerial = (item) => {
3794
4178
  }
3795
4179
  return false;
3796
4180
  };
3797
- const getColumn = (ctx, data, domains, _a) => {
3798
- var _b = _a, {
3799
- schemaName,
3800
- tableName,
3801
- name,
3802
- type,
3803
- typeSchema,
3804
- isArray,
3805
- isSerial
3806
- } = _b, params = __objRest(_b, [
3807
- "schemaName",
3808
- "tableName",
3809
- "name",
3810
- "type",
3811
- "typeSchema",
3812
- "isArray",
3813
- "isSerial"
3814
- ]);
3815
- var _a2, _b2;
4181
+ const instantiateDbColumn = (ctx, data, domains, dbColumn) => {
4182
+ var _a, _b, _c;
4183
+ const isSerial = getDbColumnIsSerial(dbColumn);
4184
+ if (isSerial) {
4185
+ dbColumn = __spreadProps$1(__spreadValues$2({}, dbColumn), { default: void 0 });
4186
+ }
3816
4187
  let column;
3817
- const columnType = getColumnType(type, isSerial);
3818
- const typeFn = ctx.columnsByType[columnType];
3819
- if (typeFn) {
3820
- column = pqb.instantiateColumn(typeFn, params);
4188
+ const col = instantiateColumnByDbType(ctx, dbColumn.type, isSerial, dbColumn);
4189
+ if (col) {
4190
+ column = col;
3821
4191
  } else {
3822
- const domainColumn = domains[`${typeSchema}.${type}`];
4192
+ const { typeSchema, type: typeName } = dbColumn;
4193
+ const typeId = typeSchema === "pg_catalog" ? typeName : `${typeSchema}.${typeName}`;
4194
+ const domainColumn = domains[typeId];
3823
4195
  if (domainColumn) {
3824
- column = new pqb.DomainColumn(ctx.columnSchemaConfig, type).as(domainColumn);
4196
+ column = new pqb.DomainColumn(ctx.columnSchemaConfig, typeId).as(
4197
+ domainColumn
4198
+ );
3825
4199
  } else {
3826
4200
  const enumType = data.enums.find(
3827
- (item) => item.name === type && item.schemaName === typeSchema
4201
+ (x) => x.name === typeName && x.schemaName === typeSchema
3828
4202
  );
3829
4203
  if (enumType) {
3830
4204
  column = new pqb.EnumColumn(
3831
4205
  ctx.columnSchemaConfig,
3832
- type,
4206
+ typeId,
3833
4207
  enumType.values,
3834
4208
  ctx.columnSchemaConfig.type
3835
4209
  );
3836
4210
  } else {
3837
- column = new pqb.CustomTypeColumn(ctx.columnSchemaConfig, type);
3838
- ((_b2 = (_a2 = ctx.unsupportedTypes)[type]) != null ? _b2 : _a2[type] = []).push(
3839
- `${schemaName}${tableName ? `.${tableName}` : ""}.${name}`
4211
+ column = new pqb.CustomTypeColumn(ctx.columnSchemaConfig, typeId);
4212
+ ((_c = (_a = ctx.unsupportedTypes)[_b = dbColumn.type]) != null ? _c : _a[_b] = []).push(
4213
+ `${dbColumn.schemaName}${dbColumn.tableName ? `.${dbColumn.tableName}` : ""}.${dbColumn.name}`
3840
4214
  );
3841
4215
  }
3842
4216
  }
3843
4217
  }
3844
- return isArray ? new pqb.ArrayColumn(
4218
+ column.data.name = void 0;
4219
+ return dbColumn.isArray ? new pqb.ArrayColumn(
3845
4220
  ctx.columnSchemaConfig,
3846
4221
  column,
3847
4222
  ctx.columnSchemaConfig.type
3848
4223
  ) : column;
3849
4224
  };
3850
- const getColumnType = (type, isSerial) => {
3851
- if (!isSerial)
3852
- return type;
3853
- return type === "int2" ? "smallserial" : type === "int4" ? "serial" : "bigserial";
4225
+ const instantiateColumnByDbType = (ctx, type, isSerial, params) => {
4226
+ const columnFn = ctx.columnsByType[!isSerial ? type : type === "int2" ? "smallserial" : type === "int4" ? "serial" : "bigserial"];
4227
+ return columnFn ? pqb.instantiateColumn(columnFn, params) : void 0;
3854
4228
  };
3855
- const pushTableAst = (ctx, ast, data, domains, table, pendingTables, innerConstraints = data.constraints) => {
3856
- const { schemaName, name: tableName, columns } = table;
3857
- const key = `${schemaName}.${table.name}`;
3858
- delete pendingTables[key];
3859
- if (tableName === "schemaMigrations")
3860
- return;
3861
- const belongsToTable = makeBelongsToTable(schemaName, tableName);
3862
- let primaryKey;
3863
- for (const item of data.constraints) {
3864
- if (belongsToTable(item) && item.primaryKey)
3865
- primaryKey = { columns: item.primaryKey, name: item.name };
3866
- }
3867
- const tableIndexes = data.indexes.filter(belongsToTable);
3868
- const tableConstraints = innerConstraints.reduce(
3869
- (acc, item) => {
3870
- var _a;
3871
- const { references, check } = item;
3872
- if (belongsToTable(item) && (references || check && !isColumnCheck(item))) {
3873
- const constraint = {
3874
- references: references ? {
3875
- columns: references.columns,
3876
- fnOrTable: getReferencesTable(ctx, references),
3877
- foreignColumns: references.foreignColumns,
3878
- options: {
3879
- match: matchMap[references.match],
3880
- onUpdate: fkeyActionMap[references.onUpdate],
3881
- onDelete: fkeyActionMap[references.onDelete]
3882
- }
3883
- } : void 0,
3884
- check: check ? pqb.raw({ raw: check.expression }) : void 0
3885
- };
3886
- const name = item.name && item.name !== getConstraintName(tableName, constraint) ? item.name : void 0;
3887
- if (name) {
3888
- constraint.name = name;
3889
- if ((_a = constraint.references) == null ? void 0 : _a.options) {
3890
- constraint.references.options.name = name;
3891
- }
3892
- }
3893
- acc.push(constraint);
3894
- }
3895
- return acc;
3896
- },
3897
- []
3898
- );
3899
- const columnChecks = innerConstraints.reduce((acc, item) => {
3900
- if (belongsToTable(item) && isColumnCheck(item)) {
3901
- acc[item.check.columns[0]] = item.check.expression;
3902
- }
3903
- return acc;
3904
- }, {});
3905
- const shape = makeColumnsShape(
3906
- ctx,
3907
- data,
3908
- domains,
3909
- tableName,
3910
- columns,
3911
- primaryKey,
3912
- tableIndexes,
3913
- tableConstraints,
3914
- columnChecks
3915
- );
3916
- ast.push({
4229
+ const tableToAst = (ctx, data, table, action, domains) => {
4230
+ const { schemaName, name: tableName } = table;
4231
+ const tableData = getDbStructureTableData(data, table);
4232
+ const { primaryKey, indexes, constraints } = tableData;
4233
+ return {
3917
4234
  type: "table",
3918
- action: "create",
4235
+ action,
3919
4236
  schema: schemaName === ctx.currentSchema ? void 0 : schemaName,
3920
4237
  comment: table.comment,
3921
4238
  name: tableName,
3922
- shape,
3923
- noPrimaryKey: primaryKey ? "error" : "ignore",
3924
- primaryKey: primaryKey && primaryKey.columns.length > 1 ? {
3925
- columns: primaryKey.columns,
3926
- options: primaryKey.name === `${tableName}_pkey` ? void 0 : { name: primaryKey.name }
3927
- } : void 0,
3928
- indexes: tableIndexes.filter(
3929
- (index) => index.columns.length > 1 || index.columns.some((it) => "expression" in it)
3930
- ).map((index) => ({
3931
- columns: index.columns.map((it) => __spreadProps$1(__spreadValues$2({}, "column" in it ? { column: it.column } : { expression: it.expression }), {
3932
- collate: it.collate,
3933
- opclass: it.opclass,
3934
- order: it.order
3935
- })),
3936
- options: {
3937
- name: index.name !== getIndexName(tableName, index.columns) ? index.name : void 0,
3938
- using: index.using === "btree" ? void 0 : index.using,
3939
- unique: index.isUnique,
3940
- include: index.include,
3941
- nullsNotDistinct: index.nullsNotDistinct,
3942
- with: index.with,
3943
- tablespace: index.tablespace,
3944
- where: index.where
4239
+ shape: makeDbStructureColumnsShape(ctx, data, domains, table, tableData),
4240
+ noPrimaryKey: tableData.primaryKey ? "error" : "ignore",
4241
+ primaryKey: primaryKey && primaryKey.columns.length > 1 ? primaryKey : void 0,
4242
+ indexes: indexes.reduce((acc, index) => {
4243
+ if (index.columns.length > 1 || index.columns.some((it) => "expression" in it)) {
4244
+ acc.push({
4245
+ columns: index.columns.map((it) => __spreadProps$1(__spreadValues$2({}, "column" in it ? { column: it.column } : { expression: it.expression }), {
4246
+ collate: it.collate,
4247
+ opclass: it.opclass,
4248
+ order: it.order
4249
+ })),
4250
+ options: makeIndexOptions(tableName, index)
4251
+ });
3945
4252
  }
3946
- })),
3947
- constraints: tableConstraints.filter(
3948
- (it) => pqb.getConstraintKind(it) === "constraint" || !isColumnFkey(it)
3949
- )
3950
- });
3951
- for (const otherKey in pendingTables) {
3952
- const item = pendingTables[otherKey];
3953
- if (item.dependsOn.delete(key) && item.dependsOn.size === 0) {
3954
- pushTableAst(ctx, ast, data, domains, item.table, pendingTables);
3955
- }
3956
- }
4253
+ return acc;
4254
+ }, []),
4255
+ constraints: constraints.reduce((acc, it) => {
4256
+ var _a;
4257
+ if (it.check && it.references || it.check && ((_a = it.check.columns) == null ? void 0 : _a.length) !== 1 || it.references && it.references.columns.length !== 1 && !checkIfIsOuterRecursiveFkey(data, table, it.references)) {
4258
+ acc.push(dbConstraintToTableConstraint(ctx, table, it));
4259
+ }
4260
+ return acc;
4261
+ }, [])
4262
+ };
4263
+ };
4264
+ const getDbStructureTableData = (data, { name, schemaName }) => {
4265
+ const constraints = data.constraints.filter(
4266
+ (c) => c.tableName === name && c.schemaName === schemaName
4267
+ );
4268
+ const primaryKey = constraints.find((c) => c.primaryKey);
4269
+ return {
4270
+ primaryKey: (primaryKey == null ? void 0 : primaryKey.primaryKey) ? {
4271
+ columns: primaryKey.primaryKey,
4272
+ options: primaryKey.name === `${name}_pkey` ? void 0 : { name: primaryKey.name }
4273
+ } : void 0,
4274
+ indexes: data.indexes.filter(
4275
+ (it) => it.tableName === name && it.schemaName === schemaName
4276
+ ),
4277
+ constraints
4278
+ };
3957
4279
  };
3958
4280
  const constraintToAst = (ctx, item) => {
3959
4281
  var _a;
@@ -3995,12 +4317,8 @@ const isColumnCheck = (it) => {
3995
4317
  var _a, _b;
3996
4318
  return !it.references && ((_b = (_a = it.check) == null ? void 0 : _a.columns) == null ? void 0 : _b.length) === 1;
3997
4319
  };
3998
- const isColumnFkey = (it) => {
3999
- var _a;
4000
- return !it.check && ((_a = it.references) == null ? void 0 : _a.columns.length) === 1;
4001
- };
4002
4320
  const viewToAst = (ctx, data, domains, view) => {
4003
- const shape = makeColumnsShape(ctx, data, domains, view.name, view.columns);
4321
+ const shape = makeDbStructureColumnsShape(ctx, data, domains, view);
4004
4322
  const options = {};
4005
4323
  if (view.isRecursive)
4006
4324
  options.recursive = true;
@@ -4019,255 +4337,852 @@ const viewToAst = (ctx, data, domains, view) => {
4019
4337
  name: view.name,
4020
4338
  shape,
4021
4339
  sql: pqb.raw({ raw: view.sql }),
4022
- options
4340
+ options,
4341
+ deps: view.deps
4023
4342
  };
4024
4343
  };
4025
- const makeColumnsShape = (ctx, data, domains, tableName, columns, primaryKey, indexes, constraints, checks) => {
4026
- var _a, _b;
4344
+ const makeDbStructureColumnsShape = (ctx, data, domains, table, tableData) => {
4027
4345
  const shape = {};
4028
- for (let item of columns) {
4029
- const isSerial = getIsSerial(item);
4030
- if (isSerial) {
4031
- item = __spreadProps$1(__spreadValues$2({}, item), { default: void 0 });
4032
- }
4033
- let column = getColumn(ctx, data, domains, __spreadProps$1(__spreadValues$2({}, item), {
4034
- type: item.type,
4035
- isArray: item.isArray,
4036
- isSerial
4037
- }));
4038
- if (item.identity) {
4039
- column.data.identity = item.identity;
4040
- if (!item.identity.always)
4041
- (_a = column.data.identity) == null ? true : delete _a.always;
4346
+ const checks = tableData ? getDbTableColumnsChecks(tableData) : void 0;
4347
+ for (const item of table.columns) {
4348
+ const [key, column] = dbColumnToAst(
4349
+ ctx,
4350
+ data,
4351
+ domains,
4352
+ table.name,
4353
+ item,
4354
+ table,
4355
+ tableData,
4356
+ checks
4357
+ );
4358
+ shape[key] = column;
4359
+ }
4360
+ return shape;
4361
+ };
4362
+ const getDbTableColumnsChecks = (tableData) => tableData.constraints.reduce((acc, item) => {
4363
+ if (isColumnCheck(item)) {
4364
+ acc[item.check.columns[0]] = item.check.expression;
4365
+ }
4366
+ return acc;
4367
+ }, {});
4368
+ const dbColumnToAst = (ctx, data, domains, tableName, item, table, tableData, checks) => {
4369
+ var _a, _b, _c, _d, _e, _f, _g;
4370
+ let column = instantiateDbColumn(ctx, data, domains, item);
4371
+ if (item.identity) {
4372
+ column.data.identity = item.identity;
4373
+ if (!item.identity.always)
4374
+ (_a = column.data.identity) == null ? true : delete _a.always;
4375
+ }
4376
+ if (((_c = (_b = tableData == null ? void 0 : tableData.primaryKey) == null ? void 0 : _b.columns) == null ? void 0 : _c.length) === 1 && ((_d = tableData == null ? void 0 : tableData.primaryKey) == null ? void 0 : _d.columns[0]) === item.name) {
4377
+ column = column.primaryKey();
4378
+ }
4379
+ if (tableData == null ? void 0 : tableData.indexes) {
4380
+ const columnIndexes = tableData == null ? void 0 : tableData.indexes.filter(
4381
+ (it) => it.columns.length === 1 && "column" in it.columns[0] && it.columns[0].column === item.name
4382
+ );
4383
+ for (const index of columnIndexes) {
4384
+ const options = index.columns[0];
4385
+ column = column.index(__spreadValues$2({
4386
+ collate: options.collate,
4387
+ opclass: options.opclass,
4388
+ order: options.order
4389
+ }, makeIndexOptions(tableName, index)));
4042
4390
  }
4043
- if (((_b = primaryKey == null ? void 0 : primaryKey.columns) == null ? void 0 : _b.length) === 1 && (primaryKey == null ? void 0 : primaryKey.columns[0]) === item.name) {
4044
- column = column.primaryKey();
4391
+ }
4392
+ if (table) {
4393
+ for (const it of data.constraints) {
4394
+ if (it.tableName !== table.name || it.schemaName !== table.schemaName || it.check || ((_e = it.references) == null ? void 0 : _e.columns.length) !== 1 || it.references.columns[0] !== item.name || checkIfIsOuterRecursiveFkey(data, table, it.references)) {
4395
+ continue;
4396
+ }
4397
+ const c = dbConstraintToTableConstraint(ctx, table, it);
4398
+ column = column.foreignKey(
4399
+ (_f = c.references) == null ? void 0 : _f.fnOrTable,
4400
+ it.references.foreignColumns[0],
4401
+ (_g = c.references) == null ? void 0 : _g.options
4402
+ );
4403
+ }
4404
+ }
4405
+ const check = checks == null ? void 0 : checks[item.name];
4406
+ if (check) {
4407
+ column.data.check = {
4408
+ sql: new pqb.RawSQL([[check]])
4409
+ };
4410
+ }
4411
+ const camelCaseName = orchidCore.toCamelCase(item.name);
4412
+ if (ctx.snakeCase) {
4413
+ const snakeCaseName = orchidCore.toSnakeCase(camelCaseName);
4414
+ if (snakeCaseName !== item.name)
4415
+ column.data.name = item.name;
4416
+ } else if (camelCaseName !== item.name) {
4417
+ column.data.name = item.name;
4418
+ }
4419
+ return [camelCaseName, column];
4420
+ };
4421
+ const dbConstraintToTableConstraint = (ctx, table, item) => {
4422
+ var _a;
4423
+ const { references, check } = item;
4424
+ const constraint = {
4425
+ references: references ? {
4426
+ columns: references.columns,
4427
+ fnOrTable: getReferencesTable(ctx, references),
4428
+ foreignColumns: references.foreignColumns,
4429
+ options: {
4430
+ match: matchMap[references.match],
4431
+ onUpdate: fkeyActionMap[references.onUpdate],
4432
+ onDelete: fkeyActionMap[references.onDelete]
4433
+ }
4434
+ } : void 0,
4435
+ check: check ? pqb.raw({ raw: check.expression }) : void 0
4436
+ };
4437
+ const name = item.name && item.name !== getConstraintName(table.name, constraint) ? item.name : void 0;
4438
+ if (name) {
4439
+ constraint.name = name;
4440
+ if ((_a = constraint.references) == null ? void 0 : _a.options) {
4441
+ constraint.references.options.name = name;
4045
4442
  }
4443
+ }
4444
+ return constraint;
4445
+ };
4446
+ const makeIndexOptions = (tableName, index) => {
4447
+ return {
4448
+ name: index.name !== getIndexName(tableName, index.columns) ? index.name : void 0,
4449
+ using: index.using === "btree" ? void 0 : index.using,
4450
+ unique: index.unique || void 0,
4451
+ include: index.include,
4452
+ nullsNotDistinct: index.nullsNotDistinct || void 0,
4453
+ with: index.with,
4454
+ tablespace: index.tablespace,
4455
+ where: index.where
4456
+ };
4457
+ };
4458
+ const checkIfIsOuterRecursiveFkey = (data, table, references) => {
4459
+ var _a;
4460
+ const referencesId = `${references.foreignSchema}.${references.foreignTable}`;
4461
+ const tableId = `${table.schemaName}.${table.name}`;
4462
+ for (const other of data.tables) {
4463
+ const id = `${other.schemaName}.${other.name}`;
4464
+ if (referencesId === id) {
4465
+ for (const c of data.constraints) {
4466
+ if (c.tableName === other.name && c.schemaName === other.schemaName && ((_a = c.references) == null ? void 0 : _a.foreignTable) === table.name && c.references.foreignSchema === table.schemaName && tableId < id) {
4467
+ return true;
4468
+ }
4469
+ }
4470
+ break;
4471
+ }
4472
+ }
4473
+ return false;
4474
+ };
4475
+
4476
+ const astToGenerateItems = (asts, currentSchema) => {
4477
+ return asts.map((ast) => astToGenerateItem(ast, currentSchema));
4478
+ };
4479
+ const astToGenerateItem = (ast, currentSchema) => {
4480
+ var _a, _b, _c, _d, _e;
4481
+ const add = [];
4482
+ const drop = [];
4483
+ const deps = [];
4484
+ const typeSchemaCache = /* @__PURE__ */ new Map();
4485
+ const resolveType = (type) => {
4486
+ let dep = typeSchemaCache.get(type);
4487
+ if (!dep) {
4488
+ const [schema = currentSchema, name] = getSchemaAndTableFromName(type);
4489
+ dep = `${schema}.${name}`;
4490
+ typeSchemaCache.set(type, dep);
4491
+ }
4492
+ return dep;
4493
+ };
4494
+ switch (ast.type) {
4495
+ case "table":
4496
+ case "changeTable":
4497
+ case "view": {
4498
+ const schema = (_a = ast.schema) != null ? _a : currentSchema;
4499
+ const table = `${schema}.${ast.name}`;
4500
+ if (ast.type === "table" || ast.type === "view") {
4501
+ const keys = ast.action === "create" ? add : drop;
4502
+ keys.push(table);
4503
+ deps.push(schema);
4504
+ const columns = Object.entries(ast.shape).map(
4505
+ ([name, column]) => [keys, name, { column }]
4506
+ );
4507
+ analyzeTableColumns(
4508
+ currentSchema,
4509
+ schema,
4510
+ table,
4511
+ deps,
4512
+ resolveType,
4513
+ columns
4514
+ );
4515
+ if (ast.type === "table") {
4516
+ analyzeTableData(currentSchema, schema, table, keys, deps, ast);
4517
+ } else {
4518
+ deps.push(
4519
+ ...ast.deps.map(({ schemaName, name }) => `${schemaName}.${name}`)
4520
+ );
4521
+ }
4522
+ } else {
4523
+ deps.push(table);
4524
+ const columns = [];
4525
+ for (const name in ast.shape) {
4526
+ const arr = orchidCore.toArray(ast.shape[name]);
4527
+ for (const item of arr) {
4528
+ if (item.type === "add") {
4529
+ columns.push([add, name, { column: item.item }]);
4530
+ } else if (item.type === "drop") {
4531
+ columns.push([drop, name, { column: item.item }]);
4532
+ } else if (item.type === "change") {
4533
+ columns.push([add, name, item.to]);
4534
+ columns.push([drop, name, item.from]);
4535
+ }
4536
+ }
4537
+ }
4538
+ analyzeTableColumns(
4539
+ currentSchema,
4540
+ schema,
4541
+ table,
4542
+ deps,
4543
+ resolveType,
4544
+ columns
4545
+ );
4546
+ analyzeTableData(currentSchema, schema, table, add, deps, ast.add);
4547
+ analyzeTableData(currentSchema, schema, table, drop, deps, ast.drop);
4548
+ }
4549
+ break;
4550
+ }
4551
+ case "renameType": {
4552
+ const { fromSchema = currentSchema, toSchema = currentSchema } = ast;
4553
+ add.push(`${toSchema}.${ast.to}`);
4554
+ drop.push(`${fromSchema}.${ast.from}`);
4555
+ deps.push(fromSchema, toSchema);
4556
+ break;
4557
+ }
4558
+ case "schema": {
4559
+ (ast.action === "create" ? add : drop).push(ast.name);
4560
+ break;
4561
+ }
4562
+ case "renameSchema": {
4563
+ drop.push(ast.from);
4564
+ add.push(ast.to);
4565
+ break;
4566
+ }
4567
+ case "enum":
4568
+ case "collation":
4569
+ case "extension": {
4570
+ const schema = (_b = ast.schema) != null ? _b : currentSchema;
4571
+ (ast.action === "create" ? add : drop).push(`${schema}.${ast.name}`);
4572
+ deps.push(schema);
4573
+ break;
4574
+ }
4575
+ case "enumValues":
4576
+ case "renameEnumValues":
4577
+ case "changeEnumValues": {
4578
+ const schema = (_c = ast.schema) != null ? _c : currentSchema;
4579
+ deps.push(schema, `${schema}.${ast.name}`);
4580
+ break;
4581
+ }
4582
+ case "domain": {
4583
+ const schema = (_d = ast.schema) != null ? _d : currentSchema;
4584
+ (ast.action === "create" ? add : drop).push(`${schema}.${ast.name}`);
4585
+ const column = ast.baseType;
4586
+ deps.push(schema, resolveType(column.dataType));
4587
+ if (column.data.collate)
4588
+ deps.push(column.data.collate);
4589
+ break;
4590
+ }
4591
+ case "constraint": {
4592
+ const { tableSchema = currentSchema, tableName } = ast;
4593
+ const name = `${tableSchema}.${(_e = ast.name) != null ? _e : getConstraintName(tableName, ast)}`;
4594
+ (ast.action === "create" ? add : drop).push(name);
4595
+ deps.push(tableSchema, `${tableSchema}.${tableName}`);
4596
+ break;
4597
+ }
4598
+ case "renameTableItem": {
4599
+ const { tableSchema = currentSchema, tableName } = ast;
4600
+ drop.push(ast.from);
4601
+ add.push(ast.to);
4602
+ deps.push(tableSchema, `${tableSchema}.${tableName}`);
4603
+ break;
4604
+ }
4605
+ default:
4606
+ exhaustive();
4607
+ }
4608
+ return {
4609
+ ast,
4610
+ add: new Set(add),
4611
+ drop: new Set(drop),
4612
+ deps: new Set(deps)
4613
+ };
4614
+ };
4615
+ const analyzeTableColumns = (currentSchema, schema, table, deps, resolveType, columns) => {
4616
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
4617
+ for (const [keys, name, change] of columns) {
4618
+ const { column } = change;
4619
+ if (column) {
4620
+ let c = column;
4621
+ while (c.dataType === "array") {
4622
+ c = column.data.item;
4623
+ }
4624
+ let type;
4625
+ if (c.dataType === "enum") {
4626
+ type = c.enumName;
4627
+ } else {
4628
+ type = c.dataType;
4629
+ }
4630
+ deps.push(resolveType(type));
4631
+ } else if (change.type) {
4632
+ deps.push(resolveType(change.type));
4633
+ }
4634
+ const collate = (_b = (_a = change.column) == null ? void 0 : _a.data.collate) != null ? _b : change.collate;
4635
+ if (collate)
4636
+ deps.push(collate);
4637
+ const primaryKey = change.primaryKey || ((_c = change.column) == null ? void 0 : _c.data.primaryKey);
4638
+ if (primaryKey) {
4639
+ keys.push(`${table}_pkey`);
4640
+ }
4641
+ const indexes = change.indexes || ((_d = change.column) == null ? void 0 : _d.data.indexes);
4046
4642
  if (indexes) {
4047
- const columnIndexes = indexes.filter(
4048
- (it) => it.columns.length === 1 && "column" in it.columns[0] && it.columns[0].column === item.name
4049
- );
4050
- for (const index of columnIndexes) {
4051
- const options = index.columns[0];
4052
- column = column.index({
4053
- collate: options.collate,
4054
- opclass: options.opclass,
4055
- order: options.order,
4056
- name: index.name !== getIndexName(tableName, index.columns) ? index.name : void 0,
4057
- using: index.using === "btree" ? void 0 : index.using,
4058
- unique: index.isUnique,
4059
- include: index.include,
4060
- nullsNotDistinct: index.nullsNotDistinct,
4061
- with: index.with,
4062
- tablespace: index.tablespace,
4063
- where: index.where
4064
- });
4643
+ for (const index of indexes) {
4644
+ keys.push(
4645
+ index.name ? `${schema}.${index.name}` : getIndexName(table, [
4646
+ { column: (_f = (_e = change.column) == null ? void 0 : _e.data.name) != null ? _f : name }
4647
+ ])
4648
+ );
4065
4649
  }
4066
4650
  }
4067
- if (constraints) {
4068
- for (const it of constraints) {
4069
- if (!isColumnFkey(it) || it.references.columns[0] !== item.name)
4070
- continue;
4071
- column = column.foreignKey(
4072
- it.references.fnOrTable,
4073
- it.references.foreignColumns[0],
4074
- it.references.options
4651
+ const foreignKeys = change.foreignKeys || ((_g = change.column) == null ? void 0 : _g.data.foreignKeys);
4652
+ if (foreignKeys) {
4653
+ for (const fkey of foreignKeys) {
4654
+ keys.push(
4655
+ fkey.name ? `${schema}.${fkey.name}` : getConstraintName(table, {
4656
+ references: { columns: [(_i = (_h = change.column) == null ? void 0 : _h.data.name) != null ? _i : name] }
4657
+ })
4075
4658
  );
4659
+ const [s = currentSchema, t] = getForeignKeyTable(
4660
+ "table" in fkey ? fkey.table : fkey.fn
4661
+ );
4662
+ deps.push(`${s}.${t}`);
4076
4663
  }
4077
4664
  }
4078
- const check = checks == null ? void 0 : checks[item.name];
4079
- if (check) {
4080
- column.data.check = pqb.raw({ raw: check });
4665
+ }
4666
+ };
4667
+ const analyzeTableData = (currentSchema, schema, table, keys, deps, data) => {
4668
+ var _a, _b;
4669
+ if (data.primaryKey) {
4670
+ const name = (_a = data.primaryKey.options) == null ? void 0 : _a.name;
4671
+ keys.push(name ? `${schema}.${name}` : `${table}_pkey`);
4672
+ }
4673
+ if (data.indexes) {
4674
+ for (const index of data.indexes) {
4675
+ const name = (_b = index.options) == null ? void 0 : _b.name;
4676
+ keys.push(
4677
+ name ? `${schema}.${name}` : getIndexName(table, index.columns)
4678
+ );
4081
4679
  }
4082
- const camelCaseName = orchidCore.toCamelCase(item.name);
4083
- if (ctx.snakeCase) {
4084
- const snakeCaseName = orchidCore.toSnakeCase(camelCaseName);
4085
- if (snakeCaseName !== item.name)
4086
- column.data.name = item.name;
4087
- } else if (camelCaseName !== item.name) {
4088
- column.data.name = item.name;
4680
+ }
4681
+ if (data.constraints) {
4682
+ for (const constraint of data.constraints) {
4683
+ keys.push(
4684
+ constraint.name ? `${schema}.${constraint.name}` : getConstraintName(table, constraint)
4685
+ );
4686
+ if (constraint.references) {
4687
+ const [s = currentSchema, t] = getForeignKeyTable(
4688
+ constraint.references.fnOrTable
4689
+ );
4690
+ deps.push(`${s}.${t}`);
4691
+ }
4089
4692
  }
4090
- shape[camelCaseName] = column;
4091
4693
  }
4092
- return shape;
4093
4694
  };
4094
4695
 
4095
- const astToMigration = (config, ast) => {
4096
- const first = [];
4097
- const tablesAndViews = [];
4098
- const constraints = [];
4099
- for (const item of ast) {
4100
- if (item.type === "schema" && item.action === "create") {
4101
- first.push(createSchema(item));
4102
- } else if (item.type === "extension" && item.action === "create") {
4103
- if (first.length)
4104
- first.push([]);
4105
- first.push(...createExtension(item));
4106
- } else if (item.type === "enum" && item.action === "create") {
4107
- if (first.length)
4108
- first.push([]);
4109
- first.push(createEnum(item));
4110
- } else if (item.type === "domain" && item.action === "create") {
4111
- if (first.length)
4112
- first.push([]);
4113
- first.push(...createDomain(item));
4114
- } else if (item.type === "collation" && item.action === "create") {
4115
- if (first.length)
4116
- first.push([]);
4117
- first.push(...createCollation(item));
4118
- } else if (item.type === "table" && item.action === "create") {
4119
- tablesAndViews.push(createTable(config, item));
4120
- } else if (item.type === "view" && item.action === "create") {
4121
- tablesAndViews.push(createView(item));
4122
- } else if (item.type === "constraint") {
4123
- if (constraints.length)
4124
- constraints.push([]);
4125
- constraints.push(...createConstraint(item));
4126
- }
4127
- }
4128
- if (!first.length && !tablesAndViews.length && !constraints.length)
4129
- return;
4130
- let code = "";
4131
- if (first.length) {
4132
- code += `
4133
- change(async (db) => {
4134
- ${orchidCore.codeToString(first, " ", " ")}
4135
- });
4136
- `;
4696
+ const astToMigration = (currentSchema, config, asts) => {
4697
+ var _a, _b, _c;
4698
+ const items = astToGenerateItems(asts, currentSchema);
4699
+ const toBeAdded = /* @__PURE__ */ new Set();
4700
+ const toBeDropped = /* @__PURE__ */ new Set();
4701
+ const remainingDeps = /* @__PURE__ */ new Map();
4702
+ const added = /* @__PURE__ */ new Set();
4703
+ const dropped = /* @__PURE__ */ new Set();
4704
+ const groups = [[]];
4705
+ const cycleAdd = /* @__PURE__ */ new Set();
4706
+ const cycleDrop = /* @__PURE__ */ new Set();
4707
+ const cycleDeps = /* @__PURE__ */ new Map();
4708
+ for (const item of items) {
4709
+ for (const add of item.add) {
4710
+ toBeAdded.add(add);
4711
+ }
4712
+ for (const drop of item.drop) {
4713
+ if (!item.add.has(drop)) {
4714
+ toBeDropped.add(drop);
4715
+ }
4716
+ }
4717
+ for (const dep of item.deps) {
4718
+ remainingDeps.set(dep, ((_a = remainingDeps.get(dep)) != null ? _a : 0) + 1);
4719
+ }
4137
4720
  }
4138
- if (tablesAndViews.length) {
4139
- for (const table of tablesAndViews) {
4140
- code += `
4141
- change(async (db) => {
4142
- ${orchidCore.codeToString(table, " ", " ")}
4143
- });
4144
- `;
4721
+ let len = items.length;
4722
+ if (!len)
4723
+ return;
4724
+ for (; ; ) {
4725
+ for (let i = 0; i < items.length; i++) {
4726
+ const item = items[i];
4727
+ let satisfied = true;
4728
+ for (const dep of item.deps) {
4729
+ if (toBeAdded.has(dep) && !added.has(dep)) {
4730
+ satisfied = false;
4731
+ break;
4732
+ }
4733
+ }
4734
+ if (satisfied) {
4735
+ for (const key of item.drop) {
4736
+ if (remainingDeps.has(key)) {
4737
+ satisfied = false;
4738
+ break;
4739
+ }
4740
+ }
4741
+ }
4742
+ if (satisfied) {
4743
+ for (const key of item.add) {
4744
+ if (toBeDropped.has(key) && !dropped.has(key)) {
4745
+ satisfied = false;
4746
+ break;
4747
+ }
4748
+ }
4749
+ }
4750
+ if (satisfied) {
4751
+ for (const key of item.add) {
4752
+ cycleAdd.add(key);
4753
+ }
4754
+ for (const key of item.drop) {
4755
+ cycleDrop.add(key);
4756
+ }
4757
+ for (const key of item.deps) {
4758
+ cycleDeps.set(key, ((_b = cycleDeps.get(key)) != null ? _b : 0) + 1);
4759
+ }
4760
+ items.splice(i, 1);
4761
+ i--;
4762
+ groups[groups.length - 1].push(item.ast);
4763
+ }
4145
4764
  }
4765
+ if (len === items.length) {
4766
+ throw Object.assign(
4767
+ new Error(
4768
+ `Cannot satisfy migration dependencies: ${JSON.stringify(
4769
+ items.map((item) => ({
4770
+ ast: item.ast,
4771
+ add: [...item.add.values()],
4772
+ drop: [...item.drop.values()],
4773
+ deps: [...item.deps.values()]
4774
+ })),
4775
+ null,
4776
+ 2
4777
+ )}`
4778
+ )
4779
+ );
4780
+ }
4781
+ for (const add of cycleAdd) {
4782
+ added.add(add);
4783
+ }
4784
+ for (const drop of cycleDrop) {
4785
+ dropped.add(drop);
4786
+ }
4787
+ for (const [key, num] of cycleDeps) {
4788
+ const set = ((_c = remainingDeps.get(key)) != null ? _c : num) - num;
4789
+ if (set)
4790
+ remainingDeps.set(key, set);
4791
+ else
4792
+ remainingDeps.delete(key);
4793
+ }
4794
+ len = items.length;
4795
+ if (!len)
4796
+ break;
4797
+ groups.push([]);
4146
4798
  }
4147
- if (constraints.length) {
4799
+ if (!groups[0].length)
4800
+ return;
4801
+ let code = "";
4802
+ for (const group of groups) {
4148
4803
  code += `
4149
4804
  change(async (db) => {
4150
- ${orchidCore.codeToString(constraints, " ", " ")}
4805
+ ${group.map(
4806
+ (ast) => orchidCore.codeToString(
4807
+ astEncoders[ast.type](ast, config, currentSchema),
4808
+ " ",
4809
+ " "
4810
+ )
4811
+ ).join("\n\n")}
4151
4812
  });
4152
4813
  `;
4153
4814
  }
4154
- return (importPath) => `import { change } from '${importPath}';
4155
- ${code}`;
4156
- };
4157
- const createSchema = (ast) => {
4158
- return `await db.createSchema(${orchidCore.singleQuote(ast.name)});`;
4815
+ return code;
4159
4816
  };
4160
- const createExtension = (ast) => {
4161
- const code = [`await db.createExtension(${orchidCore.singleQuote(ast.name)}`];
4162
- if (ast.schema || ast.version) {
4163
- orchidCore.addCode(code, ", {");
4164
- if (ast.schema) {
4165
- code.push([`schema: ${orchidCore.singleQuote(ast.schema)},`]);
4817
+ const astEncoders = {
4818
+ table(ast, config) {
4819
+ let code = [];
4820
+ const result = code;
4821
+ const hasOptions = Boolean(ast.comment || ast.noPrimaryKey === "ignore");
4822
+ if (hasOptions) {
4823
+ orchidCore.addCode(code, `await db.${ast.action}Table(`);
4824
+ const inner = [`${quoteSchemaTable(ast)},`];
4825
+ code.push(inner);
4826
+ code = inner;
4827
+ const options = [];
4828
+ if (ast.comment)
4829
+ options.push(`comment: ${JSON.stringify(ast.comment)},`);
4830
+ if (ast.noPrimaryKey === "ignore")
4831
+ options.push(`noPrimaryKey: true,`);
4832
+ code.push("{", options, "},", "(t) => ({");
4833
+ } else {
4834
+ orchidCore.addCode(
4835
+ code,
4836
+ `await db.${ast.action}Table(${quoteSchemaTable(ast)}, (t) => ({`
4837
+ );
4838
+ }
4839
+ const timestamps = getHasTimestamps(
4840
+ config,
4841
+ ast.shape.createdAt,
4842
+ ast.shape.updatedAt
4843
+ );
4844
+ for (const key in ast.shape) {
4845
+ if (timestamps.hasAnyTimestamps && (key === "createdAt" || key === "updatedAt"))
4846
+ continue;
4847
+ const line = [`${orchidCore.quoteObjectKey(key)}: `];
4848
+ for (const part of ast.shape[key].toCode("t", true)) {
4849
+ orchidCore.addCode(line, part);
4850
+ }
4851
+ orchidCore.addCode(line, ",");
4852
+ code.push(line);
4853
+ }
4854
+ if (timestamps.hasAnyTimestamps) {
4855
+ code.push([`...${timestampsToCode(config, timestamps)},`]);
4856
+ }
4857
+ if (ast.primaryKey) {
4858
+ code.push([pqb.primaryKeyToCode(ast.primaryKey, "t")]);
4859
+ }
4860
+ if (ast.indexes) {
4861
+ for (const index of ast.indexes) {
4862
+ code.push(pqb.indexToCode(index, "t"));
4863
+ }
4864
+ }
4865
+ if (ast.constraints) {
4866
+ for (const constraint of ast.constraints) {
4867
+ code.push(pqb.constraintToCode(constraint, "t", true));
4868
+ }
4869
+ }
4870
+ if (hasOptions) {
4871
+ orchidCore.addCode(code, "}),");
4872
+ orchidCore.addCode(result, ");");
4873
+ } else {
4874
+ orchidCore.addCode(result, "}));");
4875
+ }
4876
+ return result;
4877
+ },
4878
+ changeTable(ast, config, currentSchema) {
4879
+ let code = [];
4880
+ const result = code;
4881
+ const schemaTable = quoteSchemaTable({
4882
+ schema: ast.schema === currentSchema ? void 0 : ast.schema,
4883
+ name: ast.name
4884
+ });
4885
+ const { comment } = ast;
4886
+ if (comment !== void 0) {
4887
+ orchidCore.addCode(code, `await db.changeTable(`);
4888
+ const inner = [
4889
+ `${schemaTable},`,
4890
+ `{ comment: ${JSON.stringify(ast.comment)} },`,
4891
+ "(t) => ({"
4892
+ ];
4893
+ code.push(inner);
4894
+ code = inner;
4895
+ } else {
4896
+ orchidCore.addCode(code, `await db.changeTable(${schemaTable}, (t) => ({`);
4897
+ }
4898
+ const [addTimestamps, dropTimestamps] = ["add", "drop"].map(
4899
+ (type) => {
4900
+ var _a, _b;
4901
+ return getHasTimestamps(
4902
+ config,
4903
+ ast.shape.createdAt && "type" in ast.shape.createdAt && ((_a = ast.shape.createdAt) == null ? void 0 : _a.type) === type ? ast.shape.createdAt.item : void 0,
4904
+ ast.shape.updatedAt && "type" in ast.shape.updatedAt && ((_b = ast.shape.updatedAt) == null ? void 0 : _b.type) === type ? ast.shape.updatedAt.item : void 0
4905
+ );
4906
+ }
4907
+ );
4908
+ for (const key in ast.shape) {
4909
+ const changes = orchidCore.toArray(ast.shape[key]);
4910
+ for (const change of changes) {
4911
+ if (change.type === "add" || change.type === "drop") {
4912
+ if ((addTimestamps.hasAnyTimestamps || dropTimestamps.hasAnyTimestamps) && (key === "createdAt" || key === "updatedAt"))
4913
+ continue;
4914
+ const recreate = changes.length > 1;
4915
+ const line = [
4916
+ recreate ? `...t.${change.type}(t.name(${orchidCore.singleQuote(key)})` : `${orchidCore.quoteObjectKey(key)}: t.${change.type}(`
4917
+ ];
4918
+ const columnCode = change.item.toCode("t", true);
4919
+ for (let i = 0; i < columnCode.length; i++) {
4920
+ let part = columnCode[i];
4921
+ if (recreate && !i)
4922
+ part = part.slice(1);
4923
+ orchidCore.addCode(line, part);
4924
+ }
4925
+ orchidCore.addCode(line, "),");
4926
+ code.push(line);
4927
+ } else if (change.type === "change") {
4928
+ if (!change.from.column || !change.to.column)
4929
+ continue;
4930
+ const line = [
4931
+ `${orchidCore.quoteObjectKey(key)}: t${change.name ? `.name(${orchidCore.singleQuote(change.name)})` : ""}.change(`
4932
+ ];
4933
+ for (const part of change.from.column.toCode("t", true)) {
4934
+ orchidCore.addCode(line, part);
4935
+ }
4936
+ orchidCore.addCode(line, ", ");
4937
+ for (const part of change.to.column.toCode("t", true)) {
4938
+ orchidCore.addCode(line, part);
4939
+ }
4940
+ if (change.using) {
4941
+ orchidCore.addCode(line, ", {");
4942
+ const u = [];
4943
+ if (change.using.usingUp) {
4944
+ u.push(`usingUp: ${change.using.usingUp.toCode("t")},`);
4945
+ }
4946
+ if (change.using.usingDown) {
4947
+ u.push(`usingDown: ${change.using.usingDown.toCode("t")},`);
4948
+ }
4949
+ orchidCore.addCode(line, u);
4950
+ orchidCore.addCode(line, "}");
4951
+ }
4952
+ orchidCore.addCode(line, "),");
4953
+ code.push(line);
4954
+ } else if (change.type === "rename") {
4955
+ code.push([
4956
+ `${orchidCore.quoteObjectKey(key)}: t.rename(${orchidCore.singleQuote(change.name)}),`
4957
+ ]);
4958
+ } else {
4959
+ exhaustive(change.type);
4960
+ }
4961
+ }
4962
+ }
4963
+ for (const key of ["drop", "add"]) {
4964
+ const timestamps = key === "add" ? addTimestamps : dropTimestamps;
4965
+ if (timestamps.hasAnyTimestamps) {
4966
+ orchidCore.addCode(code, [
4967
+ `...t.${key}(${timestampsToCode(config, timestamps)}),`
4968
+ ]);
4969
+ }
4970
+ const { primaryKey, indexes, constraints } = ast[key];
4971
+ if (primaryKey) {
4972
+ orchidCore.addCode(code, [
4973
+ `...t.${key}(${pqb.primaryKeyInnerToCode(primaryKey, "t")}),`
4974
+ ]);
4975
+ }
4976
+ if (indexes) {
4977
+ for (const index of indexes) {
4978
+ orchidCore.addCode(code, [`...t.${key}(`, pqb.indexInnerToCode(index, "t"), "),"]);
4979
+ }
4980
+ }
4981
+ if (constraints) {
4982
+ for (const item of constraints) {
4983
+ orchidCore.addCode(code, [
4984
+ `...t.${key}(`,
4985
+ pqb.constraintInnerToCode(item, "t", true),
4986
+ "),"
4987
+ ]);
4988
+ }
4989
+ }
4166
4990
  }
4991
+ if (ast.comment !== void 0) {
4992
+ orchidCore.addCode(code, "}),");
4993
+ orchidCore.addCode(result, ");");
4994
+ } else {
4995
+ orchidCore.addCode(result, "}));");
4996
+ }
4997
+ return result;
4998
+ },
4999
+ renameType(ast, _, currentSchema) {
5000
+ var _a, _b;
5001
+ const code = [];
5002
+ const kind = ast.kind === "TABLE" ? "Table" : "Type";
5003
+ if (ast.from === ast.to) {
5004
+ orchidCore.addCode(
5005
+ code,
5006
+ `await db.change${kind}Schema(${orchidCore.singleQuote(ast.to)}, ${orchidCore.singleQuote(
5007
+ (_a = ast.fromSchema) != null ? _a : currentSchema
5008
+ )}, ${orchidCore.singleQuote((_b = ast.toSchema) != null ? _b : currentSchema)});`
5009
+ );
5010
+ } else {
5011
+ orchidCore.addCode(
5012
+ code,
5013
+ `await db.rename${kind}(${quoteSchemaTable({
5014
+ schema: ast.fromSchema === currentSchema ? void 0 : ast.fromSchema,
5015
+ name: ast.from
5016
+ })}, ${quoteSchemaTable({
5017
+ schema: ast.toSchema === currentSchema ? void 0 : ast.toSchema,
5018
+ name: ast.to
5019
+ })});`
5020
+ );
5021
+ }
5022
+ return code;
5023
+ },
5024
+ schema(ast) {
5025
+ return `await db.${ast.action === "create" ? "createSchema" : "dropSchema"}(${orchidCore.singleQuote(ast.name)});`;
5026
+ },
5027
+ renameSchema(ast) {
5028
+ return `await db.renameSchema(${orchidCore.singleQuote(ast.from)}, ${orchidCore.singleQuote(
5029
+ ast.to
5030
+ )});`;
5031
+ },
5032
+ extension(ast) {
5033
+ const code = [
5034
+ `await db.${ast.action}Extension(${quoteSchemaTable(ast)}`
5035
+ ];
4167
5036
  if (ast.version) {
4168
- code.push([`version: ${orchidCore.singleQuote(ast.version)},`]);
5037
+ orchidCore.addCode(code, ", {");
5038
+ code.push([`version: ${orchidCore.singleQuote(ast.version)},`], "}");
4169
5039
  }
4170
- orchidCore.addCode(code, "}");
4171
- }
4172
- orchidCore.addCode(code, ");");
4173
- return code;
4174
- };
4175
- const createEnum = (ast) => {
4176
- return `await db.createEnum(${quoteSchemaTable(ast)}, [${ast.values.map(orchidCore.singleQuote).join(", ")}]);`;
4177
- };
4178
- const createDomain = (ast) => {
4179
- const code = [
4180
- `await db.createDomain(${quoteSchemaTable(
5040
+ orchidCore.addCode(code, ");");
5041
+ return code;
5042
+ },
5043
+ enum(ast) {
5044
+ return `await db.${ast.action === "create" ? "createEnum" : "dropEnum"}(${quoteSchemaTable(ast)}, [${ast.values.map(orchidCore.singleQuote).join(", ")}]);`;
5045
+ },
5046
+ enumValues(ast) {
5047
+ return `await db.${ast.action}EnumValues(${quoteSchemaTable(
4181
5048
  ast
4182
- )}, (t) => ${ast.baseType.toCode("t")}`
4183
- ];
4184
- if (ast.notNull || ast.collation || ast.default || ast.check) {
4185
- const props = [];
4186
- if (ast.notNull)
4187
- props.push(`notNull: true,`);
4188
- if (ast.collation)
4189
- props.push(`collation: ${orchidCore.singleQuote(ast.collation)},`);
4190
- if (ast.default)
4191
- props.push(`default: ${ast.default.toCode("db")},`);
4192
- if (ast.check)
4193
- props.push(`check: ${ast.check.toCode("db")},`);
4194
- orchidCore.addCode(code, ", {");
4195
- code.push(props);
4196
- orchidCore.addCode(code, "}");
4197
- }
4198
- orchidCore.addCode(code, ");");
4199
- return code;
4200
- };
4201
- const createCollation = (ast) => {
4202
- const params = [];
4203
- if (ast.locale)
4204
- params.push(`locale: '${ast.locale}',`);
4205
- if (ast.lcCollate)
4206
- params.push(`lcCollate: '${ast.lcCollate}',`);
4207
- if (ast.lcCType)
4208
- params.push(`lcCType: '${ast.lcCType}',`);
4209
- if (ast.provider)
4210
- params.push(`provider: '${ast.provider}',`);
4211
- if (ast.deterministic)
4212
- params.push(`deterministic: ${ast.deterministic},`);
4213
- if (ast.version)
4214
- params.push(`version: '${ast.version}',`);
4215
- return [
4216
- `await db.createCollation(${quoteSchemaTable(ast)}, {`,
4217
- params,
4218
- "});"
4219
- ];
4220
- };
4221
- const createTable = (config, ast) => {
4222
- const code = [];
4223
- orchidCore.addCode(code, `await db.createTable(${quoteSchemaTable(ast)}, (t) => ({`);
4224
- const timestamps = getTimestampsInfo(config, ast, pqb.TimestampTZColumn);
4225
- const timestampsNoTZ = getTimestampsInfo(config, ast, pqb.TimestampTZColumn);
4226
- const hasAnyTimestamps = timestamps.hasTimestamps || timestampsNoTZ.hasTimestamps;
4227
- const hasAnyCamelCaseTimestamps = timestamps.camelCaseTimestamps || timestampsNoTZ.camelCaseTimestamps;
4228
- for (const key in ast.shape) {
4229
- if (hasAnyTimestamps && (key === "createdAt" || key === "updatedAt"))
4230
- continue;
4231
- const line = [`${orchidCore.quoteObjectKey(key)}: `];
4232
- for (const part of ast.shape[key].toCode("t", true)) {
4233
- orchidCore.addCode(line, part);
5049
+ )}, [${ast.values.map(orchidCore.singleQuote).join(", ")}]);`;
5050
+ },
5051
+ renameEnumValues(ast) {
5052
+ return `await db.renameEnumValues(${quoteSchemaTable(
5053
+ ast
5054
+ )}, { ${Object.entries(ast.values).map(([from, to]) => `${orchidCore.quoteObjectKey(from)}: ${orchidCore.singleQuote(to)}`).join(", ")} });`;
5055
+ },
5056
+ changeEnumValues(ast) {
5057
+ return `await db.changeEnumValues(${quoteSchemaTable(
5058
+ ast
5059
+ )}, [${ast.fromValues.map(orchidCore.singleQuote).join(", ")}], [${ast.toValues.map(orchidCore.singleQuote).join(", ")}]);`;
5060
+ },
5061
+ domain(ast) {
5062
+ return `await db.${ast.action}Domain(${quoteSchemaTable(
5063
+ ast
5064
+ )}, (t) => ${ast.baseType.toCode("t")});`;
5065
+ },
5066
+ collation(ast) {
5067
+ const params = [];
5068
+ if (ast.locale)
5069
+ params.push(`locale: '${ast.locale}',`);
5070
+ if (ast.lcCollate)
5071
+ params.push(`lcCollate: '${ast.lcCollate}',`);
5072
+ if (ast.lcCType)
5073
+ params.push(`lcCType: '${ast.lcCType}',`);
5074
+ if (ast.provider)
5075
+ params.push(`provider: '${ast.provider}',`);
5076
+ if (ast.deterministic)
5077
+ params.push(`deterministic: ${ast.deterministic},`);
5078
+ if (ast.version)
5079
+ params.push(`version: '${ast.version}',`);
5080
+ return [
5081
+ `await db.createCollation(${quoteSchemaTable(ast)}, {`,
5082
+ params,
5083
+ "});"
5084
+ ];
5085
+ },
5086
+ constraint(ast) {
5087
+ const kind = pqb.getConstraintKind(ast);
5088
+ const table = quoteSchemaTable({
5089
+ schema: ast.tableSchema,
5090
+ name: ast.tableName
5091
+ });
5092
+ if (kind === "foreignKey" && ast.references) {
5093
+ return [
5094
+ `await db.addForeignKey(`,
5095
+ [`${table},`, ...pqb.referencesArgsToCode(ast.references, ast.name, true)],
5096
+ ");"
5097
+ ];
4234
5098
  }
4235
- orchidCore.addCode(line, ",");
4236
- code.push(line);
4237
- }
4238
- if (hasAnyTimestamps) {
4239
- const key = timestamps.hasTimestamps ? "timestamps" : "timestampsNoTZ";
4240
- code.push([
4241
- `...t.${hasAnyCamelCaseTimestamps || config.snakeCase ? key : `${key}SnakeCase`}(),`
4242
- ]);
4243
- }
4244
- if (ast.primaryKey) {
4245
- code.push([pqb.primaryKeyToCode(ast.primaryKey, "t")]);
4246
- }
4247
- if (ast.indexes) {
4248
- for (const index of ast.indexes) {
4249
- code.push(pqb.indexToCode(index, "t"));
5099
+ if (kind === "check" && ast.check) {
5100
+ return [`await db.addCheck(${table}, ${ast.check.toCode("t")});`];
4250
5101
  }
4251
- }
4252
- if (ast.constraints) {
4253
- for (const constraint of ast.constraints) {
4254
- code.push(pqb.constraintToCode(constraint, "t"));
5102
+ return [
5103
+ `await db.addConstraint(${table}, {`,
5104
+ pqb.constraintPropsToCode("t", ast, true),
5105
+ "});"
5106
+ ];
5107
+ },
5108
+ renameTableItem(ast) {
5109
+ return [
5110
+ `await db.rename${ast.kind === "INDEX" ? "Index" : "Constraint"}(${quoteSchemaTable({
5111
+ schema: ast.tableSchema,
5112
+ name: ast.tableName
5113
+ })}, ${orchidCore.singleQuote(ast.from)}, ${orchidCore.singleQuote(ast.to)});`
5114
+ ];
5115
+ },
5116
+ view(ast) {
5117
+ const code = [`await db.createView(${quoteSchemaTable(ast)}`];
5118
+ const options = [];
5119
+ if (ast.options.recursive)
5120
+ options.push("recursive: true,");
5121
+ const w = ast.options.with;
5122
+ if (w == null ? void 0 : w.checkOption)
5123
+ options.push(`checkOption: '${w.checkOption}',`);
5124
+ if (w == null ? void 0 : w.securityBarrier)
5125
+ options.push(`securityBarrier: ${w.securityBarrier},`);
5126
+ if (w == null ? void 0 : w.securityInvoker)
5127
+ options.push(`securityInvoker: ${w.securityInvoker},`);
5128
+ if (options.length) {
5129
+ orchidCore.addCode(code, ", {");
5130
+ code.push(options, "}");
5131
+ }
5132
+ orchidCore.addCode(code, ", ");
5133
+ if (!ast.sql._values) {
5134
+ const raw = ast.sql._sql;
5135
+ let sql;
5136
+ if (typeof raw === "string") {
5137
+ sql = raw;
5138
+ } else {
5139
+ sql = "";
5140
+ const parts = raw[0];
5141
+ const last = parts.length - 1;
5142
+ for (let i = 0; i < last; i++) {
5143
+ sql += parts[i] + `\${${raw[i + 1]}}`;
5144
+ }
5145
+ sql += parts[last];
5146
+ }
5147
+ orchidCore.addCode(code, orchidCore.backtickQuote(sql));
5148
+ } else {
5149
+ orchidCore.addCode(code, ast.sql.toCode("db"));
4255
5150
  }
5151
+ orchidCore.addCode(code, ");");
5152
+ return code;
4256
5153
  }
4257
- orchidCore.addCode(code, "}));");
4258
- return code;
4259
5154
  };
4260
5155
  const isTimestamp = (column, type) => {
4261
5156
  if (!column)
4262
5157
  return false;
4263
5158
  const { default: def } = column.data;
4264
- return column instanceof type && !column.data.isNullable && def && typeof def === "object" && orchidCore.isRawSQL(def) && def._sql === "now()";
5159
+ return Boolean(
5160
+ column instanceof type && !column.data.isNullable && def && typeof def === "object" && orchidCore.isRawSQL(def) && (typeof def._sql === "object" ? def._sql[0][0] : def._sql) === "now()"
5161
+ );
4265
5162
  };
4266
- const getTimestampsInfo = (config, ast, type) => {
4267
- var _a, _b, _c, _d, _e, _f;
4268
- let hasTimestamps = isTimestamp(ast.shape.createdAt, type) && isTimestamp(ast.shape.updatedAt, type);
4269
- const camelCaseTimestamps = !config.snakeCase && hasTimestamps && !((_a = ast.shape.createdAt) == null ? void 0 : _a.data.name) && !((_b = ast.shape.updatedAt) == null ? void 0 : _b.data.name);
4270
- const snakeCaseTimestamps = hasTimestamps && !camelCaseTimestamps && (!config.snakeCase && ((_c = ast.shape.createdAt) == null ? void 0 : _c.data.name) === "created_at" && ((_d = ast.shape.updatedAt) == null ? void 0 : _d.data.name) === "updated_at" || config.snakeCase && !((_e = ast.shape.createdAt) == null ? void 0 : _e.data.name) && !((_f = ast.shape.updatedAt) == null ? void 0 : _f.data.name));
5163
+ const getHasTimestamps = (config, createdAt, updatedAt) => {
5164
+ const timestamps = getTimestampsInfo(
5165
+ config,
5166
+ createdAt,
5167
+ updatedAt,
5168
+ pqb.TimestampTZColumn
5169
+ );
5170
+ const timestampsNoTZ = getTimestampsInfo(
5171
+ config,
5172
+ createdAt,
5173
+ updatedAt,
5174
+ pqb.TimestampColumn
5175
+ );
5176
+ return {
5177
+ hasTZTimestamps: timestamps.hasTimestamps,
5178
+ hasAnyTimestamps: timestamps.hasTimestamps || timestampsNoTZ.hasTimestamps,
5179
+ hasAnyCamelCaseTimestamps: timestamps.camelCaseTimestamps || timestampsNoTZ.camelCaseTimestamps
5180
+ };
5181
+ };
5182
+ const getTimestampsInfo = (config, createdAt, updatedAt, type) => {
5183
+ let hasTimestamps = isTimestamp(createdAt, type) && isTimestamp(updatedAt, type);
5184
+ const camelCaseTimestamps = !config.snakeCase && hasTimestamps && !(createdAt == null ? void 0 : createdAt.data.name) && !(updatedAt == null ? void 0 : updatedAt.data.name);
5185
+ const snakeCaseTimestamps = hasTimestamps && !camelCaseTimestamps && (!config.snakeCase && (createdAt == null ? void 0 : createdAt.data.name) === "created_at" && (updatedAt == null ? void 0 : updatedAt.data.name) === "updated_at" || config.snakeCase && !(createdAt == null ? void 0 : createdAt.data.name) && !(updatedAt == null ? void 0 : updatedAt.data.name));
4271
5186
  if (!camelCaseTimestamps && !snakeCaseTimestamps) {
4272
5187
  hasTimestamps = false;
4273
5188
  }
@@ -4277,81 +5192,19 @@ const getTimestampsInfo = (config, ast, type) => {
4277
5192
  snakeCaseTimestamps
4278
5193
  };
4279
5194
  };
4280
- const createConstraint = (item) => {
4281
- const kind = pqb.getConstraintKind(item);
4282
- const table = quoteSchemaTable({
4283
- schema: item.tableSchema,
4284
- name: item.tableName
4285
- });
4286
- if (kind === "foreignKey" && item.references) {
4287
- return [
4288
- `await db.addForeignKey(`,
4289
- [`${table},`, ...pqb.referencesArgsToCode(item.references, item.name)],
4290
- ");"
4291
- ];
4292
- }
4293
- if (kind === "check" && item.check) {
4294
- return [`await db.addCheck(${table}, ${item.check.toCode("t")});`];
4295
- }
4296
- return [
4297
- `await db.addConstraint(${table}, {`,
4298
- pqb.constraintPropsToCode("t", item),
4299
- "});"
4300
- ];
4301
- };
4302
- const createView = (ast) => {
4303
- const code = [`await db.createView(${quoteSchemaTable(ast)}`];
4304
- const options = [];
4305
- if (ast.options.recursive)
4306
- options.push("recursive: true,");
4307
- const w = ast.options.with;
4308
- if (w == null ? void 0 : w.checkOption)
4309
- options.push(`checkOption: '${w.checkOption}',`);
4310
- if (w == null ? void 0 : w.securityBarrier)
4311
- options.push(`securityBarrier: ${w.securityBarrier},`);
4312
- if (w == null ? void 0 : w.securityInvoker)
4313
- options.push(`securityInvoker: ${w.securityInvoker},`);
4314
- if (options.length) {
4315
- orchidCore.addCode(code, ", {");
4316
- code.push(options, "}");
4317
- }
4318
- orchidCore.addCode(code, ", ");
4319
- if (!ast.sql._values) {
4320
- const raw = ast.sql._sql;
4321
- let sql;
4322
- if (typeof raw === "string") {
4323
- sql = raw;
4324
- } else {
4325
- sql = "";
4326
- const parts = raw[0];
4327
- const last = parts.length - 1;
4328
- for (let i = 0; i < last; i++) {
4329
- sql += parts[i] + `\${${raw[i + 1]}}`;
4330
- }
4331
- sql += parts[last];
4332
- }
4333
- orchidCore.addCode(code, orchidCore.backtickQuote(sql));
4334
- } else {
4335
- orchidCore.addCode(code, ast.sql.toCode("db"));
4336
- }
4337
- orchidCore.addCode(code, ");");
4338
- return code;
5195
+ const timestampsToCode = (config, { hasTZTimestamps, hasAnyCamelCaseTimestamps }) => {
5196
+ const key = hasTZTimestamps ? "timestamps" : "timestampsNoTZ";
5197
+ return `t.${hasAnyCamelCaseTimestamps || config.snakeCase ? key : `${key}SnakeCase`}()`;
4339
5198
  };
4340
5199
 
4341
5200
  const pullDbStructure = async (options, config) => {
4342
- var _a, _b, _c, _d;
5201
+ var _a, _b;
4343
5202
  const adapter = new pqb.Adapter(options);
4344
5203
  const currentSchema = adapter.schema || "public";
4345
- const ctx = {
4346
- snakeCase: config.snakeCase,
4347
- unsupportedTypes: {},
4348
- currentSchema,
4349
- columnSchemaConfig: config.schemaConfig,
4350
- columnsByType: pqb.makeColumnsByType(config.schemaConfig)
4351
- };
5204
+ const ctx = makeStructureToAstCtx(config, currentSchema);
4352
5205
  const ast = await structureToAst(ctx, adapter);
4353
5206
  await adapter.close();
4354
- const result = astToMigration(config, ast);
5207
+ const result = astToMigration(currentSchema, config, ast);
4355
5208
  if (!result)
4356
5209
  return;
4357
5210
  const version = await makeFileVersion({}, config);
@@ -4361,33 +5214,11 @@ const pullDbStructure = async (options, config) => {
4361
5214
  silentArrays: adapter.arrays
4362
5215
  });
4363
5216
  await saveMigratedVersion(silentQueries, version, "pull", config);
4364
- const cache = {};
4365
- for (const item of ast) {
4366
- await ((_a = config == null ? void 0 : config.appCodeUpdater) == null ? void 0 : _a.process({
4367
- ast: item,
4368
- options,
4369
- basePath: config.basePath,
4370
- cache,
4371
- logger: config.logger,
4372
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
4373
- baseTable: config.baseTable,
4374
- import: config.import
4375
- }));
4376
- }
4377
- await ((_b = config == null ? void 0 : config.appCodeUpdater) == null ? void 0 : _b.afterAll({
4378
- options,
4379
- basePath: config.basePath,
4380
- cache,
4381
- logger: config.logger,
4382
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
4383
- baseTable: config.baseTable,
4384
- import: config.import
4385
- }));
4386
5217
  const unsupportedEntries = Object.entries(ctx.unsupportedTypes);
4387
5218
  const len = unsupportedEntries.length;
4388
5219
  if (len) {
4389
5220
  let count = 0;
4390
- (_c = config.logger) == null ? void 0 : _c.warn(
5221
+ (_a = config.logger) == null ? void 0 : _a.warn(
4391
5222
  `Found unsupported types:
4392
5223
  ${unsupportedEntries.map(([type, columns]) => {
4393
5224
  count += columns.length;
@@ -4396,7 +5227,7 @@ ${unsupportedEntries.map(([type, columns]) => {
4396
5227
  Append \`as\` method manually to ${count > 1 ? "these" : "this"} column${count > 1 ? "s" : ""} to treat ${count > 1 ? "them" : "it"} as other column type`
4397
5228
  );
4398
5229
  }
4399
- (_d = config.logger) == null ? void 0 : _d.log("Database pulled successfully");
5230
+ (_b = config.logger) == null ? void 0 : _b.log("Database pulled successfully");
4400
5231
  adapter.close();
4401
5232
  };
4402
5233
 
@@ -4445,7 +5276,7 @@ const readdirRecursive = async (dirPath, cb) => {
4445
5276
  };
4446
5277
 
4447
5278
  const listMigrationsStatuses = async (options, config, args) => {
4448
- var _a, _b;
5279
+ var _a;
4449
5280
  const adapters = options.map((opts) => new pqb.Adapter(opts));
4450
5281
  const ctx = {};
4451
5282
  const [{ migrations }, ...migrated] = await Promise.all([
@@ -4486,23 +5317,25 @@ const listMigrationsStatuses = async (options, config, args) => {
4486
5317
  };
4487
5318
  }
4488
5319
  const showUrl = args.includes("p") || args.includes("path");
4489
- const colors = typeof config.log === "object" ? (_a = config.log.colors) != null ? _a : true : true;
4490
- const yellow = colors ? (s) => `\x1B[33m${s}\x1B[0m` : (s) => s;
4491
- const green = colors ? (s) => `\x1B[32m${s}\x1B[0m` : (s) => s;
4492
- const red = colors ? (s) => `\x1B[31m${s}\x1B[0m` : (s) => s;
4493
- const blue = colors ? (s) => `\x1B[34m${s}\x1B[0m` : (s) => s;
5320
+ const asIs = (s) => s;
5321
+ const c = typeof config.log === "object" && config.log.colors === false ? {
5322
+ yellow: asIs,
5323
+ green: asIs,
5324
+ red: asIs,
5325
+ blue: asIs
5326
+ } : colors;
4494
5327
  const log = Object.values(map).map(({ databases, migrations: migrations2 }) => {
4495
- let log2 = ` ${yellow("Database:")} ${databases.join(", ")}`;
5328
+ let log2 = ` ${c.yellow("Database:")} ${databases.join(", ")}`;
4496
5329
  if (migrations2.length === 0) {
4497
5330
  return log2 + `
4498
5331
 
4499
5332
  No migrations available`;
4500
5333
  }
4501
- const lineSeparator = yellow(
5334
+ const lineSeparator = c.yellow(
4502
5335
  makeChars(14 + maxVersionLength + maxNameLength, "-")
4503
5336
  );
4504
- const columnSeparator = yellow("|");
4505
- log2 += "\n\n " + yellow(
5337
+ const columnSeparator = c.yellow("|");
5338
+ log2 += "\n\n " + c.yellow(
4506
5339
  `Status | Migration ID${makeChars(
4507
5340
  maxVersionLength - 12,
4508
5341
  " "
@@ -4511,7 +5344,7 @@ ${lineSeparator}`
4511
5344
  );
4512
5345
  for (const migration of migrations2) {
4513
5346
  log2 += `
4514
- ${migration.up ? ` ${green("Up")} ` : red("Down")} ${columnSeparator} ${blue(migration.version)}${makeChars(
5347
+ ${migration.up ? ` ${c.green("Up")} ` : c.red("Down")} ${columnSeparator} ${c.blue(migration.version)}${makeChars(
4515
5348
  maxVersionLength - migration.version.length,
4516
5349
  " "
4517
5350
  )} ${columnSeparator} ${migration.name}`;
@@ -4524,7 +5357,7 @@ ${migration.url}
4524
5357
  return log2 += showUrl ? lineSeparator : `
4525
5358
  ${lineSeparator}`;
4526
5359
  }).join("\n\n");
4527
- ((_b = config.logger) != null ? _b : console).log(log);
5360
+ ((_a = config.logger) != null ? _a : console).log(log);
4528
5361
  await Promise.all(adapters.map((adapter) => adapter.close()));
4529
5362
  };
4530
5363
  const makeChars = (count, char) => {
@@ -4612,24 +5445,12 @@ const rebase = async (options, config) => {
4612
5445
  migratedFiles.push(moveFile);
4613
5446
  } else if (!moveFile) {
4614
5447
  move++;
4615
- const result = await prompts([
4616
- {
4617
- type: "select",
4618
- name: "file",
4619
- message: "Which should go first?",
4620
- choices: [
4621
- {
4622
- title: prev.name,
4623
- value: "prev"
4624
- },
4625
- {
4626
- title: file.name,
4627
- value: "current"
4628
- }
4629
- ]
4630
- }
4631
- ]);
4632
- moveFile = result.file === "prev" ? prev : file;
5448
+ const result = await promptSelect({
5449
+ message: "Which should go first?",
5450
+ options: [prev.name, file.name],
5451
+ active: (s) => `${colors.yellow("\u276F")} ${colors.yellow(s)}`
5452
+ });
5453
+ moveFile = result ? file : prev;
4633
5454
  }
4634
5455
  }
4635
5456
  let newVersion = file.serial;
@@ -4702,7 +5523,7 @@ const rebase = async (options, config) => {
4702
5523
  return files2;
4703
5524
  }, []).sort((a, b) => +b.version - +a.version);
4704
5525
  set.migrations = migrationsDown;
4705
- await rakeDb$1.redo(
5526
+ await redo(
4706
5527
  ctx,
4707
5528
  options,
4708
5529
  __spreadProps(__spreadValues$1({}, config), {
@@ -4782,42 +5603,72 @@ const rakeDbAliases = {
4782
5603
  rec: "recurrent"
4783
5604
  };
4784
5605
  const runCommand = async (opts, config, args = process.argv.slice(2)) => {
4785
- var _a, _b;
5606
+ var _a, _b, _c;
4786
5607
  let arg = (_a = args[0]) == null ? void 0 : _a.split(":")[0];
4787
5608
  if (rakeDbAliases[arg]) {
4788
5609
  args = [...args];
4789
5610
  arg = args[0] = rakeDbAliases[arg];
4790
5611
  }
4791
5612
  const options = orchidCore.toArray(opts);
4792
- if (arg === "create") {
4793
- await createDb(options, config);
4794
- } else if (arg === "drop") {
4795
- await dropDb(options, config);
4796
- } else if (arg === "reset") {
4797
- await resetDb(options, config);
4798
- } else if (arg === "up") {
4799
- await migrate({}, options, config, args.slice(1));
4800
- } else if (arg === "down") {
4801
- await rollback({}, options, config, args.slice(1));
4802
- } else if (arg === "redo") {
4803
- await redo({}, options, config, args.slice(1));
4804
- } else if (arg === "new") {
4805
- await generate(config, args.slice(1));
4806
- } else if (arg === "pull") {
4807
- await pullDbStructure(options[0], config);
4808
- } else if (arg === "status") {
4809
- await listMigrationsStatuses(options, config, args.slice(1));
4810
- } else if (arg === "rebase") {
4811
- await rebase(options, config);
4812
- } else if (arg === "change-ids") {
4813
- await changeIds(options, config, args.slice(1));
4814
- } else if (config.commands[arg]) {
4815
- await config.commands[arg](options, config, args.slice(1));
4816
- } else if (arg !== "recurrent") {
4817
- (_b = config.logger) == null ? void 0 : _b.log(help);
4818
- }
4819
- if (arg === "up" || arg === "recurrent" || arg === "redo") {
4820
- await runRecurrentMigrations(options, config);
5613
+ args.shift();
5614
+ const command = (_c = (_b = rakeDbCommands[arg]) == null ? void 0 : _b.run) != null ? _c : config.commands[arg];
5615
+ if (command) {
5616
+ await command(options, config, args);
5617
+ } else if (config.logger) {
5618
+ const commandsHelp = [];
5619
+ let max = 0;
5620
+ let maxArgs = 0;
5621
+ const addedCommands = /* @__PURE__ */ new Map();
5622
+ for (let key in rakeDbCommands) {
5623
+ const command2 = rakeDbCommands[key];
5624
+ const added = addedCommands.get(command2);
5625
+ if (added)
5626
+ key = added[0] += `, ${key}`;
5627
+ if (key.length > max)
5628
+ max = key.length;
5629
+ if (added)
5630
+ continue;
5631
+ if (command2.helpArguments) {
5632
+ maxArgs = Math.max(
5633
+ maxArgs,
5634
+ ...Object.keys(command2.helpArguments).map((key2) => key2.length + 5)
5635
+ );
5636
+ }
5637
+ const helpBlock = [key, command2.help, command2.helpArguments];
5638
+ addedCommands.set(command2, helpBlock);
5639
+ if (command2.helpAfter) {
5640
+ const i = commandsHelp.findIndex(([key2]) => key2 === command2.helpAfter);
5641
+ if (i === -1) {
5642
+ throw new Error(
5643
+ `${command2.helpAfter} command is required for ${key} but is not found`
5644
+ );
5645
+ }
5646
+ commandsHelp.splice(i + 1, 0, helpBlock);
5647
+ } else {
5648
+ commandsHelp.push(helpBlock);
5649
+ }
5650
+ }
5651
+ config.logger.log(`Usage: rake-db [command] [arguments]
5652
+
5653
+ See documentation at:
5654
+ https://orchid-orm.netlify.app/guide/migration-commands.html
5655
+
5656
+ Commands:
5657
+
5658
+ ${commandsHelp.map(([key, help, helpArguments]) => {
5659
+ let result = `${key} ${help.padStart(max - key.length + help.length)}`;
5660
+ if (helpArguments) {
5661
+ result += `
5662
+ arguments:
5663
+ ${Object.entries(helpArguments).map(
5664
+ ([arg2, help2]) => ` ${arg2} ${` ${help2}`.padStart(
5665
+ maxArgs - arg2.length - 5 + help2.length + 2
5666
+ )}`
5667
+ ).join("\n")}`;
5668
+ }
5669
+ return result;
5670
+ }).join("\n\n")}
5671
+ `);
4821
5672
  }
4822
5673
  return {
4823
5674
  options,
@@ -4825,70 +5676,164 @@ const runCommand = async (opts, config, args = process.argv.slice(2)) => {
4825
5676
  args
4826
5677
  };
4827
5678
  };
4828
- const help = `Usage: rake-db [command] [arguments]
4829
-
4830
- See documentation at:
4831
- https://orchid-orm.netlify.app/guide/migration-commands.html
4832
-
4833
- Commands:
4834
- create create databases
4835
- drop drop databases
4836
- reset drop, create and migrate databases
4837
- pull generate a combined migration for an existing database
4838
- new create new migration file, see below
4839
- up migrate pending migrations
4840
- migrate migrate pending migrations, also run recurrent
4841
- up|migrate force resolve the case of a non-migrated file in the middle
4842
- rollback or down rollback the last migrated
4843
- redo rollback and migrate, run recurrent
4844
- status or s list migrations statuses
4845
- status path or s p list migrations statuses and paths to files
4846
- rec or recurrent run recurrent migrations
4847
- rebase move local migrations below the new ones from upstream
4848
- change-ids serial change migrations ids to 4 digit serial
4849
- change-ids serial 42 change migrations ids to custom digits serial
4850
- change-ids timestamp change migrations ids to timestamps
4851
- no or unknown command prints this message
4852
-
4853
- Migrate arguments:
4854
- no arguments run all pending migrations
4855
- number run specific number of pending migrations
4856
-
4857
- Rollback arguments:
4858
- no arguments rollback one last applied migration
4859
- number rollback specific number of applied migrations
4860
- all rollback all applied migrations
4861
-
4862
- Migrate and rollback common arguments:
4863
- --code run code updater, overrides \`useCodeUpdater\` option
4864
- --code false do not run code updater
4865
- `;
5679
+ const upCommand = {
5680
+ run: (options, config, args) => migrate({}, options, config, args).then(
5681
+ () => runRecurrentMigrations(options, config)
5682
+ ),
5683
+ help: "migrate pending migrations",
5684
+ helpArguments: {
5685
+ "no arguments": "migrate all pending",
5686
+ "a number": "run a specific number of pending migrations",
5687
+ force: "enforce migrating a pending file in the middle"
5688
+ }
5689
+ };
5690
+ const downCommand = {
5691
+ run: (options, config, args) => rollback({}, options, config, args),
5692
+ help: "rollback migrated migrations",
5693
+ helpArguments: {
5694
+ "no arguments": "rollback one last migration",
5695
+ "a number": "rollback a specified number",
5696
+ all: "rollback all migrations"
5697
+ }
5698
+ };
5699
+ const statusCommand = {
5700
+ run: listMigrationsStatuses,
5701
+ help: "list migrations statuses",
5702
+ helpArguments: {
5703
+ "no arguments": `does not print file paths`,
5704
+ "p, path": "also print file paths"
5705
+ }
5706
+ };
5707
+ const recurrentCommand = {
5708
+ run: runRecurrentMigrations,
5709
+ help: "run recurrent migrations"
5710
+ };
5711
+ const rakeDbCommands = {
5712
+ create: {
5713
+ run: createDb,
5714
+ help: "create databases"
5715
+ },
5716
+ drop: {
5717
+ run: dropDb,
5718
+ help: "drop databases"
5719
+ },
5720
+ reset: {
5721
+ run: resetDb,
5722
+ help: "drop, create and migrate databases"
5723
+ },
5724
+ up: upCommand,
5725
+ migrate: upCommand,
5726
+ down: downCommand,
5727
+ rollback: downCommand,
5728
+ redo: {
5729
+ run: (options, config, args) => redo({}, options, config, args).then(
5730
+ () => runRecurrentMigrations(options, config)
5731
+ ),
5732
+ help: "rollback and migrate, run recurrent"
5733
+ },
5734
+ pull: {
5735
+ run: ([options], config) => pullDbStructure(options, config),
5736
+ help: "generate a combined migration for an existing database"
5737
+ },
5738
+ new: {
5739
+ run: (_, config, args) => newMigration(config, args),
5740
+ help: "create new migration file"
5741
+ },
5742
+ s: statusCommand,
5743
+ status: statusCommand,
5744
+ rec: recurrentCommand,
5745
+ recurrent: recurrentCommand,
5746
+ rebase: {
5747
+ run: rebase,
5748
+ help: "move local migrations below the new ones from upstream"
5749
+ },
5750
+ "change-ids": {
5751
+ run: changeIds,
5752
+ help: "change migrations ids format",
5753
+ helpArguments: {
5754
+ serial: "change ids to 4 digit serial",
5755
+ "serial *number*": "change ids to serial number of custom length",
5756
+ "change-ids timestamp": "change ids to timestamps"
5757
+ }
5758
+ }
5759
+ };
4866
5760
 
4867
5761
  exports.Migration = Migration;
4868
5762
  exports.NoMigrationsTableError = NoMigrationsTableError;
4869
5763
  exports.RAKE_DB_LOCK_KEY = RAKE_DB_LOCK_KEY;
5764
+ exports.addColumnComment = addColumnComment;
5765
+ exports.addColumnIndex = addColumnIndex;
4870
5766
  exports.addOrDropEnumValues = addOrDropEnumValues;
5767
+ exports.astToMigration = astToMigration;
4871
5768
  exports.changeCache = changeCache;
4872
5769
  exports.changeEnumValues = changeEnumValues;
5770
+ exports.clearChanges = clearChanges;
5771
+ exports.colors = colors;
5772
+ exports.columnToSql = columnToSql;
5773
+ exports.columnTypeToSql = columnTypeToSql;
5774
+ exports.commentsToQuery = commentsToQuery;
5775
+ exports.concatSchemaAndName = concatSchemaAndName;
5776
+ exports.constraintToSql = constraintToSql;
4873
5777
  exports.createDb = createDb;
4874
5778
  exports.createMigrationInterface = createMigrationInterface;
5779
+ exports.dbColumnToAst = dbColumnToAst;
4875
5780
  exports.deleteMigratedVersion = deleteMigratedVersion;
4876
5781
  exports.dropDb = dropDb;
4877
- exports.generate = generate;
5782
+ exports.encodeColumnDefault = encodeColumnDefault;
5783
+ exports.exhaustive = exhaustive;
4878
5784
  exports.generateTimeStamp = generateTimeStamp;
5785
+ exports.getColumnName = getColumnName;
5786
+ exports.getConstraintName = getConstraintName;
5787
+ exports.getCurrentChanges = getCurrentChanges;
4879
5788
  exports.getDatabaseAndUserFromOptions = getDatabaseAndUserFromOptions;
5789
+ exports.getDbStructureTableData = getDbStructureTableData;
5790
+ exports.getDbTableColumnsChecks = getDbTableColumnsChecks;
5791
+ exports.getFirstWordAndRest = getFirstWordAndRest;
5792
+ exports.getForeignKeyTable = getForeignKeyTable;
5793
+ exports.getIndexName = getIndexName;
4880
5794
  exports.getMigratedVersionsMap = getMigratedVersionsMap;
5795
+ exports.getSchemaAndTableFromName = getSchemaAndTableFromName;
5796
+ exports.getTextAfterFrom = getTextAfterFrom;
5797
+ exports.getTextAfterTo = getTextAfterTo;
5798
+ exports.identityToSql = identityToSql;
5799
+ exports.indexesToQuery = indexesToQuery;
5800
+ exports.instantiateDbColumn = instantiateDbColumn;
5801
+ exports.introspectDbSchema = introspectDbSchema;
5802
+ exports.joinColumns = joinColumns;
5803
+ exports.joinWords = joinWords;
5804
+ exports.makeDbStructureColumnsShape = makeDbStructureColumnsShape;
5805
+ exports.makeDomainsMap = makeDomainsMap;
4881
5806
  exports.makeFileVersion = makeFileVersion;
5807
+ exports.makePopulateEnumQuery = makePopulateEnumQuery;
5808
+ exports.makeStructureToAstCtx = makeStructureToAstCtx;
4882
5809
  exports.migrate = migrate;
4883
5810
  exports.migrateOrRollback = migrateOrRollback;
4884
5811
  exports.migrationConfigDefaults = migrationConfigDefaults;
5812
+ exports.newMigration = newMigration;
5813
+ exports.pluralize = pluralize;
5814
+ exports.primaryKeyToSql = primaryKeyToSql;
4885
5815
  exports.processRakeDbConfig = processRakeDbConfig;
5816
+ exports.promptConfirm = promptConfirm;
5817
+ exports.promptSelect = promptSelect;
5818
+ exports.promptText = promptText;
5819
+ exports.pushChange = pushChange;
5820
+ exports.queryLock = queryLock;
5821
+ exports.quoteNameFromString = quoteNameFromString;
5822
+ exports.quoteSchemaTable = quoteSchemaTable;
5823
+ exports.quoteTable = quoteTable;
5824
+ exports.quoteWithSchema = quoteWithSchema;
4886
5825
  exports.rakeDb = rakeDb;
4887
5826
  exports.rakeDbAliases = rakeDbAliases;
5827
+ exports.rakeDbCommands = rakeDbCommands;
4888
5828
  exports.redo = redo;
5829
+ exports.referencesToSql = referencesToSql;
4889
5830
  exports.renameType = renameType;
4890
5831
  exports.resetDb = resetDb;
4891
5832
  exports.rollback = rollback;
4892
5833
  exports.saveMigratedVersion = saveMigratedVersion;
5834
+ exports.structureToAst = structureToAst;
5835
+ exports.tableToAst = tableToAst;
5836
+ exports.transaction = transaction;
5837
+ exports.versionToString = versionToString;
4893
5838
  exports.writeMigrationFile = writeMigrationFile;
4894
5839
  //# sourceMappingURL=index.js.map