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.esm.js CHANGED
@@ -1,30 +1,30 @@
1
- import { quote, isRaw, getRaw, toArray, columnTypes, raw, getColumnTypes, getTableData, resetTableData, ColumnType, emptyObject, Operators, TransactionAdapter, logParamToLogObject, Adapter } from 'pqb';
1
+ import { singleQuote, quote, isRaw, getRaw, toArray, columnTypes, raw, getColumnTypes, getTableData, resetTableData, ColumnType, emptyObject, Operators, TransactionAdapter, logParamToLogObject, Adapter, columnsByType, instantiateColumn, codeToString, addCode, quoteObjectKey, primaryKeyToCode, indexToCode, foreignKeyToCode, TimestampColumn } from 'pqb';
2
2
  import Enquirer from 'enquirer';
3
3
  import path from 'path';
4
4
  import { readdir, mkdir, writeFile } from 'fs/promises';
5
5
  import { singular } from 'pluralize';
6
6
 
7
- var __defProp$6 = Object.defineProperty;
8
- var __defProps$5 = Object.defineProperties;
9
- var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
10
- var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
11
- var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
12
- var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
13
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
- var __spreadValues$6 = (a, b) => {
7
+ var __defProp$7 = Object.defineProperty;
8
+ var __defProps$6 = Object.defineProperties;
9
+ var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
10
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
11
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
12
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
13
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
+ var __spreadValues$7 = (a, b) => {
15
15
  for (var prop in b || (b = {}))
16
- if (__hasOwnProp$6.call(b, prop))
17
- __defNormalProp$6(a, prop, b[prop]);
18
- if (__getOwnPropSymbols$6)
19
- for (var prop of __getOwnPropSymbols$6(b)) {
20
- if (__propIsEnum$6.call(b, prop))
21
- __defNormalProp$6(a, prop, b[prop]);
16
+ if (__hasOwnProp$7.call(b, prop))
17
+ __defNormalProp$7(a, prop, b[prop]);
18
+ if (__getOwnPropSymbols$7)
19
+ for (var prop of __getOwnPropSymbols$7(b)) {
20
+ if (__propIsEnum$7.call(b, prop))
21
+ __defNormalProp$7(a, prop, b[prop]);
22
22
  }
23
23
  return a;
24
24
  };
25
- var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
25
+ var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
26
26
  const migrationConfigDefaults = {
27
- migrationsPath: path.resolve(process.cwd(), "src", "migrations"),
27
+ migrationsPath: path.resolve("src", "migrations"),
28
28
  migrationsTable: "schemaMigrations",
29
29
  requireTs: require,
30
30
  log: true,
@@ -32,7 +32,7 @@ const migrationConfigDefaults = {
32
32
  useCodeUpdater: true
33
33
  };
34
34
  const getMigrationConfigWithDefaults = (config) => {
35
- return __spreadValues$6(__spreadValues$6({}, migrationConfigDefaults), config);
35
+ return __spreadValues$7(__spreadValues$7({}, migrationConfigDefaults), config);
36
36
  };
37
37
  const getDatabaseAndUserFromOptions = (options) => {
38
38
  if (options.databaseURL) {
@@ -60,9 +60,9 @@ const setAdapterOptions = (options, set) => {
60
60
  if (set.password !== void 0) {
61
61
  url.password = set.password;
62
62
  }
63
- return __spreadProps$5(__spreadValues$6({}, options), { databaseURL: url.toString() });
63
+ return __spreadProps$6(__spreadValues$7({}, options), { databaseURL: url.toString() });
64
64
  } else {
65
- return __spreadValues$6(__spreadValues$6({}, options), set);
65
+ return __spreadValues$7(__spreadValues$7({}, options), set);
66
66
  }
67
67
  };
68
68
  const askAdminCredentials = async () => {
@@ -139,7 +139,7 @@ const getMigrationFiles = async (config, up) => {
139
139
  const { migrationsPath } = config;
140
140
  let files;
141
141
  try {
142
- files = await readdir(migrationsPath);
142
+ files = await readdir(path.resolve(migrationsPath));
143
143
  } catch (_) {
144
144
  return [];
145
145
  }
@@ -157,7 +157,7 @@ const getMigrationFiles = async (config, up) => {
157
157
  );
158
158
  }
159
159
  return {
160
- path: path.join(migrationsPath, file),
160
+ path: path.resolve(migrationsPath, file),
161
161
  version: timestampMatch[1]
162
162
  };
163
163
  });
@@ -183,6 +183,12 @@ const getSchemaAndTableFromName = (name) => {
183
183
  const index = name.indexOf(".");
184
184
  return index !== -1 ? [name.slice(0, index), name.slice(index + 1)] : [void 0, name];
185
185
  };
186
+ const quoteSchemaTable = ({
187
+ schema,
188
+ name
189
+ }) => {
190
+ return singleQuote(schema ? `${schema}.${name}` : name);
191
+ };
186
192
 
187
193
  let currentMigration;
188
194
  let currentPromise;
@@ -203,25 +209,25 @@ const setCurrentMigrationUp = (up) => {
203
209
  const getCurrentPromise = () => currentPromise;
204
210
  const getCurrentChangeCallback = () => currentChangeCallback;
205
211
 
206
- var __defProp$5 = Object.defineProperty;
207
- var __defProps$4 = Object.defineProperties;
208
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
209
- var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
210
- var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
211
- var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
212
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
213
- var __spreadValues$5 = (a, b) => {
212
+ var __defProp$6 = Object.defineProperty;
213
+ var __defProps$5 = Object.defineProperties;
214
+ var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
215
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
216
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
217
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
218
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
219
+ var __spreadValues$6 = (a, b) => {
214
220
  for (var prop in b || (b = {}))
215
- if (__hasOwnProp$5.call(b, prop))
216
- __defNormalProp$5(a, prop, b[prop]);
217
- if (__getOwnPropSymbols$5)
218
- for (var prop of __getOwnPropSymbols$5(b)) {
219
- if (__propIsEnum$5.call(b, prop))
220
- __defNormalProp$5(a, prop, b[prop]);
221
+ if (__hasOwnProp$6.call(b, prop))
222
+ __defNormalProp$6(a, prop, b[prop]);
223
+ if (__getOwnPropSymbols$6)
224
+ for (var prop of __getOwnPropSymbols$6(b)) {
225
+ if (__propIsEnum$6.call(b, prop))
226
+ __defNormalProp$6(a, prop, b[prop]);
221
227
  }
222
228
  return a;
223
229
  };
224
- var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
230
+ var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
225
231
  const columnToSql = (key, item, values, hasMultiplePrimaryKeys) => {
226
232
  const line = [`"${key}" ${item.toSQL()}`];
227
233
  if (item.data.compression) {
@@ -260,7 +266,7 @@ const addColumnIndex = (indexes, key, item) => {
260
266
  if (item.data.indexes) {
261
267
  indexes.push(
262
268
  ...item.data.indexes.map((index) => ({
263
- columns: [__spreadProps$4(__spreadValues$5({}, index), { column: key })],
269
+ columns: [__spreadProps$5(__spreadValues$6({}, index), { column: key })],
264
270
  options: index
265
271
  }))
266
272
  );
@@ -407,29 +413,29 @@ WHERE
407
413
  return rows;
408
414
  };
409
415
 
410
- var __defProp$4 = Object.defineProperty;
411
- var __defProps$3 = Object.defineProperties;
412
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
413
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
414
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
415
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
416
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
417
- var __spreadValues$4 = (a, b) => {
416
+ var __defProp$5 = Object.defineProperty;
417
+ var __defProps$4 = Object.defineProperties;
418
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
419
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
420
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
421
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
422
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
423
+ var __spreadValues$5 = (a, b) => {
418
424
  for (var prop in b || (b = {}))
419
- if (__hasOwnProp$4.call(b, prop))
420
- __defNormalProp$4(a, prop, b[prop]);
421
- if (__getOwnPropSymbols$4)
422
- for (var prop of __getOwnPropSymbols$4(b)) {
423
- if (__propIsEnum$4.call(b, prop))
424
- __defNormalProp$4(a, prop, b[prop]);
425
+ if (__hasOwnProp$5.call(b, prop))
426
+ __defNormalProp$5(a, prop, b[prop]);
427
+ if (__getOwnPropSymbols$5)
428
+ for (var prop of __getOwnPropSymbols$5(b)) {
429
+ if (__propIsEnum$5.call(b, prop))
430
+ __defNormalProp$5(a, prop, b[prop]);
425
431
  }
426
432
  return a;
427
433
  };
428
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
434
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
429
435
  const types = Object.assign(Object.create(columnTypes), {
430
436
  raw
431
437
  });
432
- const createTable = async (migration, up, tableName, options, fn) => {
438
+ const createTable$1 = async (migration, up, tableName, options, fn) => {
433
439
  const shape = getColumnTypes(types, fn);
434
440
  const tableData = getTableData();
435
441
  const ast = makeAst$1(
@@ -456,14 +462,14 @@ const makeAst$1 = (up, tableName, shape, tableData, options, noPrimaryKey) => {
456
462
  }
457
463
  const primaryKey = tableData.primaryKey;
458
464
  const [schema, table] = getSchemaAndTableFromName(tableName);
459
- return __spreadProps$3(__spreadValues$4(__spreadProps$3(__spreadValues$4({
465
+ return __spreadProps$4(__spreadValues$5(__spreadProps$4(__spreadValues$5({
460
466
  type: "table",
461
467
  action: up ? "create" : "drop",
462
468
  schema,
463
469
  name: table,
464
470
  shape
465
471
  }, tableData), {
466
- primaryKey: shapePKeys.length <= 1 ? primaryKey : primaryKey ? __spreadProps$3(__spreadValues$4({}, primaryKey), { columns: [...shapePKeys, ...primaryKey.columns] }) : { columns: shapePKeys }
472
+ primaryKey: shapePKeys.length <= 1 ? primaryKey : primaryKey ? __spreadProps$4(__spreadValues$5({}, primaryKey), { columns: [...shapePKeys, ...primaryKey.columns] }) : { columns: shapePKeys }
467
473
  }), options), {
468
474
  noPrimaryKey: options.noPrimaryKey ? "ignore" : noPrimaryKey || "error"
469
475
  });
@@ -537,25 +543,25 @@ const astToQueries$1 = (ast) => {
537
543
  return result;
538
544
  };
539
545
 
540
- var __defProp$3 = Object.defineProperty;
541
- var __defProps$2 = Object.defineProperties;
542
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
543
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
544
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
545
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
546
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
547
- var __spreadValues$3 = (a, b) => {
546
+ var __defProp$4 = Object.defineProperty;
547
+ var __defProps$3 = Object.defineProperties;
548
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
549
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
550
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
551
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
552
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
553
+ var __spreadValues$4 = (a, b) => {
548
554
  for (var prop in b || (b = {}))
549
- if (__hasOwnProp$3.call(b, prop))
550
- __defNormalProp$3(a, prop, b[prop]);
551
- if (__getOwnPropSymbols$3)
552
- for (var prop of __getOwnPropSymbols$3(b)) {
553
- if (__propIsEnum$3.call(b, prop))
554
- __defNormalProp$3(a, prop, b[prop]);
555
+ if (__hasOwnProp$4.call(b, prop))
556
+ __defNormalProp$4(a, prop, b[prop]);
557
+ if (__getOwnPropSymbols$4)
558
+ for (var prop of __getOwnPropSymbols$4(b)) {
559
+ if (__propIsEnum$4.call(b, prop))
560
+ __defNormalProp$4(a, prop, b[prop]);
555
561
  }
556
562
  return a;
557
563
  };
558
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
564
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
559
565
  const newChangeTableData = () => ({
560
566
  add: { indexes: [], foreignKeys: [] },
561
567
  drop: { indexes: [], foreignKeys: [] }
@@ -571,7 +577,7 @@ const mergeTableData = (a, b) => {
571
577
  } else {
572
578
  a.primaryKey = {
573
579
  columns: [...a.primaryKey.columns, ...b.primaryKey.columns],
574
- options: __spreadValues$3(__spreadValues$3({}, a.primaryKey.options), b.primaryKey.options)
580
+ options: __spreadValues$4(__spreadValues$4({}, a.primaryKey.options), b.primaryKey.options)
575
581
  };
576
582
  }
577
583
  }
@@ -622,7 +628,7 @@ const columnTypeToColumnChange = (item) => {
622
628
  if (foreignKeys == null ? void 0 : foreignKeys.some((it) => "fn" in it)) {
623
629
  throw new Error("Callback in foreignKey is not allowed in migration");
624
630
  }
625
- return __spreadProps$2(__spreadValues$3({
631
+ return __spreadProps$3(__spreadValues$4({
626
632
  column: item,
627
633
  type: item.toSQL(),
628
634
  nullable: item.data.isNullable,
@@ -638,7 +644,7 @@ const tableChangeMethods = {
638
644
  add,
639
645
  drop,
640
646
  change(from, to, options) {
641
- return __spreadValues$3({
647
+ return __spreadValues$4({
642
648
  type: "change",
643
649
  from: columnTypeToColumnChange(from),
644
650
  to: columnTypeToColumnChange(to)
@@ -688,18 +694,18 @@ const makeAst = (up, name, changeData, changeTableData2, options) => {
688
694
  const item = changeData[key];
689
695
  if ("type" in item) {
690
696
  if (up) {
691
- shape[key] = item.type === "change" && item.usingUp ? __spreadProps$2(__spreadValues$3({}, item), { using: item.usingUp }) : item;
697
+ shape[key] = item.type === "change" && item.usingUp ? __spreadProps$3(__spreadValues$4({}, item), { using: item.usingUp }) : item;
692
698
  } else {
693
699
  if (item.type === "rename") {
694
- shape[item.name] = __spreadProps$2(__spreadValues$3({}, item), { name: key });
700
+ shape[item.name] = __spreadProps$3(__spreadValues$4({}, item), { name: key });
695
701
  } else {
696
- 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;
702
+ 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;
697
703
  }
698
704
  }
699
705
  }
700
706
  }
701
707
  const [schema, table] = getSchemaAndTableFromName(name);
702
- return __spreadValues$3({
708
+ return __spreadValues$4({
703
709
  type: "changeTable",
704
710
  schema,
705
711
  name: table,
@@ -716,10 +722,10 @@ const astToQueries = (ast) => {
716
722
  values: []
717
723
  });
718
724
  }
719
- const addPrimaryKeys = ast.add.primaryKey ? __spreadValues$3({}, ast.add.primaryKey) : {
725
+ const addPrimaryKeys = ast.add.primaryKey ? __spreadValues$4({}, ast.add.primaryKey) : {
720
726
  columns: []
721
727
  };
722
- const dropPrimaryKeys = ast.drop.primaryKey ? __spreadValues$3({}, ast.drop.primaryKey) : {
728
+ const dropPrimaryKeys = ast.drop.primaryKey ? __spreadValues$4({}, ast.drop.primaryKey) : {
723
729
  columns: []
724
730
  };
725
731
  for (const key in ast.shape) {
@@ -827,7 +833,7 @@ const astToQueries = (ast) => {
827
833
  if (fromIndex) {
828
834
  dropIndexes.push({
829
835
  columns: [
830
- __spreadValues$3({
836
+ __spreadValues$4({
831
837
  column: key
832
838
  }, fromIndex)
833
839
  ],
@@ -837,7 +843,7 @@ const astToQueries = (ast) => {
837
843
  if (toIndex) {
838
844
  addIndexes.push({
839
845
  columns: [
840
- __spreadValues$3({
846
+ __spreadValues$4({
841
847
  column: key
842
848
  }, toIndex)
843
849
  ],
@@ -887,25 +893,25 @@ const astToQueries = (ast) => {
887
893
  return result;
888
894
  };
889
895
 
890
- var __defProp$2 = Object.defineProperty;
891
- var __defProps$1 = Object.defineProperties;
892
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
893
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
894
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
895
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
896
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
897
- var __spreadValues$2 = (a, b) => {
896
+ var __defProp$3 = Object.defineProperty;
897
+ var __defProps$2 = Object.defineProperties;
898
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
899
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
900
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
901
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
902
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
903
+ var __spreadValues$3 = (a, b) => {
898
904
  for (var prop in b || (b = {}))
899
- if (__hasOwnProp$2.call(b, prop))
900
- __defNormalProp$2(a, prop, b[prop]);
901
- if (__getOwnPropSymbols$2)
902
- for (var prop of __getOwnPropSymbols$2(b)) {
903
- if (__propIsEnum$2.call(b, prop))
904
- __defNormalProp$2(a, prop, b[prop]);
905
+ if (__hasOwnProp$3.call(b, prop))
906
+ __defNormalProp$3(a, prop, b[prop]);
907
+ if (__getOwnPropSymbols$3)
908
+ for (var prop of __getOwnPropSymbols$3(b)) {
909
+ if (__propIsEnum$3.call(b, prop))
910
+ __defNormalProp$3(a, prop, b[prop]);
905
911
  }
906
912
  return a;
907
913
  };
908
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
914
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
909
915
  class UnknownColumn extends ColumnType {
910
916
  constructor(dataType) {
911
917
  super();
@@ -919,18 +925,18 @@ class UnknownColumn extends ColumnType {
919
925
  const createJoinTable = async (migration, up, tables, options, fn) => {
920
926
  const tableName = options.tableName || joinWords(...tables);
921
927
  if (!up) {
922
- return createTable(
928
+ return createTable$1(
923
929
  migration,
924
930
  up,
925
931
  tableName,
926
- __spreadProps$1(__spreadValues$2({}, options), { noPrimaryKey: true }),
932
+ __spreadProps$2(__spreadValues$3({}, options), { noPrimaryKey: true }),
927
933
  () => ({})
928
934
  );
929
935
  }
930
936
  const tablesWithPrimaryKeys = await Promise.all(
931
937
  tables.map(async (table) => {
932
938
  const primaryKeys = await getPrimaryKeysOfTable(migration, table).then(
933
- (items) => items.map((item) => __spreadProps$1(__spreadValues$2({}, item), {
939
+ (items) => items.map((item) => __spreadProps$2(__spreadValues$3({}, item), {
934
940
  joinedName: joinWords(singular(table), item.name)
935
941
  }))
936
942
  );
@@ -946,7 +952,7 @@ const createJoinTable = async (migration, up, tables, options, fn) => {
946
952
  return [schema, table, primaryKeys];
947
953
  })
948
954
  );
949
- return createTable(migration, up, tableName, options, (t) => {
955
+ return createTable$1(migration, up, tableName, options, (t) => {
950
956
  const result = {};
951
957
  tablesWithPrimaryKeys.forEach(([schema, table, primaryKeys]) => {
952
958
  if (primaryKeys.length === 1) {
@@ -979,25 +985,25 @@ const createJoinTable = async (migration, up, tables, options, fn) => {
979
985
  });
980
986
  };
981
987
 
982
- var __defProp$1 = Object.defineProperty;
983
- var __defProps = Object.defineProperties;
984
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
985
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
986
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
987
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
988
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
989
- var __spreadValues$1 = (a, b) => {
988
+ var __defProp$2 = Object.defineProperty;
989
+ var __defProps$1 = Object.defineProperties;
990
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
991
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
992
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
993
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
994
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
995
+ var __spreadValues$2 = (a, b) => {
990
996
  for (var prop in b || (b = {}))
991
- if (__hasOwnProp$1.call(b, prop))
992
- __defNormalProp$1(a, prop, b[prop]);
993
- if (__getOwnPropSymbols$1)
994
- for (var prop of __getOwnPropSymbols$1(b)) {
995
- if (__propIsEnum$1.call(b, prop))
996
- __defNormalProp$1(a, prop, b[prop]);
997
+ if (__hasOwnProp$2.call(b, prop))
998
+ __defNormalProp$2(a, prop, b[prop]);
999
+ if (__getOwnPropSymbols$2)
1000
+ for (var prop of __getOwnPropSymbols$2(b)) {
1001
+ if (__propIsEnum$2.call(b, prop))
1002
+ __defNormalProp$2(a, prop, b[prop]);
997
1003
  }
998
1004
  return a;
999
1005
  };
1000
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1006
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
1001
1007
  class Migration extends TransactionAdapter {
1002
1008
  constructor(tx, up, options, adapterOptions, appCodeUpdaterCache) {
1003
1009
  super(tx, tx.client, tx.types);
@@ -1016,12 +1022,12 @@ class Migration extends TransactionAdapter {
1016
1022
  createTable(tableName, cbOrOptions, cb) {
1017
1023
  const options = typeof cbOrOptions === "function" ? {} : cbOrOptions;
1018
1024
  const fn = cb || cbOrOptions;
1019
- return createTable(this, this.up, tableName, options, fn);
1025
+ return createTable$1(this, this.up, tableName, options, fn);
1020
1026
  }
1021
1027
  dropTable(tableName, cbOrOptions, cb) {
1022
1028
  const options = typeof cbOrOptions === "function" ? {} : cbOrOptions;
1023
1029
  const fn = cb || cbOrOptions;
1024
- return createTable(this, !this.up, tableName, options, fn);
1030
+ return createTable$1(this, !this.up, tableName, options, fn);
1025
1031
  }
1026
1032
  async createJoinTable(tables, cbOrOptions, cb) {
1027
1033
  const options = typeof cbOrOptions === "function" ? {} : cbOrOptions || {};
@@ -1104,10 +1110,10 @@ class Migration extends TransactionAdapter {
1104
1110
  }));
1105
1111
  }
1106
1112
  createSchema(schemaName) {
1107
- return createSchema(this, this.up, schemaName);
1113
+ return createSchema$1(this, this.up, schemaName);
1108
1114
  }
1109
1115
  dropSchema(schemaName) {
1110
- return createSchema(this, !this.up, schemaName);
1116
+ return createSchema$1(this, !this.up, schemaName);
1111
1117
  }
1112
1118
  createExtension(name, options = {}) {
1113
1119
  return createExtension(this, this.up, name, options);
@@ -1138,7 +1144,7 @@ const wrapWithLog = async (log, query, fn) => {
1138
1144
  if (!log) {
1139
1145
  return fn();
1140
1146
  } else {
1141
- const sql = typeof query === "string" ? { text: query, values: [] } : query.values ? query : __spreadProps(__spreadValues$1({}, query), { values: [] });
1147
+ const sql = typeof query === "string" ? { text: query, values: [] } : query.values ? query : __spreadProps$1(__spreadValues$2({}, query), { values: [] });
1142
1148
  const logData = log.beforeQuery(sql);
1143
1149
  try {
1144
1150
  const result = await fn();
@@ -1156,15 +1162,15 @@ const addColumn = (migration, up, tableName, columnName, fn) => {
1156
1162
  }));
1157
1163
  };
1158
1164
  const addIndex = (migration, up, tableName, columns, options) => {
1159
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$1({}, t.add(t.index(columns, options))));
1165
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$2({}, t.add(t.index(columns, options))));
1160
1166
  };
1161
1167
  const addForeignKey = (migration, up, tableName, columns, foreignTable, foreignColumns, options) => {
1162
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$1({}, t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))));
1168
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$2({}, t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))));
1163
1169
  };
1164
1170
  const addPrimaryKey = (migration, up, tableName, columns, options) => {
1165
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$1({}, t.add(t.primaryKey(columns, options))));
1171
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$2({}, t.add(t.primaryKey(columns, options))));
1166
1172
  };
1167
- const createSchema = async (migration, up, name) => {
1173
+ const createSchema$1 = async (migration, up, name) => {
1168
1174
  const ast = {
1169
1175
  type: "schema",
1170
1176
  action: up ? "create" : "drop",
@@ -1176,7 +1182,7 @@ const createSchema = async (migration, up, name) => {
1176
1182
  await runCodeUpdater(migration, ast);
1177
1183
  };
1178
1184
  const createExtension = async (migration, up, name, options) => {
1179
- const ast = __spreadValues$1({
1185
+ const ast = __spreadValues$2({
1180
1186
  type: "extension",
1181
1187
  action: up ? "create" : "drop",
1182
1188
  name
@@ -1202,25 +1208,25 @@ const runCodeUpdater = (migration, ast) => {
1202
1208
  });
1203
1209
  };
1204
1210
 
1205
- var __defProp = Object.defineProperty;
1206
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1207
- var __hasOwnProp = Object.prototype.hasOwnProperty;
1208
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
1209
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1210
- var __spreadValues = (a, b) => {
1211
+ var __defProp$1 = Object.defineProperty;
1212
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
1213
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
1214
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
1215
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1216
+ var __spreadValues$1 = (a, b) => {
1211
1217
  for (var prop in b || (b = {}))
1212
- if (__hasOwnProp.call(b, prop))
1213
- __defNormalProp(a, prop, b[prop]);
1214
- if (__getOwnPropSymbols)
1215
- for (var prop of __getOwnPropSymbols(b)) {
1216
- if (__propIsEnum.call(b, prop))
1217
- __defNormalProp(a, prop, b[prop]);
1218
+ if (__hasOwnProp$1.call(b, prop))
1219
+ __defNormalProp$1(a, prop, b[prop]);
1220
+ if (__getOwnPropSymbols$1)
1221
+ for (var prop of __getOwnPropSymbols$1(b)) {
1222
+ if (__propIsEnum$1.call(b, prop))
1223
+ __defNormalProp$1(a, prop, b[prop]);
1218
1224
  }
1219
1225
  return a;
1220
1226
  };
1221
1227
  const migrateOrRollback = async (options, config, args, up) => {
1222
1228
  var _a;
1223
- config = __spreadValues({}, config);
1229
+ config = __spreadValues$1({}, config);
1224
1230
  const files = await getMigrationFiles(config, up);
1225
1231
  let count = up ? Infinity : 1;
1226
1232
  let argI = 0;
@@ -1389,18 +1395,21 @@ const resetDb = async (arg, config) => {
1389
1395
  await migrate(arg, config);
1390
1396
  };
1391
1397
 
1392
- const generate = async (config, args) => {
1393
- const name = args[0];
1394
- if (!name)
1395
- throw new Error("Migration name is missing");
1396
- await mkdir(config.migrationsPath, { recursive: true });
1398
+ const writeMigrationFile = async (config, name, content) => {
1399
+ await mkdir(path.resolve(config.migrationsPath), { recursive: true });
1397
1400
  const filePath = path.resolve(
1398
1401
  config.migrationsPath,
1399
1402
  `${makeFileTimeStamp()}_${name}.ts`
1400
1403
  );
1401
- await writeFile(filePath, makeContent(name, args.slice(1)));
1404
+ await writeFile(filePath, content);
1402
1405
  console.log(`Created ${filePath}`);
1403
1406
  };
1407
+ const generate = async (config, args) => {
1408
+ const name = args[0];
1409
+ if (!name)
1410
+ throw new Error("Migration name is missing");
1411
+ await writeMigrationFile(config, name, makeContent(name, args.slice(1)));
1412
+ };
1404
1413
  const makeFileTimeStamp = () => {
1405
1414
  const now = new Date();
1406
1415
  return [
@@ -1455,6 +1464,547 @@ const makeColumnsContent = (args, method) => {
1455
1464
  return content;
1456
1465
  };
1457
1466
 
1467
+ const filterSchema = (table) => `${table} !~ '^pg_' AND ${table} != 'information_schema'`;
1468
+ class DbStructure {
1469
+ constructor(db) {
1470
+ this.db = db;
1471
+ }
1472
+ async getSchemas() {
1473
+ const { rows } = await this.db.arrays(
1474
+ `SELECT n.nspname "name"
1475
+ FROM pg_catalog.pg_namespace n
1476
+ WHERE ${filterSchema("n.nspname")}
1477
+ ORDER BY "name"`
1478
+ );
1479
+ return rows.flat();
1480
+ }
1481
+ async getTables() {
1482
+ const { rows } = await this.db.query(
1483
+ `SELECT
1484
+ nspname AS "schemaName",
1485
+ relname AS "name",
1486
+ obj_description(c.oid) AS comment
1487
+ FROM pg_class c
1488
+ JOIN pg_catalog.pg_namespace n ON n.oid = relnamespace
1489
+ WHERE relkind = 'r'
1490
+ AND ${filterSchema("nspname")}
1491
+ ORDER BY relname`
1492
+ );
1493
+ return rows;
1494
+ }
1495
+ async getViews() {
1496
+ const { rows } = await this.db.query(
1497
+ `SELECT
1498
+ table_schema "schemaName",
1499
+ table_name "name"
1500
+ FROM information_schema.tables
1501
+ WHERE table_type = 'VIEW'
1502
+ AND ${filterSchema("table_schema")}
1503
+ ORDER BY table_name`
1504
+ );
1505
+ return rows;
1506
+ }
1507
+ async getProcedures() {
1508
+ const { rows } = await this.db.query(
1509
+ `SELECT
1510
+ n.nspname AS "schemaName",
1511
+ proname AS name,
1512
+ proretset AS "returnSet",
1513
+ (
1514
+ SELECT typname FROM pg_type WHERE oid = prorettype
1515
+ ) AS "returnType",
1516
+ prokind AS "kind",
1517
+ coalesce((
1518
+ SELECT true FROM information_schema.triggers
1519
+ WHERE n.nspname = trigger_schema AND trigger_name = proname
1520
+ LIMIT 1
1521
+ ), false) AS "isTrigger",
1522
+ coalesce((
1523
+ SELECT json_agg(pg_type.typname)
1524
+ FROM unnest(coalesce(proallargtypes, proargtypes)) typeId
1525
+ JOIN pg_type ON pg_type.oid = typeId
1526
+ ), '[]') AS "types",
1527
+ coalesce(to_json(proallargtypes::int[]), to_json(proargtypes::int[])) AS "argTypes",
1528
+ coalesce(to_json(proargmodes), '[]') AS "argModes",
1529
+ to_json(proargnames) AS "argNames"
1530
+ FROM pg_proc p
1531
+ JOIN pg_namespace n ON p.pronamespace = n.oid
1532
+ WHERE ${filterSchema("n.nspname")}`
1533
+ );
1534
+ return rows;
1535
+ }
1536
+ async getColumns() {
1537
+ const { rows } = await this.db.query(
1538
+ `SELECT
1539
+ table_schema "schemaName",
1540
+ table_name "tableName",
1541
+ column_name "name",
1542
+ udt_name "type",
1543
+ character_maximum_length AS "maxChars",
1544
+ numeric_precision AS "numericPrecision",
1545
+ numeric_scale AS "numericScale",
1546
+ datetime_precision AS "dateTimePrecision",
1547
+ column_default "default",
1548
+ is_nullable::boolean "isNullable",
1549
+ collation_name AS "collation",
1550
+ NULLIF(a.attcompression, '') AS compression,
1551
+ pgd.description AS "comment"
1552
+ FROM information_schema.columns c
1553
+ LEFT JOIN pg_catalog.pg_statio_all_tables AS st
1554
+ ON c.table_schema = st.schemaname
1555
+ AND c.table_name = st.relname
1556
+ LEFT JOIN pg_catalog.pg_description pgd
1557
+ ON pgd.objoid = st.relid
1558
+ AND pgd.objsubid = c.ordinal_position
1559
+ LEFT JOIN pg_catalog.pg_attribute a
1560
+ ON a.attrelid = st.relid
1561
+ AND a.attnum = c.ordinal_position
1562
+ WHERE ${filterSchema("table_schema")}
1563
+ ORDER BY c.ordinal_position`
1564
+ );
1565
+ return rows;
1566
+ }
1567
+ async getIndexes() {
1568
+ const { rows } = await this.db.query(
1569
+ `SELECT
1570
+ n.nspname "schemaName",
1571
+ t.relname "tableName",
1572
+ ic.relname "name",
1573
+ am.amname AS "using",
1574
+ i.indisunique "isUnique",
1575
+ (
1576
+ SELECT json_agg(
1577
+ (
1578
+ CASE WHEN t.e = 0
1579
+ THEN jsonb_build_object('expression', pg_get_indexdef(i.indexrelid, t.i::int4, false))
1580
+ ELSE jsonb_build_object('column', (
1581
+ (
1582
+ SELECT attname
1583
+ FROM pg_catalog.pg_attribute
1584
+ WHERE attrelid = i.indrelid
1585
+ AND attnum = t.e
1586
+ )
1587
+ ))
1588
+ END
1589
+ ) || (
1590
+ CASE WHEN i.indcollation[t.i - 1] = 0
1591
+ THEN '{}'::jsonb
1592
+ ELSE (
1593
+ SELECT (
1594
+ CASE WHEN collname = 'default'
1595
+ THEN '{}'::jsonb
1596
+ ELSE jsonb_build_object('collate', collname)
1597
+ END
1598
+ )
1599
+ FROM pg_catalog.pg_collation
1600
+ WHERE oid = i.indcollation[t.i - 1]
1601
+ )
1602
+ END
1603
+ ) || (
1604
+ SELECT
1605
+ CASE WHEN opcdefault AND attoptions IS NULL
1606
+ THEN '{}'::jsonb
1607
+ ELSE jsonb_build_object(
1608
+ 'opclass', opcname || COALESCE('(' || array_to_string(attoptions, ', ') || ')', '')
1609
+ )
1610
+ END
1611
+ FROM pg_opclass
1612
+ LEFT JOIN pg_attribute
1613
+ ON attrelid = i.indexrelid
1614
+ AND attnum = t.i
1615
+ WHERE oid = i.indclass[t.i - 1]
1616
+ ) || (
1617
+ CASE WHEN i.indoption[t.i - 1] = 0
1618
+ THEN '{}'::jsonb
1619
+ ELSE jsonb_build_object(
1620
+ 'order',
1621
+ CASE
1622
+ WHEN i.indoption[t.i - 1] = 1 THEN 'DESC NULLS LAST'
1623
+ WHEN i.indoption[t.i - 1] = 2 THEN 'ASC NULLS FIRST'
1624
+ WHEN i.indoption[t.i - 1] = 3 THEN 'DESC'
1625
+ ELSE NULL
1626
+ END
1627
+ )
1628
+ END
1629
+ )
1630
+ )
1631
+ FROM unnest(i.indkey[:indnkeyatts - 1]) WITH ORDINALITY AS t(e, i)
1632
+ ) "columns",
1633
+ (
1634
+ SELECT json_agg(
1635
+ (
1636
+ SELECT attname
1637
+ FROM pg_catalog.pg_attribute
1638
+ WHERE attrelid = i.indrelid
1639
+ AND attnum = j.e
1640
+ )
1641
+ )
1642
+ FROM unnest(i.indkey[indnkeyatts:]) AS j(e)
1643
+ ) AS "include",
1644
+ NULLIF(pg_catalog.array_to_string(
1645
+ ic.reloptions || array(SELECT 'toast.' || x FROM pg_catalog.unnest(tc.reloptions) x),
1646
+ ', '
1647
+ ), '') AS "with",
1648
+ (
1649
+ SELECT tablespace
1650
+ FROM pg_indexes
1651
+ WHERE schemaname = n.nspname
1652
+ AND indexname = ic.relname
1653
+ ) AS tablespace,
1654
+ pg_get_expr(i.indpred, i.indrelid) AS "where"
1655
+ FROM pg_index i
1656
+ JOIN pg_class t ON t.oid = i.indrelid
1657
+ JOIN pg_namespace n ON n.oid = t.relnamespace
1658
+ JOIN pg_class ic ON ic.oid = i.indexrelid
1659
+ JOIN pg_am am ON am.oid = ic.relam
1660
+ LEFT JOIN pg_catalog.pg_class tc ON (ic.reltoastrelid = tc.oid)
1661
+ WHERE ${filterSchema("n.nspname")}
1662
+ AND NOT i.indisprimary
1663
+ ORDER BY ic.relname`
1664
+ );
1665
+ return rows;
1666
+ }
1667
+ async getForeignKeys() {
1668
+ const { rows } = await this.db.query(
1669
+ `SELECT
1670
+ s.nspname AS "schemaName",
1671
+ t.relname AS "tableName",
1672
+ fs.nspname AS "foreignTableSchemaName",
1673
+ ft.relname AS "foreignTableName",
1674
+ c.conname AS "name",
1675
+ (
1676
+ SELECT json_agg(ccu.column_name)
1677
+ FROM information_schema.key_column_usage ccu
1678
+ WHERE ccu.constraint_name = c.conname
1679
+ AND ccu.table_schema = cs.nspname
1680
+ ) AS "columnNames",
1681
+ (
1682
+ SELECT json_agg(ccu.column_name)
1683
+ FROM information_schema.constraint_column_usage ccu
1684
+ WHERE ccu.constraint_name = c.conname
1685
+ AND ccu.table_schema = cs.nspname
1686
+ ) AS "foreignColumnNames",
1687
+ c.confmatchtype AS match,
1688
+ c.confupdtype AS "onUpdate",
1689
+ c.confdeltype AS "onDelete"
1690
+ FROM pg_catalog.pg_constraint c
1691
+ JOIN pg_class t ON t.oid = conrelid
1692
+ JOIN pg_catalog.pg_namespace s ON s.oid = t.relnamespace
1693
+ JOIN pg_class ft ON ft.oid = confrelid
1694
+ JOIN pg_catalog.pg_namespace fs ON fs.oid = ft.relnamespace
1695
+ JOIN pg_catalog.pg_namespace cs ON cs.oid = c.connamespace
1696
+ WHERE contype = 'f'
1697
+ ORDER BY c.conname`
1698
+ );
1699
+ return rows;
1700
+ }
1701
+ async getPrimaryKeys() {
1702
+ const { rows } = await this.db.query(
1703
+ `SELECT tc.table_schema AS "schemaName",
1704
+ tc.table_name AS "tableName",
1705
+ tc.constraint_name AS "name",
1706
+ json_agg(ccu.column_name) "columnNames"
1707
+ FROM information_schema.table_constraints tc
1708
+ JOIN information_schema.constraint_column_usage ccu
1709
+ ON ccu.constraint_name = tc.constraint_name
1710
+ AND ccu.table_schema = tc.table_schema
1711
+ WHERE tc.constraint_type = 'PRIMARY KEY'
1712
+ AND ${filterSchema("tc.table_schema")}
1713
+ GROUP BY "schemaName", "tableName", "name"
1714
+ ORDER BY "name"`
1715
+ );
1716
+ return rows;
1717
+ }
1718
+ async getTriggers() {
1719
+ const { rows } = await this.db.query(
1720
+ `SELECT event_object_schema AS "schemaName",
1721
+ event_object_table AS "tableName",
1722
+ trigger_schema AS "triggerSchema",
1723
+ trigger_name AS name,
1724
+ json_agg(event_manipulation) AS events,
1725
+ action_timing AS activation,
1726
+ action_condition AS condition,
1727
+ action_statement AS definition
1728
+ FROM information_schema.triggers
1729
+ WHERE ${filterSchema("event_object_schema")}
1730
+ GROUP BY event_object_schema, event_object_table, trigger_schema, trigger_name, action_timing, action_condition, action_statement
1731
+ ORDER BY trigger_name`
1732
+ );
1733
+ return rows;
1734
+ }
1735
+ async getExtensions() {
1736
+ const { rows } = await this.db.query(
1737
+ `SELECT
1738
+ nspname AS "schemaName",
1739
+ extname AS "name",
1740
+ extversion AS version
1741
+ FROM pg_extension
1742
+ JOIN pg_catalog.pg_namespace n ON n.oid = extnamespace
1743
+ AND ${filterSchema("n.nspname")}`
1744
+ );
1745
+ return rows;
1746
+ }
1747
+ }
1748
+
1749
+ var __defProp = Object.defineProperty;
1750
+ var __defProps = Object.defineProperties;
1751
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1752
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1753
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1754
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
1755
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1756
+ var __spreadValues = (a, b) => {
1757
+ for (var prop in b || (b = {}))
1758
+ if (__hasOwnProp.call(b, prop))
1759
+ __defNormalProp(a, prop, b[prop]);
1760
+ if (__getOwnPropSymbols)
1761
+ for (var prop of __getOwnPropSymbols(b)) {
1762
+ if (__propIsEnum.call(b, prop))
1763
+ __defNormalProp(a, prop, b[prop]);
1764
+ }
1765
+ return a;
1766
+ };
1767
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1768
+ const matchMap = {
1769
+ s: void 0,
1770
+ f: "FULL",
1771
+ p: "PARTIAL"
1772
+ };
1773
+ const fkeyActionMap = {
1774
+ a: void 0,
1775
+ r: "RESTRICT",
1776
+ c: "CASCADE",
1777
+ n: "SET NULL",
1778
+ d: "SET DEFAULT"
1779
+ };
1780
+ const structureToAst = async (db) => {
1781
+ const ast = [];
1782
+ const [
1783
+ schemas,
1784
+ tables,
1785
+ allColumns,
1786
+ allPrimaryKeys,
1787
+ allIndexes,
1788
+ allForeignKeys,
1789
+ extensions
1790
+ ] = await Promise.all([
1791
+ db.getSchemas(),
1792
+ db.getTables(),
1793
+ db.getColumns(),
1794
+ db.getPrimaryKeys(),
1795
+ db.getIndexes(),
1796
+ db.getForeignKeys(),
1797
+ db.getExtensions()
1798
+ ]);
1799
+ for (const name of schemas) {
1800
+ if (name === "public")
1801
+ continue;
1802
+ ast.push({
1803
+ type: "schema",
1804
+ action: "create",
1805
+ name
1806
+ });
1807
+ }
1808
+ for (const table of tables) {
1809
+ const { schemaName, name } = table;
1810
+ if (name === "schemaMigrations")
1811
+ continue;
1812
+ const belongsToTable = makeBelongsToTable(schemaName, name);
1813
+ const columns = allColumns.filter(belongsToTable);
1814
+ const primaryKey = allPrimaryKeys.find(belongsToTable);
1815
+ const tableIndexes = allIndexes.filter(belongsToTable);
1816
+ const tableForeignKeys = allForeignKeys.filter(belongsToTable);
1817
+ const shape = {};
1818
+ for (let item of columns) {
1819
+ const isSerial = getIsSerial(item);
1820
+ if (isSerial) {
1821
+ item = __spreadProps(__spreadValues({}, item), { default: void 0 });
1822
+ }
1823
+ const klass = columnsByType[getColumnType(item, isSerial)];
1824
+ if (!klass) {
1825
+ throw new Error(`Column type \`${item.type}\` is not supported`);
1826
+ }
1827
+ let column = instantiateColumn(klass, item);
1828
+ if ((primaryKey == null ? void 0 : primaryKey.columnNames.length) === 1 && (primaryKey == null ? void 0 : primaryKey.columnNames[0]) === item.name) {
1829
+ column = column.primaryKey();
1830
+ }
1831
+ const indexes = tableIndexes.filter(
1832
+ (it) => it.columns.length === 1 && "column" in it.columns[0] && it.columns[0].column === item.name
1833
+ );
1834
+ for (const index of indexes) {
1835
+ const options = index.columns[0];
1836
+ column = column.index({
1837
+ collate: options.collate,
1838
+ opclass: options.opclass,
1839
+ order: options.order,
1840
+ name: index.name,
1841
+ using: index.using === "btree" ? void 0 : index.using,
1842
+ unique: index.isUnique,
1843
+ include: index.include,
1844
+ with: index.with,
1845
+ tablespace: index.tablespace,
1846
+ where: index.where
1847
+ });
1848
+ }
1849
+ const foreignKeys = tableForeignKeys.filter(
1850
+ (it) => it.columnNames.length === 1 && it.columnNames[0] === item.name
1851
+ );
1852
+ for (const foreignKey of foreignKeys) {
1853
+ column = column.foreignKey(
1854
+ foreignKey.foreignTableName,
1855
+ foreignKey.foreignColumnNames[0],
1856
+ {
1857
+ name: foreignKey.name,
1858
+ match: matchMap[foreignKey.match],
1859
+ onUpdate: fkeyActionMap[foreignKey.onUpdate],
1860
+ onDelete: fkeyActionMap[foreignKey.onDelete]
1861
+ }
1862
+ );
1863
+ }
1864
+ shape[item.name] = column;
1865
+ }
1866
+ ast.push({
1867
+ type: "table",
1868
+ action: "create",
1869
+ schema: schemaName === "public" ? void 0 : schemaName,
1870
+ comment: table.comment,
1871
+ name,
1872
+ shape,
1873
+ noPrimaryKey: primaryKey ? "error" : "ignore",
1874
+ primaryKey: primaryKey && primaryKey.columnNames.length > 1 ? {
1875
+ columns: primaryKey.columnNames,
1876
+ options: primaryKey.name === `${name}_pkey` ? void 0 : { name: primaryKey.name }
1877
+ } : void 0,
1878
+ indexes: tableIndexes.filter(
1879
+ (index) => index.columns.length > 1 || index.columns.some((it) => "expression" in it)
1880
+ ).map((index) => ({
1881
+ columns: index.columns.map((it) => __spreadProps(__spreadValues({}, "column" in it ? { column: it.column } : { expression: it.expression }), {
1882
+ collate: it.collate,
1883
+ opclass: it.opclass,
1884
+ order: it.order
1885
+ })),
1886
+ options: {
1887
+ name: index.name,
1888
+ using: index.using === "btree" ? void 0 : index.using,
1889
+ unique: index.isUnique,
1890
+ include: index.include,
1891
+ with: index.with,
1892
+ tablespace: index.tablespace,
1893
+ where: index.where
1894
+ }
1895
+ })),
1896
+ foreignKeys: tableForeignKeys.filter((it) => it.columnNames.length > 1).map((it) => ({
1897
+ columns: it.columnNames,
1898
+ fnOrTable: it.foreignTableName,
1899
+ foreignColumns: it.foreignColumnNames,
1900
+ options: {
1901
+ name: it.name,
1902
+ match: matchMap[it.match],
1903
+ onUpdate: fkeyActionMap[it.onUpdate],
1904
+ onDelete: fkeyActionMap[it.onDelete]
1905
+ }
1906
+ }))
1907
+ });
1908
+ }
1909
+ for (const it of extensions) {
1910
+ ast.push({
1911
+ type: "extension",
1912
+ action: "create",
1913
+ name: it.name,
1914
+ schema: it.schemaName === "public" ? void 0 : it.schemaName,
1915
+ version: it.version
1916
+ });
1917
+ }
1918
+ return ast;
1919
+ };
1920
+ const makeBelongsToTable = (schema, table) => (item) => item.schemaName === schema && item.tableName === table;
1921
+ const getIsSerial = (item) => {
1922
+ if (item.type === "int2" || item.type === "int4" || item.type === "int8") {
1923
+ const { default: def, schemaName, tableName, name } = item;
1924
+ const seq = `${tableName}_${name}_seq`;
1925
+ if (def && (def === `nextval(${singleQuote(`${seq}`)}::regclass)` || def === `nextval(${singleQuote(`"${seq}"`)}::regclass)` || def === `nextval(${singleQuote(`${schemaName}.${seq}`)}::regclass)` || def === `nextval(${singleQuote(`"${schemaName}".${seq}`)}::regclass)` || def === `nextval(${singleQuote(`${schemaName}."${seq}"`)}::regclass)` || def === `nextval(${singleQuote(`"${schemaName}"."${seq}"`)}::regclass)`)) {
1926
+ return true;
1927
+ }
1928
+ }
1929
+ return false;
1930
+ };
1931
+ const getColumnType = (item, isSerial) => {
1932
+ if (isSerial) {
1933
+ return item.type === "int2" ? "smallserial" : item.type === "int4" ? "serial" : "bigserial";
1934
+ }
1935
+ return item.type;
1936
+ };
1937
+
1938
+ const astToMigration = (ast) => {
1939
+ const code = [];
1940
+ for (const item of ast) {
1941
+ if (item.type === "schema" && item.action === "create") {
1942
+ code.push(createSchema(item));
1943
+ } else if (item.type === "table" && item.action === "create") {
1944
+ if (code.length)
1945
+ code.push([]);
1946
+ code.push(...createTable(item));
1947
+ }
1948
+ }
1949
+ if (!code.length)
1950
+ return;
1951
+ return `import { change } from 'rake-db';
1952
+
1953
+ change(async (db) => {
1954
+ ${codeToString(code, " ", " ")}
1955
+ });
1956
+ `;
1957
+ };
1958
+ const createSchema = (ast) => {
1959
+ return `await db.createSchema(${singleQuote(ast.name)});`;
1960
+ };
1961
+ const createTable = (ast) => {
1962
+ const code = [];
1963
+ addCode(code, `await db.createTable(${quoteSchemaTable(ast)}, (t) => ({`);
1964
+ const hasTimestamps = isTimestamp(ast.shape.createdAt) && isTimestamp(ast.shape.updatedAt);
1965
+ for (const key in ast.shape) {
1966
+ if (hasTimestamps && (key === "createdAt" || key === "updatedAt"))
1967
+ continue;
1968
+ const line = [`${quoteObjectKey(key)}: `];
1969
+ for (const part of ast.shape[key].toCode("t")) {
1970
+ addCode(line, part);
1971
+ }
1972
+ addCode(line, ",");
1973
+ code.push(line);
1974
+ }
1975
+ if (hasTimestamps) {
1976
+ code.push(["...t.timestamps(),"]);
1977
+ }
1978
+ if (ast.primaryKey) {
1979
+ code.push([primaryKeyToCode(ast.primaryKey, "t")]);
1980
+ }
1981
+ for (const index of ast.indexes) {
1982
+ code.push(indexToCode(index, "t"));
1983
+ }
1984
+ for (const foreignKey of ast.foreignKeys) {
1985
+ code.push(foreignKeyToCode(foreignKey, "t"));
1986
+ }
1987
+ addCode(code, "}));");
1988
+ return code;
1989
+ };
1990
+ const isTimestamp = (column) => {
1991
+ if (!column)
1992
+ return false;
1993
+ const { default: def } = column.data;
1994
+ return column instanceof TimestampColumn && !column.data.isNullable && def && typeof def === "object" && isRaw(def) && def.__raw === "now()";
1995
+ };
1996
+
1997
+ const pullDbStructure = async (options, config) => {
1998
+ const adapter = new Adapter(options);
1999
+ const db = new DbStructure(adapter);
2000
+ const ast = await structureToAst(db);
2001
+ await adapter.close();
2002
+ const result = astToMigration(ast);
2003
+ if (!result)
2004
+ return;
2005
+ await writeMigrationFile(config, "pull", result);
2006
+ };
2007
+
1458
2008
  const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2)) => {
1459
2009
  var _a;
1460
2010
  const config = getMigrationConfigWithDefaults(partialConfig);
@@ -1471,6 +2021,8 @@ const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2))
1471
2021
  await rollback(options, config, args.slice(1));
1472
2022
  } else if (command === "g" || command === "generate") {
1473
2023
  await generate(config, args.slice(1));
2024
+ } else if (command === "pull") {
2025
+ await pullDbStructure(toArray(options)[0], config);
1474
2026
  } else {
1475
2027
  printHelp();
1476
2028
  }
@@ -1513,5 +2065,5 @@ Generate arguments:
1513
2065
  `
1514
2066
  );
1515
2067
 
1516
- export { Migration, change, createDb, dropDb, generate, migrate, rakeDb, resetDb, rollback, runCodeUpdater };
2068
+ export { Migration, change, createDb, dropDb, generate, migrate, rakeDb, resetDb, rollback, runCodeUpdater, writeMigrationFile };
1517
2069
  //# sourceMappingURL=index.esm.js.map