rake-db 2.23.11 → 2.23.13

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
@@ -18,10 +18,8 @@ const getFirstWordAndRest = (input) => {
18
18
  };
19
19
  const getTextAfterRegExp = (input, regex, length) => {
20
20
  let index = input.search(regex);
21
- if (index === -1)
22
- return;
23
- if (input[index] === "-" || input[index] === "_")
24
- index++;
21
+ if (index === -1) return;
22
+ if (input[index] === "-" || input[index] === "_") index++;
25
23
  index += length;
26
24
  const start = input[index] == "-" || input[index] === "_" ? index + 1 : index;
27
25
  const text = input.slice(start);
@@ -97,25 +95,6 @@ const clearChanges = () => {
97
95
  const getCurrentChanges = () => currentChanges;
98
96
  const pushChange = (fn) => currentChanges.push(fn);
99
97
 
100
- var __defProp$9 = Object.defineProperty;
101
- var __defProps$7 = Object.defineProperties;
102
- var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
103
- var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
104
- var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
105
- var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
106
- var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
107
- var __spreadValues$9 = (a, b) => {
108
- for (var prop in b || (b = {}))
109
- if (__hasOwnProp$9.call(b, prop))
110
- __defNormalProp$9(a, prop, b[prop]);
111
- if (__getOwnPropSymbols$9)
112
- for (var prop of __getOwnPropSymbols$9(b)) {
113
- if (__propIsEnum$9.call(b, prop))
114
- __defNormalProp$9(a, prop, b[prop]);
115
- }
116
- return a;
117
- };
118
- var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
119
98
  const versionToString = (config, version) => config.migrationId === "timestamp" ? `${version}` : `${version}`.padStart(config.migrationId.serial, "0");
120
99
  const columnTypeToSql = (item) => {
121
100
  return item.data.isOfCustomType ? item instanceof pqb.DomainColumn ? quoteNameFromString(item.dataType) : quoteCustomType(item.toSQL()) : item.toSQL();
@@ -124,7 +103,6 @@ const getColumnName = (item, key, snakeCase) => {
124
103
  return item.data.name || (snakeCase ? orchidCore.toSnakeCase(key) : key);
125
104
  };
126
105
  const columnToSql = (name, item, values, hasMultiplePrimaryKeys, snakeCase) => {
127
- var _a, _b;
128
106
  const line = [`"${name}" ${columnTypeToSql(item)}`];
129
107
  if (item.data.compression) {
130
108
  line.push(`COMPRESSION ${item.data.compression}`);
@@ -154,19 +132,19 @@ const columnToSql = (name, item, values, hasMultiplePrimaryKeys, snakeCase) => {
154
132
  line.push(checkToSql(item.data.check.sql, values));
155
133
  }
156
134
  const def = encodeColumnDefault(item.data.default, values, item);
157
- if (def !== null)
158
- line.push(`DEFAULT ${def}`);
135
+ if (def !== null) line.push(`DEFAULT ${def}`);
159
136
  const { foreignKeys } = item.data;
160
137
  if (foreignKeys) {
161
138
  for (const foreignKey of foreignKeys) {
162
- if ((_a = foreignKey.options) == null ? void 0 : _a.name) {
163
- line.push(`CONSTRAINT "${(_b = foreignKey.options) == null ? void 0 : _b.name}"`);
139
+ if (foreignKey.options?.name) {
140
+ line.push(`CONSTRAINT "${foreignKey.options?.name}"`);
164
141
  }
165
142
  line.push(
166
143
  referencesToSql(
167
- __spreadValues$9({
168
- columns: [name]
169
- }, foreignKey),
144
+ {
145
+ columns: [name],
146
+ ...foreignKey
147
+ },
170
148
  snakeCase
171
149
  )
172
150
  );
@@ -180,7 +158,7 @@ const encodeColumnDefault = (def, values, column) => {
180
158
  return def.toSQL({ values });
181
159
  } else {
182
160
  return pqb.escapeForMigration(
183
- (column == null ? void 0 : column.data.encode) ? column.data.encode(def) : def
161
+ column?.data.encode ? column.data.encode(def) : def
184
162
  );
185
163
  }
186
164
  }
@@ -192,20 +170,13 @@ const identityToSql = (identity) => {
192
170
  };
193
171
  const sequenceOptionsToSql = (item) => {
194
172
  const line = [];
195
- if (item.dataType)
196
- line.push(`AS ${item.dataType}`);
197
- if (item.increment !== void 0)
198
- line.push(`INCREMENT BY ${item.increment}`);
199
- if (item.min !== void 0)
200
- line.push(`MINVALUE ${item.min}`);
201
- if (item.max !== void 0)
202
- line.push(`MAXVALUE ${item.max}`);
203
- if (item.start !== void 0)
204
- line.push(`START WITH ${item.start}`);
205
- if (item.cache !== void 0)
206
- line.push(`CACHE ${item.cache}`);
207
- if (item.cycle)
208
- line.push(`CYCLE`);
173
+ if (item.dataType) line.push(`AS ${item.dataType}`);
174
+ if (item.increment !== void 0) line.push(`INCREMENT BY ${item.increment}`);
175
+ if (item.min !== void 0) line.push(`MINVALUE ${item.min}`);
176
+ if (item.max !== void 0) line.push(`MAXVALUE ${item.max}`);
177
+ if (item.start !== void 0) line.push(`START WITH ${item.start}`);
178
+ if (item.cache !== void 0) line.push(`CACHE ${item.cache}`);
179
+ if (item.cycle) line.push(`CYCLE`);
209
180
  if (item.ownedBy) {
210
181
  const [schema, table] = getSchemaAndTableFromName(item.ownedBy);
211
182
  line.push(`OWNED BY ${quoteTable(schema, table)}`);
@@ -215,9 +186,10 @@ const sequenceOptionsToSql = (item) => {
215
186
  const addColumnIndex = (indexes, name, item) => {
216
187
  if (item.data.indexes) {
217
188
  indexes.push(
218
- ...item.data.indexes.map((index) => __spreadValues$9({
219
- columns: [__spreadProps$7(__spreadValues$9({}, index.options), { column: name })]
220
- }, index))
189
+ ...item.data.indexes.map((index) => ({
190
+ columns: [{ ...index.options, column: name }],
191
+ ...index
192
+ }))
221
193
  );
222
194
  }
223
195
  };
@@ -240,10 +212,8 @@ const getConstraintName = (table, constraint, snakeCase) => {
240
212
  "_"
241
213
  )}_fkey`;
242
214
  }
243
- if (constraint.check)
244
- return `${table}_check`;
245
- if (constraint.identity)
246
- return `${table}_identity`;
215
+ if (constraint.check) return `${table}_check`;
216
+ if (constraint.identity) return `${table}_identity`;
247
217
  return `${table}_constraint`;
248
218
  };
249
219
  const constraintToSql = ({ name }, up, constraint, values, snakeCase) => {
@@ -277,14 +247,14 @@ const referencesToSql = (references, snakeCase) => {
277
247
  )})`
278
248
  ];
279
249
  const { options } = references;
280
- if (options == null ? void 0 : options.match) {
281
- sql.push(`MATCH ${options == null ? void 0 : options.match.toUpperCase()}`);
250
+ if (options?.match) {
251
+ sql.push(`MATCH ${options?.match.toUpperCase()}`);
282
252
  }
283
- if (options == null ? void 0 : options.onDelete) {
284
- sql.push(`ON DELETE ${options == null ? void 0 : options.onDelete.toUpperCase()}`);
253
+ if (options?.onDelete) {
254
+ sql.push(`ON DELETE ${options?.onDelete.toUpperCase()}`);
285
255
  }
286
- if (options == null ? void 0 : options.onUpdate) {
287
- sql.push(`ON UPDATE ${options == null ? void 0 : options.onUpdate.toUpperCase()}`);
256
+ if (options?.onUpdate) {
257
+ sql.push(`ON UPDATE ${options?.onUpdate.toUpperCase()}`);
288
258
  }
289
259
  return sql.join(" ");
290
260
  };
@@ -296,10 +266,9 @@ const indexesToQuery = (up, { schema, name: tableName }, indexes, snakeCase, lan
296
266
  let include = options.include ? orchidCore.toArray(options.include) : void 0;
297
267
  if (snakeCase) {
298
268
  columns = columns.map(
299
- (c) => "column" in c ? __spreadProps$7(__spreadValues$9({}, c), { column: orchidCore.toSnakeCase(c.column) }) : c
269
+ (c) => "column" in c ? { ...c, column: orchidCore.toSnakeCase(c.column) } : c
300
270
  );
301
- if (include)
302
- include = include.map(orchidCore.toSnakeCase);
271
+ if (include) include = include.map(orchidCore.toSnakeCase);
303
272
  }
304
273
  const indexName = name || getIndexName(tableName, columns);
305
274
  if (!up) {
@@ -387,7 +356,7 @@ const primaryKeyToSql = (primaryKey) => {
387
356
  return `${primaryKey.name ? `CONSTRAINT "${primaryKey.name}" ` : ""}PRIMARY KEY (${joinColumns(primaryKey.columns)})`;
388
357
  };
389
358
  const interpolateSqlValues = ({ text, values }) => {
390
- return (values == null ? void 0 : values.length) ? text.replace(/\$(\d+)/g, (_, n) => {
359
+ return values?.length ? text.replace(/\$(\d+)/g, (_, n) => {
391
360
  const i = +n - 1;
392
361
  return pqb.escapeForMigration(values[i]);
393
362
  }) : text;
@@ -409,39 +378,7 @@ class RakeDbError extends Error {
409
378
  class NoPrimaryKey extends RakeDbError {
410
379
  }
411
380
 
412
- var __defProp$8 = Object.defineProperty;
413
- var __defProps$6 = Object.defineProperties;
414
- var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
415
- var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
416
- var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
417
- var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
418
- var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
419
- var __spreadValues$8 = (a, b) => {
420
- for (var prop in b || (b = {}))
421
- if (__hasOwnProp$8.call(b, prop))
422
- __defNormalProp$8(a, prop, b[prop]);
423
- if (__getOwnPropSymbols$8)
424
- for (var prop of __getOwnPropSymbols$8(b)) {
425
- if (__propIsEnum$8.call(b, prop))
426
- __defNormalProp$8(a, prop, b[prop]);
427
- }
428
- return a;
429
- };
430
- var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
431
- var __objRest$1 = (source, exclude) => {
432
- var target = {};
433
- for (var prop in source)
434
- if (__hasOwnProp$8.call(source, prop) && exclude.indexOf(prop) < 0)
435
- target[prop] = source[prop];
436
- if (source != null && __getOwnPropSymbols$8)
437
- for (var prop of __getOwnPropSymbols$8(source)) {
438
- if (exclude.indexOf(prop) < 0 && __propIsEnum$8.call(source, prop))
439
- target[prop] = source[prop];
440
- }
441
- return target;
442
- };
443
381
  const createTable = async (migration, up, tableName, first, second, third) => {
444
- var _a;
445
382
  let options;
446
383
  let fn;
447
384
  let dataFn;
@@ -467,7 +404,7 @@ const createTable = async (migration, up, tableName, first, second, third) => {
467
404
  shape = pqb.getColumnTypes(
468
405
  types,
469
406
  fn,
470
- (_a = migration.options.baseTable) == null ? void 0 : _a.nowSQL,
407
+ migration.options.baseTable?.nowSQL,
471
408
  language
472
409
  );
473
410
  tableData = pqb.parseTableData(dataFn);
@@ -484,15 +421,14 @@ const createTable = async (migration, up, tableName, first, second, third) => {
484
421
  );
485
422
  fn && validatePrimaryKey(ast);
486
423
  const queries = astToQueries$1(ast, snakeCase, language);
487
- for (const _b of queries) {
488
- const _c = _b, { then } = _c, query = __objRest$1(_c, ["then"]);
424
+ for (const { then, ...query } of queries) {
489
425
  const result = await migration.adapter.arrays(interpolateSqlValues(query));
490
- then == null ? void 0 : then(result);
426
+ then?.(result);
491
427
  }
492
428
  let table;
493
429
  return {
494
430
  get table() {
495
- return table != null ? table : table = migration(
431
+ return table ?? (table = migration(
496
432
  tableName,
497
433
  shape,
498
434
  void 0,
@@ -500,7 +436,7 @@ const createTable = async (migration, up, tableName, first, second, third) => {
500
436
  noPrimaryKey: options.noPrimaryKey ? "ignore" : void 0,
501
437
  snakeCase
502
438
  }
503
- );
439
+ ));
504
440
  }
505
441
  };
506
442
  };
@@ -514,24 +450,24 @@ const makeAst$2 = (up, tableName, shape, tableData, options, noPrimaryKey) => {
514
450
  }
515
451
  const { primaryKey } = tableData;
516
452
  const [schema, table] = getSchemaAndTableFromName(tableName);
517
- return __spreadProps$6(__spreadValues$8(__spreadProps$6(__spreadValues$8({
453
+ return {
518
454
  type: "table",
519
455
  action: up ? "create" : "drop",
520
456
  schema,
521
457
  name: table,
522
- shape
523
- }, tableData), {
524
- primaryKey: shapePKeys.length <= 1 ? primaryKey : primaryKey ? __spreadProps$6(__spreadValues$8({}, primaryKey), {
458
+ shape,
459
+ ...tableData,
460
+ primaryKey: shapePKeys.length <= 1 ? primaryKey : primaryKey ? {
461
+ ...primaryKey,
525
462
  columns: [.../* @__PURE__ */ new Set([...shapePKeys, ...primaryKey.columns])]
526
- }) : { columns: shapePKeys }
527
- }), options), {
463
+ } : { columns: shapePKeys },
464
+ ...options,
528
465
  noPrimaryKey: options.noPrimaryKey ? "ignore" : noPrimaryKey || "error"
529
- });
466
+ };
530
467
  };
531
468
  const validatePrimaryKey = (ast) => {
532
- var _a, _b;
533
469
  if (ast.noPrimaryKey !== "ignore") {
534
- let hasPrimaryKey = !!((_b = (_a = ast.primaryKey) == null ? void 0 : _a.columns) == null ? void 0 : _b.length);
470
+ let hasPrimaryKey = !!ast.primaryKey?.columns?.length;
535
471
  if (!hasPrimaryKey) {
536
472
  for (const key in ast.shape) {
537
473
  if (ast.shape[key].data.primaryKey) {
@@ -554,13 +490,11 @@ You can suppress this error by setting { noPrimaryKey: true } after a table name
554
490
  }
555
491
  };
556
492
  const astToQueries$1 = (ast, snakeCase, language) => {
557
- var _a, _b;
558
493
  const queries = [];
559
494
  const { shape } = ast;
560
495
  for (const key in shape) {
561
496
  const item = shape[key];
562
- if (!(item instanceof pqb.EnumColumn))
563
- continue;
497
+ if (!(item instanceof pqb.EnumColumn)) continue;
564
498
  queries.push(makePopulateEnumQuery(item));
565
499
  }
566
500
  if (ast.action === "drop") {
@@ -594,30 +528,36 @@ const astToQueries$1 = (ast, snakeCase, language) => {
594
528
  })}`
595
529
  );
596
530
  }
597
- (_a = ast.constraints) == null ? void 0 : _a.forEach((item) => {
531
+ ast.constraints?.forEach((item) => {
598
532
  lines.push(
599
533
  `
600
534
  ${constraintToSql(
601
535
  ast,
602
536
  true,
603
- __spreadProps$6(__spreadValues$8({}, item), {
604
- references: item.references ? __spreadProps$6(__spreadValues$8({}, item.references), {
537
+ {
538
+ ...item,
539
+ references: item.references ? {
540
+ ...item.references,
605
541
  columns: item.references.columns.map(
606
542
  (column) => getColumnName(shape[column], column, snakeCase)
607
543
  )
608
- }) : void 0
609
- }),
544
+ } : void 0
545
+ },
610
546
  values,
611
547
  snakeCase
612
548
  )}`
613
549
  );
614
550
  });
615
551
  indexes.push(
616
- ...((_b = ast.indexes) == null ? void 0 : _b.map((index) => __spreadProps$6(__spreadValues$8({}, index), {
617
- columns: index.columns.map((item) => __spreadValues$8(__spreadValues$8({}, item), "column" in item ? {
618
- column: getColumnName(shape[item.column], item.column, snakeCase)
619
- } : {}))
620
- }))) || []
552
+ ...ast.indexes?.map((index) => ({
553
+ ...index,
554
+ columns: index.columns.map((item) => ({
555
+ ...item,
556
+ ..."column" in item ? {
557
+ column: getColumnName(shape[item.column], item.column, snakeCase)
558
+ } : {}
559
+ }))
560
+ })) || []
621
561
  );
622
562
  queries.push(
623
563
  {
@@ -638,25 +578,6 @@ const astToQueries$1 = (ast, snakeCase, language) => {
638
578
  return queries;
639
579
  };
640
580
 
641
- var __defProp$7 = Object.defineProperty;
642
- var __defProps$5 = Object.defineProperties;
643
- var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
644
- var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
645
- var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
646
- var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
647
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
648
- var __spreadValues$7 = (a, b) => {
649
- for (var prop in b || (b = {}))
650
- if (__hasOwnProp$7.call(b, prop))
651
- __defNormalProp$7(a, prop, b[prop]);
652
- if (__getOwnPropSymbols$7)
653
- for (var prop of __getOwnPropSymbols$7(b)) {
654
- if (__propIsEnum$7.call(b, prop))
655
- __defNormalProp$7(a, prop, b[prop]);
656
- }
657
- return a;
658
- };
659
- var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
660
581
  const newChangeTableData = () => ({
661
582
  add: {},
662
583
  drop: {}
@@ -671,8 +592,7 @@ function add(item, options) {
671
592
  setName(this, item);
672
593
  if (item instanceof pqb.ColumnType) {
673
594
  const result = addOrDrop("add", item, options);
674
- if (result.type === "change")
675
- return result;
595
+ if (result.type === "change") return result;
676
596
  addOrDropChanges.push(result);
677
597
  return addOrDropChanges.length - 1;
678
598
  }
@@ -683,7 +603,7 @@ function add(item, options) {
683
603
  result[key2] = {
684
604
  type: "add",
685
605
  item: item[key2],
686
- dropMode: options == null ? void 0 : options.dropMode
606
+ dropMode: options?.dropMode
687
607
  };
688
608
  }
689
609
  return result;
@@ -698,8 +618,7 @@ const drop = function(item, options) {
698
618
  setName(this, item);
699
619
  if (item instanceof pqb.ColumnType) {
700
620
  const result = addOrDrop("drop", item, options);
701
- if (result.type === "change")
702
- return result;
621
+ if (result.type === "change") return result;
703
622
  addOrDropChanges.push(result);
704
623
  return addOrDropChanges.length - 1;
705
624
  }
@@ -710,7 +629,7 @@ const drop = function(item, options) {
710
629
  result[key2] = {
711
630
  type: "drop",
712
631
  item: item[key2],
713
- dropMode: options == null ? void 0 : options.dropMode
632
+ dropMode: options?.dropMode
714
633
  };
715
634
  }
716
635
  return result;
@@ -734,55 +653,53 @@ const addOrDrop = (type, item, options) => {
734
653
  check: item.data.check
735
654
  }
736
655
  });
737
- return __spreadValues$7({
656
+ return {
738
657
  type: "change",
739
658
  from: type === "add" ? empty : add2,
740
- to: type === "add" ? add2 : empty
741
- }, options);
659
+ to: type === "add" ? add2 : empty,
660
+ ...options
661
+ };
742
662
  }
743
663
  return {
744
664
  type,
745
665
  item,
746
- dropMode: options == null ? void 0 : options.dropMode
666
+ dropMode: options?.dropMode
747
667
  };
748
668
  };
749
669
  const columnTypeToColumnChange = (item, name) => {
750
670
  if (item instanceof pqb.ColumnType) {
751
671
  let column = item;
752
672
  const foreignKeys = column.data.foreignKeys;
753
- if (foreignKeys == null ? void 0 : foreignKeys.some((it) => "fn" in it)) {
673
+ if (foreignKeys?.some((it) => "fn" in it)) {
754
674
  throw new Error("Callback in foreignKey is not allowed in migration");
755
675
  }
756
- if (name && !column.data.name) {
757
- column = Object.create(column);
758
- column.data = __spreadProps$5(__spreadValues$7({}, column.data), { name });
759
- }
760
- return __spreadProps$5(__spreadValues$7({
676
+ return {
761
677
  column,
762
678
  type: column.toSQL(),
763
- nullable: column.data.isNullable
764
- }, column.data), {
679
+ nullable: column.data.isNullable,
680
+ ...column.data,
765
681
  primaryKey: column.data.primaryKey === void 0 ? void 0 : true,
766
682
  foreignKeys
767
- });
683
+ };
768
684
  }
769
685
  return item.to;
770
686
  };
771
687
  const nameKey = Symbol("name");
772
688
  const setName = (self, item) => {
773
- var _a, _b, _c, _d, _e;
689
+ var _a, _b;
774
690
  const name = self[nameKey];
775
- if (!name)
776
- return;
691
+ if (!name) return;
777
692
  if ("column" in item && item.column instanceof pqb.ColumnType) {
778
- (_b = (_a = item.column.data).name) != null ? _b : _a.name = name;
693
+ (_a = item.column.data).name ?? (_a.name = name);
779
694
  } else if (item instanceof pqb.ColumnType) {
780
- (_d = (_c = item.data).name) != null ? _d : _c.name = name;
695
+ (_b = item.data).name ?? (_b.name = name);
781
696
  } else {
782
- (_e = item.name) != null ? _e : item.name = name;
697
+ item.name ?? (item.name = name);
783
698
  }
784
699
  };
785
- const tableChangeMethods = __spreadProps$5(__spreadValues$7(__spreadValues$7({}, tableMethods), pqb.tableDataMethods), {
700
+ const tableChangeMethods = {
701
+ ...tableMethods,
702
+ ...pqb.tableDataMethods,
786
703
  name(name) {
787
704
  orchidCore.setCurrentColumnName(name);
788
705
  const types = Object.create(this);
@@ -848,9 +765,8 @@ const tableChangeMethods = __spreadProps$5(__spreadValues$7(__spreadValues$7({},
848
765
  rename(name) {
849
766
  return { type: "rename", name };
850
767
  }
851
- });
768
+ };
852
769
  const changeTable = async (migration, up, tableName, options, fn) => {
853
- var _a;
854
770
  const snakeCase = "snakeCase" in options ? options.snakeCase : migration.options.snakeCase;
855
771
  const language = "language" in options ? options.language : migration.options.language;
856
772
  orchidCore.setDefaultLanguage(language);
@@ -861,12 +777,12 @@ const changeTable = async (migration, up, tableName, options, fn) => {
861
777
  Object.assign(tableChanger, tableChangeMethods);
862
778
  tableChanger[orchidCore.snakeCaseKey] = snakeCase;
863
779
  addOrDropChanges.length = 0;
864
- const changeData = (fn == null ? void 0 : fn(tableChanger)) || {};
780
+ const changeData = fn?.(tableChanger) || {};
865
781
  const ast = makeAst$1(up, tableName, changeData, changeTableData, options);
866
782
  const queries = astToQueries(ast, snakeCase, language);
867
783
  for (const query of queries) {
868
784
  const result = await migration.adapter.arrays(interpolateSqlValues(query));
869
- (_a = query.then) == null ? void 0 : _a.call(query, result);
785
+ query.then?.(result);
870
786
  }
871
787
  };
872
788
  const makeAst$1 = (up, name, changeData, changeTableData2, options) => {
@@ -886,23 +802,23 @@ const makeAst$1 = (up, name, changeData, changeTableData2, options) => {
886
802
  shape[key] = item;
887
803
  } else {
888
804
  if (item.type === "rename") {
889
- shape[item.name] = __spreadProps$5(__spreadValues$7({}, item), { name: key });
805
+ shape[item.name] = { ...item, name: key };
890
806
  } else {
891
- 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), {
807
+ shape[key] = item.type === "add" ? { ...item, type: "drop" } : item.type === "drop" ? { ...item, type: "add" } : item.type === "change" ? {
808
+ ...item,
892
809
  from: item.to,
893
810
  to: item.from,
894
811
  using: item.using && {
895
812
  usingUp: item.using.usingDown,
896
813
  usingDown: item.using.usingUp
897
814
  }
898
- }) : item;
815
+ } : item;
899
816
  }
900
817
  }
901
818
  }
902
819
  }
903
820
  for (let i = 0; i < addOrDropChanges.length; i++) {
904
- if (consumedChanges[i])
905
- continue;
821
+ if (consumedChanges[i]) continue;
906
822
  const change = addOrDropChanges[i];
907
823
  const name2 = change.item.data.name;
908
824
  if (!name2) {
@@ -910,21 +826,21 @@ const makeAst$1 = (up, name, changeData, changeTableData2, options) => {
910
826
  }
911
827
  const arr = shape[name2] ? orchidCore.toArray(shape[name2]) : [];
912
828
  arr[up ? "push" : "unshift"](
913
- up ? change : __spreadProps$5(__spreadValues$7({}, change), { type: change.type === "add" ? "drop" : "add" })
829
+ up ? change : { ...change, type: change.type === "add" ? "drop" : "add" }
914
830
  );
915
831
  shape[name2] = arr;
916
832
  }
917
833
  const [schema, table] = getSchemaAndTableFromName(name);
918
- return __spreadValues$7({
834
+ return {
919
835
  type: "changeTable",
920
836
  schema,
921
837
  name: table,
922
838
  comment: comment ? up ? Array.isArray(comment) ? comment[1] : comment : Array.isArray(comment) ? comment[0] : null : void 0,
923
- shape
924
- }, up ? changeTableData2 : { add: changeTableData2.drop, drop: changeTableData2.add });
839
+ shape,
840
+ ...up ? changeTableData2 : { add: changeTableData2.drop, drop: changeTableData2.add }
841
+ };
925
842
  };
926
843
  const astToQueries = (ast, snakeCase, language) => {
927
- var _a, _b, _c, _d;
928
844
  const queries = [];
929
845
  if (ast.comment !== void 0) {
930
846
  queries.push({
@@ -980,10 +896,10 @@ const astToQueries = (ast, snakeCase, language) => {
980
896
  const alterTable = [];
981
897
  const renameItems = [];
982
898
  const values = [];
983
- const addIndexes = (_a = ast.add.indexes) != null ? _a : [];
984
- const dropIndexes = (_b = ast.drop.indexes) != null ? _b : [];
985
- const addConstraints = (_c = ast.add.constraints) != null ? _c : [];
986
- const dropConstraints = (_d = ast.drop.constraints) != null ? _d : [];
899
+ const addIndexes = ast.add.indexes ?? [];
900
+ const dropIndexes = ast.drop.indexes ?? [];
901
+ const addConstraints = ast.add.constraints ?? [];
902
+ const dropConstraints = ast.drop.constraints ?? [];
987
903
  const comments = [];
988
904
  for (const key in ast.shape) {
989
905
  const item = ast.shape[key];
@@ -1112,7 +1028,6 @@ const handlePrerequisitesForTableItem = (key, item, queries, addPrimaryKeys, dro
1112
1028
  }
1113
1029
  };
1114
1030
  const handleTableItemChange = (key, item, ast, alterTable, renameItems, values, addPrimaryKeys, addIndexes, dropIndexes, addConstraints, dropConstraints, comments, snakeCase) => {
1115
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
1116
1031
  if (item.type === "add") {
1117
1032
  const column = item.item;
1118
1033
  const name = getColumnName(column, key, snakeCase);
@@ -1144,7 +1059,7 @@ const handleTableItemChange = (key, item, ast, alterTable, renameItems, values,
1144
1059
  changeType = true;
1145
1060
  const type = !to.column || to.column.data.isOfCustomType ? to.column && to.column instanceof pqb.DomainColumn ? quoteNameFromString(to.type) : quoteCustomType(to.type) : to.type;
1146
1061
  alterTable.push(
1147
- `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}` : ""}`
1062
+ `ALTER COLUMN "${name}" TYPE ${type}${to.collate ? ` COLLATE ${quoteNameFromString(to.collate)}` : ""}${item.using?.usingUp ? ` USING ${item.using.usingUp.toSQL({ values })}` : to.column instanceof pqb.EnumColumn ? ` USING "${name}"::text::${type}` : ""}`
1148
1063
  );
1149
1064
  }
1150
1065
  if (typeof from.identity !== typeof to.identity || !orchidCore.deepCompare(from.identity, to.identity)) {
@@ -1190,62 +1105,66 @@ const handleTableItemChange = (key, item, ast, alterTable, renameItems, values,
1190
1105
  }
1191
1106
  }
1192
1107
  const foreignKeysLen = Math.max(
1193
- ((_b = from.foreignKeys) == null ? void 0 : _b.length) || 0,
1194
- ((_c = to.foreignKeys) == null ? void 0 : _c.length) || 0
1108
+ from.foreignKeys?.length || 0,
1109
+ to.foreignKeys?.length || 0
1195
1110
  );
1196
1111
  for (let i = 0; i < foreignKeysLen; i++) {
1197
- const fromFkey = (_d = from.foreignKeys) == null ? void 0 : _d[i];
1198
- const toFkey = (_e = to.foreignKeys) == null ? void 0 : _e[i];
1199
- if ((fromFkey || toFkey) && (!fromFkey || !toFkey || ((_f = fromFkey.options) == null ? void 0 : _f.name) !== ((_g = toFkey.options) == null ? void 0 : _g.name) || ((_h = fromFkey.options) == null ? void 0 : _h.match) !== ((_i = toFkey.options) == null ? void 0 : _i.match) || ((_j = fromFkey.options) == null ? void 0 : _j.onUpdate) !== ((_k = toFkey.options) == null ? void 0 : _k.onUpdate) || ((_l = fromFkey.options) == null ? void 0 : _l.onDelete) !== ((_m = toFkey.options) == null ? void 0 : _m.onDelete) || ((_n = fromFkey.options) == null ? void 0 : _n.dropMode) !== ((_o = toFkey.options) == null ? void 0 : _o.dropMode) || fromFkey.fnOrTable !== toFkey.fnOrTable)) {
1112
+ const fromFkey = from.foreignKeys?.[i];
1113
+ const toFkey = to.foreignKeys?.[i];
1114
+ if ((fromFkey || toFkey) && (!fromFkey || !toFkey || fromFkey.options?.name !== toFkey.options?.name || fromFkey.options?.match !== toFkey.options?.match || fromFkey.options?.onUpdate !== toFkey.options?.onUpdate || fromFkey.options?.onDelete !== toFkey.options?.onDelete || fromFkey.options?.dropMode !== toFkey.options?.dropMode || fromFkey.fnOrTable !== toFkey.fnOrTable)) {
1200
1115
  if (fromFkey) {
1201
1116
  dropConstraints.push({
1202
- name: (_p = fromFkey.options) == null ? void 0 : _p.name,
1203
- dropMode: (_q = fromFkey.options) == null ? void 0 : _q.dropMode,
1204
- references: __spreadProps$5(__spreadValues$7({
1205
- columns: [name]
1206
- }, fromFkey), {
1117
+ name: fromFkey.options?.name,
1118
+ dropMode: fromFkey.options?.dropMode,
1119
+ references: {
1120
+ columns: [name],
1121
+ ...fromFkey,
1207
1122
  foreignColumns: snakeCase ? fromFkey.foreignColumns.map(orchidCore.toSnakeCase) : fromFkey.foreignColumns
1208
- })
1123
+ }
1209
1124
  });
1210
1125
  }
1211
1126
  if (toFkey) {
1212
1127
  addConstraints.push({
1213
- name: (_r = toFkey.options) == null ? void 0 : _r.name,
1214
- dropMode: (_s = toFkey.options) == null ? void 0 : _s.dropMode,
1215
- references: __spreadProps$5(__spreadValues$7({
1216
- columns: [name]
1217
- }, toFkey), {
1128
+ name: toFkey.options?.name,
1129
+ dropMode: toFkey.options?.dropMode,
1130
+ references: {
1131
+ columns: [name],
1132
+ ...toFkey,
1218
1133
  foreignColumns: snakeCase ? toFkey.foreignColumns.map(orchidCore.toSnakeCase) : toFkey.foreignColumns
1219
- })
1134
+ }
1220
1135
  });
1221
1136
  }
1222
1137
  }
1223
1138
  }
1224
1139
  const indexesLen = Math.max(
1225
- ((_t = from.indexes) == null ? void 0 : _t.length) || 0,
1226
- ((_u = to.indexes) == null ? void 0 : _u.length) || 0
1140
+ from.indexes?.length || 0,
1141
+ to.indexes?.length || 0
1227
1142
  );
1228
1143
  for (let i = 0; i < indexesLen; i++) {
1229
- const fromIndex = (_v = from.indexes) == null ? void 0 : _v[i];
1230
- const toIndex = (_w = to.indexes) == null ? void 0 : _w[i];
1144
+ const fromIndex = from.indexes?.[i];
1145
+ const toIndex = to.indexes?.[i];
1231
1146
  if ((fromIndex || toIndex) && (!fromIndex || !toIndex || !orchidCore.deepCompare(fromIndex, toIndex))) {
1232
1147
  if (fromIndex) {
1233
- dropIndexes.push(__spreadProps$5(__spreadValues$7({}, fromIndex), {
1148
+ dropIndexes.push({
1149
+ ...fromIndex,
1234
1150
  columns: [
1235
- __spreadValues$7({
1236
- column: name
1237
- }, fromIndex.options)
1151
+ {
1152
+ column: name,
1153
+ ...fromIndex.options
1154
+ }
1238
1155
  ]
1239
- }));
1156
+ });
1240
1157
  }
1241
1158
  if (toIndex) {
1242
- addIndexes.push(__spreadProps$5(__spreadValues$7({}, toIndex), {
1159
+ addIndexes.push({
1160
+ ...toIndex,
1243
1161
  columns: [
1244
- __spreadValues$7({
1245
- column: name
1246
- }, toIndex.options)
1162
+ {
1163
+ column: name,
1164
+ ...toIndex.options
1165
+ }
1247
1166
  ]
1248
- }));
1167
+ });
1249
1168
  }
1250
1169
  }
1251
1170
  }
@@ -1293,36 +1212,29 @@ const astToQuery = (ast) => {
1293
1212
  const { options } = ast;
1294
1213
  if (ast.action === "create") {
1295
1214
  sql.push("CREATE");
1296
- if (options == null ? void 0 : options.createOrReplace)
1297
- sql.push("OR REPLACE");
1298
- if (options == null ? void 0 : options.temporary)
1299
- sql.push("TEMPORARY");
1300
- if (options == null ? void 0 : options.recursive)
1301
- sql.push("RECURSIVE");
1215
+ if (options?.createOrReplace) sql.push("OR REPLACE");
1216
+ if (options?.temporary) sql.push("TEMPORARY");
1217
+ if (options?.recursive) sql.push("RECURSIVE");
1302
1218
  sql.push(`VIEW "${ast.name}"`);
1303
- if (options == null ? void 0 : options.columns) {
1219
+ if (options?.columns) {
1304
1220
  sql.push(
1305
1221
  `(${options.columns.map((column) => `"${column}"`).join(", ")})`
1306
1222
  );
1307
1223
  }
1308
- if (options == null ? void 0 : options.with) {
1224
+ if (options?.with) {
1309
1225
  const list = [];
1310
1226
  if (options.with.checkOption)
1311
1227
  list.push(`check_option = ${orchidCore.singleQuote(options.with.checkOption)}`);
1312
- if (options.with.securityBarrier)
1313
- list.push(`security_barrier = true`);
1314
- if (options.with.securityInvoker)
1315
- list.push(`security_invoker = true`);
1228
+ if (options.with.securityBarrier) list.push(`security_barrier = true`);
1229
+ if (options.with.securityInvoker) list.push(`security_invoker = true`);
1316
1230
  sql.push(`WITH ( ${list.join(", ")} )`);
1317
1231
  }
1318
1232
  sql.push(`AS (${ast.sql.toSQL({ values })})`);
1319
1233
  } else {
1320
1234
  sql.push("DROP VIEW");
1321
- if (options == null ? void 0 : options.dropIfExists)
1322
- sql.push(`IF EXISTS`);
1235
+ if (options?.dropIfExists) sql.push(`IF EXISTS`);
1323
1236
  sql.push(`"${ast.name}"`);
1324
- if (options == null ? void 0 : options.dropMode)
1325
- sql.push(options.dropMode);
1237
+ if (options?.dropMode) sql.push(options.dropMode);
1326
1238
  }
1327
1239
  return {
1328
1240
  text: sql.join(" "),
@@ -1330,33 +1242,13 @@ const astToQuery = (ast) => {
1330
1242
  };
1331
1243
  };
1332
1244
 
1333
- var __defProp$6 = Object.defineProperty;
1334
- var __defProps$4 = Object.defineProperties;
1335
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
1336
- var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
1337
- var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
1338
- var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
1339
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1340
- var __spreadValues$6 = (a, b) => {
1341
- for (var prop in b || (b = {}))
1342
- if (__hasOwnProp$6.call(b, prop))
1343
- __defNormalProp$6(a, prop, b[prop]);
1344
- if (__getOwnPropSymbols$6)
1345
- for (var prop of __getOwnPropSymbols$6(b)) {
1346
- if (__propIsEnum$6.call(b, prop))
1347
- __defNormalProp$6(a, prop, b[prop]);
1348
- }
1349
- return a;
1350
- };
1351
- var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
1352
1245
  const createMigrationInterface = (tx, up, config) => {
1353
- var _a;
1354
1246
  const adapter = new pqb.TransactionAdapter(
1355
1247
  tx,
1356
1248
  tx.client,
1357
1249
  tx.types
1358
1250
  );
1359
- adapter.schema = (_a = adapter.adapter.schema) != null ? _a : "public";
1251
+ adapter.schema = adapter.adapter.schema ?? "public";
1360
1252
  const { query, arrays } = adapter;
1361
1253
  const log = pqb.logParamToLogObject(config.logger || console, config.log);
1362
1254
  adapter.query = (q, types) => {
@@ -2210,7 +2102,7 @@ const wrapWithLog = async (log, query, fn) => {
2210
2102
  if (!log) {
2211
2103
  return fn();
2212
2104
  } else {
2213
- const sql = typeof query === "string" ? { text: query, values: [] } : query.values ? query : __spreadProps$4(__spreadValues$6({}, query), { values: [] });
2105
+ const sql = typeof query === "string" ? { text: query, values: [] } : query.values ? query : { ...query, values: [] };
2214
2106
  const logData = log.beforeQuery(sql);
2215
2107
  try {
2216
2108
  const result = await fn();
@@ -2228,16 +2120,24 @@ const addColumn = (migration, up, tableName, columnName, fn) => {
2228
2120
  }));
2229
2121
  };
2230
2122
  const addIndex = (migration, up, tableName, columns, args) => {
2231
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$6({}, t.add(t.index(columns, ...args))));
2123
+ return changeTable(migration, up, tableName, {}, (t) => ({
2124
+ ...t.add(t.index(columns, ...args))
2125
+ }));
2232
2126
  };
2233
2127
  const addForeignKey = (migration, up, tableName, columns, foreignTable, foreignColumns, options) => {
2234
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$6({}, t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))));
2128
+ return changeTable(migration, up, tableName, {}, (t) => ({
2129
+ ...t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))
2130
+ }));
2235
2131
  };
2236
2132
  const addPrimaryKey = (migration, up, tableName, columns, name) => {
2237
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$6({}, t.add(t.primaryKey(columns, name))));
2133
+ return changeTable(migration, up, tableName, {}, (t) => ({
2134
+ ...t.add(t.primaryKey(columns, name))
2135
+ }));
2238
2136
  };
2239
2137
  const addCheck = (migration, up, tableName, check) => {
2240
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$6({}, t.add(t.check(check))));
2138
+ return changeTable(migration, up, tableName, {}, (t) => ({
2139
+ ...t.add(t.check(check))
2140
+ }));
2241
2141
  };
2242
2142
  const createSchema = async (migration, up, name) => {
2243
2143
  const ast = {
@@ -2251,12 +2151,13 @@ const createSchema = async (migration, up, name) => {
2251
2151
  };
2252
2152
  const createExtension = async (migration, up, fullName, options) => {
2253
2153
  const [schema, name] = getSchemaAndTableFromName(fullName);
2254
- const ast = __spreadValues$6({
2154
+ const ast = {
2255
2155
  type: "extension",
2256
2156
  action: up ? "create" : "drop",
2257
2157
  schema,
2258
- name
2259
- }, options);
2158
+ name,
2159
+ ...options
2160
+ };
2260
2161
  let query;
2261
2162
  if (ast.action === "drop") {
2262
2163
  query = `DROP EXTENSION${ast.dropIfExists ? " IF EXISTS" : ""} "${ast.name}"${ast.cascade ? " CASCADE" : ""}`;
@@ -2267,13 +2168,14 @@ const createExtension = async (migration, up, fullName, options) => {
2267
2168
  };
2268
2169
  const createEnum = async (migration, up, name, values, options = {}) => {
2269
2170
  const [schema, enumName] = getSchemaAndTableFromName(name);
2270
- const ast = __spreadValues$6({
2171
+ const ast = {
2271
2172
  type: "enum",
2272
2173
  action: up ? "create" : "drop",
2273
2174
  schema,
2274
2175
  name: enumName,
2275
- values
2276
- }, options);
2176
+ values,
2177
+ ...options
2178
+ };
2277
2179
  let query;
2278
2180
  const quotedName = quoteWithSchema(ast);
2279
2181
  if (ast.action === "create") {
@@ -2315,12 +2217,13 @@ DEFAULT ${encodeColumnDefault(column.data.default, values)}` : ""}${!column.data
2315
2217
  };
2316
2218
  const createCollation = async (migration, up, name, options) => {
2317
2219
  const [schema, collationName] = getSchemaAndTableFromName(name);
2318
- const ast = __spreadValues$6({
2220
+ const ast = {
2319
2221
  type: "collation",
2320
2222
  action: up ? "create" : "drop",
2321
2223
  schema,
2322
- name: collationName
2323
- }, options);
2224
+ name: collationName,
2225
+ ...options
2226
+ };
2324
2227
  let query;
2325
2228
  const quotedName = quoteWithSchema(ast);
2326
2229
  if (ast.action === "create") {
@@ -2329,18 +2232,13 @@ const createCollation = async (migration, up, name, options) => {
2329
2232
  query += `FROM ${quoteNameFromString(ast.fromExisting)}`;
2330
2233
  } else {
2331
2234
  const config = [];
2332
- if (ast.locale)
2333
- config.push(`locale = '${ast.locale}'`);
2334
- if (ast.lcCollate)
2335
- config.push(`lc_collate = '${ast.lcCollate}'`);
2336
- if (ast.lcCType)
2337
- config.push(`lc_ctype = '${ast.lcCType}'`);
2338
- if (ast.provider)
2339
- config.push(`provider = ${ast.provider}`);
2235
+ if (ast.locale) config.push(`locale = '${ast.locale}'`);
2236
+ if (ast.lcCollate) config.push(`lc_collate = '${ast.lcCollate}'`);
2237
+ if (ast.lcCType) config.push(`lc_ctype = '${ast.lcCType}'`);
2238
+ if (ast.provider) config.push(`provider = ${ast.provider}`);
2340
2239
  if (ast.deterministic !== void 0)
2341
2240
  config.push(`deterministic = ${ast.deterministic}`);
2342
- if (ast.version)
2343
- config.push(`version = '${ast.version}'`);
2241
+ if (ast.version) config.push(`version = '${ast.version}'`);
2344
2242
  query += `(
2345
2243
  ${config.join(",\n ")}
2346
2244
  )`;
@@ -2354,7 +2252,6 @@ const queryExists = (db, sql) => {
2354
2252
  return db.adapter.query(sql).then(({ rowCount }) => rowCount > 0);
2355
2253
  };
2356
2254
  const renameType = async (migration, from, to, kind) => {
2357
- var _a;
2358
2255
  const [fromSchema, f] = getSchemaAndTableFromName(migration.up ? from : to);
2359
2256
  const [toSchema, t] = getSchemaAndTableFromName(migration.up ? to : from);
2360
2257
  const ast = {
@@ -2372,7 +2269,7 @@ const renameType = async (migration, from, to, kind) => {
2372
2269
  }
2373
2270
  if (ast.fromSchema !== ast.toSchema) {
2374
2271
  await migration.adapter.query(
2375
- `ALTER ${ast.kind} ${quoteTable(ast.fromSchema, ast.to)} SET SCHEMA "${(_a = ast.toSchema) != null ? _a : migration.adapter.schema}"`
2272
+ `ALTER ${ast.kind} ${quoteTable(ast.fromSchema, ast.to)} SET SCHEMA "${ast.toSchema ?? migration.adapter.schema}"`
2376
2273
  );
2377
2274
  }
2378
2275
  };
@@ -2387,7 +2284,6 @@ const renameTableItem = async (migration, tableName, from, to, kind) => {
2387
2284
  );
2388
2285
  };
2389
2286
  const addOrDropEnumValues = async (migration, up, enumName, values, options) => {
2390
- var _a;
2391
2287
  const [schema, name] = getSchemaAndTableFromName(enumName);
2392
2288
  const quotedName = quoteTable(schema, name);
2393
2289
  const ast = {
@@ -2396,9 +2292,9 @@ const addOrDropEnumValues = async (migration, up, enumName, values, options) =>
2396
2292
  schema,
2397
2293
  name,
2398
2294
  values,
2399
- place: (options == null ? void 0 : options.before) ? "before" : (options == null ? void 0 : options.after) ? "after" : void 0,
2400
- relativeTo: (_a = options == null ? void 0 : options.before) != null ? _a : options == null ? void 0 : options.after,
2401
- ifNotExists: options == null ? void 0 : options.ifNotExists
2295
+ place: options?.before ? "before" : options?.after ? "after" : void 0,
2296
+ relativeTo: options?.before ?? options?.after,
2297
+ ifNotExists: options?.ifNotExists
2402
2298
  };
2403
2299
  if (ast.action === "add") {
2404
2300
  await Promise.all(
@@ -2458,7 +2354,7 @@ JOIN pg_catalog.pg_namespace n ON n.oid = relnamespace
2458
2354
  JOIN pg_attribute a ON a.attrelid = c.oid
2459
2355
  JOIN pg_type t ON a.atttypid = t.oid AND t.typname = ${orchidCore.singleQuote(name)}
2460
2356
  JOIN pg_namespace tn ON tn.oid = t.typnamespace AND tn.nspname = ${orchidCore.singleQuote(
2461
- schema != null ? schema : defaultSchema
2357
+ schema ?? defaultSchema
2462
2358
  )}
2463
2359
  GROUP BY n.nspname, c.relname`
2464
2360
  );
@@ -2490,7 +2386,6 @@ GROUP BY n.nspname, c.relname`
2490
2386
  };
2491
2387
 
2492
2388
  const writeMigrationFile = async (config, version, name, migrationCode) => {
2493
- var _a;
2494
2389
  await fs.mkdir(config.migrationsPath, { recursive: true });
2495
2390
  const filePath = path.resolve(config.migrationsPath, `${version}_${name}.ts`);
2496
2391
  const importPath = orchidCore.getImportPath(
@@ -2502,11 +2397,10 @@ const writeMigrationFile = async (config, version, name, migrationCode) => {
2502
2397
  `import { change } from '${importPath}';
2503
2398
  ${migrationCode}`
2504
2399
  );
2505
- (_a = config.logger) == null ? void 0 : _a.log(`Created ${orchidCore.pathToLog(filePath)}`);
2400
+ config.logger?.log(`Created ${orchidCore.pathToLog(filePath)}`);
2506
2401
  };
2507
2402
  const newMigration = async (config, [name]) => {
2508
- if (!name)
2509
- throw new Error("Migration name is missing");
2403
+ if (!name) throw new Error("Migration name is missing");
2510
2404
  const version = await makeFileVersion({}, config);
2511
2405
  await writeMigrationFile(config, version, name, makeContent(name));
2512
2406
  };
@@ -2565,15 +2459,13 @@ const fileNamesToChangeMigrationIdMap = Object.fromEntries(
2565
2459
  Object.entries(fileNamesToChangeMigrationId).map(([_, name]) => [name, true])
2566
2460
  );
2567
2461
  const changeIds = async (options, config, [arg, digitsArg]) => {
2568
- var _a, _b, _c, _d;
2569
2462
  if (arg !== "serial" && arg !== "timestamp") {
2570
2463
  throw new Error(
2571
2464
  `Pass "serial" or "timestamp" argument to the "change-ids" command`
2572
2465
  );
2573
2466
  }
2574
2467
  let digits = digitsArg && parseInt(digitsArg);
2575
- if (!digits || isNaN(digits))
2576
- digits = 4;
2468
+ if (!digits || isNaN(digits)) digits = 4;
2577
2469
  const data = await getMigrations({}, config, true, false, (_, filePath) => {
2578
2470
  const fileName = path.basename(filePath);
2579
2471
  const match = fileName.match(/^(\d+)\D/);
@@ -2586,7 +2478,7 @@ const changeIds = async (options, config, [arg, digitsArg]) => {
2586
2478
  });
2587
2479
  if (data.renameTo) {
2588
2480
  if (arg === "serial" && typeof data.renameTo.to === "object" && digits === data.renameTo.to.serial || arg === "timestamp" && data.renameTo.to === "timestamp") {
2589
- (_a = config.logger) == null ? void 0 : _a.log(
2481
+ config.logger?.log(
2590
2482
  config.migrations ? "`renameMigrations` setting is already set" : `${fileNamesToChangeMigrationId[arg]} already exists`
2591
2483
  );
2592
2484
  return;
@@ -2606,7 +2498,7 @@ const changeIds = async (options, config, [arg, digitsArg]) => {
2606
2498
  );
2607
2499
  if (config.migrations) {
2608
2500
  const to = arg === "timestamp" ? `'${arg}'` : `{ serial: ${digits} }`;
2609
- (_b = config.logger) == null ? void 0 : _b.log(
2501
+ config.logger?.log(
2610
2502
  `Save the following settings into your rake-db config under the \`migrations\` setting, it will instruct rake-db to rename migration entries during the next deploy:
2611
2503
  ${arg !== "serial" || digits !== 4 ? `
2612
2504
  migrationId: ${to},` : ""}
@@ -2624,16 +2516,14 @@ renameMigrations: {
2624
2516
  const values = data.migrations.map(
2625
2517
  (item, i) => {
2626
2518
  let newVersion = String(version + i);
2627
- if (arg === "serial")
2628
- newVersion = newVersion.padStart(digits, "0");
2519
+ if (arg === "serial") newVersion = newVersion.padStart(digits, "0");
2629
2520
  const name = path.basename(item.path).slice(item.version.length + 1);
2630
2521
  return [item.version, name, newVersion];
2631
2522
  }
2632
2523
  );
2633
- if (!values.length)
2634
- return;
2524
+ if (!values.length) return;
2635
2525
  if (config.migrations) {
2636
- (_c = config.logger) == null ? void 0 : _c.log(
2526
+ config.logger?.log(
2637
2527
  `If your migrations are stored in files, navigate to migrations directory and run the following commands to rename them:
2638
2528
 
2639
2529
  ${values.map(
@@ -2661,7 +2551,7 @@ After setting \`renameMigrations\` (see above) and renaming the files, run the d
2661
2551
  () => adapter.close()
2662
2552
  );
2663
2553
  });
2664
- (_d = config.logger) == null ? void 0 : _d.log(
2554
+ config.logger?.log(
2665
2555
  `Migration files were renamed, a config file ${fileNamesToChangeMigrationId[arg]} for renaming migrations after deploy was created, and migrations in local db were renamed successfully.
2666
2556
 
2667
2557
  ${arg === "timestamp" || digits !== 4 ? `Set \`migrationId\`: ${arg === "timestamp" ? `'timestamp'` : `{ serial: ${digits} }`}` : `Remove \`migrationId\``} setting in the rake-db config`
@@ -2678,32 +2568,12 @@ const renameMigrationVersionsInDb = async (config, adapter, values) => {
2678
2568
  });
2679
2569
  };
2680
2570
 
2681
- var __defProp$5 = Object.defineProperty;
2682
- var __defProps$3 = Object.defineProperties;
2683
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
2684
- var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
2685
- var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
2686
- var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
2687
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2688
- var __spreadValues$5 = (a, b) => {
2689
- for (var prop in b || (b = {}))
2690
- if (__hasOwnProp$5.call(b, prop))
2691
- __defNormalProp$5(a, prop, b[prop]);
2692
- if (__getOwnPropSymbols$5)
2693
- for (var prop of __getOwnPropSymbols$5(b)) {
2694
- if (__propIsEnum$5.call(b, prop))
2695
- __defNormalProp$5(a, prop, b[prop]);
2696
- }
2697
- return a;
2698
- };
2699
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
2700
2571
  const getMigrations = async (ctx, config, up, allowDuplicates, getVersion = getMigrationVersionOrThrow) => {
2701
- var _a;
2702
- return ((_a = ctx.migrationsPromise) != null ? _a : ctx.migrationsPromise = config.migrations ? getMigrationsFromConfig(
2703
- __spreadProps$3(__spreadValues$5({}, config), { migrations: config.migrations }),
2572
+ return (ctx.migrationsPromise ?? (ctx.migrationsPromise = config.migrations ? getMigrationsFromConfig(
2573
+ { ...config, migrations: config.migrations },
2704
2574
  allowDuplicates,
2705
2575
  getVersion
2706
- ) : getMigrationsFromFiles(config, allowDuplicates, getVersion)).then(
2576
+ ) : getMigrationsFromFiles(config, allowDuplicates, getVersion))).then(
2707
2577
  (data) => up ? data : {
2708
2578
  renameTo: data.renameTo,
2709
2579
  migrations: [...data.migrations].reverse()
@@ -2743,8 +2613,7 @@ async function getMigrationsFromFiles(config, allowDuplicates, getVersion = getM
2743
2613
  const versions = {};
2744
2614
  const result = entries.reduce(
2745
2615
  (data, file) => {
2746
- if (!file.isFile())
2747
- return data;
2616
+ if (!file.isFile()) return data;
2748
2617
  if (fileNamesToChangeMigrationIdMap[file.name]) {
2749
2618
  if (data.renameTo) {
2750
2619
  throw new Error(
@@ -2827,8 +2696,7 @@ function checkExt(filePath) {
2827
2696
  function getMigrationVersionOrThrow(config, filePath) {
2828
2697
  const name = path.basename(filePath);
2829
2698
  const value = getMigrationVersion(config, name);
2830
- if (value)
2831
- return value;
2699
+ if (value) return value;
2832
2700
  if (config.migrationId === "timestamp") {
2833
2701
  throw new Error(
2834
2702
  `Migration file name should start with 14 digit timestamp, received ${name}`
@@ -2842,12 +2710,10 @@ To keep using timestamp ids, set \`migrationId\` option of rake-db to 'timestamp
2842
2710
  }
2843
2711
  }
2844
2712
  function getMigrationVersion(config, name) {
2845
- var _a;
2846
- return (_a = config.migrationId === "timestamp" ? name.match(/^(\d{14})(_|\b)/) : name.match(/^(\d{4})(_|\b)/)) == null ? void 0 : _a[1];
2713
+ return (config.migrationId === "timestamp" ? name.match(/^(\d{14})(_|\b)/) : name.match(/^(\d{4})(_|\b)/))?.[1];
2847
2714
  }
2848
2715
  function getDigitsPrefix(name) {
2849
- var _a;
2850
- const value = (_a = name.match(/^(\d+)\D/)) == null ? void 0 : _a[1];
2716
+ const value = name.match(/^(\d+)\D/)?.[1];
2851
2717
  if (!value) {
2852
2718
  throw new Error(
2853
2719
  `Migration file should be prefixed with a serial number, received ${name}`
@@ -2928,8 +2794,7 @@ async function renameMigrations(config, trx, versions, renameTo) {
2928
2794
  first = version;
2929
2795
  break;
2930
2796
  }
2931
- if (!first || getMigrationVersion(config, first))
2932
- return versions;
2797
+ if (!first || getMigrationVersion(config, first)) return versions;
2933
2798
  const values = [];
2934
2799
  const updatedVersions = {};
2935
2800
  const data = await renameTo.map();
@@ -2953,12 +2818,11 @@ async function renameMigrations(config, trx, versions, renameTo) {
2953
2818
  }
2954
2819
 
2955
2820
  const createMigrationsTable = async (db, config) => {
2956
- var _a, _b, _c;
2957
2821
  const { schema } = db;
2958
2822
  if (schema && schema !== "public") {
2959
2823
  try {
2960
2824
  await db.query(`CREATE SCHEMA "${schema}"`);
2961
- (_a = config.logger) == null ? void 0 : _a.log(`Created schema ${schema}`);
2825
+ config.logger?.log(`Created schema ${schema}`);
2962
2826
  } catch (err) {
2963
2827
  if (err.code !== "42P06") {
2964
2828
  throw err;
@@ -2969,10 +2833,10 @@ const createMigrationsTable = async (db, config) => {
2969
2833
  await db.query(
2970
2834
  `CREATE TABLE "${config.migrationsTable}" ( version TEXT NOT NULL, name TEXT NOT NULL )`
2971
2835
  );
2972
- (_b = config.logger) == null ? void 0 : _b.log("Created versions table");
2836
+ config.logger?.log("Created versions table");
2973
2837
  } catch (err) {
2974
2838
  if (err.code === "42P07") {
2975
- (_c = config.logger) == null ? void 0 : _c.log("Versions table exists");
2839
+ config.logger?.log("Versions table exists");
2976
2840
  } else {
2977
2841
  throw err;
2978
2842
  }
@@ -2982,7 +2846,6 @@ const createMigrationsTable = async (db, config) => {
2982
2846
  const RAKE_DB_LOCK_KEY = "8582141715823621641";
2983
2847
  function makeMigrateFn(defaultCount, up, fn) {
2984
2848
  return async (ctx, options, config, args = [], adapters = options.map((opts) => new pqb.Adapter(opts)), dontClose) => {
2985
- var _a;
2986
2849
  const set = await getMigrations(ctx, config, up);
2987
2850
  const arg = args[0];
2988
2851
  let force = arg === "force";
@@ -3013,7 +2876,7 @@ function makeMigrateFn(defaultCount, up, fn) {
3013
2876
  conf,
3014
2877
  set,
3015
2878
  versions,
3016
- count != null ? count : defaultCount,
2879
+ count ?? defaultCount,
3017
2880
  force
3018
2881
  );
3019
2882
  });
@@ -3033,7 +2896,7 @@ function makeMigrateFn(defaultCount, up, fn) {
3033
2896
  config2,
3034
2897
  set,
3035
2898
  versions,
3036
- count != null ? count : defaultCount,
2899
+ count ?? defaultCount,
3037
2900
  force
3038
2901
  );
3039
2902
  });
@@ -3041,10 +2904,9 @@ function makeMigrateFn(defaultCount, up, fn) {
3041
2904
  throw err;
3042
2905
  }
3043
2906
  } finally {
3044
- if (!dontClose)
3045
- await adapter.close();
2907
+ if (!dontClose) await adapter.close();
3046
2908
  }
3047
- (_a = config.afterChangeCommit) == null ? void 0 : _a.call(config, {
2909
+ config.afterChangeCommit?.({
3048
2910
  options: opts,
3049
2911
  up,
3050
2912
  migrations
@@ -3085,7 +2947,6 @@ const redo = makeMigrateFn(
3085
2947
  );
3086
2948
  const getDb = (adapter) => pqb.createDb({ adapter });
3087
2949
  const migrateOrRollback = async (trx, config, set, versions, count, up, redo2, force, skipLock) => {
3088
- var _a, _b, _c, _d;
3089
2950
  const { sequence, map: versionsMap } = versions;
3090
2951
  if (up) {
3091
2952
  const rollbackTo = checkMigrationOrder(config, set, versions, force);
@@ -3097,8 +2958,7 @@ const migrateOrRollback = async (trx, config, set, versions, count, up, redo2, f
3097
2958
  break;
3098
2959
  }
3099
2960
  }
3100
- if (i < 0)
3101
- i = 0;
2961
+ if (i < 0) i = 0;
3102
2962
  set.migrations.reverse();
3103
2963
  await migrateOrRollback(
3104
2964
  trx,
@@ -3112,15 +2972,14 @@ const migrateOrRollback = async (trx, config, set, versions, count, up, redo2, f
3112
2972
  set.migrations.reverse();
3113
2973
  }
3114
2974
  }
3115
- if (!skipLock)
3116
- await queryLock(trx);
2975
+ if (!skipLock) await queryLock(trx);
3117
2976
  let db;
3118
2977
  const beforeMigrate = config[up ? "beforeMigrate" : "beforeRollback"];
3119
2978
  if (beforeMigrate || config.beforeChange) {
3120
- db != null ? db : db = getDb(trx);
2979
+ db ?? (db = getDb(trx));
3121
2980
  const { migrations: migrations2 } = set;
3122
- await (beforeMigrate == null ? void 0 : beforeMigrate({ db, migrations: migrations2 }));
3123
- await ((_a = config.beforeChange) == null ? void 0 : _a.call(config, { db, migrations: migrations2, up, redo: redo2 }));
2981
+ await beforeMigrate?.({ db, migrations: migrations2 });
2982
+ await config.beforeChange?.({ db, migrations: migrations2, up, redo: redo2 });
3124
2983
  }
3125
2984
  let loggedAboutStarting = false;
3126
2985
  let migrations;
@@ -3128,17 +2987,16 @@ const migrateOrRollback = async (trx, config, set, versions, count, up, redo2, f
3128
2987
  if (up && versionsMap[file.version] || !up && !versionsMap[file.version]) {
3129
2988
  continue;
3130
2989
  }
3131
- if (count-- <= 0)
3132
- break;
2990
+ if (count-- <= 0) break;
3133
2991
  if (!loggedAboutStarting && (!redo2 || !up)) {
3134
2992
  loggedAboutStarting = true;
3135
- (_b = config.logger) == null ? void 0 : _b.log(
2993
+ config.logger?.log(
3136
2994
  `${redo2 ? "Reapplying migrations for" : up ? "Migrating" : "Rolling back"} database ${trx.config.connectionString ? new URL(trx.config.connectionString).pathname.slice(1) : trx.config.database}
3137
2995
  `
3138
2996
  );
3139
2997
  }
3140
2998
  await runMigration(trx, up, file, config);
3141
- (migrations != null ? migrations : migrations = []).push(file);
2999
+ (migrations ?? (migrations = [])).push(file);
3142
3000
  if (up) {
3143
3001
  const name = path.basename(file.path);
3144
3002
  versionsMap[file.version] = name;
@@ -3147,17 +3005,17 @@ const migrateOrRollback = async (trx, config, set, versions, count, up, redo2, f
3147
3005
  versionsMap[file.version] = void 0;
3148
3006
  sequence.pop();
3149
3007
  }
3150
- (_c = config.logger) == null ? void 0 : _c.log(
3008
+ config.logger?.log(
3151
3009
  `${up ? "Migrated" : "Rolled back"} ${orchidCore.pathToLog(file.path)}
3152
3010
  `
3153
3011
  );
3154
3012
  }
3155
- migrations != null ? migrations : migrations = orchidCore.emptyArray;
3013
+ migrations ?? (migrations = orchidCore.emptyArray);
3156
3014
  const afterMigrate = config[up ? "afterMigrate" : "afterRollback"];
3157
3015
  if (config.afterChange || afterMigrate) {
3158
- db != null ? db : db = getDb(trx);
3159
- await ((_d = config.afterChange) == null ? void 0 : _d.call(config, { db, up, redo: redo2, migrations }));
3160
- await (afterMigrate == null ? void 0 : afterMigrate({ db, migrations }));
3016
+ db ?? (db = getDb(trx));
3017
+ await config.afterChange?.({ db, up, redo: redo2, migrations });
3018
+ await afterMigrate?.({ db, migrations });
3161
3019
  }
3162
3020
  return migrations;
3163
3021
  };
@@ -3166,8 +3024,7 @@ const checkMigrationOrder = (config, set, { sequence, map }, force) => {
3166
3024
  if (last) {
3167
3025
  for (const file of set.migrations) {
3168
3026
  const version = +file.version;
3169
- if (version > last || map[file.version])
3170
- continue;
3027
+ if (version > last || map[file.version]) continue;
3171
3028
  if (!force) {
3172
3029
  throw new Error(
3173
3030
  `Cannot migrate ${path.basename(
@@ -3187,7 +3044,7 @@ const runMigration = async (trx, up, file, config) => {
3187
3044
  let changes = changeCache[file.path];
3188
3045
  if (!changes) {
3189
3046
  const module = await file.load();
3190
- const exported = (module == null ? void 0 : module.default) && orchidCore.toArray(module.default);
3047
+ const exported = module?.default && orchidCore.toArray(module.default);
3191
3048
  if (config.forceDefaultExports && !exported) {
3192
3049
  throw new RakeDbError(
3193
3050
  `Missing a default export in ${file.path} migration`
@@ -3213,22 +3070,6 @@ const runMigration = async (trx, up, file, config) => {
3213
3070
  );
3214
3071
  };
3215
3072
 
3216
- var __defProp$4 = Object.defineProperty;
3217
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
3218
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
3219
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
3220
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3221
- var __spreadValues$4 = (a, b) => {
3222
- for (var prop in b || (b = {}))
3223
- if (__hasOwnProp$4.call(b, prop))
3224
- __defNormalProp$4(a, prop, b[prop]);
3225
- if (__getOwnPropSymbols$4)
3226
- for (var prop of __getOwnPropSymbols$4(b)) {
3227
- if (__propIsEnum$4.call(b, prop))
3228
- __defNormalProp$4(a, prop, b[prop]);
3229
- }
3230
- return a;
3231
- };
3232
3073
  const migrationConfigDefaults = {
3233
3074
  schemaConfig: pqb.defaultSchemaConfig,
3234
3075
  migrationsPath: path.join("src", "db", "migrations"),
@@ -3243,8 +3084,7 @@ const migrationConfigDefaults = {
3243
3084
  }
3244
3085
  };
3245
3086
  const processRakeDbConfig = (config) => {
3246
- var _a;
3247
- const result = __spreadValues$4(__spreadValues$4({}, migrationConfigDefaults), config);
3087
+ const result = { ...migrationConfigDefaults, ...config };
3248
3088
  if (!result.recurrentPath) {
3249
3089
  result.recurrentPath = path.join(result.migrationsPath, "recurrent");
3250
3090
  }
@@ -3252,7 +3092,7 @@ const processRakeDbConfig = (config) => {
3252
3092
  delete result.logger;
3253
3093
  }
3254
3094
  if (!result.basePath || !result.dbScript) {
3255
- let filePath = (_a = orchidCore.getStackTrace()) == null ? void 0 : _a[3].getFileName();
3095
+ let filePath = orchidCore.getStackTrace()?.[3].getFileName();
3256
3096
  if (!filePath) {
3257
3097
  throw new Error(
3258
3098
  "Failed to determine path to db script. Please set basePath option of rakeDb"
@@ -3282,10 +3122,8 @@ const processRakeDbConfig = (config) => {
3282
3122
  if ("baseTable" in config && config.baseTable) {
3283
3123
  const { types, snakeCase, language } = config.baseTable.prototype;
3284
3124
  result.columnTypes = types || pqb.makeColumnTypes(pqb.defaultSchemaConfig);
3285
- if (snakeCase)
3286
- result.snakeCase = true;
3287
- if (language)
3288
- result.language = language;
3125
+ if (snakeCase) result.snakeCase = true;
3126
+ if (language) result.language = language;
3289
3127
  } else {
3290
3128
  const ct = "columnTypes" in config && config.columnTypes;
3291
3129
  result.columnTypes = (typeof ct === "function" ? ct(
@@ -3356,11 +3194,9 @@ const prompt = async ({
3356
3194
  cursor: showCursor
3357
3195
  }) => {
3358
3196
  stdin.resume();
3359
- if (stdin.isTTY)
3360
- stdin.setRawMode(true);
3197
+ if (stdin.isTTY) stdin.setRawMode(true);
3361
3198
  stdin.setEncoding("utf-8");
3362
- if (!showCursor)
3363
- stdout.write(cursorHide);
3199
+ if (!showCursor) stdout.write(cursorHide);
3364
3200
  return new Promise((res) => {
3365
3201
  let prevText;
3366
3202
  const ctx = {
@@ -3368,16 +3204,13 @@ const prompt = async ({
3368
3204
  submitted: false,
3369
3205
  render() {
3370
3206
  let text = (ctx.submitted ? colors.greenBold("\u2714") : colors.yellowBold("?")) + " " + render(ctx);
3371
- if (ctx.submitted)
3372
- text += "\n";
3207
+ if (ctx.submitted) text += "\n";
3373
3208
  stdout.write(prevText ? clear(prevText) + "\r" + text : text);
3374
3209
  prevText = text;
3375
3210
  },
3376
3211
  submit(value2) {
3377
- if (value2 !== void 0)
3378
- ctx.value = value2;
3379
- if (ctx.value === void 0 || validate && !(validate == null ? void 0 : validate(ctx)))
3380
- return;
3212
+ if (value2 !== void 0) ctx.value = value2;
3213
+ if (ctx.value === void 0 || validate && !validate?.(ctx)) return;
3381
3214
  ctx.submitted = true;
3382
3215
  ctx.render();
3383
3216
  close();
@@ -3385,16 +3218,14 @@ const prompt = async ({
3385
3218
  }
3386
3219
  };
3387
3220
  const close = () => {
3388
- if (!showCursor)
3389
- stdout.write(cursorShow);
3390
- if (stdin.isTTY)
3391
- stdin.setRawMode(false);
3221
+ if (!showCursor) stdout.write(cursorShow);
3222
+ if (stdin.isTTY) stdin.setRawMode(false);
3392
3223
  stdin.off("data", keypress);
3393
3224
  stdin.pause();
3394
3225
  };
3395
3226
  const keypress = (s) => {
3396
3227
  if (s === "" || s === "") {
3397
- close == null ? void 0 : close();
3228
+ close?.();
3398
3229
  process.exit(0);
3399
3230
  }
3400
3231
  if (s === "\r" || s === "\n" || s === "\r\n") {
@@ -3442,10 +3273,8 @@ ${ctx.submitted ? `> ${ctx.value ? colors.greenBold("Yes") : colors.yellowBold("
3442
3273
  },
3443
3274
  onKeyPress(ctx, s) {
3444
3275
  let ok;
3445
- if (s === "y" || s === "Y")
3446
- ok = true;
3447
- else if (s === "n" || s === "N")
3448
- ok = false;
3276
+ if (s === "y" || s === "Y") ok = true;
3277
+ else if (s === "n" || s === "N") ok = false;
3449
3278
  if (ok !== void 0) {
3450
3279
  ctx.submit(ok);
3451
3280
  }
@@ -3467,8 +3296,7 @@ const promptText = ({
3467
3296
  render(ctx) {
3468
3297
  let text = `${colors.bright(message)}
3469
3298
  > ${ctx.submitted ? renderValue(ctx) : showDefault ? colors.pale(def) + "\b".repeat(def.length) : ctx.value}`;
3470
- if (ctx.submitted)
3471
- text += "\n";
3299
+ if (ctx.submitted) text += "\n";
3472
3300
  return text;
3473
3301
  },
3474
3302
  onKeyPress(ctx, s) {
@@ -3480,8 +3308,7 @@ const promptText = ({
3480
3308
  stdout.write(value[x]);
3481
3309
  x++;
3482
3310
  }
3483
- if (s !== "\x7F" && s !== "\x1B[3~" && !visibleChars(s))
3484
- return;
3311
+ if (s !== "\x7F" && s !== "\x1B[3~" && !visibleChars(s)) return;
3485
3312
  if (showDefault) {
3486
3313
  showDefault = false;
3487
3314
  stdout.write(" ".repeat(def.length) + "\b".repeat(def.length));
@@ -3510,25 +3337,6 @@ const promptText = ({
3510
3337
  });
3511
3338
  };
3512
3339
 
3513
- var __defProp$3 = Object.defineProperty;
3514
- var __defProps$2 = Object.defineProperties;
3515
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
3516
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
3517
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
3518
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
3519
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3520
- var __spreadValues$3 = (a, b) => {
3521
- for (var prop in b || (b = {}))
3522
- if (__hasOwnProp$3.call(b, prop))
3523
- __defNormalProp$3(a, prop, b[prop]);
3524
- if (__getOwnPropSymbols$3)
3525
- for (var prop of __getOwnPropSymbols$3(b)) {
3526
- if (__propIsEnum$3.call(b, prop))
3527
- __defNormalProp$3(a, prop, b[prop]);
3528
- }
3529
- return a;
3530
- };
3531
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
3532
3340
  const setAdapterOptions = (options, set) => {
3533
3341
  if (options.databaseURL) {
3534
3342
  const url = new URL(options.databaseURL);
@@ -3541,9 +3349,12 @@ const setAdapterOptions = (options, set) => {
3541
3349
  if (set.password !== void 0) {
3542
3350
  url.password = set.password;
3543
3351
  }
3544
- return __spreadProps$2(__spreadValues$3({}, options), { databaseURL: url.toString() });
3352
+ return { ...options, databaseURL: url.toString() };
3545
3353
  } else {
3546
- return __spreadValues$3(__spreadValues$3({}, options), set);
3354
+ return {
3355
+ ...options,
3356
+ ...set
3357
+ };
3547
3358
  }
3548
3359
  };
3549
3360
  const setAdminCredentialsToOptions = async (options, create) => {
@@ -3590,18 +3401,17 @@ const execute = async (options, sql) => {
3590
3401
  }
3591
3402
  };
3592
3403
  const createOrDrop = async (options, adminOptions, config, args) => {
3593
- var _a, _b, _c, _d;
3594
3404
  const params = getDatabaseAndUserFromOptions(options);
3595
3405
  const result = await execute(
3596
3406
  setAdapterOptions(adminOptions, { database: "postgres" }),
3597
3407
  args.sql(params)
3598
3408
  );
3599
3409
  if (result === "ok") {
3600
- (_a = config.logger) == null ? void 0 : _a.log(args.successMessage(params));
3410
+ config.logger?.log(args.successMessage(params));
3601
3411
  } else if (result === "already") {
3602
- (_b = config.logger) == null ? void 0 : _b.log(args.alreadyMessage(params));
3412
+ config.logger?.log(args.alreadyMessage(params));
3603
3413
  } else if (result === "ssl required") {
3604
- (_c = config.logger) == null ? void 0 : _c.log(
3414
+ config.logger?.log(
3605
3415
  "SSL is required: append ?ssl=true to the database url string"
3606
3416
  );
3607
3417
  return;
@@ -3613,20 +3423,18 @@ const createOrDrop = async (options, adminOptions, config, args) => {
3613
3423
  message += `
3614
3424
  Don't use this command for database service providers, only for a local db.`;
3615
3425
  }
3616
- (_d = config.logger) == null ? void 0 : _d.log(message);
3426
+ config.logger?.log(message);
3617
3427
  const updatedOptions = await setAdminCredentialsToOptions(
3618
3428
  options,
3619
3429
  args.create
3620
3430
  );
3621
- if (!updatedOptions)
3622
- return;
3431
+ if (!updatedOptions) return;
3623
3432
  await createOrDrop(options, updatedOptions, config, args);
3624
3433
  return;
3625
3434
  } else {
3626
3435
  throw result.error;
3627
3436
  }
3628
- if (!args.create)
3629
- return;
3437
+ if (!args.create) return;
3630
3438
  const db = new pqb.Adapter(options);
3631
3439
  await createMigrationsTable(db, config);
3632
3440
  await db.close();
@@ -4048,7 +3856,6 @@ const sql = `SELECT (${schemasSql}) AS "schemas", ${jsonAgg(
4048
3856
  "collations"
4049
3857
  )}`;
4050
3858
  async function introspectDbSchema(db) {
4051
- var _a;
4052
3859
  const data = await db.query(sql);
4053
3860
  const result = data.rows[0];
4054
3861
  for (const domain of result.domains) {
@@ -4057,8 +3864,7 @@ async function introspectDbSchema(db) {
4057
3864
  for (const table of result.tables) {
4058
3865
  for (const column of table.columns) {
4059
3866
  nullsToUndefined(column);
4060
- if (column.identity)
4061
- nullsToUndefined(column.identity);
3867
+ if (column.identity) nullsToUndefined(column.identity);
4062
3868
  if (column.compression) {
4063
3869
  column.compression = column.compression === "p" ? "pglz" : "lz4";
4064
3870
  }
@@ -4067,8 +3873,7 @@ async function introspectDbSchema(db) {
4067
3873
  for (const index of result.indexes) {
4068
3874
  nullsToUndefined(index);
4069
3875
  for (const column of index.columns) {
4070
- if (!("expression" in column))
4071
- continue;
3876
+ if (!("expression" in column)) continue;
4072
3877
  const s = column.expression;
4073
3878
  const columnR = `"?\\w+"?`;
4074
3879
  const langR = `(${columnR}|'\\w+'::regconfig)`;
@@ -4083,16 +3888,15 @@ async function introspectDbSchema(db) {
4083
3888
  const match = s.match(
4084
3889
  new RegExp(`^([\\(]*${setWeightOrTsVectorR}[\\)]*( ${concatR} )?)+$`)
4085
3890
  );
4086
- if (!match)
4087
- continue;
3891
+ if (!match) continue;
4088
3892
  let language;
4089
3893
  let languageColumn;
4090
- const tokens = (_a = match[0].match(
3894
+ const tokens = match[0].match(
4091
3895
  new RegExp(
4092
3896
  `setweight\\(|to_tsvector\\(${langR}|[:']?${columnR}\\(?`,
4093
3897
  "g"
4094
3898
  )
4095
- )) == null ? void 0 : _a.reduce((acc, token) => {
3899
+ )?.reduce((acc, token) => {
4096
3900
  if (token === "setweight(" || token === "COALESCE(" || token[0] === ":")
4097
3901
  return acc;
4098
3902
  if (token.startsWith("to_tsvector(")) {
@@ -4104,14 +3908,12 @@ async function introspectDbSchema(db) {
4104
3908
  } else if (token[0] === "'") {
4105
3909
  acc.push({ kind: "weight", value: token[1] });
4106
3910
  } else {
4107
- if (token[0] === '"')
4108
- token = token.slice(1, -1);
3911
+ if (token[0] === '"') token = token.slice(1, -1);
4109
3912
  acc.push({ kind: "column", value: token });
4110
3913
  }
4111
3914
  return acc;
4112
3915
  }, []);
4113
- if (!tokens)
4114
- continue;
3916
+ if (!tokens) continue;
4115
3917
  index.language = language;
4116
3918
  index.languageColumn = languageColumn;
4117
3919
  index.tsVector = true;
@@ -4136,37 +3938,6 @@ const nullsToUndefined = (obj) => {
4136
3938
  }
4137
3939
  };
4138
3940
 
4139
- var __defProp$2 = Object.defineProperty;
4140
- var __defProps$1 = Object.defineProperties;
4141
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
4142
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
4143
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
4144
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
4145
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4146
- var __spreadValues$2 = (a, b) => {
4147
- for (var prop in b || (b = {}))
4148
- if (__hasOwnProp$2.call(b, prop))
4149
- __defNormalProp$2(a, prop, b[prop]);
4150
- if (__getOwnPropSymbols$2)
4151
- for (var prop of __getOwnPropSymbols$2(b)) {
4152
- if (__propIsEnum$2.call(b, prop))
4153
- __defNormalProp$2(a, prop, b[prop]);
4154
- }
4155
- return a;
4156
- };
4157
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
4158
- var __objRest = (source, exclude) => {
4159
- var target = {};
4160
- for (var prop in source)
4161
- if (__hasOwnProp$2.call(source, prop) && exclude.indexOf(prop) < 0)
4162
- target[prop] = source[prop];
4163
- if (source != null && __getOwnPropSymbols$2)
4164
- for (var prop of __getOwnPropSymbols$2(source)) {
4165
- if (exclude.indexOf(prop) < 0 && __propIsEnum$2.call(source, prop))
4166
- target[prop] = source[prop];
4167
- }
4168
- return target;
4169
- };
4170
3941
  const matchMap = {
4171
3942
  s: void 0,
4172
3943
  f: "FULL",
@@ -4191,8 +3962,7 @@ const structureToAst = async (ctx, adapter, config) => {
4191
3962
  const ast = [];
4192
3963
  const data = await introspectDbSchema(adapter);
4193
3964
  for (const name of data.schemas) {
4194
- if (name === "public")
4195
- continue;
3965
+ if (name === "public") continue;
4196
3966
  ast.push({
4197
3967
  type: "schema",
4198
3968
  action: "create",
@@ -4200,17 +3970,16 @@ const structureToAst = async (ctx, adapter, config) => {
4200
3970
  });
4201
3971
  }
4202
3972
  for (const it of data.collations) {
4203
- ast.push(__spreadProps$1(__spreadValues$2({
3973
+ ast.push({
4204
3974
  type: "collation",
4205
- action: "create"
4206
- }, it), {
3975
+ action: "create",
3976
+ ...it,
4207
3977
  schema: it.schemaName === ctx.currentSchema ? void 0 : it.schemaName
4208
- }));
3978
+ });
4209
3979
  }
4210
3980
  const domains = makeDomainsMap(ctx, data);
4211
3981
  for (const table of data.tables) {
4212
- if (table.name === config.migrationsTable)
4213
- continue;
3982
+ if (table.name === config.migrationsTable) continue;
4214
3983
  ast.push(tableToAst(ctx, data, table, "create", domains));
4215
3984
  }
4216
3985
  for (const it of data.extensions) {
@@ -4243,12 +4012,13 @@ const structureToAst = async (ctx, adapter, config) => {
4243
4012
  for (const table of data.tables) {
4244
4013
  for (const fkey of data.constraints) {
4245
4014
  if (fkey.references && fkey.tableName === table.name && fkey.schemaName === table.schemaName && checkIfIsOuterRecursiveFkey(data, table, fkey.references)) {
4246
- ast.push(__spreadProps$1(__spreadValues$2({}, constraintToAst(ctx, fkey)), {
4015
+ ast.push({
4016
+ ...constraintToAst(ctx, fkey),
4247
4017
  type: "constraint",
4248
4018
  action: "create",
4249
4019
  tableSchema: table.schemaName === ctx.currentSchema ? void 0 : table.schemaName,
4250
4020
  tableName: fkey.tableName
4251
- }));
4021
+ });
4252
4022
  }
4253
4023
  }
4254
4024
  }
@@ -4292,10 +4062,10 @@ const getDbColumnIsSerial = (item) => {
4292
4062
  return false;
4293
4063
  };
4294
4064
  const instantiateDbColumn = (ctx, data, domains, dbColumn) => {
4295
- var _a, _b, _c;
4065
+ var _a, _b;
4296
4066
  const isSerial = getDbColumnIsSerial(dbColumn);
4297
4067
  if (isSerial) {
4298
- dbColumn = __spreadProps$1(__spreadValues$2({}, dbColumn), { default: void 0 });
4068
+ dbColumn = { ...dbColumn, default: void 0 };
4299
4069
  }
4300
4070
  let column;
4301
4071
  const col = instantiateColumnByDbType(ctx, dbColumn.type, isSerial, dbColumn);
@@ -4328,15 +4098,14 @@ const instantiateDbColumn = (ctx, data, domains, dbColumn) => {
4328
4098
  typeId,
4329
4099
  dbColumn.extension
4330
4100
  );
4331
- ((_c = (_a = ctx.unsupportedTypes)[_b = dbColumn.type]) != null ? _c : _a[_b] = []).push(
4101
+ ((_a = ctx.unsupportedTypes)[_b = dbColumn.type] ?? (_a[_b] = [])).push(
4332
4102
  `${dbColumn.schemaName}${dbColumn.tableName ? `.${dbColumn.tableName}` : ""}.${dbColumn.name}`
4333
4103
  );
4334
4104
  }
4335
4105
  }
4336
4106
  }
4337
4107
  column.data.name = void 0;
4338
- if (!column.data.isNullable)
4339
- column.data.isNullable = void 0;
4108
+ if (!column.data.isNullable) column.data.isNullable = void 0;
4340
4109
  if (dbColumn.arrayDims) {
4341
4110
  const arr = new pqb.ArrayColumn(
4342
4111
  ctx.columnSchemaConfig,
@@ -4368,28 +4137,28 @@ const tableToAst = (ctx, data, table, action, domains) => {
4368
4137
  name: tableName,
4369
4138
  shape: makeDbStructureColumnsShape(ctx, data, domains, table, tableData),
4370
4139
  noPrimaryKey: tableData.primaryKey ? "error" : "ignore",
4371
- primaryKey: primaryKey && primaryKey.columns.length > 1 ? __spreadProps$1(__spreadValues$2({}, primaryKey), { columns: primaryKey.columns.map(orchidCore.toCamelCase) }) : void 0,
4140
+ primaryKey: primaryKey && primaryKey.columns.length > 1 ? { ...primaryKey, columns: primaryKey.columns.map(orchidCore.toCamelCase) } : void 0,
4372
4141
  indexes: indexes.reduce((acc, index) => {
4373
- var _b;
4374
4142
  if (index.columns.length > 1 || index.columns.some((it) => "expression" in it)) {
4375
- const _a = makeIndexOptions(tableName, index), { name } = _a, options = __objRest(_a, ["name"]);
4143
+ const { name, ...options } = makeIndexOptions(tableName, index);
4376
4144
  acc.push({
4377
- columns: index.columns.map((it) => __spreadProps$1(__spreadValues$2({}, "column" in it ? { column: orchidCore.toCamelCase(it.column) } : { expression: it.expression }), {
4145
+ columns: index.columns.map((it) => ({
4146
+ ..."column" in it ? { column: orchidCore.toCamelCase(it.column) } : { expression: it.expression },
4378
4147
  collate: it.collate,
4379
4148
  opclass: it.opclass,
4380
4149
  order: it.order
4381
4150
  })),
4382
- options: __spreadProps$1(__spreadValues$2({}, options), {
4383
- include: (_b = index.include) == null ? void 0 : _b.map(orchidCore.toCamelCase)
4384
- }),
4151
+ options: {
4152
+ ...options,
4153
+ include: index.include?.map(orchidCore.toCamelCase)
4154
+ },
4385
4155
  name
4386
4156
  });
4387
4157
  }
4388
4158
  return acc;
4389
4159
  }, []),
4390
4160
  constraints: constraints.reduce((acc, it) => {
4391
- var _a;
4392
- 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)) {
4161
+ if (it.check && it.references || it.check && it.check.columns?.length !== 1 || it.references && it.references.columns.length !== 1 && !checkIfIsOuterRecursiveFkey(data, table, it.references)) {
4393
4162
  acc.push(dbConstraintToTableConstraint(ctx, table, it));
4394
4163
  }
4395
4164
  return acc;
@@ -4402,7 +4171,7 @@ const getDbStructureTableData = (data, { name, schemaName }) => {
4402
4171
  );
4403
4172
  const primaryKey = constraints.find((c) => c.primaryKey);
4404
4173
  return {
4405
- primaryKey: (primaryKey == null ? void 0 : primaryKey.primaryKey) ? {
4174
+ primaryKey: primaryKey?.primaryKey ? {
4406
4175
  columns: primaryKey.primaryKey,
4407
4176
  name: primaryKey.name === `${name}_pkey` ? void 0 : primaryKey.name
4408
4177
  } : void 0,
@@ -4413,7 +4182,6 @@ const getDbStructureTableData = (data, { name, schemaName }) => {
4413
4182
  };
4414
4183
  };
4415
4184
  const constraintToAst = (ctx, item) => {
4416
- var _a;
4417
4185
  const result = {};
4418
4186
  const { references, check } = item;
4419
4187
  if (references) {
@@ -4425,21 +4193,18 @@ const constraintToAst = (ctx, item) => {
4425
4193
  options
4426
4194
  };
4427
4195
  const match = matchMap[references.match];
4428
- if (match)
4429
- options.match = match;
4196
+ if (match) options.match = match;
4430
4197
  const onUpdate = fkeyActionMap[references.onUpdate];
4431
- if (onUpdate)
4432
- options.onUpdate = onUpdate;
4198
+ if (onUpdate) options.onUpdate = onUpdate;
4433
4199
  const onDelete = fkeyActionMap[references.onDelete];
4434
- if (onDelete)
4435
- options.onDelete = onDelete;
4200
+ if (onDelete) options.onDelete = onDelete;
4436
4201
  }
4437
4202
  if (check) {
4438
4203
  result.check = pqb.raw({ raw: check.expression });
4439
4204
  }
4440
4205
  if (item.name && item.name !== getConstraintName(item.tableName, result, ctx.snakeCase)) {
4441
4206
  result.name = item.name;
4442
- if ((_a = result.references) == null ? void 0 : _a.options) {
4207
+ if (result.references?.options) {
4443
4208
  result.references.options.name = item.name;
4444
4209
  }
4445
4210
  }
@@ -4449,14 +4214,12 @@ const getReferencesTable = (ctx, references) => {
4449
4214
  return references.foreignSchema !== ctx.currentSchema ? `${references.foreignSchema}.${references.foreignTable}` : references.foreignTable;
4450
4215
  };
4451
4216
  const isColumnCheck = (it) => {
4452
- var _a, _b;
4453
- return !it.references && ((_b = (_a = it.check) == null ? void 0 : _a.columns) == null ? void 0 : _b.length) === 1;
4217
+ return !it.references && it.check?.columns?.length === 1;
4454
4218
  };
4455
4219
  const viewToAst = (ctx, data, domains, view) => {
4456
4220
  const shape = makeDbStructureColumnsShape(ctx, data, domains, view);
4457
4221
  const options = {};
4458
- if (view.isRecursive)
4459
- options.recursive = true;
4222
+ if (view.isRecursive) options.recursive = true;
4460
4223
  if (view.with) {
4461
4224
  const withOptions = {};
4462
4225
  options.with = withOptions;
@@ -4501,48 +4264,48 @@ const getDbTableColumnsChecks = (tableData) => tableData.constraints.reduce((acc
4501
4264
  return acc;
4502
4265
  }, {});
4503
4266
  const dbColumnToAst = (ctx, data, domains, tableName, item, table, tableData, checks) => {
4504
- var _a, _b, _c, _d, _f, _g, _h, _i, _j;
4267
+ var _a;
4505
4268
  let column = instantiateDbColumn(ctx, data, domains, item);
4506
4269
  column.data.name = item.name;
4507
4270
  if (item.identity) {
4508
4271
  column.data.identity = item.identity;
4509
- if (!item.identity.always)
4510
- (_a = column.data.identity) == null ? true : delete _a.always;
4272
+ if (!item.identity.always) delete column.data.identity?.always;
4511
4273
  }
4512
- 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) {
4274
+ if (tableData?.primaryKey?.columns?.length === 1 && tableData?.primaryKey?.columns[0] === item.name) {
4513
4275
  column = column.primaryKey();
4514
4276
  }
4515
- if (tableData == null ? void 0 : tableData.indexes) {
4516
- const columnIndexes = tableData == null ? void 0 : tableData.indexes.filter(
4277
+ if (tableData?.indexes) {
4278
+ const columnIndexes = tableData?.indexes.filter(
4517
4279
  (it) => it.columns.length === 1 && "column" in it.columns[0] && it.columns[0].column === item.name
4518
4280
  );
4519
4281
  for (const index of columnIndexes) {
4520
4282
  const columnOptions = index.columns[0];
4521
- const _e = makeIndexOptions(tableName, index), { name } = _e, indexOptions = __objRest(_e, ["name"]);
4522
- ((_g = (_f = column.data).indexes) != null ? _g : _f.indexes = []).push({
4523
- options: __spreadValues$2({
4283
+ const { name, ...indexOptions } = makeIndexOptions(tableName, index);
4284
+ ((_a = column.data).indexes ?? (_a.indexes = [])).push({
4285
+ options: {
4524
4286
  collate: columnOptions.collate,
4525
4287
  opclass: columnOptions.opclass,
4526
- order: columnOptions.order
4527
- }, indexOptions),
4288
+ order: columnOptions.order,
4289
+ ...indexOptions
4290
+ },
4528
4291
  name
4529
4292
  });
4530
4293
  }
4531
4294
  }
4532
4295
  if (table) {
4533
4296
  for (const it of data.constraints) {
4534
- if (it.tableName !== table.name || it.schemaName !== table.schemaName || it.check || ((_h = it.references) == null ? void 0 : _h.columns.length) !== 1 || it.references.columns[0] !== item.name || checkIfIsOuterRecursiveFkey(data, table, it.references)) {
4297
+ if (it.tableName !== table.name || it.schemaName !== table.schemaName || it.check || it.references?.columns.length !== 1 || it.references.columns[0] !== item.name || checkIfIsOuterRecursiveFkey(data, table, it.references)) {
4535
4298
  continue;
4536
4299
  }
4537
4300
  const c = dbConstraintToTableConstraint(ctx, table, it);
4538
4301
  column = column.foreignKey(
4539
- (_i = c.references) == null ? void 0 : _i.fnOrTable,
4302
+ c.references?.fnOrTable,
4540
4303
  it.references.foreignColumns[0],
4541
- (_j = c.references) == null ? void 0 : _j.options
4304
+ c.references?.options
4542
4305
  );
4543
4306
  }
4544
4307
  }
4545
- const check = checks == null ? void 0 : checks[item.name];
4308
+ const check = checks?.[item.name];
4546
4309
  if (check) {
4547
4310
  column.data.check = {
4548
4311
  sql: new pqb.RawSQL([[check]])
@@ -4551,15 +4314,13 @@ const dbColumnToAst = (ctx, data, domains, tableName, item, table, tableData, ch
4551
4314
  const camelCaseName = orchidCore.toCamelCase(item.name);
4552
4315
  if (ctx.snakeCase) {
4553
4316
  const snakeCaseName = orchidCore.toSnakeCase(camelCaseName);
4554
- if (snakeCaseName !== item.name)
4555
- column.data.name = item.name;
4317
+ if (snakeCaseName !== item.name) column.data.name = item.name;
4556
4318
  } else if (camelCaseName !== item.name) {
4557
4319
  column.data.name = item.name;
4558
4320
  }
4559
4321
  return [camelCaseName, column];
4560
4322
  };
4561
4323
  const dbConstraintToTableConstraint = (ctx, table, item) => {
4562
- var _a;
4563
4324
  const { references, check } = item;
4564
4325
  const constraint = {
4565
4326
  references: references ? {
@@ -4577,7 +4338,7 @@ const dbConstraintToTableConstraint = (ctx, table, item) => {
4577
4338
  const name = item.name && item.name !== getConstraintName(table.name, constraint, ctx.snakeCase) ? item.name : void 0;
4578
4339
  if (name) {
4579
4340
  constraint.name = name;
4580
- if ((_a = constraint.references) == null ? void 0 : _a.options) {
4341
+ if (constraint.references?.options) {
4581
4342
  constraint.references.options.name = name;
4582
4343
  }
4583
4344
  }
@@ -4596,14 +4357,13 @@ const makeIndexOptions = (tableName, index) => {
4596
4357
  };
4597
4358
  };
4598
4359
  const checkIfIsOuterRecursiveFkey = (data, table, references) => {
4599
- var _a;
4600
4360
  const referencesId = `${references.foreignSchema}.${references.foreignTable}`;
4601
4361
  const tableId = `${table.schemaName}.${table.name}`;
4602
4362
  for (const other of data.tables) {
4603
4363
  const id = `${other.schemaName}.${other.name}`;
4604
4364
  if (referencesId === id) {
4605
4365
  for (const c of data.constraints) {
4606
- 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) {
4366
+ if (c.tableName === other.name && c.schemaName === other.schemaName && c.references?.foreignTable === table.name && c.references.foreignSchema === table.schemaName && tableId < id) {
4607
4367
  return true;
4608
4368
  }
4609
4369
  }
@@ -4617,7 +4377,6 @@ const astToGenerateItems = (config, asts, currentSchema) => {
4617
4377
  return asts.map((ast) => astToGenerateItem(config, ast, currentSchema));
4618
4378
  };
4619
4379
  const astToGenerateItem = (config, ast, currentSchema) => {
4620
- var _a, _b, _c, _d, _e;
4621
4380
  const add = [];
4622
4381
  const drop = [];
4623
4382
  const deps = [];
@@ -4635,7 +4394,7 @@ const astToGenerateItem = (config, ast, currentSchema) => {
4635
4394
  case "table":
4636
4395
  case "changeTable":
4637
4396
  case "view": {
4638
- const schema = (_a = ast.schema) != null ? _a : currentSchema;
4397
+ const schema = ast.schema ?? currentSchema;
4639
4398
  const table = `${schema}.${ast.name}`;
4640
4399
  if (ast.type === "table" || ast.type === "view") {
4641
4400
  const keys = ast.action === "create" ? add : drop;
@@ -4733,7 +4492,7 @@ const astToGenerateItem = (config, ast, currentSchema) => {
4733
4492
  case "enum":
4734
4493
  case "collation":
4735
4494
  case "extension": {
4736
- const schema = (_b = ast.schema) != null ? _b : currentSchema;
4495
+ const schema = ast.schema ?? currentSchema;
4737
4496
  (ast.action === "create" ? add : drop).push(`${schema}.${ast.name}`);
4738
4497
  deps.push(schema);
4739
4498
  break;
@@ -4741,22 +4500,21 @@ const astToGenerateItem = (config, ast, currentSchema) => {
4741
4500
  case "enumValues":
4742
4501
  case "renameEnumValues":
4743
4502
  case "changeEnumValues": {
4744
- const schema = (_c = ast.schema) != null ? _c : currentSchema;
4503
+ const schema = ast.schema ?? currentSchema;
4745
4504
  deps.push(schema, `${schema}.${ast.name}`);
4746
4505
  break;
4747
4506
  }
4748
4507
  case "domain": {
4749
- const schema = (_d = ast.schema) != null ? _d : currentSchema;
4508
+ const schema = ast.schema ?? currentSchema;
4750
4509
  (ast.action === "create" ? add : drop).push(`${schema}.${ast.name}`);
4751
4510
  const column = ast.baseType;
4752
4511
  deps.push(schema, resolveType(column.dataType));
4753
- if (column.data.collate)
4754
- deps.push(column.data.collate);
4512
+ if (column.data.collate) deps.push(column.data.collate);
4755
4513
  break;
4756
4514
  }
4757
4515
  case "constraint": {
4758
4516
  const { tableSchema = currentSchema, tableName } = ast;
4759
- const name = `${tableSchema}.${(_e = ast.name) != null ? _e : getConstraintName(tableName, ast, config.snakeCase)}`;
4517
+ const name = `${tableSchema}.${ast.name ?? getConstraintName(tableName, ast, config.snakeCase)}`;
4760
4518
  (ast.action === "create" ? add : drop).push(name);
4761
4519
  deps.push(tableSchema, `${tableSchema}.${tableName}`);
4762
4520
  break;
@@ -4779,7 +4537,6 @@ const astToGenerateItem = (config, ast, currentSchema) => {
4779
4537
  };
4780
4538
  };
4781
4539
  const analyzeTableColumns = (config, currentSchema, schema, table, deps, resolveType, columns) => {
4782
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
4783
4540
  for (const [keys, name, change] of columns) {
4784
4541
  const { column } = change;
4785
4542
  if (column) {
@@ -4797,31 +4554,30 @@ const analyzeTableColumns = (config, currentSchema, schema, table, deps, resolve
4797
4554
  } else if (change.type) {
4798
4555
  deps.push(resolveType(change.type));
4799
4556
  }
4800
- const collate = (_b = (_a = change.column) == null ? void 0 : _a.data.collate) != null ? _b : change.collate;
4801
- if (collate)
4802
- deps.push(collate);
4803
- const primaryKey = change.primaryKey || ((_c = change.column) == null ? void 0 : _c.data.primaryKey);
4557
+ const collate = change.column?.data.collate ?? change.collate;
4558
+ if (collate) deps.push(collate);
4559
+ const primaryKey = change.primaryKey || change.column?.data.primaryKey;
4804
4560
  if (primaryKey) {
4805
4561
  keys.push(`${table}_pkey`);
4806
4562
  }
4807
- const indexes = change.indexes || ((_d = change.column) == null ? void 0 : _d.data.indexes);
4563
+ const indexes = change.indexes || change.column?.data.indexes;
4808
4564
  if (indexes) {
4809
4565
  for (const index of indexes) {
4810
4566
  keys.push(
4811
4567
  index.name ? `${schema}.${index.name}` : getIndexName(table, [
4812
- { column: (_f = (_e = change.column) == null ? void 0 : _e.data.name) != null ? _f : name }
4568
+ { column: change.column?.data.name ?? name }
4813
4569
  ])
4814
4570
  );
4815
4571
  }
4816
4572
  }
4817
- const foreignKeys = change.foreignKeys || ((_g = change.column) == null ? void 0 : _g.data.foreignKeys);
4573
+ const foreignKeys = change.foreignKeys || change.column?.data.foreignKeys;
4818
4574
  if (foreignKeys) {
4819
4575
  for (const fkey of foreignKeys) {
4820
4576
  keys.push(
4821
- ((_h = fkey.options) == null ? void 0 : _h.name) ? `${schema}.${fkey.options.name}` : getConstraintName(
4577
+ fkey.options?.name ? `${schema}.${fkey.options.name}` : getConstraintName(
4822
4578
  table,
4823
4579
  {
4824
- references: { columns: [(_j = (_i = change.column) == null ? void 0 : _i.data.name) != null ? _j : name] }
4580
+ references: { columns: [change.column?.data.name ?? name] }
4825
4581
  },
4826
4582
  config.snakeCase
4827
4583
  )
@@ -4860,7 +4616,6 @@ const analyzeTableData = (config, currentSchema, schema, table, keys, deps, data
4860
4616
  };
4861
4617
 
4862
4618
  const astToMigration = (currentSchema, config, asts) => {
4863
- var _a, _b, _c;
4864
4619
  const items = astToGenerateItems(config, asts, currentSchema);
4865
4620
  const toBeAdded = /* @__PURE__ */ new Set();
4866
4621
  const toBeDropped = /* @__PURE__ */ new Set();
@@ -4881,12 +4636,11 @@ const astToMigration = (currentSchema, config, asts) => {
4881
4636
  }
4882
4637
  }
4883
4638
  for (const dep of item.deps) {
4884
- remainingDeps.set(dep, ((_a = remainingDeps.get(dep)) != null ? _a : 0) + 1);
4639
+ remainingDeps.set(dep, (remainingDeps.get(dep) ?? 0) + 1);
4885
4640
  }
4886
4641
  }
4887
4642
  let len = items.length;
4888
- if (!len)
4889
- return;
4643
+ if (!len) return;
4890
4644
  for (; ; ) {
4891
4645
  for (let i = 0; i < items.length; i++) {
4892
4646
  const item = items[i];
@@ -4921,7 +4675,7 @@ const astToMigration = (currentSchema, config, asts) => {
4921
4675
  cycleDrop.add(key);
4922
4676
  }
4923
4677
  for (const key of item.deps) {
4924
- cycleDeps.set(key, ((_b = cycleDeps.get(key)) != null ? _b : 0) + 1);
4678
+ cycleDeps.set(key, (cycleDeps.get(key) ?? 0) + 1);
4925
4679
  }
4926
4680
  items.splice(i, 1);
4927
4681
  i--;
@@ -4951,19 +4705,15 @@ const astToMigration = (currentSchema, config, asts) => {
4951
4705
  dropped.add(drop);
4952
4706
  }
4953
4707
  for (const [key, num] of cycleDeps) {
4954
- const set = ((_c = remainingDeps.get(key)) != null ? _c : num) - num;
4955
- if (set)
4956
- remainingDeps.set(key, set);
4957
- else
4958
- remainingDeps.delete(key);
4708
+ const set = (remainingDeps.get(key) ?? num) - num;
4709
+ if (set) remainingDeps.set(key, set);
4710
+ else remainingDeps.delete(key);
4959
4711
  }
4960
4712
  len = items.length;
4961
- if (!len)
4962
- break;
4713
+ if (!len) break;
4963
4714
  groups.push([]);
4964
4715
  }
4965
- if (!groups[0].length)
4966
- return;
4716
+ if (!groups[0].length) return;
4967
4717
  let code = "";
4968
4718
  for (const group of groups) {
4969
4719
  code += `
@@ -4982,12 +4732,11 @@ ${group.map(
4982
4732
  };
4983
4733
  const astEncoders = {
4984
4734
  table(ast, config) {
4985
- var _a, _b;
4986
4735
  let code = [];
4987
4736
  const result = code;
4988
4737
  const hasOptions = Boolean(ast.comment || ast.noPrimaryKey === "ignore");
4989
4738
  const hasTableData = Boolean(
4990
- ast.primaryKey || ((_a = ast.indexes) == null ? void 0 : _a.length) || ((_b = ast.constraints) == null ? void 0 : _b.length)
4739
+ ast.primaryKey || ast.indexes?.length || ast.constraints?.length
4991
4740
  );
4992
4741
  const isShifted = hasOptions || hasTableData;
4993
4742
  if (isShifted) {
@@ -4999,8 +4748,7 @@ const astEncoders = {
4999
4748
  const options = [];
5000
4749
  if (ast.comment)
5001
4750
  options.push(`comment: ${JSON.stringify(ast.comment)},`);
5002
- if (ast.noPrimaryKey === "ignore")
5003
- options.push(`noPrimaryKey: true,`);
4751
+ if (ast.noPrimaryKey === "ignore") options.push(`noPrimaryKey: true,`);
5004
4752
  code.push("{", options, "},");
5005
4753
  }
5006
4754
  code.push("(t) => ({");
@@ -5036,8 +4784,7 @@ const astEncoders = {
5036
4784
  }
5037
4785
  if (isShifted) {
5038
4786
  orchidCore.addCode(code, "}),");
5039
- if (hasTableData)
5040
- pqb.pushTableDataCode(code, ast);
4787
+ if (hasTableData) pqb.pushTableDataCode(code, ast);
5041
4788
  orchidCore.addCode(result, ");");
5042
4789
  } else {
5043
4790
  orchidCore.addCode(result, "}));");
@@ -5045,7 +4792,6 @@ const astEncoders = {
5045
4792
  return result;
5046
4793
  },
5047
4794
  changeTable(ast, config, currentSchema) {
5048
- var _a;
5049
4795
  let code = [];
5050
4796
  const result = code;
5051
4797
  const schemaTable = quoteSchemaTable({
@@ -5066,13 +4812,10 @@ const astEncoders = {
5066
4812
  orchidCore.addCode(code, `await db.changeTable(${schemaTable}, (t) => ({`);
5067
4813
  }
5068
4814
  const [addTimestamps, dropTimestamps] = ["add", "drop"].map(
5069
- (type) => {
5070
- var _a2, _b;
5071
- return getHasTimestamps(
5072
- ast.shape.createdAt && "type" in ast.shape.createdAt && ((_a2 = ast.shape.createdAt) == null ? void 0 : _a2.type) === type ? ast.shape.createdAt.item : void 0,
5073
- ast.shape.updatedAt && "type" in ast.shape.updatedAt && ((_b = ast.shape.updatedAt) == null ? void 0 : _b.type) === type ? ast.shape.updatedAt.item : void 0
5074
- );
5075
- }
4815
+ (type) => getHasTimestamps(
4816
+ ast.shape.createdAt && "type" in ast.shape.createdAt && ast.shape.createdAt?.type === type ? ast.shape.createdAt.item : void 0,
4817
+ ast.shape.updatedAt && "type" in ast.shape.updatedAt && ast.shape.updatedAt?.type === type ? ast.shape.updatedAt.item : void 0
4818
+ )
5076
4819
  );
5077
4820
  const toCodeCtx = {
5078
4821
  t: "t",
@@ -5089,21 +4832,19 @@ const astEncoders = {
5089
4832
  const recreate = changes.length > 1;
5090
4833
  const line = [
5091
4834
  recreate ? `...t.${change.type}(t.name(${orchidCore.singleQuote(
5092
- (_a = change.item.data.name) != null ? _a : key
4835
+ change.item.data.name ?? key
5093
4836
  )})` : `${orchidCore.quoteObjectKey(key)}: t.${change.type}(`
5094
4837
  ];
5095
4838
  const columnCode = change.item.toCode(toCodeCtx, key);
5096
4839
  for (let i = 0; i < columnCode.length; i++) {
5097
4840
  let part = columnCode[i];
5098
- if (recreate && !i)
5099
- part = part.slice(1);
4841
+ if (recreate && !i) part = part.slice(1);
5100
4842
  orchidCore.addCode(line, part);
5101
4843
  }
5102
4844
  orchidCore.addCode(line, "),");
5103
4845
  code.push(line);
5104
4846
  } else if (change.type === "change") {
5105
- if (!change.from.column || !change.to.column)
5106
- continue;
4847
+ if (!change.from.column || !change.to.column) continue;
5107
4848
  const line = [
5108
4849
  `${orchidCore.quoteObjectKey(key)}: t${change.name ? `.name(${orchidCore.singleQuote(change.name)})` : ""}.change(`
5109
4850
  ];
@@ -5182,15 +4923,14 @@ const astEncoders = {
5182
4923
  return result;
5183
4924
  },
5184
4925
  renameType(ast, _, currentSchema) {
5185
- var _a, _b;
5186
4926
  const code = [];
5187
4927
  const kind = ast.kind === "TABLE" ? "Table" : "Type";
5188
4928
  if (ast.from === ast.to) {
5189
4929
  orchidCore.addCode(
5190
4930
  code,
5191
4931
  `await db.change${kind}Schema(${orchidCore.singleQuote(ast.to)}, ${orchidCore.singleQuote(
5192
- (_a = ast.fromSchema) != null ? _a : currentSchema
5193
- )}, ${orchidCore.singleQuote((_b = ast.toSchema) != null ? _b : currentSchema)});`
4932
+ ast.fromSchema ?? currentSchema
4933
+ )}, ${orchidCore.singleQuote(ast.toSchema ?? currentSchema)});`
5194
4934
  );
5195
4935
  } else {
5196
4936
  orchidCore.addCode(
@@ -5244,28 +4984,21 @@ const astEncoders = {
5244
4984
  )}, [${ast.fromValues.map(orchidCore.singleQuote).join(", ")}], [${ast.toValues.map(orchidCore.singleQuote).join(", ")}]);`;
5245
4985
  },
5246
4986
  domain(ast) {
5247
- var _a;
5248
4987
  return `await db.${ast.action}Domain(${quoteSchemaTable(
5249
4988
  ast
5250
4989
  )}, (t) => ${ast.baseType.toCode(
5251
4990
  { t: "t", table: ast.name },
5252
- (_a = ast.baseType.data.name) != null ? _a : ""
4991
+ ast.baseType.data.name ?? ""
5253
4992
  )});`;
5254
4993
  },
5255
4994
  collation(ast) {
5256
4995
  const params = [];
5257
- if (ast.locale)
5258
- params.push(`locale: '${ast.locale}',`);
5259
- if (ast.lcCollate)
5260
- params.push(`lcCollate: '${ast.lcCollate}',`);
5261
- if (ast.lcCType)
5262
- params.push(`lcCType: '${ast.lcCType}',`);
5263
- if (ast.provider)
5264
- params.push(`provider: '${ast.provider}',`);
5265
- if (ast.deterministic)
5266
- params.push(`deterministic: ${ast.deterministic},`);
5267
- if (ast.version)
5268
- params.push(`version: '${ast.version}',`);
4996
+ if (ast.locale) params.push(`locale: '${ast.locale}',`);
4997
+ if (ast.lcCollate) params.push(`lcCollate: '${ast.lcCollate}',`);
4998
+ if (ast.lcCType) params.push(`lcCType: '${ast.lcCType}',`);
4999
+ if (ast.provider) params.push(`provider: '${ast.provider}',`);
5000
+ if (ast.deterministic) params.push(`deterministic: ${ast.deterministic},`);
5001
+ if (ast.version) params.push(`version: '${ast.version}',`);
5269
5002
  return [
5270
5003
  `await db.createCollation(${quoteSchemaTable(ast)}, {`,
5271
5004
  params,
@@ -5300,14 +5033,12 @@ const astEncoders = {
5300
5033
  view(ast) {
5301
5034
  const code = [`await db.createView(${quoteSchemaTable(ast)}`];
5302
5035
  const options = [];
5303
- if (ast.options.recursive)
5304
- options.push("recursive: true,");
5036
+ if (ast.options.recursive) options.push("recursive: true,");
5305
5037
  const w = ast.options.with;
5306
- if (w == null ? void 0 : w.checkOption)
5307
- options.push(`checkOption: '${w.checkOption}',`);
5308
- if (w == null ? void 0 : w.securityBarrier)
5038
+ if (w?.checkOption) options.push(`checkOption: '${w.checkOption}',`);
5039
+ if (w?.securityBarrier)
5309
5040
  options.push(`securityBarrier: ${w.securityBarrier},`);
5310
- if (w == null ? void 0 : w.securityInvoker)
5041
+ if (w?.securityInvoker)
5311
5042
  options.push(`securityInvoker: ${w.securityInvoker},`);
5312
5043
  if (options.length) {
5313
5044
  orchidCore.addCode(code, ", {");
@@ -5337,8 +5068,7 @@ const astEncoders = {
5337
5068
  }
5338
5069
  };
5339
5070
  const isTimestamp = (column, type) => {
5340
- if (!column)
5341
- return false;
5071
+ if (!column) return false;
5342
5072
  const { default: def } = column.data;
5343
5073
  return Boolean(
5344
5074
  column instanceof type && !column.data.isNullable && def && typeof def === "object" && orchidCore.isRawSQL(def) && (typeof def._sql === "object" ? def._sql[0][0] : def._sql) === "now()"
@@ -5357,7 +5087,7 @@ const getHasTimestamps = (createdAt, updatedAt) => {
5357
5087
  };
5358
5088
  };
5359
5089
  const getTimestampsInfo = (createdAt, updatedAt, type) => {
5360
- return isTimestamp(createdAt, type) && isTimestamp(updatedAt, type) && (!(createdAt == null ? void 0 : createdAt.data.name) || (createdAt == null ? void 0 : createdAt.data.name) === "created_at") && (!(updatedAt == null ? void 0 : updatedAt.data.name) || (updatedAt == null ? void 0 : updatedAt.data.name) === "updated_at");
5090
+ return isTimestamp(createdAt, type) && isTimestamp(updatedAt, type) && (!createdAt?.data.name || createdAt?.data.name === "created_at") && (!updatedAt?.data.name || updatedAt?.data.name === "updated_at");
5361
5091
  };
5362
5092
  const timestampsToCode = ({ hasTZTimestamps }) => {
5363
5093
  const key = hasTZTimestamps ? "timestamps" : "timestampsNoTZ";
@@ -5365,15 +5095,13 @@ const timestampsToCode = ({ hasTZTimestamps }) => {
5365
5095
  };
5366
5096
 
5367
5097
  const pullDbStructure = async (options, config) => {
5368
- var _a, _b;
5369
5098
  const adapter = new pqb.Adapter(options);
5370
5099
  const currentSchema = adapter.schema || "public";
5371
5100
  const ctx = makeStructureToAstCtx(config, currentSchema);
5372
5101
  const ast = await structureToAst(ctx, adapter, config);
5373
5102
  await adapter.close();
5374
5103
  const result = astToMigration(currentSchema, config, ast);
5375
- if (!result)
5376
- return;
5104
+ if (!result) return;
5377
5105
  const version = await makeFileVersion({}, config);
5378
5106
  await writeMigrationFile(config, version, "pull", result);
5379
5107
  const silentQueries = Object.assign(adapter, {
@@ -5385,7 +5113,7 @@ const pullDbStructure = async (options, config) => {
5385
5113
  const len = unsupportedEntries.length;
5386
5114
  if (len) {
5387
5115
  let count = 0;
5388
- (_a = config.logger) == null ? void 0 : _a.warn(
5116
+ config.logger?.warn(
5389
5117
  `Found unsupported types:
5390
5118
  ${unsupportedEntries.map(([type, columns]) => {
5391
5119
  count += columns.length;
@@ -5394,17 +5122,16 @@ ${unsupportedEntries.map(([type, columns]) => {
5394
5122
  Append \`as\` method manually to ${count > 1 ? "these" : "this"} column${count > 1 ? "s" : ""} to treat ${count > 1 ? "them" : "it"} as other column type`
5395
5123
  );
5396
5124
  }
5397
- (_b = config.logger) == null ? void 0 : _b.log("Database pulled successfully");
5125
+ config.logger?.log("Database pulled successfully");
5398
5126
  adapter.close();
5399
5127
  };
5400
5128
 
5401
5129
  const runRecurrentMigrations = async (options, config) => {
5402
- var _a;
5403
5130
  let dbs;
5404
5131
  let files = 0;
5405
5132
  await readdirRecursive(config.recurrentPath, async (path) => {
5406
5133
  files++;
5407
- dbs != null ? dbs : dbs = options.map((opts) => pqb.createDb({ adapter: new pqb.Adapter(opts) }));
5134
+ dbs ?? (dbs = options.map((opts) => pqb.createDb({ adapter: new pqb.Adapter(opts) })));
5408
5135
  const sql = await fs.readFile(path, "utf-8");
5409
5136
  await Promise.all(
5410
5137
  dbs.map(async (db) => {
@@ -5415,7 +5142,7 @@ const runRecurrentMigrations = async (options, config) => {
5415
5142
  if (dbs) {
5416
5143
  await Promise.all(dbs.map((db) => db.close()));
5417
5144
  if (files > 0) {
5418
- (_a = config.logger) == null ? void 0 : _a.log(
5145
+ config.logger?.log(
5419
5146
  `Applied ${files} recurrent migration file${files > 1 ? "s" : ""}`
5420
5147
  );
5421
5148
  }
@@ -5423,12 +5150,10 @@ const runRecurrentMigrations = async (options, config) => {
5423
5150
  };
5424
5151
  const readdirRecursive = async (dirPath, cb) => {
5425
5152
  const list = await fs.readdir(dirPath).catch((err) => {
5426
- if (err.code !== "ENOENT")
5427
- throw err;
5153
+ if (err.code !== "ENOENT") throw err;
5428
5154
  return;
5429
5155
  });
5430
- if (!list)
5431
- return;
5156
+ if (!list) return;
5432
5157
  await Promise.all(
5433
5158
  list.map(async (item) => {
5434
5159
  const path$1 = path.join(dirPath, item);
@@ -5443,7 +5168,6 @@ const readdirRecursive = async (dirPath, cb) => {
5443
5168
  };
5444
5169
 
5445
5170
  const listMigrationsStatuses = async (options, config, args) => {
5446
- var _a;
5447
5171
  const adapters = options.map((opts) => new pqb.Adapter(opts));
5448
5172
  const ctx = {};
5449
5173
  const [{ migrations }, ...migrated] = await Promise.all([
@@ -5524,7 +5248,7 @@ ${migration.url}
5524
5248
  return log2 += showUrl ? lineSeparator : `
5525
5249
  ${lineSeparator}`;
5526
5250
  }).join("\n\n");
5527
- ((_a = config.logger) != null ? _a : console).log(log);
5251
+ (config.logger ?? console).log(log);
5528
5252
  await Promise.all(adapters.map((adapter) => adapter.close()));
5529
5253
  };
5530
5254
  const makeChars = (count, char) => {
@@ -5535,27 +5259,7 @@ const makeChars = (count, char) => {
5535
5259
  return chars;
5536
5260
  };
5537
5261
 
5538
- var __defProp$1 = Object.defineProperty;
5539
- var __defProps = Object.defineProperties;
5540
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
5541
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
5542
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
5543
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
5544
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5545
- var __spreadValues$1 = (a, b) => {
5546
- for (var prop in b || (b = {}))
5547
- if (__hasOwnProp$1.call(b, prop))
5548
- __defNormalProp$1(a, prop, b[prop]);
5549
- if (__getOwnPropSymbols$1)
5550
- for (var prop of __getOwnPropSymbols$1(b)) {
5551
- if (__propIsEnum$1.call(b, prop))
5552
- __defNormalProp$1(a, prop, b[prop]);
5553
- }
5554
- return a;
5555
- };
5556
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
5557
5262
  const rebase = async (options, config) => {
5558
- var _a, _b;
5559
5263
  if (config.migrations) {
5560
5264
  throw new Error("Cannot rebase migrations defined in the config");
5561
5265
  }
@@ -5571,24 +5275,23 @@ const rebase = async (options, config) => {
5571
5275
  ...adapters.map((adapter) => getMigratedVersionsMap(ctx, adapter, config))
5572
5276
  ]);
5573
5277
  await Promise.all(adapters.map((adapter) => adapter.close()));
5574
- const files = set.migrations.map((file) => __spreadProps(__spreadValues$1({}, file), {
5278
+ const files = set.migrations.map((file) => ({
5279
+ ...file,
5575
5280
  name: path.basename(file.path),
5576
5281
  serial: +file.version
5577
5282
  }));
5578
- if (!files.length)
5579
- return;
5283
+ if (!files.length) return;
5580
5284
  const start = files.findIndex(
5581
5285
  (file, i) => i !== 0 && file.serial === files[i - 1].serial
5582
5286
  );
5583
- if (start === -1)
5584
- return;
5287
+ if (start === -1) return;
5585
5288
  const combinedVersionsMap = {};
5586
5289
  for (const versions of versionMaps) {
5587
5290
  Object.assign(combinedVersionsMap, versions.map);
5588
5291
  }
5589
5292
  const renames = [];
5590
5293
  const renamesMap = {};
5591
- let minVersionToMigrate = (_b = (_a = files.find((file) => !combinedVersionsMap[file.version])) == null ? void 0 : _a.serial) != null ? _b : Infinity;
5294
+ let minVersionToMigrate = files.find((file) => !combinedVersionsMap[file.version])?.serial ?? Infinity;
5592
5295
  const migratedFiles = [];
5593
5296
  let maxNewVersion = 0;
5594
5297
  let move = 0;
@@ -5623,11 +5326,9 @@ const rebase = async (options, config) => {
5623
5326
  let newVersion = file.serial;
5624
5327
  if (move) {
5625
5328
  newVersion += move;
5626
- if (moveFile === prev && !renamesMap[prev.path])
5627
- newVersion--;
5329
+ if (moveFile === prev && !renamesMap[prev.path]) newVersion--;
5628
5330
  if (file.serial !== newVersion) {
5629
- if (newVersion < minVersionToMigrate)
5630
- minVersionToMigrate = newVersion;
5331
+ if (newVersion < minVersionToMigrate) minVersionToMigrate = newVersion;
5631
5332
  const values = [file.path, newVersion];
5632
5333
  renames.push(values);
5633
5334
  renamesMap[file.path] = values;
@@ -5643,8 +5344,7 @@ const rebase = async (options, config) => {
5643
5344
  const rename = renames[i2];
5644
5345
  rename[1]--;
5645
5346
  renames[i2] = item;
5646
- if (rename[0] === prev.path)
5647
- break;
5347
+ if (rename[0] === prev.path) break;
5648
5348
  renamesMap[item[0]] = item;
5649
5349
  item = rename;
5650
5350
  }
@@ -5658,8 +5358,7 @@ const rebase = async (options, config) => {
5658
5358
  maxNewVersion = newVersion;
5659
5359
  }
5660
5360
  }
5661
- if (!renames.length && !migratedFiles.length)
5662
- return;
5361
+ if (!renames.length && !migratedFiles.length) return;
5663
5362
  maxNewVersion++;
5664
5363
  renames.push(
5665
5364
  ...migratedFiles.map((file, i) => {
@@ -5668,8 +5367,7 @@ const rebase = async (options, config) => {
5668
5367
  return rename;
5669
5368
  })
5670
5369
  );
5671
- if (!renames.length)
5672
- return;
5370
+ if (!renames.length) return;
5673
5371
  const migrationsDown = files.filter(
5674
5372
  (file) => combinedVersionsMap[file.version] === file.name && file.serial >= minVersionToMigrate
5675
5373
  );
@@ -5677,13 +5375,14 @@ const rebase = async (options, config) => {
5677
5375
  const rename = renamesMap[file.path];
5678
5376
  if (rename) {
5679
5377
  const version = String(rename[1]).padStart(4, "0");
5680
- files2.push(__spreadProps(__spreadValues$1({}, file), {
5378
+ files2.push({
5379
+ ...file,
5681
5380
  path: path.join(
5682
5381
  path.dirname(rename[0]),
5683
5382
  version + path.basename(rename[0]).slice(version.length)
5684
5383
  ),
5685
5384
  version
5686
- }));
5385
+ });
5687
5386
  } else if (!combinedVersionsMap[file.version] || file.serial >= minVersionToMigrate) {
5688
5387
  files2.push(file);
5689
5388
  }
@@ -5693,14 +5392,15 @@ const rebase = async (options, config) => {
5693
5392
  await redo(
5694
5393
  ctx,
5695
5394
  options,
5696
- __spreadProps(__spreadValues$1({}, config), {
5395
+ {
5396
+ ...config,
5697
5397
  async afterRollback() {
5698
5398
  set.migrations = migrationsUp;
5699
5399
  },
5700
5400
  async afterMigrate() {
5701
5401
  set.migrations = migrationsDown;
5702
5402
  }
5703
- }),
5403
+ },
5704
5404
  ["all"]
5705
5405
  );
5706
5406
  for (let i = renames.length - 1; i >= 0; i--) {
@@ -5716,22 +5416,6 @@ const rebase = async (options, config) => {
5716
5416
  }
5717
5417
  };
5718
5418
 
5719
- var __defProp = Object.defineProperty;
5720
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5721
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5722
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
5723
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5724
- var __spreadValues = (a, b) => {
5725
- for (var prop in b || (b = {}))
5726
- if (__hasOwnProp.call(b, prop))
5727
- __defNormalProp(a, prop, b[prop]);
5728
- if (__getOwnPropSymbols)
5729
- for (var prop of __getOwnPropSymbols(b)) {
5730
- if (__propIsEnum.call(b, prop))
5731
- __defNormalProp(a, prop, b[prop]);
5732
- }
5733
- return a;
5734
- };
5735
5419
  const rakeDb = (options, partialConfig, args = process.argv.slice(2)) => {
5736
5420
  const config = processRakeDbConfig(partialConfig);
5737
5421
  const promise = runCommand(
@@ -5739,9 +5423,8 @@ const rakeDb = (options, partialConfig, args = process.argv.slice(2)) => {
5739
5423
  config,
5740
5424
  args
5741
5425
  ).catch((err) => {
5742
- var _a;
5743
5426
  if (err instanceof RakeDbError) {
5744
- (_a = config.logger) == null ? void 0 : _a.error(err.message);
5427
+ config.logger?.error(err.message);
5745
5428
  process.exit(1);
5746
5429
  }
5747
5430
  throw err;
@@ -5755,7 +5438,7 @@ rakeDb.lazy = (options, partialConfig) => {
5755
5438
  return {
5756
5439
  change,
5757
5440
  run(args, conf) {
5758
- return runCommand(options, conf ? __spreadValues(__spreadValues({}, config), conf) : config, args);
5441
+ return runCommand(options, conf ? { ...config, ...conf } : config, args);
5759
5442
  }
5760
5443
  };
5761
5444
  };
@@ -5770,15 +5453,14 @@ const rakeDbAliases = {
5770
5453
  rec: "recurrent"
5771
5454
  };
5772
5455
  const runCommand = async (opts, config, args = process.argv.slice(2)) => {
5773
- var _a, _b, _c;
5774
- let arg = (_a = args[0]) == null ? void 0 : _a.split(":")[0];
5456
+ let arg = args[0]?.split(":")[0];
5775
5457
  if (rakeDbAliases[arg]) {
5776
5458
  args = [...args];
5777
5459
  arg = args[0] = rakeDbAliases[arg];
5778
5460
  }
5779
5461
  const options = orchidCore.toArray(opts);
5780
5462
  args.shift();
5781
- const command = (_c = (_b = rakeDbCommands[arg]) == null ? void 0 : _b.run) != null ? _c : config.commands[arg];
5463
+ const command = rakeDbCommands[arg]?.run ?? config.commands[arg];
5782
5464
  if (command) {
5783
5465
  await command(options, config, args);
5784
5466
  } else if (config.logger) {
@@ -5789,12 +5471,9 @@ const runCommand = async (opts, config, args = process.argv.slice(2)) => {
5789
5471
  for (let key in rakeDbCommands) {
5790
5472
  const command2 = rakeDbCommands[key];
5791
5473
  const added = addedCommands.get(command2);
5792
- if (added)
5793
- key = added[0] += `, ${key}`;
5794
- if (key.length > max)
5795
- max = key.length;
5796
- if (added)
5797
- continue;
5474
+ if (added) key = added[0] += `, ${key}`;
5475
+ if (key.length > max) max = key.length;
5476
+ if (added) continue;
5798
5477
  if (command2.helpArguments) {
5799
5478
  maxArgs = Math.max(
5800
5479
  maxArgs,