rake-db 2.2.6 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 } 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) {
@@ -242,26 +248,28 @@ const columnToSql = (key, item, values, hasMultiplePrimaryKeys) => {
242
248
  line.push(`DEFAULT ${quote(item.data.default)}`);
243
249
  }
244
250
  }
245
- const { foreignKey } = item.data;
246
- if (foreignKey) {
247
- const [schema, table] = getForeignKeyTable(
248
- "fn" in foreignKey ? foreignKey.fn : foreignKey.table
249
- );
250
- if (foreignKey.name) {
251
- line.push(`CONSTRAINT "${foreignKey.name}"`);
251
+ const { foreignKeys } = item.data;
252
+ if (foreignKeys) {
253
+ for (const foreignKey of foreignKeys) {
254
+ const [schema, table] = getForeignKeyTable(
255
+ "fn" in foreignKey ? foreignKey.fn : foreignKey.table
256
+ );
257
+ if (foreignKey.name) {
258
+ line.push(`CONSTRAINT "${foreignKey.name}"`);
259
+ }
260
+ line.push(referencesToSql(schema, table, foreignKey.columns, foreignKey));
252
261
  }
253
- line.push(referencesToSql(schema, table, foreignKey.columns, foreignKey));
254
262
  }
255
263
  return line.join(" ");
256
264
  };
257
265
  const addColumnIndex = (indexes, key, item) => {
258
- if (item.data) {
259
- if (item.data.index) {
260
- indexes.push({
261
- columns: [__spreadProps$4(__spreadValues$5({}, item.data.index), { column: key })],
262
- options: item.data.index
263
- });
264
- }
266
+ if (item.data.indexes) {
267
+ indexes.push(
268
+ ...item.data.indexes.map((index) => ({
269
+ columns: [__spreadProps$5(__spreadValues$6({}, index), { column: key })],
270
+ options: index
271
+ }))
272
+ );
265
273
  }
266
274
  };
267
275
  const addColumnComment = (comments, key, item) => {
@@ -311,7 +319,11 @@ const referencesToSql = (schema, table, columns, foreignKey) => {
311
319
  };
312
320
  const indexesToQuery = (up, { schema, name }, indexes) => {
313
321
  return indexes.map(({ columns, options }) => {
314
- const indexName = options.name || joinWords(name, ...columns.map(({ column }) => column), "index");
322
+ const indexName = options.name || joinWords(
323
+ name,
324
+ ...columns.filter((it) => "column" in it).map((it) => it.column),
325
+ "index"
326
+ );
315
327
  if (!up) {
316
328
  return {
317
329
  text: `DROP INDEX "${indexName}"${options.dropMode ? ` ${options.dropMode}` : ""}`,
@@ -330,13 +342,13 @@ const indexesToQuery = (up, { schema, name }, indexes) => {
330
342
  const columnsSql = [];
331
343
  columns.forEach((column) => {
332
344
  const columnSql = [
333
- `"${column.column}"${column.expression ? `(${column.expression})` : ""}`
345
+ "column" in column ? `"${column.column}"` : `(${column.expression})`
334
346
  ];
335
347
  if (column.collate) {
336
348
  columnSql.push(`COLLATE '${column.collate}'`);
337
349
  }
338
- if (column.operator) {
339
- columnSql.push(column.operator);
350
+ if (column.opclass) {
351
+ columnSql.push(column.opclass);
340
352
  }
341
353
  if (column.order) {
342
354
  columnSql.push(column.order);
@@ -401,29 +413,29 @@ WHERE
401
413
  return rows;
402
414
  };
403
415
 
404
- var __defProp$4 = Object.defineProperty;
405
- var __defProps$3 = Object.defineProperties;
406
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
407
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
408
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
409
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
410
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
411
- 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) => {
412
424
  for (var prop in b || (b = {}))
413
- if (__hasOwnProp$4.call(b, prop))
414
- __defNormalProp$4(a, prop, b[prop]);
415
- if (__getOwnPropSymbols$4)
416
- for (var prop of __getOwnPropSymbols$4(b)) {
417
- if (__propIsEnum$4.call(b, prop))
418
- __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]);
419
431
  }
420
432
  return a;
421
433
  };
422
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
434
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
423
435
  const types = Object.assign(Object.create(columnTypes), {
424
436
  raw
425
437
  });
426
- const createTable = async (migration, up, tableName, options, fn) => {
438
+ const createTable$1 = async (migration, up, tableName, options, fn) => {
427
439
  const shape = getColumnTypes(types, fn);
428
440
  const tableData = getTableData();
429
441
  const ast = makeAst$1(
@@ -450,14 +462,14 @@ const makeAst$1 = (up, tableName, shape, tableData, options, noPrimaryKey) => {
450
462
  }
451
463
  const primaryKey = tableData.primaryKey;
452
464
  const [schema, table] = getSchemaAndTableFromName(tableName);
453
- return __spreadProps$3(__spreadValues$4(__spreadProps$3(__spreadValues$4({
465
+ return __spreadProps$4(__spreadValues$5(__spreadProps$4(__spreadValues$5({
454
466
  type: "table",
455
467
  action: up ? "create" : "drop",
456
468
  schema,
457
469
  name: table,
458
470
  shape
459
471
  }, tableData), {
460
- 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 }
461
473
  }), options), {
462
474
  noPrimaryKey: options.noPrimaryKey ? "ignore" : noPrimaryKey || "error"
463
475
  });
@@ -531,25 +543,25 @@ const astToQueries$1 = (ast) => {
531
543
  return result;
532
544
  };
533
545
 
534
- var __defProp$3 = Object.defineProperty;
535
- var __defProps$2 = Object.defineProperties;
536
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
537
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
538
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
539
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
540
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
541
- 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) => {
542
554
  for (var prop in b || (b = {}))
543
- if (__hasOwnProp$3.call(b, prop))
544
- __defNormalProp$3(a, prop, b[prop]);
545
- if (__getOwnPropSymbols$3)
546
- for (var prop of __getOwnPropSymbols$3(b)) {
547
- if (__propIsEnum$3.call(b, prop))
548
- __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]);
549
561
  }
550
562
  return a;
551
563
  };
552
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
564
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
553
565
  const newChangeTableData = () => ({
554
566
  add: { indexes: [], foreignKeys: [] },
555
567
  drop: { indexes: [], foreignKeys: [] }
@@ -565,7 +577,7 @@ const mergeTableData = (a, b) => {
565
577
  } else {
566
578
  a.primaryKey = {
567
579
  columns: [...a.primaryKey.columns, ...b.primaryKey.columns],
568
- options: __spreadValues$3(__spreadValues$3({}, a.primaryKey.options), b.primaryKey.options)
580
+ options: __spreadValues$4(__spreadValues$4({}, a.primaryKey.options), b.primaryKey.options)
569
581
  };
570
582
  }
571
583
  }
@@ -612,17 +624,17 @@ const drop = (item, options) => {
612
624
  };
613
625
  const columnTypeToColumnChange = (item) => {
614
626
  if (item instanceof ColumnType) {
615
- const foreignKey = item.data.foreignKey;
616
- if (foreignKey && "fn" in foreignKey) {
627
+ const foreignKeys = item.data.foreignKeys;
628
+ if (foreignKeys == null ? void 0 : foreignKeys.some((it) => "fn" in it)) {
617
629
  throw new Error("Callback in foreignKey is not allowed in migration");
618
630
  }
619
- return __spreadProps$2(__spreadValues$3({
631
+ return __spreadProps$3(__spreadValues$4({
620
632
  column: item,
621
633
  type: item.toSQL(),
622
634
  nullable: item.data.isNullable,
623
635
  primaryKey: item.isPrimaryKey
624
636
  }, item.data), {
625
- foreignKey
637
+ foreignKeys
626
638
  });
627
639
  }
628
640
  return item.to;
@@ -632,7 +644,7 @@ const tableChangeMethods = {
632
644
  add,
633
645
  drop,
634
646
  change(from, to, options) {
635
- return __spreadValues$3({
647
+ return __spreadValues$4({
636
648
  type: "change",
637
649
  from: columnTypeToColumnChange(from),
638
650
  to: columnTypeToColumnChange(to)
@@ -682,18 +694,18 @@ const makeAst = (up, name, changeData, changeTableData2, options) => {
682
694
  const item = changeData[key];
683
695
  if ("type" in item) {
684
696
  if (up) {
685
- 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;
686
698
  } else {
687
699
  if (item.type === "rename") {
688
- shape[item.name] = __spreadProps$2(__spreadValues$3({}, item), { name: key });
700
+ shape[item.name] = __spreadProps$3(__spreadValues$4({}, item), { name: key });
689
701
  } else {
690
- 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;
691
703
  }
692
704
  }
693
705
  }
694
706
  }
695
707
  const [schema, table] = getSchemaAndTableFromName(name);
696
- return __spreadValues$3({
708
+ return __spreadValues$4({
697
709
  type: "changeTable",
698
710
  schema,
699
711
  name: table,
@@ -702,7 +714,7 @@ const makeAst = (up, name, changeData, changeTableData2, options) => {
702
714
  }, up ? changeTableData2 : { add: changeTableData2.drop, drop: changeTableData2.add });
703
715
  };
704
716
  const astToQueries = (ast) => {
705
- var _a;
717
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
706
718
  const result = [];
707
719
  if (ast.comment !== void 0) {
708
720
  result.push({
@@ -710,10 +722,10 @@ const astToQueries = (ast) => {
710
722
  values: []
711
723
  });
712
724
  }
713
- const addPrimaryKeys = ast.add.primaryKey ? __spreadValues$3({}, ast.add.primaryKey) : {
725
+ const addPrimaryKeys = ast.add.primaryKey ? __spreadValues$4({}, ast.add.primaryKey) : {
714
726
  columns: []
715
727
  };
716
- const dropPrimaryKeys = ast.drop.primaryKey ? __spreadValues$3({}, ast.drop.primaryKey) : {
728
+ const dropPrimaryKeys = ast.drop.primaryKey ? __spreadValues$4({}, ast.drop.primaryKey) : {
717
729
  columns: []
718
730
  };
719
731
  for (const key in ast.shape) {
@@ -784,48 +796,60 @@ const astToQueries = (ast) => {
784
796
  `ALTER COLUMN "${key}" SET COMPRESSION ${to.compression || "DEFAULT"}`
785
797
  );
786
798
  }
787
- const fromFkey = from.foreignKey;
788
- const toFkey = to.foreignKey;
789
- if ((fromFkey || toFkey) && (!fromFkey || !toFkey || fromFkey.name !== toFkey.name || fromFkey.match !== toFkey.match || fromFkey.onUpdate !== toFkey.onUpdate || fromFkey.onDelete !== toFkey.onDelete || fromFkey.dropMode !== toFkey.dropMode || fromFkey.table !== toFkey.table || fromFkey.columns.join(",") !== toFkey.columns.join(","))) {
790
- if (fromFkey) {
791
- dropForeignKeys.push({
792
- columns: [key],
793
- fnOrTable: fromFkey.table,
794
- foreignColumns: fromFkey.columns,
795
- options: fromFkey
796
- });
797
- }
798
- if (toFkey) {
799
- addForeignKeys.push({
800
- columns: [key],
801
- fnOrTable: toFkey.table,
802
- foreignColumns: toFkey.columns,
803
- options: toFkey
804
- });
799
+ const foreignKeysLen = Math.max(
800
+ ((_a = from.foreignKeys) == null ? void 0 : _a.length) || 0,
801
+ ((_b = to.foreignKeys) == null ? void 0 : _b.length) || 0
802
+ );
803
+ for (let i = 0; i < foreignKeysLen; i++) {
804
+ const fromFkey = (_c = from.foreignKeys) == null ? void 0 : _c[i];
805
+ const toFkey = (_d = to.foreignKeys) == null ? void 0 : _d[i];
806
+ if ((fromFkey || toFkey) && (!fromFkey || !toFkey || fromFkey.name !== toFkey.name || fromFkey.match !== toFkey.match || fromFkey.onUpdate !== toFkey.onUpdate || fromFkey.onDelete !== toFkey.onDelete || fromFkey.dropMode !== toFkey.dropMode || fromFkey.table !== toFkey.table || fromFkey.columns.join(",") !== toFkey.columns.join(","))) {
807
+ if (fromFkey) {
808
+ dropForeignKeys.push({
809
+ columns: [key],
810
+ fnOrTable: fromFkey.table,
811
+ foreignColumns: fromFkey.columns,
812
+ options: fromFkey
813
+ });
814
+ }
815
+ if (toFkey) {
816
+ addForeignKeys.push({
817
+ columns: [key],
818
+ fnOrTable: toFkey.table,
819
+ foreignColumns: toFkey.columns,
820
+ options: toFkey
821
+ });
822
+ }
805
823
  }
806
824
  }
807
- const fromIndex = from.index;
808
- const toIndex = to.index;
809
- if ((fromIndex || toIndex) && (!fromIndex || !toIndex || fromIndex.expression !== toIndex.expression || fromIndex.collate !== toIndex.collate || fromIndex.operator !== toIndex.operator || fromIndex.order !== toIndex.order || fromIndex.name !== toIndex.name || fromIndex.unique !== toIndex.unique || fromIndex.using !== toIndex.using || fromIndex.include !== toIndex.include || Array.isArray(fromIndex.include) && Array.isArray(toIndex.include) && fromIndex.include.join(",") !== toIndex.include.join(",") || fromIndex.with !== toIndex.with || fromIndex.tablespace !== toIndex.tablespace || fromIndex.where !== toIndex.where || fromIndex.dropMode !== toIndex.dropMode)) {
810
- if (fromIndex) {
811
- dropIndexes.push({
812
- columns: [
813
- __spreadValues$3({
814
- column: key
815
- }, fromIndex)
816
- ],
817
- options: fromIndex
818
- });
819
- }
820
- if (toIndex) {
821
- addIndexes.push({
822
- columns: [
823
- __spreadValues$3({
824
- column: key
825
- }, toIndex)
826
- ],
827
- options: toIndex
828
- });
825
+ const indexesLen = Math.max(
826
+ ((_e = from.indexes) == null ? void 0 : _e.length) || 0,
827
+ ((_f = to.indexes) == null ? void 0 : _f.length) || 0
828
+ );
829
+ for (let i = 0; i < indexesLen; i++) {
830
+ const fromIndex = (_g = from.indexes) == null ? void 0 : _g[i];
831
+ const toIndex = (_h = to.indexes) == null ? void 0 : _h[i];
832
+ if ((fromIndex || toIndex) && (!fromIndex || !toIndex || fromIndex.collate !== toIndex.collate || fromIndex.opclass !== toIndex.opclass || fromIndex.order !== toIndex.order || fromIndex.name !== toIndex.name || fromIndex.unique !== toIndex.unique || fromIndex.using !== toIndex.using || fromIndex.include !== toIndex.include || Array.isArray(fromIndex.include) && Array.isArray(toIndex.include) && fromIndex.include.join(",") !== toIndex.include.join(",") || fromIndex.with !== toIndex.with || fromIndex.tablespace !== toIndex.tablespace || fromIndex.where !== toIndex.where || fromIndex.dropMode !== toIndex.dropMode)) {
833
+ if (fromIndex) {
834
+ dropIndexes.push({
835
+ columns: [
836
+ __spreadValues$4({
837
+ column: key
838
+ }, fromIndex)
839
+ ],
840
+ options: fromIndex
841
+ });
842
+ }
843
+ if (toIndex) {
844
+ addIndexes.push({
845
+ columns: [
846
+ __spreadValues$4({
847
+ column: key
848
+ }, toIndex)
849
+ ],
850
+ options: toIndex
851
+ });
852
+ }
829
853
  }
830
854
  }
831
855
  if (from.comment !== to.comment) {
@@ -837,7 +861,7 @@ const astToQueries = (ast) => {
837
861
  }
838
862
  const prependAlterTable = [];
839
863
  if (ast.drop.primaryKey || dropPrimaryKeys.change || dropPrimaryKeys.columns.length > 1) {
840
- const name = ((_a = dropPrimaryKeys.options) == null ? void 0 : _a.name) || `${ast.name}_pkey`;
864
+ const name = ((_i = dropPrimaryKeys.options) == null ? void 0 : _i.name) || `${ast.name}_pkey`;
841
865
  prependAlterTable.push(`DROP CONSTRAINT "${name}"`);
842
866
  }
843
867
  prependAlterTable.push(
@@ -869,25 +893,25 @@ const astToQueries = (ast) => {
869
893
  return result;
870
894
  };
871
895
 
872
- var __defProp$2 = Object.defineProperty;
873
- var __defProps$1 = Object.defineProperties;
874
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
875
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
876
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
877
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
878
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
879
- 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) => {
880
904
  for (var prop in b || (b = {}))
881
- if (__hasOwnProp$2.call(b, prop))
882
- __defNormalProp$2(a, prop, b[prop]);
883
- if (__getOwnPropSymbols$2)
884
- for (var prop of __getOwnPropSymbols$2(b)) {
885
- if (__propIsEnum$2.call(b, prop))
886
- __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]);
887
911
  }
888
912
  return a;
889
913
  };
890
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
914
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
891
915
  class UnknownColumn extends ColumnType {
892
916
  constructor(dataType) {
893
917
  super();
@@ -901,18 +925,18 @@ class UnknownColumn extends ColumnType {
901
925
  const createJoinTable = async (migration, up, tables, options, fn) => {
902
926
  const tableName = options.tableName || joinWords(...tables);
903
927
  if (!up) {
904
- return createTable(
928
+ return createTable$1(
905
929
  migration,
906
930
  up,
907
931
  tableName,
908
- __spreadProps$1(__spreadValues$2({}, options), { noPrimaryKey: true }),
932
+ __spreadProps$2(__spreadValues$3({}, options), { noPrimaryKey: true }),
909
933
  () => ({})
910
934
  );
911
935
  }
912
936
  const tablesWithPrimaryKeys = await Promise.all(
913
937
  tables.map(async (table) => {
914
938
  const primaryKeys = await getPrimaryKeysOfTable(migration, table).then(
915
- (items) => items.map((item) => __spreadProps$1(__spreadValues$2({}, item), {
939
+ (items) => items.map((item) => __spreadProps$2(__spreadValues$3({}, item), {
916
940
  joinedName: joinWords(singular(table), item.name)
917
941
  }))
918
942
  );
@@ -928,7 +952,7 @@ const createJoinTable = async (migration, up, tables, options, fn) => {
928
952
  return [schema, table, primaryKeys];
929
953
  })
930
954
  );
931
- return createTable(migration, up, tableName, options, (t) => {
955
+ return createTable$1(migration, up, tableName, options, (t) => {
932
956
  const result = {};
933
957
  tablesWithPrimaryKeys.forEach(([schema, table, primaryKeys]) => {
934
958
  if (primaryKeys.length === 1) {
@@ -961,25 +985,25 @@ const createJoinTable = async (migration, up, tables, options, fn) => {
961
985
  });
962
986
  };
963
987
 
964
- var __defProp$1 = Object.defineProperty;
965
- var __defProps = Object.defineProperties;
966
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
967
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
968
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
969
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
970
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
971
- 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) => {
972
996
  for (var prop in b || (b = {}))
973
- if (__hasOwnProp$1.call(b, prop))
974
- __defNormalProp$1(a, prop, b[prop]);
975
- if (__getOwnPropSymbols$1)
976
- for (var prop of __getOwnPropSymbols$1(b)) {
977
- if (__propIsEnum$1.call(b, prop))
978
- __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]);
979
1003
  }
980
1004
  return a;
981
1005
  };
982
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1006
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
983
1007
  class Migration extends TransactionAdapter {
984
1008
  constructor(tx, up, options, adapterOptions, appCodeUpdaterCache) {
985
1009
  super(tx, tx.client, tx.types);
@@ -998,12 +1022,12 @@ class Migration extends TransactionAdapter {
998
1022
  createTable(tableName, cbOrOptions, cb) {
999
1023
  const options = typeof cbOrOptions === "function" ? {} : cbOrOptions;
1000
1024
  const fn = cb || cbOrOptions;
1001
- return createTable(this, this.up, tableName, options, fn);
1025
+ return createTable$1(this, this.up, tableName, options, fn);
1002
1026
  }
1003
1027
  dropTable(tableName, cbOrOptions, cb) {
1004
1028
  const options = typeof cbOrOptions === "function" ? {} : cbOrOptions;
1005
1029
  const fn = cb || cbOrOptions;
1006
- return createTable(this, !this.up, tableName, options, fn);
1030
+ return createTable$1(this, !this.up, tableName, options, fn);
1007
1031
  }
1008
1032
  async createJoinTable(tables, cbOrOptions, cb) {
1009
1033
  const options = typeof cbOrOptions === "function" ? {} : cbOrOptions || {};
@@ -1086,10 +1110,10 @@ class Migration extends TransactionAdapter {
1086
1110
  }));
1087
1111
  }
1088
1112
  createSchema(schemaName) {
1089
- return createSchema(this, this.up, schemaName);
1113
+ return createSchema$1(this, this.up, schemaName);
1090
1114
  }
1091
1115
  dropSchema(schemaName) {
1092
- return createSchema(this, !this.up, schemaName);
1116
+ return createSchema$1(this, !this.up, schemaName);
1093
1117
  }
1094
1118
  createExtension(name, options = {}) {
1095
1119
  return createExtension(this, this.up, name, options);
@@ -1120,7 +1144,7 @@ const wrapWithLog = async (log, query, fn) => {
1120
1144
  if (!log) {
1121
1145
  return fn();
1122
1146
  } else {
1123
- 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: [] });
1124
1148
  const logData = log.beforeQuery(sql);
1125
1149
  try {
1126
1150
  const result = await fn();
@@ -1138,15 +1162,15 @@ const addColumn = (migration, up, tableName, columnName, fn) => {
1138
1162
  }));
1139
1163
  };
1140
1164
  const addIndex = (migration, up, tableName, columns, options) => {
1141
- 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))));
1142
1166
  };
1143
1167
  const addForeignKey = (migration, up, tableName, columns, foreignTable, foreignColumns, options) => {
1144
- 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))));
1145
1169
  };
1146
1170
  const addPrimaryKey = (migration, up, tableName, columns, options) => {
1147
- 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))));
1148
1172
  };
1149
- const createSchema = async (migration, up, name) => {
1173
+ const createSchema$1 = async (migration, up, name) => {
1150
1174
  const ast = {
1151
1175
  type: "schema",
1152
1176
  action: up ? "create" : "drop",
@@ -1158,7 +1182,7 @@ const createSchema = async (migration, up, name) => {
1158
1182
  await runCodeUpdater(migration, ast);
1159
1183
  };
1160
1184
  const createExtension = async (migration, up, name, options) => {
1161
- const ast = __spreadValues$1({
1185
+ const ast = __spreadValues$2({
1162
1186
  type: "extension",
1163
1187
  action: up ? "create" : "drop",
1164
1188
  name
@@ -1184,25 +1208,25 @@ const runCodeUpdater = (migration, ast) => {
1184
1208
  });
1185
1209
  };
1186
1210
 
1187
- var __defProp = Object.defineProperty;
1188
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1189
- var __hasOwnProp = Object.prototype.hasOwnProperty;
1190
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
1191
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1192
- 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) => {
1193
1217
  for (var prop in b || (b = {}))
1194
- if (__hasOwnProp.call(b, prop))
1195
- __defNormalProp(a, prop, b[prop]);
1196
- if (__getOwnPropSymbols)
1197
- for (var prop of __getOwnPropSymbols(b)) {
1198
- if (__propIsEnum.call(b, prop))
1199
- __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]);
1200
1224
  }
1201
1225
  return a;
1202
1226
  };
1203
1227
  const migrateOrRollback = async (options, config, args, up) => {
1204
1228
  var _a;
1205
- config = __spreadValues({}, config);
1229
+ config = __spreadValues$1({}, config);
1206
1230
  const files = await getMigrationFiles(config, up);
1207
1231
  let count = up ? Infinity : 1;
1208
1232
  let argI = 0;
@@ -1371,18 +1395,21 @@ const resetDb = async (arg, config) => {
1371
1395
  await migrate(arg, config);
1372
1396
  };
1373
1397
 
1374
- const generate = async (config, args) => {
1375
- const name = args[0];
1376
- if (!name)
1377
- throw new Error("Migration name is missing");
1378
- await mkdir(config.migrationsPath, { recursive: true });
1398
+ const writeMigrationFile = async (config, name, content) => {
1399
+ await mkdir(path.resolve(config.migrationsPath), { recursive: true });
1379
1400
  const filePath = path.resolve(
1380
1401
  config.migrationsPath,
1381
1402
  `${makeFileTimeStamp()}_${name}.ts`
1382
1403
  );
1383
- await writeFile(filePath, makeContent(name, args.slice(1)));
1404
+ await writeFile(filePath, content);
1384
1405
  console.log(`Created ${filePath}`);
1385
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
+ };
1386
1413
  const makeFileTimeStamp = () => {
1387
1414
  const now = new Date();
1388
1415
  return [
@@ -1437,6 +1464,529 @@ const makeColumnsContent = (args, method) => {
1437
1464
  return content;
1438
1465
  };
1439
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: "NO ACTION",
1775
+ r: void 0,
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
+ const belongsToTable = makeBelongsToTable(schemaName, name);
1811
+ const columns = allColumns.filter(belongsToTable);
1812
+ const primaryKey = allPrimaryKeys.find(belongsToTable);
1813
+ const tableIndexes = allIndexes.filter(belongsToTable);
1814
+ const tableForeignKeys = allForeignKeys.filter(belongsToTable);
1815
+ const shape = {};
1816
+ for (let item of columns) {
1817
+ const isSerial = getIsSerial(item);
1818
+ const klass = columnsByType[getColumnType(item, isSerial)];
1819
+ if (!klass) {
1820
+ throw new Error(`Column type \`${item.type}\` is not supported`);
1821
+ }
1822
+ if (isSerial) {
1823
+ item = __spreadProps(__spreadValues({}, item), { default: void 0 });
1824
+ }
1825
+ let column = instantiateColumn(klass, item);
1826
+ if ((primaryKey == null ? void 0 : primaryKey.columnNames.length) === 1 && (primaryKey == null ? void 0 : primaryKey.columnNames[0]) === item.name) {
1827
+ column = column.primaryKey();
1828
+ }
1829
+ const indexes = tableIndexes.filter(
1830
+ (it) => it.columns.length === 1 && "column" in it.columns[0] && it.columns[0].column === item.name
1831
+ );
1832
+ for (const index of indexes) {
1833
+ const options = index.columns[0];
1834
+ column = column.index({
1835
+ collate: options.collate,
1836
+ opclass: options.opclass,
1837
+ order: options.order,
1838
+ name: index.name,
1839
+ using: index.using === "btree" ? void 0 : index.using,
1840
+ unique: index.isUnique,
1841
+ include: index.include,
1842
+ with: index.with,
1843
+ tablespace: index.tablespace,
1844
+ where: index.where
1845
+ });
1846
+ }
1847
+ const foreignKeys = tableForeignKeys.filter(
1848
+ (it) => it.columnNames.length === 1 && it.columnNames[0] === item.name
1849
+ );
1850
+ for (const foreignKey of foreignKeys) {
1851
+ column = column.foreignKey(
1852
+ foreignKey.foreignTableName,
1853
+ foreignKey.foreignColumnNames[0],
1854
+ {
1855
+ name: foreignKey.name,
1856
+ match: matchMap[foreignKey.match],
1857
+ onUpdate: fkeyActionMap[foreignKey.onUpdate],
1858
+ onDelete: fkeyActionMap[foreignKey.onDelete]
1859
+ }
1860
+ );
1861
+ }
1862
+ shape[item.name] = column;
1863
+ }
1864
+ ast.push({
1865
+ type: "table",
1866
+ action: "create",
1867
+ schema: schemaName === "public" ? void 0 : schemaName,
1868
+ comment: table.comment,
1869
+ name,
1870
+ shape,
1871
+ noPrimaryKey: primaryKey ? "error" : "ignore",
1872
+ primaryKey: primaryKey && primaryKey.columnNames.length > 1 ? {
1873
+ columns: primaryKey.columnNames,
1874
+ options: primaryKey.name === `${name}_pkey` ? void 0 : { name: primaryKey.name }
1875
+ } : void 0,
1876
+ indexes: tableIndexes.filter(
1877
+ (index) => index.columns.length > 1 || index.columns.some((it) => "expression" in it)
1878
+ ).map((index) => ({
1879
+ columns: index.columns.map((it) => __spreadProps(__spreadValues({}, "column" in it ? { column: it.column } : { expression: it.expression }), {
1880
+ collate: it.collate,
1881
+ opclass: it.opclass,
1882
+ order: it.order
1883
+ })),
1884
+ options: {
1885
+ name: index.name,
1886
+ using: index.using === "btree" ? void 0 : index.using,
1887
+ unique: index.isUnique,
1888
+ include: index.include,
1889
+ with: index.with,
1890
+ tablespace: index.tablespace,
1891
+ where: index.where
1892
+ }
1893
+ })),
1894
+ foreignKeys: tableForeignKeys.filter((it) => it.columnNames.length > 1).map((it) => ({
1895
+ columns: it.columnNames,
1896
+ fnOrTable: it.foreignTableName,
1897
+ foreignColumns: it.foreignColumnNames,
1898
+ options: {
1899
+ name: it.name,
1900
+ match: matchMap[it.match],
1901
+ onUpdate: fkeyActionMap[it.onUpdate],
1902
+ onDelete: fkeyActionMap[it.onDelete]
1903
+ }
1904
+ }))
1905
+ });
1906
+ }
1907
+ for (const it of extensions) {
1908
+ ast.push({
1909
+ type: "extension",
1910
+ action: "create",
1911
+ name: it.name,
1912
+ schema: it.schemaName === "public" ? void 0 : it.schemaName,
1913
+ version: it.version
1914
+ });
1915
+ }
1916
+ return ast;
1917
+ };
1918
+ const makeBelongsToTable = (schema, table) => (item) => item.schemaName === schema && item.tableName === table;
1919
+ const getIsSerial = (item) => {
1920
+ if (item.type === "int2" || item.type === "int4" || item.type === "int8") {
1921
+ const { default: def, schemaName, tableName, name } = item;
1922
+ const seq = `${tableName}_${name}_seq`;
1923
+ 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)`)) {
1924
+ return true;
1925
+ }
1926
+ }
1927
+ return false;
1928
+ };
1929
+ const getColumnType = (item, isSerial) => {
1930
+ if (isSerial) {
1931
+ return item.type === "int2" ? "smallserial" : item.type === "int4" ? "serial" : "bigserial";
1932
+ }
1933
+ return item.type;
1934
+ };
1935
+
1936
+ const astToMigration = (ast) => {
1937
+ const code = [];
1938
+ for (const item of ast) {
1939
+ if (item.type === "schema" && item.action === "create") {
1940
+ code.push(createSchema(item));
1941
+ } else if (item.type === "table" && item.action === "create") {
1942
+ if (code.length)
1943
+ code.push([]);
1944
+ code.push(...createTable(item));
1945
+ }
1946
+ }
1947
+ if (!code.length)
1948
+ return;
1949
+ return `import { change } from 'rake-db';
1950
+
1951
+ change(async (db) => {
1952
+ ${codeToString(code, " ", " ")}
1953
+ });
1954
+ `;
1955
+ };
1956
+ const createSchema = (ast) => {
1957
+ return `await db.createSchema(${singleQuote(ast.name)});`;
1958
+ };
1959
+ const createTable = (ast) => {
1960
+ const code = [];
1961
+ addCode(code, `await db.createTable(${quoteSchemaTable(ast)}, (t) => ({`);
1962
+ for (const key in ast.shape) {
1963
+ const line = [`${quoteObjectKey(key)}: `];
1964
+ addCode(line, ast.shape[key].toCode("t"));
1965
+ addCode(line, ",");
1966
+ code.push(line);
1967
+ }
1968
+ if (ast.primaryKey) {
1969
+ code.push([primaryKeyToCode(ast.primaryKey, "t")]);
1970
+ }
1971
+ for (const index of ast.indexes) {
1972
+ code.push(indexToCode(index, "t"));
1973
+ }
1974
+ for (const foreignKey of ast.foreignKeys) {
1975
+ code.push(foreignKeyToCode(foreignKey, "t"));
1976
+ }
1977
+ addCode(code, "}));");
1978
+ return code;
1979
+ };
1980
+
1981
+ const pullDbStructure = async (options, config) => {
1982
+ const db = new DbStructure(new Adapter(options));
1983
+ const ast = await structureToAst(db);
1984
+ const result = astToMigration(ast);
1985
+ if (!result)
1986
+ return;
1987
+ await writeMigrationFile(config, "pull", result);
1988
+ };
1989
+
1440
1990
  const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2)) => {
1441
1991
  var _a;
1442
1992
  const config = getMigrationConfigWithDefaults(partialConfig);
@@ -1453,6 +2003,8 @@ const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2))
1453
2003
  await rollback(options, config, args.slice(1));
1454
2004
  } else if (command === "g" || command === "generate") {
1455
2005
  await generate(config, args.slice(1));
2006
+ } else if (command === "pull") {
2007
+ await pullDbStructure(toArray(options)[0], config);
1456
2008
  } else {
1457
2009
  printHelp();
1458
2010
  }
@@ -1495,5 +2047,5 @@ Generate arguments:
1495
2047
  `
1496
2048
  );
1497
2049
 
1498
- export { Migration, change, createDb, dropDb, generate, migrate, rakeDb, resetDb, rollback, runCodeUpdater };
2050
+ export { Migration, change, createDb, dropDb, generate, migrate, rakeDb, resetDb, rollback, runCodeUpdater, writeMigrationFile };
1499
2051
  //# sourceMappingURL=index.esm.js.map