rake-db 2.3.0 → 2.3.2

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
@@ -13,27 +13,27 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
13
13
  var Enquirer__default = /*#__PURE__*/_interopDefaultLegacy(Enquirer);
14
14
  var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
15
15
 
16
- var __defProp$6 = Object.defineProperty;
17
- var __defProps$5 = Object.defineProperties;
18
- var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
19
- var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
20
- var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
21
- var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
22
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
23
- var __spreadValues$6 = (a, b) => {
16
+ var __defProp$7 = Object.defineProperty;
17
+ var __defProps$6 = Object.defineProperties;
18
+ var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
19
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
20
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
21
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
22
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
23
+ var __spreadValues$7 = (a, b) => {
24
24
  for (var prop in b || (b = {}))
25
- if (__hasOwnProp$6.call(b, prop))
26
- __defNormalProp$6(a, prop, b[prop]);
27
- if (__getOwnPropSymbols$6)
28
- for (var prop of __getOwnPropSymbols$6(b)) {
29
- if (__propIsEnum$6.call(b, prop))
30
- __defNormalProp$6(a, prop, b[prop]);
25
+ if (__hasOwnProp$7.call(b, prop))
26
+ __defNormalProp$7(a, prop, b[prop]);
27
+ if (__getOwnPropSymbols$7)
28
+ for (var prop of __getOwnPropSymbols$7(b)) {
29
+ if (__propIsEnum$7.call(b, prop))
30
+ __defNormalProp$7(a, prop, b[prop]);
31
31
  }
32
32
  return a;
33
33
  };
34
- var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
34
+ var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
35
35
  const migrationConfigDefaults = {
36
- migrationsPath: path__default["default"].resolve(process.cwd(), "src", "migrations"),
36
+ migrationsPath: path__default["default"].resolve("src", "migrations"),
37
37
  migrationsTable: "schemaMigrations",
38
38
  requireTs: require,
39
39
  log: true,
@@ -41,7 +41,7 @@ const migrationConfigDefaults = {
41
41
  useCodeUpdater: true
42
42
  };
43
43
  const getMigrationConfigWithDefaults = (config) => {
44
- return __spreadValues$6(__spreadValues$6({}, migrationConfigDefaults), config);
44
+ return __spreadValues$7(__spreadValues$7({}, migrationConfigDefaults), config);
45
45
  };
46
46
  const getDatabaseAndUserFromOptions = (options) => {
47
47
  if (options.databaseURL) {
@@ -69,9 +69,9 @@ const setAdapterOptions = (options, set) => {
69
69
  if (set.password !== void 0) {
70
70
  url.password = set.password;
71
71
  }
72
- return __spreadProps$5(__spreadValues$6({}, options), { databaseURL: url.toString() });
72
+ return __spreadProps$6(__spreadValues$7({}, options), { databaseURL: url.toString() });
73
73
  } else {
74
- return __spreadValues$6(__spreadValues$6({}, options), set);
74
+ return __spreadValues$7(__spreadValues$7({}, options), set);
75
75
  }
76
76
  };
77
77
  const askAdminCredentials = async () => {
@@ -148,7 +148,7 @@ const getMigrationFiles = async (config, up) => {
148
148
  const { migrationsPath } = config;
149
149
  let files;
150
150
  try {
151
- files = await promises.readdir(migrationsPath);
151
+ files = await promises.readdir(path__default["default"].resolve(migrationsPath));
152
152
  } catch (_) {
153
153
  return [];
154
154
  }
@@ -166,7 +166,7 @@ const getMigrationFiles = async (config, up) => {
166
166
  );
167
167
  }
168
168
  return {
169
- path: path__default["default"].join(migrationsPath, file),
169
+ path: path__default["default"].resolve(migrationsPath, file),
170
170
  version: timestampMatch[1]
171
171
  };
172
172
  });
@@ -192,6 +192,12 @@ const getSchemaAndTableFromName = (name) => {
192
192
  const index = name.indexOf(".");
193
193
  return index !== -1 ? [name.slice(0, index), name.slice(index + 1)] : [void 0, name];
194
194
  };
195
+ const quoteSchemaTable = ({
196
+ schema,
197
+ name
198
+ }) => {
199
+ return pqb.singleQuote(schema ? `${schema}.${name}` : name);
200
+ };
195
201
 
196
202
  let currentMigration;
197
203
  let currentPromise;
@@ -212,25 +218,25 @@ const setCurrentMigrationUp = (up) => {
212
218
  const getCurrentPromise = () => currentPromise;
213
219
  const getCurrentChangeCallback = () => currentChangeCallback;
214
220
 
215
- var __defProp$5 = Object.defineProperty;
216
- var __defProps$4 = Object.defineProperties;
217
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
218
- var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
219
- var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
220
- var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
221
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
222
- var __spreadValues$5 = (a, b) => {
221
+ var __defProp$6 = Object.defineProperty;
222
+ var __defProps$5 = Object.defineProperties;
223
+ var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
224
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
225
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
226
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
227
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
228
+ var __spreadValues$6 = (a, b) => {
223
229
  for (var prop in b || (b = {}))
224
- if (__hasOwnProp$5.call(b, prop))
225
- __defNormalProp$5(a, prop, b[prop]);
226
- if (__getOwnPropSymbols$5)
227
- for (var prop of __getOwnPropSymbols$5(b)) {
228
- if (__propIsEnum$5.call(b, prop))
229
- __defNormalProp$5(a, prop, b[prop]);
230
+ if (__hasOwnProp$6.call(b, prop))
231
+ __defNormalProp$6(a, prop, b[prop]);
232
+ if (__getOwnPropSymbols$6)
233
+ for (var prop of __getOwnPropSymbols$6(b)) {
234
+ if (__propIsEnum$6.call(b, prop))
235
+ __defNormalProp$6(a, prop, b[prop]);
230
236
  }
231
237
  return a;
232
238
  };
233
- var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
239
+ var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
234
240
  const columnToSql = (key, item, values, hasMultiplePrimaryKeys) => {
235
241
  const line = [`"${key}" ${item.toSQL()}`];
236
242
  if (item.data.compression) {
@@ -269,7 +275,7 @@ const addColumnIndex = (indexes, key, item) => {
269
275
  if (item.data.indexes) {
270
276
  indexes.push(
271
277
  ...item.data.indexes.map((index) => ({
272
- columns: [__spreadProps$4(__spreadValues$5({}, index), { column: key })],
278
+ columns: [__spreadProps$5(__spreadValues$6({}, index), { column: key })],
273
279
  options: index
274
280
  }))
275
281
  );
@@ -416,29 +422,29 @@ WHERE
416
422
  return rows;
417
423
  };
418
424
 
419
- var __defProp$4 = Object.defineProperty;
420
- var __defProps$3 = Object.defineProperties;
421
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
422
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
423
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
424
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
425
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
426
- var __spreadValues$4 = (a, b) => {
425
+ var __defProp$5 = Object.defineProperty;
426
+ var __defProps$4 = Object.defineProperties;
427
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
428
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
429
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
430
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
431
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
432
+ var __spreadValues$5 = (a, b) => {
427
433
  for (var prop in b || (b = {}))
428
- if (__hasOwnProp$4.call(b, prop))
429
- __defNormalProp$4(a, prop, b[prop]);
430
- if (__getOwnPropSymbols$4)
431
- for (var prop of __getOwnPropSymbols$4(b)) {
432
- if (__propIsEnum$4.call(b, prop))
433
- __defNormalProp$4(a, prop, b[prop]);
434
+ if (__hasOwnProp$5.call(b, prop))
435
+ __defNormalProp$5(a, prop, b[prop]);
436
+ if (__getOwnPropSymbols$5)
437
+ for (var prop of __getOwnPropSymbols$5(b)) {
438
+ if (__propIsEnum$5.call(b, prop))
439
+ __defNormalProp$5(a, prop, b[prop]);
434
440
  }
435
441
  return a;
436
442
  };
437
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
443
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
438
444
  const types = Object.assign(Object.create(pqb.columnTypes), {
439
445
  raw: pqb.raw
440
446
  });
441
- const createTable = async (migration, up, tableName, options, fn) => {
447
+ const createTable$1 = async (migration, up, tableName, options, fn) => {
442
448
  const shape = pqb.getColumnTypes(types, fn);
443
449
  const tableData = pqb.getTableData();
444
450
  const ast = makeAst$1(
@@ -465,14 +471,14 @@ const makeAst$1 = (up, tableName, shape, tableData, options, noPrimaryKey) => {
465
471
  }
466
472
  const primaryKey = tableData.primaryKey;
467
473
  const [schema, table] = getSchemaAndTableFromName(tableName);
468
- return __spreadProps$3(__spreadValues$4(__spreadProps$3(__spreadValues$4({
474
+ return __spreadProps$4(__spreadValues$5(__spreadProps$4(__spreadValues$5({
469
475
  type: "table",
470
476
  action: up ? "create" : "drop",
471
477
  schema,
472
478
  name: table,
473
479
  shape
474
480
  }, tableData), {
475
- primaryKey: shapePKeys.length <= 1 ? primaryKey : primaryKey ? __spreadProps$3(__spreadValues$4({}, primaryKey), { columns: [...shapePKeys, ...primaryKey.columns] }) : { columns: shapePKeys }
481
+ primaryKey: shapePKeys.length <= 1 ? primaryKey : primaryKey ? __spreadProps$4(__spreadValues$5({}, primaryKey), { columns: [...shapePKeys, ...primaryKey.columns] }) : { columns: shapePKeys }
476
482
  }), options), {
477
483
  noPrimaryKey: options.noPrimaryKey ? "ignore" : noPrimaryKey || "error"
478
484
  });
@@ -546,25 +552,25 @@ const astToQueries$1 = (ast) => {
546
552
  return result;
547
553
  };
548
554
 
549
- var __defProp$3 = Object.defineProperty;
550
- var __defProps$2 = Object.defineProperties;
551
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
552
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
553
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
554
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
555
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
556
- var __spreadValues$3 = (a, b) => {
555
+ var __defProp$4 = Object.defineProperty;
556
+ var __defProps$3 = Object.defineProperties;
557
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
558
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
559
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
560
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
561
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
562
+ var __spreadValues$4 = (a, b) => {
557
563
  for (var prop in b || (b = {}))
558
- if (__hasOwnProp$3.call(b, prop))
559
- __defNormalProp$3(a, prop, b[prop]);
560
- if (__getOwnPropSymbols$3)
561
- for (var prop of __getOwnPropSymbols$3(b)) {
562
- if (__propIsEnum$3.call(b, prop))
563
- __defNormalProp$3(a, prop, b[prop]);
564
+ if (__hasOwnProp$4.call(b, prop))
565
+ __defNormalProp$4(a, prop, b[prop]);
566
+ if (__getOwnPropSymbols$4)
567
+ for (var prop of __getOwnPropSymbols$4(b)) {
568
+ if (__propIsEnum$4.call(b, prop))
569
+ __defNormalProp$4(a, prop, b[prop]);
564
570
  }
565
571
  return a;
566
572
  };
567
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
573
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
568
574
  const newChangeTableData = () => ({
569
575
  add: { indexes: [], foreignKeys: [] },
570
576
  drop: { indexes: [], foreignKeys: [] }
@@ -580,7 +586,7 @@ const mergeTableData = (a, b) => {
580
586
  } else {
581
587
  a.primaryKey = {
582
588
  columns: [...a.primaryKey.columns, ...b.primaryKey.columns],
583
- options: __spreadValues$3(__spreadValues$3({}, a.primaryKey.options), b.primaryKey.options)
589
+ options: __spreadValues$4(__spreadValues$4({}, a.primaryKey.options), b.primaryKey.options)
584
590
  };
585
591
  }
586
592
  }
@@ -631,7 +637,7 @@ const columnTypeToColumnChange = (item) => {
631
637
  if (foreignKeys == null ? void 0 : foreignKeys.some((it) => "fn" in it)) {
632
638
  throw new Error("Callback in foreignKey is not allowed in migration");
633
639
  }
634
- return __spreadProps$2(__spreadValues$3({
640
+ return __spreadProps$3(__spreadValues$4({
635
641
  column: item,
636
642
  type: item.toSQL(),
637
643
  nullable: item.data.isNullable,
@@ -647,7 +653,7 @@ const tableChangeMethods = {
647
653
  add,
648
654
  drop,
649
655
  change(from, to, options) {
650
- return __spreadValues$3({
656
+ return __spreadValues$4({
651
657
  type: "change",
652
658
  from: columnTypeToColumnChange(from),
653
659
  to: columnTypeToColumnChange(to)
@@ -697,18 +703,18 @@ const makeAst = (up, name, changeData, changeTableData2, options) => {
697
703
  const item = changeData[key];
698
704
  if ("type" in item) {
699
705
  if (up) {
700
- shape[key] = item.type === "change" && item.usingUp ? __spreadProps$2(__spreadValues$3({}, item), { using: item.usingUp }) : item;
706
+ shape[key] = item.type === "change" && item.usingUp ? __spreadProps$3(__spreadValues$4({}, item), { using: item.usingUp }) : item;
701
707
  } else {
702
708
  if (item.type === "rename") {
703
- shape[item.name] = __spreadProps$2(__spreadValues$3({}, item), { name: key });
709
+ shape[item.name] = __spreadProps$3(__spreadValues$4({}, item), { name: key });
704
710
  } else {
705
- shape[key] = item.type === "add" ? __spreadProps$2(__spreadValues$3({}, item), { type: "drop" }) : item.type === "drop" ? __spreadProps$2(__spreadValues$3({}, item), { type: "add" }) : item.type === "change" ? __spreadProps$2(__spreadValues$3({}, item), { from: item.to, to: item.from, using: item.usingDown }) : item;
711
+ shape[key] = item.type === "add" ? __spreadProps$3(__spreadValues$4({}, item), { type: "drop" }) : item.type === "drop" ? __spreadProps$3(__spreadValues$4({}, item), { type: "add" }) : item.type === "change" ? __spreadProps$3(__spreadValues$4({}, item), { from: item.to, to: item.from, using: item.usingDown }) : item;
706
712
  }
707
713
  }
708
714
  }
709
715
  }
710
716
  const [schema, table] = getSchemaAndTableFromName(name);
711
- return __spreadValues$3({
717
+ return __spreadValues$4({
712
718
  type: "changeTable",
713
719
  schema,
714
720
  name: table,
@@ -725,10 +731,10 @@ const astToQueries = (ast) => {
725
731
  values: []
726
732
  });
727
733
  }
728
- const addPrimaryKeys = ast.add.primaryKey ? __spreadValues$3({}, ast.add.primaryKey) : {
734
+ const addPrimaryKeys = ast.add.primaryKey ? __spreadValues$4({}, ast.add.primaryKey) : {
729
735
  columns: []
730
736
  };
731
- const dropPrimaryKeys = ast.drop.primaryKey ? __spreadValues$3({}, ast.drop.primaryKey) : {
737
+ const dropPrimaryKeys = ast.drop.primaryKey ? __spreadValues$4({}, ast.drop.primaryKey) : {
732
738
  columns: []
733
739
  };
734
740
  for (const key in ast.shape) {
@@ -836,7 +842,7 @@ const astToQueries = (ast) => {
836
842
  if (fromIndex) {
837
843
  dropIndexes.push({
838
844
  columns: [
839
- __spreadValues$3({
845
+ __spreadValues$4({
840
846
  column: key
841
847
  }, fromIndex)
842
848
  ],
@@ -846,7 +852,7 @@ const astToQueries = (ast) => {
846
852
  if (toIndex) {
847
853
  addIndexes.push({
848
854
  columns: [
849
- __spreadValues$3({
855
+ __spreadValues$4({
850
856
  column: key
851
857
  }, toIndex)
852
858
  ],
@@ -896,25 +902,25 @@ const astToQueries = (ast) => {
896
902
  return result;
897
903
  };
898
904
 
899
- var __defProp$2 = Object.defineProperty;
900
- var __defProps$1 = Object.defineProperties;
901
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
902
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
903
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
904
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
905
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
906
- var __spreadValues$2 = (a, b) => {
905
+ var __defProp$3 = Object.defineProperty;
906
+ var __defProps$2 = Object.defineProperties;
907
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
908
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
909
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
910
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
911
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
912
+ var __spreadValues$3 = (a, b) => {
907
913
  for (var prop in b || (b = {}))
908
- if (__hasOwnProp$2.call(b, prop))
909
- __defNormalProp$2(a, prop, b[prop]);
910
- if (__getOwnPropSymbols$2)
911
- for (var prop of __getOwnPropSymbols$2(b)) {
912
- if (__propIsEnum$2.call(b, prop))
913
- __defNormalProp$2(a, prop, b[prop]);
914
+ if (__hasOwnProp$3.call(b, prop))
915
+ __defNormalProp$3(a, prop, b[prop]);
916
+ if (__getOwnPropSymbols$3)
917
+ for (var prop of __getOwnPropSymbols$3(b)) {
918
+ if (__propIsEnum$3.call(b, prop))
919
+ __defNormalProp$3(a, prop, b[prop]);
914
920
  }
915
921
  return a;
916
922
  };
917
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
923
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
918
924
  class UnknownColumn extends pqb.ColumnType {
919
925
  constructor(dataType) {
920
926
  super();
@@ -928,18 +934,18 @@ class UnknownColumn extends pqb.ColumnType {
928
934
  const createJoinTable = async (migration, up, tables, options, fn) => {
929
935
  const tableName = options.tableName || joinWords(...tables);
930
936
  if (!up) {
931
- return createTable(
937
+ return createTable$1(
932
938
  migration,
933
939
  up,
934
940
  tableName,
935
- __spreadProps$1(__spreadValues$2({}, options), { noPrimaryKey: true }),
941
+ __spreadProps$2(__spreadValues$3({}, options), { noPrimaryKey: true }),
936
942
  () => ({})
937
943
  );
938
944
  }
939
945
  const tablesWithPrimaryKeys = await Promise.all(
940
946
  tables.map(async (table) => {
941
947
  const primaryKeys = await getPrimaryKeysOfTable(migration, table).then(
942
- (items) => items.map((item) => __spreadProps$1(__spreadValues$2({}, item), {
948
+ (items) => items.map((item) => __spreadProps$2(__spreadValues$3({}, item), {
943
949
  joinedName: joinWords(pluralize.singular(table), item.name)
944
950
  }))
945
951
  );
@@ -955,7 +961,7 @@ const createJoinTable = async (migration, up, tables, options, fn) => {
955
961
  return [schema, table, primaryKeys];
956
962
  })
957
963
  );
958
- return createTable(migration, up, tableName, options, (t) => {
964
+ return createTable$1(migration, up, tableName, options, (t) => {
959
965
  const result = {};
960
966
  tablesWithPrimaryKeys.forEach(([schema, table, primaryKeys]) => {
961
967
  if (primaryKeys.length === 1) {
@@ -988,25 +994,25 @@ const createJoinTable = async (migration, up, tables, options, fn) => {
988
994
  });
989
995
  };
990
996
 
991
- var __defProp$1 = Object.defineProperty;
992
- var __defProps = Object.defineProperties;
993
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
994
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
995
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
996
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
997
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
998
- var __spreadValues$1 = (a, b) => {
997
+ var __defProp$2 = Object.defineProperty;
998
+ var __defProps$1 = Object.defineProperties;
999
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
1000
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
1001
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
1002
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
1003
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1004
+ var __spreadValues$2 = (a, b) => {
999
1005
  for (var prop in b || (b = {}))
1000
- if (__hasOwnProp$1.call(b, prop))
1001
- __defNormalProp$1(a, prop, b[prop]);
1002
- if (__getOwnPropSymbols$1)
1003
- for (var prop of __getOwnPropSymbols$1(b)) {
1004
- if (__propIsEnum$1.call(b, prop))
1005
- __defNormalProp$1(a, prop, b[prop]);
1006
+ if (__hasOwnProp$2.call(b, prop))
1007
+ __defNormalProp$2(a, prop, b[prop]);
1008
+ if (__getOwnPropSymbols$2)
1009
+ for (var prop of __getOwnPropSymbols$2(b)) {
1010
+ if (__propIsEnum$2.call(b, prop))
1011
+ __defNormalProp$2(a, prop, b[prop]);
1006
1012
  }
1007
1013
  return a;
1008
1014
  };
1009
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1015
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
1010
1016
  class Migration extends pqb.TransactionAdapter {
1011
1017
  constructor(tx, up, options, adapterOptions, appCodeUpdaterCache) {
1012
1018
  super(tx, tx.client, tx.types);
@@ -1025,12 +1031,12 @@ class Migration extends pqb.TransactionAdapter {
1025
1031
  createTable(tableName, cbOrOptions, cb) {
1026
1032
  const options = typeof cbOrOptions === "function" ? {} : cbOrOptions;
1027
1033
  const fn = cb || cbOrOptions;
1028
- return createTable(this, this.up, tableName, options, fn);
1034
+ return createTable$1(this, this.up, tableName, options, fn);
1029
1035
  }
1030
1036
  dropTable(tableName, cbOrOptions, cb) {
1031
1037
  const options = typeof cbOrOptions === "function" ? {} : cbOrOptions;
1032
1038
  const fn = cb || cbOrOptions;
1033
- return createTable(this, !this.up, tableName, options, fn);
1039
+ return createTable$1(this, !this.up, tableName, options, fn);
1034
1040
  }
1035
1041
  async createJoinTable(tables, cbOrOptions, cb) {
1036
1042
  const options = typeof cbOrOptions === "function" ? {} : cbOrOptions || {};
@@ -1113,10 +1119,10 @@ class Migration extends pqb.TransactionAdapter {
1113
1119
  }));
1114
1120
  }
1115
1121
  createSchema(schemaName) {
1116
- return createSchema(this, this.up, schemaName);
1122
+ return createSchema$1(this, this.up, schemaName);
1117
1123
  }
1118
1124
  dropSchema(schemaName) {
1119
- return createSchema(this, !this.up, schemaName);
1125
+ return createSchema$1(this, !this.up, schemaName);
1120
1126
  }
1121
1127
  createExtension(name, options = {}) {
1122
1128
  return createExtension(this, this.up, name, options);
@@ -1147,7 +1153,7 @@ const wrapWithLog = async (log, query, fn) => {
1147
1153
  if (!log) {
1148
1154
  return fn();
1149
1155
  } else {
1150
- const sql = typeof query === "string" ? { text: query, values: [] } : query.values ? query : __spreadProps(__spreadValues$1({}, query), { values: [] });
1156
+ const sql = typeof query === "string" ? { text: query, values: [] } : query.values ? query : __spreadProps$1(__spreadValues$2({}, query), { values: [] });
1151
1157
  const logData = log.beforeQuery(sql);
1152
1158
  try {
1153
1159
  const result = await fn();
@@ -1165,15 +1171,15 @@ const addColumn = (migration, up, tableName, columnName, fn) => {
1165
1171
  }));
1166
1172
  };
1167
1173
  const addIndex = (migration, up, tableName, columns, options) => {
1168
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$1({}, t.add(t.index(columns, options))));
1174
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$2({}, t.add(t.index(columns, options))));
1169
1175
  };
1170
1176
  const addForeignKey = (migration, up, tableName, columns, foreignTable, foreignColumns, options) => {
1171
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$1({}, t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))));
1177
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$2({}, t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))));
1172
1178
  };
1173
1179
  const addPrimaryKey = (migration, up, tableName, columns, options) => {
1174
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$1({}, t.add(t.primaryKey(columns, options))));
1180
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$2({}, t.add(t.primaryKey(columns, options))));
1175
1181
  };
1176
- const createSchema = async (migration, up, name) => {
1182
+ const createSchema$1 = async (migration, up, name) => {
1177
1183
  const ast = {
1178
1184
  type: "schema",
1179
1185
  action: up ? "create" : "drop",
@@ -1185,7 +1191,7 @@ const createSchema = async (migration, up, name) => {
1185
1191
  await runCodeUpdater(migration, ast);
1186
1192
  };
1187
1193
  const createExtension = async (migration, up, name, options) => {
1188
- const ast = __spreadValues$1({
1194
+ const ast = __spreadValues$2({
1189
1195
  type: "extension",
1190
1196
  action: up ? "create" : "drop",
1191
1197
  name
@@ -1211,25 +1217,25 @@ const runCodeUpdater = (migration, ast) => {
1211
1217
  });
1212
1218
  };
1213
1219
 
1214
- var __defProp = Object.defineProperty;
1215
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1216
- var __hasOwnProp = Object.prototype.hasOwnProperty;
1217
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
1218
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1219
- var __spreadValues = (a, b) => {
1220
+ var __defProp$1 = Object.defineProperty;
1221
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
1222
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
1223
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
1224
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1225
+ var __spreadValues$1 = (a, b) => {
1220
1226
  for (var prop in b || (b = {}))
1221
- if (__hasOwnProp.call(b, prop))
1222
- __defNormalProp(a, prop, b[prop]);
1223
- if (__getOwnPropSymbols)
1224
- for (var prop of __getOwnPropSymbols(b)) {
1225
- if (__propIsEnum.call(b, prop))
1226
- __defNormalProp(a, prop, b[prop]);
1227
+ if (__hasOwnProp$1.call(b, prop))
1228
+ __defNormalProp$1(a, prop, b[prop]);
1229
+ if (__getOwnPropSymbols$1)
1230
+ for (var prop of __getOwnPropSymbols$1(b)) {
1231
+ if (__propIsEnum$1.call(b, prop))
1232
+ __defNormalProp$1(a, prop, b[prop]);
1227
1233
  }
1228
1234
  return a;
1229
1235
  };
1230
1236
  const migrateOrRollback = async (options, config, args, up) => {
1231
1237
  var _a;
1232
- config = __spreadValues({}, config);
1238
+ config = __spreadValues$1({}, config);
1233
1239
  const files = await getMigrationFiles(config, up);
1234
1240
  let count = up ? Infinity : 1;
1235
1241
  let argI = 0;
@@ -1398,18 +1404,21 @@ const resetDb = async (arg, config) => {
1398
1404
  await migrate(arg, config);
1399
1405
  };
1400
1406
 
1401
- const generate = async (config, args) => {
1402
- const name = args[0];
1403
- if (!name)
1404
- throw new Error("Migration name is missing");
1405
- await promises.mkdir(config.migrationsPath, { recursive: true });
1407
+ const writeMigrationFile = async (config, name, content) => {
1408
+ await promises.mkdir(path__default["default"].resolve(config.migrationsPath), { recursive: true });
1406
1409
  const filePath = path__default["default"].resolve(
1407
1410
  config.migrationsPath,
1408
1411
  `${makeFileTimeStamp()}_${name}.ts`
1409
1412
  );
1410
- await promises.writeFile(filePath, makeContent(name, args.slice(1)));
1413
+ await promises.writeFile(filePath, content);
1411
1414
  console.log(`Created ${filePath}`);
1412
1415
  };
1416
+ const generate = async (config, args) => {
1417
+ const name = args[0];
1418
+ if (!name)
1419
+ throw new Error("Migration name is missing");
1420
+ await writeMigrationFile(config, name, makeContent(name, args.slice(1)));
1421
+ };
1413
1422
  const makeFileTimeStamp = () => {
1414
1423
  const now = new Date();
1415
1424
  return [
@@ -1464,6 +1473,547 @@ const makeColumnsContent = (args, method) => {
1464
1473
  return content;
1465
1474
  };
1466
1475
 
1476
+ const filterSchema = (table) => `${table} !~ '^pg_' AND ${table} != 'information_schema'`;
1477
+ class DbStructure {
1478
+ constructor(db) {
1479
+ this.db = db;
1480
+ }
1481
+ async getSchemas() {
1482
+ const { rows } = await this.db.arrays(
1483
+ `SELECT n.nspname "name"
1484
+ FROM pg_catalog.pg_namespace n
1485
+ WHERE ${filterSchema("n.nspname")}
1486
+ ORDER BY "name"`
1487
+ );
1488
+ return rows.flat();
1489
+ }
1490
+ async getTables() {
1491
+ const { rows } = await this.db.query(
1492
+ `SELECT
1493
+ nspname AS "schemaName",
1494
+ relname AS "name",
1495
+ obj_description(c.oid) AS comment
1496
+ FROM pg_class c
1497
+ JOIN pg_catalog.pg_namespace n ON n.oid = relnamespace
1498
+ WHERE relkind = 'r'
1499
+ AND ${filterSchema("nspname")}
1500
+ ORDER BY relname`
1501
+ );
1502
+ return rows;
1503
+ }
1504
+ async getViews() {
1505
+ const { rows } = await this.db.query(
1506
+ `SELECT
1507
+ table_schema "schemaName",
1508
+ table_name "name"
1509
+ FROM information_schema.tables
1510
+ WHERE table_type = 'VIEW'
1511
+ AND ${filterSchema("table_schema")}
1512
+ ORDER BY table_name`
1513
+ );
1514
+ return rows;
1515
+ }
1516
+ async getProcedures() {
1517
+ const { rows } = await this.db.query(
1518
+ `SELECT
1519
+ n.nspname AS "schemaName",
1520
+ proname AS name,
1521
+ proretset AS "returnSet",
1522
+ (
1523
+ SELECT typname FROM pg_type WHERE oid = prorettype
1524
+ ) AS "returnType",
1525
+ prokind AS "kind",
1526
+ coalesce((
1527
+ SELECT true FROM information_schema.triggers
1528
+ WHERE n.nspname = trigger_schema AND trigger_name = proname
1529
+ LIMIT 1
1530
+ ), false) AS "isTrigger",
1531
+ coalesce((
1532
+ SELECT json_agg(pg_type.typname)
1533
+ FROM unnest(coalesce(proallargtypes, proargtypes)) typeId
1534
+ JOIN pg_type ON pg_type.oid = typeId
1535
+ ), '[]') AS "types",
1536
+ coalesce(to_json(proallargtypes::int[]), to_json(proargtypes::int[])) AS "argTypes",
1537
+ coalesce(to_json(proargmodes), '[]') AS "argModes",
1538
+ to_json(proargnames) AS "argNames"
1539
+ FROM pg_proc p
1540
+ JOIN pg_namespace n ON p.pronamespace = n.oid
1541
+ WHERE ${filterSchema("n.nspname")}`
1542
+ );
1543
+ return rows;
1544
+ }
1545
+ async getColumns() {
1546
+ const { rows } = await this.db.query(
1547
+ `SELECT
1548
+ table_schema "schemaName",
1549
+ table_name "tableName",
1550
+ column_name "name",
1551
+ udt_name "type",
1552
+ character_maximum_length AS "maxChars",
1553
+ numeric_precision AS "numericPrecision",
1554
+ numeric_scale AS "numericScale",
1555
+ datetime_precision AS "dateTimePrecision",
1556
+ column_default "default",
1557
+ is_nullable::boolean "isNullable",
1558
+ collation_name AS "collation",
1559
+ NULLIF(a.attcompression, '') AS compression,
1560
+ pgd.description AS "comment"
1561
+ FROM information_schema.columns c
1562
+ LEFT JOIN pg_catalog.pg_statio_all_tables AS st
1563
+ ON c.table_schema = st.schemaname
1564
+ AND c.table_name = st.relname
1565
+ LEFT JOIN pg_catalog.pg_description pgd
1566
+ ON pgd.objoid = st.relid
1567
+ AND pgd.objsubid = c.ordinal_position
1568
+ LEFT JOIN pg_catalog.pg_attribute a
1569
+ ON a.attrelid = st.relid
1570
+ AND a.attnum = c.ordinal_position
1571
+ WHERE ${filterSchema("table_schema")}
1572
+ ORDER BY c.ordinal_position`
1573
+ );
1574
+ return rows;
1575
+ }
1576
+ async getIndexes() {
1577
+ const { rows } = await this.db.query(
1578
+ `SELECT
1579
+ n.nspname "schemaName",
1580
+ t.relname "tableName",
1581
+ ic.relname "name",
1582
+ am.amname AS "using",
1583
+ i.indisunique "isUnique",
1584
+ (
1585
+ SELECT json_agg(
1586
+ (
1587
+ CASE WHEN t.e = 0
1588
+ THEN jsonb_build_object('expression', pg_get_indexdef(i.indexrelid, t.i::int4, false))
1589
+ ELSE jsonb_build_object('column', (
1590
+ (
1591
+ SELECT attname
1592
+ FROM pg_catalog.pg_attribute
1593
+ WHERE attrelid = i.indrelid
1594
+ AND attnum = t.e
1595
+ )
1596
+ ))
1597
+ END
1598
+ ) || (
1599
+ CASE WHEN i.indcollation[t.i - 1] = 0
1600
+ THEN '{}'::jsonb
1601
+ ELSE (
1602
+ SELECT (
1603
+ CASE WHEN collname = 'default'
1604
+ THEN '{}'::jsonb
1605
+ ELSE jsonb_build_object('collate', collname)
1606
+ END
1607
+ )
1608
+ FROM pg_catalog.pg_collation
1609
+ WHERE oid = i.indcollation[t.i - 1]
1610
+ )
1611
+ END
1612
+ ) || (
1613
+ SELECT
1614
+ CASE WHEN opcdefault AND attoptions IS NULL
1615
+ THEN '{}'::jsonb
1616
+ ELSE jsonb_build_object(
1617
+ 'opclass', opcname || COALESCE('(' || array_to_string(attoptions, ', ') || ')', '')
1618
+ )
1619
+ END
1620
+ FROM pg_opclass
1621
+ LEFT JOIN pg_attribute
1622
+ ON attrelid = i.indexrelid
1623
+ AND attnum = t.i
1624
+ WHERE oid = i.indclass[t.i - 1]
1625
+ ) || (
1626
+ CASE WHEN i.indoption[t.i - 1] = 0
1627
+ THEN '{}'::jsonb
1628
+ ELSE jsonb_build_object(
1629
+ 'order',
1630
+ CASE
1631
+ WHEN i.indoption[t.i - 1] = 1 THEN 'DESC NULLS LAST'
1632
+ WHEN i.indoption[t.i - 1] = 2 THEN 'ASC NULLS FIRST'
1633
+ WHEN i.indoption[t.i - 1] = 3 THEN 'DESC'
1634
+ ELSE NULL
1635
+ END
1636
+ )
1637
+ END
1638
+ )
1639
+ )
1640
+ FROM unnest(i.indkey[:indnkeyatts - 1]) WITH ORDINALITY AS t(e, i)
1641
+ ) "columns",
1642
+ (
1643
+ SELECT json_agg(
1644
+ (
1645
+ SELECT attname
1646
+ FROM pg_catalog.pg_attribute
1647
+ WHERE attrelid = i.indrelid
1648
+ AND attnum = j.e
1649
+ )
1650
+ )
1651
+ FROM unnest(i.indkey[indnkeyatts:]) AS j(e)
1652
+ ) AS "include",
1653
+ NULLIF(pg_catalog.array_to_string(
1654
+ ic.reloptions || array(SELECT 'toast.' || x FROM pg_catalog.unnest(tc.reloptions) x),
1655
+ ', '
1656
+ ), '') AS "with",
1657
+ (
1658
+ SELECT tablespace
1659
+ FROM pg_indexes
1660
+ WHERE schemaname = n.nspname
1661
+ AND indexname = ic.relname
1662
+ ) AS tablespace,
1663
+ pg_get_expr(i.indpred, i.indrelid) AS "where"
1664
+ FROM pg_index i
1665
+ JOIN pg_class t ON t.oid = i.indrelid
1666
+ JOIN pg_namespace n ON n.oid = t.relnamespace
1667
+ JOIN pg_class ic ON ic.oid = i.indexrelid
1668
+ JOIN pg_am am ON am.oid = ic.relam
1669
+ LEFT JOIN pg_catalog.pg_class tc ON (ic.reltoastrelid = tc.oid)
1670
+ WHERE ${filterSchema("n.nspname")}
1671
+ AND NOT i.indisprimary
1672
+ ORDER BY ic.relname`
1673
+ );
1674
+ return rows;
1675
+ }
1676
+ async getForeignKeys() {
1677
+ const { rows } = await this.db.query(
1678
+ `SELECT
1679
+ s.nspname AS "schemaName",
1680
+ t.relname AS "tableName",
1681
+ fs.nspname AS "foreignTableSchemaName",
1682
+ ft.relname AS "foreignTableName",
1683
+ c.conname AS "name",
1684
+ (
1685
+ SELECT json_agg(ccu.column_name)
1686
+ FROM information_schema.key_column_usage ccu
1687
+ WHERE ccu.constraint_name = c.conname
1688
+ AND ccu.table_schema = cs.nspname
1689
+ ) AS "columnNames",
1690
+ (
1691
+ SELECT json_agg(ccu.column_name)
1692
+ FROM information_schema.constraint_column_usage ccu
1693
+ WHERE ccu.constraint_name = c.conname
1694
+ AND ccu.table_schema = cs.nspname
1695
+ ) AS "foreignColumnNames",
1696
+ c.confmatchtype AS match,
1697
+ c.confupdtype AS "onUpdate",
1698
+ c.confdeltype AS "onDelete"
1699
+ FROM pg_catalog.pg_constraint c
1700
+ JOIN pg_class t ON t.oid = conrelid
1701
+ JOIN pg_catalog.pg_namespace s ON s.oid = t.relnamespace
1702
+ JOIN pg_class ft ON ft.oid = confrelid
1703
+ JOIN pg_catalog.pg_namespace fs ON fs.oid = ft.relnamespace
1704
+ JOIN pg_catalog.pg_namespace cs ON cs.oid = c.connamespace
1705
+ WHERE contype = 'f'
1706
+ ORDER BY c.conname`
1707
+ );
1708
+ return rows;
1709
+ }
1710
+ async getPrimaryKeys() {
1711
+ const { rows } = await this.db.query(
1712
+ `SELECT tc.table_schema AS "schemaName",
1713
+ tc.table_name AS "tableName",
1714
+ tc.constraint_name AS "name",
1715
+ json_agg(ccu.column_name) "columnNames"
1716
+ FROM information_schema.table_constraints tc
1717
+ JOIN information_schema.constraint_column_usage ccu
1718
+ ON ccu.constraint_name = tc.constraint_name
1719
+ AND ccu.table_schema = tc.table_schema
1720
+ WHERE tc.constraint_type = 'PRIMARY KEY'
1721
+ AND ${filterSchema("tc.table_schema")}
1722
+ GROUP BY "schemaName", "tableName", "name"
1723
+ ORDER BY "name"`
1724
+ );
1725
+ return rows;
1726
+ }
1727
+ async getTriggers() {
1728
+ const { rows } = await this.db.query(
1729
+ `SELECT event_object_schema AS "schemaName",
1730
+ event_object_table AS "tableName",
1731
+ trigger_schema AS "triggerSchema",
1732
+ trigger_name AS name,
1733
+ json_agg(event_manipulation) AS events,
1734
+ action_timing AS activation,
1735
+ action_condition AS condition,
1736
+ action_statement AS definition
1737
+ FROM information_schema.triggers
1738
+ WHERE ${filterSchema("event_object_schema")}
1739
+ GROUP BY event_object_schema, event_object_table, trigger_schema, trigger_name, action_timing, action_condition, action_statement
1740
+ ORDER BY trigger_name`
1741
+ );
1742
+ return rows;
1743
+ }
1744
+ async getExtensions() {
1745
+ const { rows } = await this.db.query(
1746
+ `SELECT
1747
+ nspname AS "schemaName",
1748
+ extname AS "name",
1749
+ extversion AS version
1750
+ FROM pg_extension
1751
+ JOIN pg_catalog.pg_namespace n ON n.oid = extnamespace
1752
+ AND ${filterSchema("n.nspname")}`
1753
+ );
1754
+ return rows;
1755
+ }
1756
+ }
1757
+
1758
+ var __defProp = Object.defineProperty;
1759
+ var __defProps = Object.defineProperties;
1760
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1761
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1762
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1763
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
1764
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1765
+ var __spreadValues = (a, b) => {
1766
+ for (var prop in b || (b = {}))
1767
+ if (__hasOwnProp.call(b, prop))
1768
+ __defNormalProp(a, prop, b[prop]);
1769
+ if (__getOwnPropSymbols)
1770
+ for (var prop of __getOwnPropSymbols(b)) {
1771
+ if (__propIsEnum.call(b, prop))
1772
+ __defNormalProp(a, prop, b[prop]);
1773
+ }
1774
+ return a;
1775
+ };
1776
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1777
+ const matchMap = {
1778
+ s: void 0,
1779
+ f: "FULL",
1780
+ p: "PARTIAL"
1781
+ };
1782
+ const fkeyActionMap = {
1783
+ a: void 0,
1784
+ r: "RESTRICT",
1785
+ c: "CASCADE",
1786
+ n: "SET NULL",
1787
+ d: "SET DEFAULT"
1788
+ };
1789
+ const structureToAst = async (db) => {
1790
+ const ast = [];
1791
+ const [
1792
+ schemas,
1793
+ tables,
1794
+ allColumns,
1795
+ allPrimaryKeys,
1796
+ allIndexes,
1797
+ allForeignKeys,
1798
+ extensions
1799
+ ] = await Promise.all([
1800
+ db.getSchemas(),
1801
+ db.getTables(),
1802
+ db.getColumns(),
1803
+ db.getPrimaryKeys(),
1804
+ db.getIndexes(),
1805
+ db.getForeignKeys(),
1806
+ db.getExtensions()
1807
+ ]);
1808
+ for (const name of schemas) {
1809
+ if (name === "public")
1810
+ continue;
1811
+ ast.push({
1812
+ type: "schema",
1813
+ action: "create",
1814
+ name
1815
+ });
1816
+ }
1817
+ for (const table of tables) {
1818
+ const { schemaName, name } = table;
1819
+ if (name === "schemaMigrations")
1820
+ continue;
1821
+ const belongsToTable = makeBelongsToTable(schemaName, name);
1822
+ const columns = allColumns.filter(belongsToTable);
1823
+ const primaryKey = allPrimaryKeys.find(belongsToTable);
1824
+ const tableIndexes = allIndexes.filter(belongsToTable);
1825
+ const tableForeignKeys = allForeignKeys.filter(belongsToTable);
1826
+ const shape = {};
1827
+ for (let item of columns) {
1828
+ const isSerial = getIsSerial(item);
1829
+ if (isSerial) {
1830
+ item = __spreadProps(__spreadValues({}, item), { default: void 0 });
1831
+ }
1832
+ const klass = pqb.columnsByType[getColumnType(item, isSerial)];
1833
+ if (!klass) {
1834
+ throw new Error(`Column type \`${item.type}\` is not supported`);
1835
+ }
1836
+ let column = pqb.instantiateColumn(klass, item);
1837
+ if ((primaryKey == null ? void 0 : primaryKey.columnNames.length) === 1 && (primaryKey == null ? void 0 : primaryKey.columnNames[0]) === item.name) {
1838
+ column = column.primaryKey();
1839
+ }
1840
+ const indexes = tableIndexes.filter(
1841
+ (it) => it.columns.length === 1 && "column" in it.columns[0] && it.columns[0].column === item.name
1842
+ );
1843
+ for (const index of indexes) {
1844
+ const options = index.columns[0];
1845
+ column = column.index({
1846
+ collate: options.collate,
1847
+ opclass: options.opclass,
1848
+ order: options.order,
1849
+ name: index.name,
1850
+ using: index.using === "btree" ? void 0 : index.using,
1851
+ unique: index.isUnique,
1852
+ include: index.include,
1853
+ with: index.with,
1854
+ tablespace: index.tablespace,
1855
+ where: index.where
1856
+ });
1857
+ }
1858
+ const foreignKeys = tableForeignKeys.filter(
1859
+ (it) => it.columnNames.length === 1 && it.columnNames[0] === item.name
1860
+ );
1861
+ for (const foreignKey of foreignKeys) {
1862
+ column = column.foreignKey(
1863
+ foreignKey.foreignTableName,
1864
+ foreignKey.foreignColumnNames[0],
1865
+ {
1866
+ name: foreignKey.name,
1867
+ match: matchMap[foreignKey.match],
1868
+ onUpdate: fkeyActionMap[foreignKey.onUpdate],
1869
+ onDelete: fkeyActionMap[foreignKey.onDelete]
1870
+ }
1871
+ );
1872
+ }
1873
+ shape[item.name] = column;
1874
+ }
1875
+ ast.push({
1876
+ type: "table",
1877
+ action: "create",
1878
+ schema: schemaName === "public" ? void 0 : schemaName,
1879
+ comment: table.comment,
1880
+ name,
1881
+ shape,
1882
+ noPrimaryKey: primaryKey ? "error" : "ignore",
1883
+ primaryKey: primaryKey && primaryKey.columnNames.length > 1 ? {
1884
+ columns: primaryKey.columnNames,
1885
+ options: primaryKey.name === `${name}_pkey` ? void 0 : { name: primaryKey.name }
1886
+ } : void 0,
1887
+ indexes: tableIndexes.filter(
1888
+ (index) => index.columns.length > 1 || index.columns.some((it) => "expression" in it)
1889
+ ).map((index) => ({
1890
+ columns: index.columns.map((it) => __spreadProps(__spreadValues({}, "column" in it ? { column: it.column } : { expression: it.expression }), {
1891
+ collate: it.collate,
1892
+ opclass: it.opclass,
1893
+ order: it.order
1894
+ })),
1895
+ options: {
1896
+ name: index.name,
1897
+ using: index.using === "btree" ? void 0 : index.using,
1898
+ unique: index.isUnique,
1899
+ include: index.include,
1900
+ with: index.with,
1901
+ tablespace: index.tablespace,
1902
+ where: index.where
1903
+ }
1904
+ })),
1905
+ foreignKeys: tableForeignKeys.filter((it) => it.columnNames.length > 1).map((it) => ({
1906
+ columns: it.columnNames,
1907
+ fnOrTable: it.foreignTableName,
1908
+ foreignColumns: it.foreignColumnNames,
1909
+ options: {
1910
+ name: it.name,
1911
+ match: matchMap[it.match],
1912
+ onUpdate: fkeyActionMap[it.onUpdate],
1913
+ onDelete: fkeyActionMap[it.onDelete]
1914
+ }
1915
+ }))
1916
+ });
1917
+ }
1918
+ for (const it of extensions) {
1919
+ ast.push({
1920
+ type: "extension",
1921
+ action: "create",
1922
+ name: it.name,
1923
+ schema: it.schemaName === "public" ? void 0 : it.schemaName,
1924
+ version: it.version
1925
+ });
1926
+ }
1927
+ return ast;
1928
+ };
1929
+ const makeBelongsToTable = (schema, table) => (item) => item.schemaName === schema && item.tableName === table;
1930
+ const getIsSerial = (item) => {
1931
+ if (item.type === "int2" || item.type === "int4" || item.type === "int8") {
1932
+ const { default: def, schemaName, tableName, name } = item;
1933
+ const seq = `${tableName}_${name}_seq`;
1934
+ if (def && (def === `nextval(${pqb.singleQuote(`${seq}`)}::regclass)` || def === `nextval(${pqb.singleQuote(`"${seq}"`)}::regclass)` || def === `nextval(${pqb.singleQuote(`${schemaName}.${seq}`)}::regclass)` || def === `nextval(${pqb.singleQuote(`"${schemaName}".${seq}`)}::regclass)` || def === `nextval(${pqb.singleQuote(`${schemaName}."${seq}"`)}::regclass)` || def === `nextval(${pqb.singleQuote(`"${schemaName}"."${seq}"`)}::regclass)`)) {
1935
+ return true;
1936
+ }
1937
+ }
1938
+ return false;
1939
+ };
1940
+ const getColumnType = (item, isSerial) => {
1941
+ if (isSerial) {
1942
+ return item.type === "int2" ? "smallserial" : item.type === "int4" ? "serial" : "bigserial";
1943
+ }
1944
+ return item.type;
1945
+ };
1946
+
1947
+ const astToMigration = (ast) => {
1948
+ const code = [];
1949
+ for (const item of ast) {
1950
+ if (item.type === "schema" && item.action === "create") {
1951
+ code.push(createSchema(item));
1952
+ } else if (item.type === "table" && item.action === "create") {
1953
+ if (code.length)
1954
+ code.push([]);
1955
+ code.push(...createTable(item));
1956
+ }
1957
+ }
1958
+ if (!code.length)
1959
+ return;
1960
+ return `import { change } from 'rake-db';
1961
+
1962
+ change(async (db) => {
1963
+ ${pqb.codeToString(code, " ", " ")}
1964
+ });
1965
+ `;
1966
+ };
1967
+ const createSchema = (ast) => {
1968
+ return `await db.createSchema(${pqb.singleQuote(ast.name)});`;
1969
+ };
1970
+ const createTable = (ast) => {
1971
+ const code = [];
1972
+ pqb.addCode(code, `await db.createTable(${quoteSchemaTable(ast)}, (t) => ({`);
1973
+ const hasTimestamps = isTimestamp(ast.shape.createdAt) && isTimestamp(ast.shape.updatedAt);
1974
+ for (const key in ast.shape) {
1975
+ if (hasTimestamps && (key === "createdAt" || key === "updatedAt"))
1976
+ continue;
1977
+ const line = [`${pqb.quoteObjectKey(key)}: `];
1978
+ for (const part of ast.shape[key].toCode("t")) {
1979
+ pqb.addCode(line, part);
1980
+ }
1981
+ pqb.addCode(line, ",");
1982
+ code.push(line);
1983
+ }
1984
+ if (hasTimestamps) {
1985
+ code.push(["...t.timestamps(),"]);
1986
+ }
1987
+ if (ast.primaryKey) {
1988
+ code.push([pqb.primaryKeyToCode(ast.primaryKey, "t")]);
1989
+ }
1990
+ for (const index of ast.indexes) {
1991
+ code.push(pqb.indexToCode(index, "t"));
1992
+ }
1993
+ for (const foreignKey of ast.foreignKeys) {
1994
+ code.push(pqb.foreignKeyToCode(foreignKey, "t"));
1995
+ }
1996
+ pqb.addCode(code, "}));");
1997
+ return code;
1998
+ };
1999
+ const isTimestamp = (column) => {
2000
+ if (!column)
2001
+ return false;
2002
+ const { default: def } = column.data;
2003
+ return column instanceof pqb.TimestampColumn && !column.data.isNullable && def && typeof def === "object" && pqb.isRaw(def) && def.__raw === "now()";
2004
+ };
2005
+
2006
+ const pullDbStructure = async (options, config) => {
2007
+ const adapter = new pqb.Adapter(options);
2008
+ const db = new DbStructure(adapter);
2009
+ const ast = await structureToAst(db);
2010
+ await adapter.close();
2011
+ const result = astToMigration(ast);
2012
+ if (!result)
2013
+ return;
2014
+ await writeMigrationFile(config, "pull", result);
2015
+ };
2016
+
1467
2017
  const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2)) => {
1468
2018
  var _a;
1469
2019
  const config = getMigrationConfigWithDefaults(partialConfig);
@@ -1480,6 +2030,8 @@ const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2))
1480
2030
  await rollback(options, config, args.slice(1));
1481
2031
  } else if (command === "g" || command === "generate") {
1482
2032
  await generate(config, args.slice(1));
2033
+ } else if (command === "pull") {
2034
+ await pullDbStructure(pqb.toArray(options)[0], config);
1483
2035
  } else {
1484
2036
  printHelp();
1485
2037
  }
@@ -1532,4 +2084,5 @@ exports.rakeDb = rakeDb;
1532
2084
  exports.resetDb = resetDb;
1533
2085
  exports.rollback = rollback;
1534
2086
  exports.runCodeUpdater = runCodeUpdater;
2087
+ exports.writeMigrationFile = writeMigrationFile;
1535
2088
  //# sourceMappingURL=index.js.map