rake-db 2.0.1 → 2.0.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,24 +1,24 @@
1
- import { toArray, Adapter, quote, isRaw, getRaw, getColumnTypes, columnTypes, getTableData, ColumnType, Operators, resetTableData, emptyObject, TransactionAdapter } from 'pqb';
1
+ import { toArray, Adapter, quote, isRaw, getRaw, getColumnTypes, columnTypes, getTableData, ColumnType, Operators, resetTableData, emptyObject, TransactionAdapter, logParamToLogObject } 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$4 = Object.defineProperty;
7
+ var __defProp$3 = Object.defineProperty;
8
8
  var __defProps$3 = Object.defineProperties;
9
9
  var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
10
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
11
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
12
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
13
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
- var __spreadValues$4 = (a, b) => {
10
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
11
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
12
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
13
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
+ var __spreadValues$3 = (a, b) => {
15
15
  for (var prop in b || (b = {}))
16
- if (__hasOwnProp$4.call(b, prop))
17
- __defNormalProp$4(a, prop, b[prop]);
18
- if (__getOwnPropSymbols$4)
19
- for (var prop of __getOwnPropSymbols$4(b)) {
20
- if (__propIsEnum$4.call(b, prop))
21
- __defNormalProp$4(a, prop, b[prop]);
16
+ if (__hasOwnProp$3.call(b, prop))
17
+ __defNormalProp$3(a, prop, b[prop]);
18
+ if (__getOwnPropSymbols$3)
19
+ for (var prop of __getOwnPropSymbols$3(b)) {
20
+ if (__propIsEnum$3.call(b, prop))
21
+ __defNormalProp$3(a, prop, b[prop]);
22
22
  }
23
23
  return a;
24
24
  };
@@ -31,7 +31,12 @@ const migrationConfigDefaults = {
31
31
  require("ts-node").register({ compilerOptions: { module: "CommonJS" } });
32
32
  }
33
33
  require(path2);
34
- }
34
+ },
35
+ log: true,
36
+ logger: console
37
+ };
38
+ const getMigrationConfigWithDefaults = (config) => {
39
+ return __spreadValues$3(__spreadValues$3({}, migrationConfigDefaults), config);
35
40
  };
36
41
  const getDatabaseAndUserFromOptions = (options) => {
37
42
  if (options.connectionString) {
@@ -59,9 +64,9 @@ const setAdapterOptions = (options, set) => {
59
64
  if (set.password !== void 0) {
60
65
  url.password = set.password;
61
66
  }
62
- return __spreadProps$3(__spreadValues$4({}, options), { connectionString: url.toString() });
67
+ return __spreadProps$3(__spreadValues$3({}, options), { connectionString: url.toString() });
63
68
  } else {
64
- return __spreadValues$4(__spreadValues$4({}, options), set);
69
+ return __spreadValues$3(__spreadValues$3({}, options), set);
65
70
  }
66
71
  };
67
72
  const askAdminCredentials = async () => {
@@ -94,7 +99,9 @@ const setAdminCredentialsToOptions = async (options) => {
94
99
  const createSchemaMigrations = async (db, config) => {
95
100
  try {
96
101
  await db.query(
97
- `CREATE TABLE "${config.migrationsTable}" ( version TEXT NOT NULL )`
102
+ `CREATE TABLE ${quoteTable(
103
+ config.migrationsTable
104
+ )} ( version TEXT NOT NULL )`
98
105
  );
99
106
  console.log("Created versions table");
100
107
  } catch (err) {
@@ -170,6 +177,14 @@ const joinWords = (...words) => {
170
177
  const joinColumns = (columns) => {
171
178
  return columns.map((column) => `"${column}"`).join(", ");
172
179
  };
180
+ const quoteTable = (table) => {
181
+ const index = table.indexOf(".");
182
+ if (index !== -1) {
183
+ return `"${table.slice(0, index)}"."${table.slice(index + 1)}"`;
184
+ } else {
185
+ return `"${table}"`;
186
+ }
187
+ };
173
188
 
174
189
  const execute = async (options, sql) => {
175
190
  const db = new Adapter(options);
@@ -279,17 +294,17 @@ change(async (db) => {`;
279
294
  if (rest) {
280
295
  if (first === "create" || first === "drop") {
281
296
  content += `
282
- db.${first === "create" ? "createTable" : "dropTable"}('${rest}', (t) => ({`;
297
+ await db.${first === "create" ? "createTable" : "dropTable"}('${rest}', (t) => ({`;
283
298
  content += makeColumnsContent(args);
284
299
  content += "\n }));";
285
300
  } else if (first === "change") {
286
301
  content += `
287
- db.changeTable('${rest}', (t) => ({`;
302
+ await db.changeTable('${rest}', (t) => ({`;
288
303
  content += "\n }));";
289
304
  } else if (first === "add" || first === "remove") {
290
305
  const table = first === "add" ? getTextAfterTo(rest) : getTextAfterFrom(rest);
291
306
  content += `
292
- db.changeTable(${table ? `'${table}'` : "tableName"}, (t) => ({`;
307
+ await db.changeTable(${table ? `'${table}'` : "tableName"}, (t) => ({`;
293
308
  content += makeColumnsContent(args, first);
294
309
  content += "\n }));";
295
310
  }
@@ -330,21 +345,21 @@ const setCurrentMigrationUp = (up) => {
330
345
  };
331
346
  const getCurrentPromise = () => currentPromise;
332
347
 
333
- var __defProp$3 = Object.defineProperty;
348
+ var __defProp$2 = Object.defineProperty;
334
349
  var __defProps$2 = Object.defineProperties;
335
350
  var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
336
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
337
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
338
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
339
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
340
- var __spreadValues$3 = (a, b) => {
351
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
352
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
353
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
354
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
355
+ var __spreadValues$2 = (a, b) => {
341
356
  for (var prop in b || (b = {}))
342
- if (__hasOwnProp$3.call(b, prop))
343
- __defNormalProp$3(a, prop, b[prop]);
344
- if (__getOwnPropSymbols$3)
345
- for (var prop of __getOwnPropSymbols$3(b)) {
346
- if (__propIsEnum$3.call(b, prop))
347
- __defNormalProp$3(a, prop, b[prop]);
357
+ if (__hasOwnProp$2.call(b, prop))
358
+ __defNormalProp$2(a, prop, b[prop]);
359
+ if (__getOwnPropSymbols$2)
360
+ for (var prop of __getOwnPropSymbols$2(b)) {
361
+ if (__propIsEnum$2.call(b, prop))
362
+ __defNormalProp$2(a, prop, b[prop]);
348
363
  }
349
364
  return a;
350
365
  };
@@ -385,7 +400,7 @@ const addColumnIndex = (indexes, key, item) => {
385
400
  if (item.data) {
386
401
  if (item.data.index) {
387
402
  indexes.push({
388
- columns: [__spreadProps$2(__spreadValues$3({}, item.data.index), { column: key })],
403
+ columns: [__spreadProps$2(__spreadValues$2({}, item.data.index), { column: key })],
389
404
  options: item.data.index
390
405
  });
391
406
  }
@@ -415,7 +430,9 @@ const constraintToSql = (tableName, up, foreignKey) => {
415
430
  )}) ${referencesToSql(table, foreignKey.foreignColumns, foreignKey.options)}`;
416
431
  };
417
432
  const referencesToSql = (table, columns, foreignKey) => {
418
- const sql = [`REFERENCES "${table}"(${joinColumns(columns)})`];
433
+ const sql = [
434
+ `REFERENCES ${quoteTable(table)}(${joinColumns(columns)})`
435
+ ];
419
436
  if (foreignKey.match) {
420
437
  sql.push(`MATCH ${foreignKey.match.toUpperCase()}`);
421
438
  }
@@ -444,7 +461,7 @@ const migrateIndex = (state, up, { columns, options }) => {
444
461
  if (options.unique) {
445
462
  sql.push("UNIQUE");
446
463
  }
447
- sql.push(`INDEX "${indexName}" ON "${state.tableName}"`);
464
+ sql.push(`INDEX "${indexName}" ON ${quoteTable(state.tableName)}`);
448
465
  if (options.using) {
449
466
  sql.push(`USING ${options.using}`);
450
467
  }
@@ -486,7 +503,9 @@ const migrateIndex = (state, up, { columns, options }) => {
486
503
  const migrateComments = async (state, comments) => {
487
504
  for (const { column, comment } of comments) {
488
505
  await state.migration.query(
489
- `COMMENT ON COLUMN "${state.tableName}"."${column}" IS ${quote(comment)}`
506
+ `COMMENT ON COLUMN ${quoteTable(state.tableName)}."${column}" IS ${quote(
507
+ comment
508
+ )}`
490
509
  );
491
510
  }
492
511
  };
@@ -498,8 +517,9 @@ const primaryKeyToSql = (primaryKey) => {
498
517
  )})`;
499
518
  };
500
519
  const getPrimaryKeysOfTable = async (db, tableName) => {
501
- const { rows } = await db.query({
502
- text: `SELECT
520
+ const { rows } = await db.query(
521
+ {
522
+ text: `SELECT
503
523
  pg_attribute.attname AS name,
504
524
  format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS type
505
525
  FROM pg_index, pg_class, pg_attribute, pg_namespace
@@ -511,26 +531,29 @@ WHERE
511
531
  pg_attribute.attrelid = pg_class.oid AND
512
532
  pg_attribute.attnum = any(pg_index.indkey) AND
513
533
  indisprimary`,
514
- values: [tableName]
515
- });
534
+ values: [tableName]
535
+ },
536
+ db.types,
537
+ void 0
538
+ );
516
539
  return rows;
517
540
  };
518
541
 
519
- var __defProp$2 = Object.defineProperty;
542
+ var __defProp$1 = Object.defineProperty;
520
543
  var __defProps$1 = Object.defineProperties;
521
544
  var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
522
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
523
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
524
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
525
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
526
- var __spreadValues$2 = (a, b) => {
545
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
546
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
547
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
548
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
549
+ var __spreadValues$1 = (a, b) => {
527
550
  for (var prop in b || (b = {}))
528
- if (__hasOwnProp$2.call(b, prop))
529
- __defNormalProp$2(a, prop, b[prop]);
530
- if (__getOwnPropSymbols$2)
531
- for (var prop of __getOwnPropSymbols$2(b)) {
532
- if (__propIsEnum$2.call(b, prop))
533
- __defNormalProp$2(a, prop, b[prop]);
551
+ if (__hasOwnProp$1.call(b, prop))
552
+ __defNormalProp$1(a, prop, b[prop]);
553
+ if (__getOwnPropSymbols$1)
554
+ for (var prop of __getOwnPropSymbols$1(b)) {
555
+ if (__propIsEnum$1.call(b, prop))
556
+ __defNormalProp$1(a, prop, b[prop]);
534
557
  }
535
558
  return a;
536
559
  };
@@ -548,16 +571,19 @@ const createJoinTable = async (migration, up, tables, options, fn) => {
548
571
  return createTable(migration, up, tableName, options, () => ({}));
549
572
  }
550
573
  const tablesWithPrimaryKeys = await Promise.all(
551
- tables.map(
552
- async (table) => [
553
- table,
554
- await getPrimaryKeysOfTable(migration, table).then(
555
- (items) => items.map((item) => __spreadProps$1(__spreadValues$2({}, item), {
556
- joinedName: joinWords(singular(table), item.name)
557
- }))
558
- )
559
- ]
560
- )
574
+ tables.map(async (table) => {
575
+ const primaryKeys = await getPrimaryKeysOfTable(migration, table).then(
576
+ (items) => items.map((item) => __spreadProps$1(__spreadValues$1({}, item), {
577
+ joinedName: joinWords(singular(table), item.name)
578
+ }))
579
+ );
580
+ if (!primaryKeys.length) {
581
+ throw new Error(
582
+ `Primary key for table ${quoteTable(table)} is not defined`
583
+ );
584
+ }
585
+ return [table, primaryKeys];
586
+ })
561
587
  );
562
588
  return createTable(migration, up, tableName, options, (t) => {
563
589
  const result = {};
@@ -593,7 +619,7 @@ const createTable = async (migration, up, tableName, options, fn) => {
593
619
  if (!up) {
594
620
  const { dropMode } = options;
595
621
  await migration.query(
596
- `DROP TABLE "${tableName}"${dropMode ? ` ${dropMode}` : ""}`
622
+ `DROP TABLE ${quoteTable(tableName)}${dropMode ? ` ${dropMode}` : ""}`
597
623
  );
598
624
  return;
599
625
  }
@@ -622,7 +648,7 @@ const createTable = async (migration, up, tableName, options, fn) => {
622
648
  ${constraintToSql(state.tableName, up, foreignKey)}`);
623
649
  });
624
650
  await migration.query({
625
- text: `CREATE TABLE "${tableName}" (${lines.join(",")}
651
+ text: `CREATE TABLE ${quoteTable(tableName)} (${lines.join(",")}
626
652
  )`,
627
653
  values: state.values
628
654
  });
@@ -631,7 +657,7 @@ const createTable = async (migration, up, tableName, options, fn) => {
631
657
  await migrateComments(state, state.comments);
632
658
  if (options.comment) {
633
659
  await migration.query(
634
- `COMMENT ON TABLE "${tableName}" IS ${quote(options.comment)}`
660
+ `COMMENT ON TABLE ${quoteTable(tableName)} IS ${quote(options.comment)}`
635
661
  );
636
662
  }
637
663
  };
@@ -743,7 +769,7 @@ const changeTable = async (migration, up, tableName, options, fn) => {
743
769
  });
744
770
  if (state.alterTable.length) {
745
771
  await migration.query(
746
- `ALTER TABLE "${tableName}"
772
+ `ALTER TABLE ${quoteTable(tableName)}
747
773
  ${state.alterTable.join(",\n ")}`
748
774
  );
749
775
  }
@@ -762,7 +788,7 @@ const changeActions = {
762
788
  value = Array.isArray(comment) ? comment[0] : null;
763
789
  }
764
790
  return migration.query(
765
- `COMMENT ON TABLE "${tableName}" IS ${quote(value)}`
791
+ `COMMENT ON TABLE ${quoteTable(tableName)} IS ${quote(value)}`
766
792
  );
767
793
  },
768
794
  add(state, up, key, item, options) {
@@ -856,26 +882,36 @@ const getRawOrValue = (item, values) => {
856
882
  return typeof item === "object" && item && isRaw(item) ? getRaw(item, values) : quote(item);
857
883
  };
858
884
 
859
- var __defProp$1 = Object.defineProperty;
860
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
861
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
862
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
863
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
864
- var __spreadValues$1 = (a, b) => {
885
+ var __defProp = Object.defineProperty;
886
+ var __defProps = Object.defineProperties;
887
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
888
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
889
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
890
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
891
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
892
+ var __spreadValues = (a, b) => {
865
893
  for (var prop in b || (b = {}))
866
- if (__hasOwnProp$1.call(b, prop))
867
- __defNormalProp$1(a, prop, b[prop]);
868
- if (__getOwnPropSymbols$1)
869
- for (var prop of __getOwnPropSymbols$1(b)) {
870
- if (__propIsEnum$1.call(b, prop))
871
- __defNormalProp$1(a, prop, b[prop]);
894
+ if (__hasOwnProp.call(b, prop))
895
+ __defNormalProp(a, prop, b[prop]);
896
+ if (__getOwnPropSymbols)
897
+ for (var prop of __getOwnPropSymbols(b)) {
898
+ if (__propIsEnum.call(b, prop))
899
+ __defNormalProp(a, prop, b[prop]);
872
900
  }
873
901
  return a;
874
902
  };
903
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
875
904
  class Migration extends TransactionAdapter {
876
- constructor(tx, up) {
905
+ constructor(tx, up, options) {
877
906
  super(tx.pool, tx.client, tx.types);
878
907
  this.up = up;
908
+ this.log = logParamToLogObject(options.logger || console, options.log);
909
+ }
910
+ async query(query, types = this.types, log = this.log) {
911
+ return wrapWithLog(log, query, () => super.query(query, types));
912
+ }
913
+ async arrays(query, types = this.types, log = this.log) {
914
+ return wrapWithLog(log, query, () => super.arrays(query, types));
879
915
  }
880
916
  createTable(tableName, cbOrOptions, cb) {
881
917
  const options = typeof cbOrOptions === "function" ? {} : cbOrOptions;
@@ -903,7 +939,7 @@ class Migration extends TransactionAdapter {
903
939
  }
904
940
  async renameTable(from, to) {
905
941
  const [table, newName] = this.up ? [from, to] : [to, from];
906
- await this.query(`ALTER TABLE "${table}" RENAME TO "${newName}"`);
942
+ await this.query(`ALTER TABLE ${quoteTable(table)} RENAME TO "${newName}"`);
907
943
  }
908
944
  addColumn(tableName, columnName, fn) {
909
945
  return addColumn(this, this.up, tableName, columnName, fn);
@@ -950,6 +986,22 @@ class Migration extends TransactionAdapter {
950
986
  [from]: t.rename(to)
951
987
  }));
952
988
  }
989
+ createSchema(schemaName) {
990
+ return createSchema(this, this.up, schemaName);
991
+ }
992
+ dropSchema(schemaName) {
993
+ return createSchema(this, !this.up, schemaName);
994
+ }
995
+ createExtension(name, options = {}) {
996
+ return createExtension(this, this.up, name, __spreadProps(__spreadValues({}, options), {
997
+ checkExists: options.ifNotExists
998
+ }));
999
+ }
1000
+ dropExtension(name, options = {}) {
1001
+ return createExtension(this, !this.up, name, __spreadProps(__spreadValues({}, options), {
1002
+ checkExists: options.ifExists
1003
+ }));
1004
+ }
953
1005
  async tableExists(tableName) {
954
1006
  return queryExists(this, {
955
1007
  text: `SELECT 1 FROM "information_schema"."tables" WHERE "table_name" = $1`,
@@ -969,26 +1021,62 @@ class Migration extends TransactionAdapter {
969
1021
  });
970
1022
  }
971
1023
  }
1024
+ const wrapWithLog = async (log, query, fn) => {
1025
+ if (!log) {
1026
+ return fn();
1027
+ } else {
1028
+ const sql = typeof query === "string" ? { text: query, values: [] } : query.values ? query : __spreadProps(__spreadValues({}, query), { values: [] });
1029
+ const logData = log.beforeQuery(sql);
1030
+ try {
1031
+ const result = await fn();
1032
+ log.afterQuery(sql, logData);
1033
+ return result;
1034
+ } catch (err) {
1035
+ log.onError(err, sql, logData);
1036
+ throw err;
1037
+ }
1038
+ }
1039
+ };
972
1040
  const addColumn = (migration, up, tableName, columnName, fn) => {
973
1041
  return changeTable(migration, up, tableName, {}, (t) => ({
974
1042
  [columnName]: t.add(fn(t))
975
1043
  }));
976
1044
  };
977
1045
  const addIndex = (migration, up, tableName, columns, options) => {
978
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$1({}, t.add(t.index(columns, options))));
1046
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues({}, t.add(t.index(columns, options))));
979
1047
  };
980
1048
  const addForeignKey = (migration, up, tableName, columns, foreignTable, foreignColumns, options) => {
981
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$1({}, t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))));
1049
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues({}, t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))));
982
1050
  };
983
1051
  const addPrimaryKey = (migration, up, tableName, columns, options) => {
984
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$1({}, t.add(t.primaryKey(columns, options))));
1052
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues({}, t.add(t.primaryKey(columns, options))));
1053
+ };
1054
+ const createSchema = (migration, up, schemaName) => {
1055
+ if (up) {
1056
+ return migration.query(`CREATE SCHEMA "${schemaName}"`);
1057
+ } else {
1058
+ return migration.query(`DROP SCHEMA "${schemaName}"`);
1059
+ }
1060
+ };
1061
+ const createExtension = (migration, up, name, options) => {
1062
+ if (!up) {
1063
+ return migration.query(
1064
+ `DROP EXTENSION${options.checkExists ? " IF EXISTS" : ""} "${name}"${options.cascade ? " CASCADE" : ""}`
1065
+ );
1066
+ }
1067
+ return migration.query(
1068
+ `CREATE EXTENSION${options.checkExists ? " IF NOT EXISTS" : ""} "${name}"${options.schema ? ` SCHEMA "${options.schema}"` : ""}${options.version ? ` VERSION '${options.version}'` : ""}${options.cascade ? " CASCADE" : ""}`
1069
+ );
985
1070
  };
986
1071
  const queryExists = (db, sql) => {
987
1072
  return db.query(sql).then(({ rowCount }) => rowCount > 0);
988
1073
  };
989
1074
 
990
- const migrateOrRollback = async (options, config, up) => {
1075
+ const migrateOrRollback = async (options, config, args, up) => {
1076
+ var _a;
991
1077
  const files = await getMigrationFiles(config, up);
1078
+ const argCount = parseInt(args[0]);
1079
+ let count = isNaN(argCount) ? up ? Infinity : 1 : argCount;
992
1080
  for (const opts of toArray(options)) {
993
1081
  const db = new Adapter(opts);
994
1082
  const migratedVersions = await getMigratedVersionsMap(db, config);
@@ -997,7 +1085,10 @@ const migrateOrRollback = async (options, config, up) => {
997
1085
  if (up && migratedVersions[file.version] || !up && !migratedVersions[file.version]) {
998
1086
  continue;
999
1087
  }
1088
+ if (count-- <= 0)
1089
+ break;
1000
1090
  await processMigration(db, up, file, config);
1091
+ (_a = config.logger) == null ? void 0 : _a.log(`${file.path} ${up ? "migrated" : "rolled back"}`);
1001
1092
  }
1002
1093
  } finally {
1003
1094
  await db.destroy();
@@ -1006,7 +1097,7 @@ const migrateOrRollback = async (options, config, up) => {
1006
1097
  };
1007
1098
  const processMigration = async (db, up, file, config) => {
1008
1099
  await db.transaction(async (tx) => {
1009
- const db2 = new Migration(tx, up);
1100
+ const db2 = new Migration(tx, up, config);
1010
1101
  setCurrentMigration(db2);
1011
1102
  setCurrentMigrationUp(up);
1012
1103
  config.requireTs(file.path);
@@ -1020,18 +1111,20 @@ const processMigration = async (db, up, file, config) => {
1020
1111
  };
1021
1112
  const saveMigratedVersion = async (db, version, config) => {
1022
1113
  await db.query(
1023
- `INSERT INTO "${config.migrationsTable}" VALUES ('${version}')`
1114
+ `INSERT INTO ${quoteTable(config.migrationsTable)} VALUES ('${version}')`
1024
1115
  );
1025
1116
  };
1026
1117
  const removeMigratedVersion = async (db, version, config) => {
1027
1118
  await db.query(
1028
- `DELETE FROM "${config.migrationsTable}" WHERE version = '${version}'`
1119
+ `DELETE FROM ${quoteTable(
1120
+ config.migrationsTable
1121
+ )} WHERE version = '${version}'`
1029
1122
  );
1030
1123
  };
1031
1124
  const getMigratedVersionsMap = async (db, config) => {
1032
1125
  try {
1033
1126
  const result = await db.arrays(
1034
- `SELECT * FROM "${config.migrationsTable}"`
1127
+ `SELECT * FROM ${quoteTable(config.migrationsTable)}`
1035
1128
  );
1036
1129
  return Object.fromEntries(result.rows.map((row) => [row[0], true]));
1037
1130
  } catch (err) {
@@ -1042,114 +1135,26 @@ const getMigratedVersionsMap = async (db, config) => {
1042
1135
  throw err;
1043
1136
  }
1044
1137
  };
1045
- const migrate = (options, config) => migrateOrRollback(options, config, true);
1046
- const rollback = (options, config) => migrateOrRollback(options, config, false);
1138
+ const migrate = (options, config, args) => migrateOrRollback(options, config, args, true);
1139
+ const rollback = (options, config, args) => migrateOrRollback(options, config, args, false);
1047
1140
 
1048
- var __defProp = Object.defineProperty;
1049
- var __defProps = Object.defineProperties;
1050
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1051
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1052
- var __hasOwnProp = Object.prototype.hasOwnProperty;
1053
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
1054
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1055
- var __spreadValues = (a, b) => {
1056
- for (var prop in b || (b = {}))
1057
- if (__hasOwnProp.call(b, prop))
1058
- __defNormalProp(a, prop, b[prop]);
1059
- if (__getOwnPropSymbols)
1060
- for (var prop of __getOwnPropSymbols(b)) {
1061
- if (__propIsEnum.call(b, prop))
1062
- __defNormalProp(a, prop, b[prop]);
1063
- }
1064
- return a;
1141
+ const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2)) => {
1142
+ const config = getMigrationConfigWithDefaults(partialConfig);
1143
+ const command = args[0].split(":")[0];
1144
+ if (command === "create") {
1145
+ await createDb(options, config);
1146
+ } else if (command === "drop") {
1147
+ await dropDb(options);
1148
+ } else if (command === "migrate") {
1149
+ await migrate(options, config, args.slice(1));
1150
+ } else if (command === "rollback") {
1151
+ await rollback(options, config, args.slice(1));
1152
+ } else if (command === "g" || command === "generate") {
1153
+ await generate(config, args.slice(1));
1154
+ } else {
1155
+ console.log(`Usage: rake-db [command] [arguments]`);
1156
+ }
1065
1157
  };
1066
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1067
- jest.mock("../common", () => __spreadProps(__spreadValues({}, jest.requireActual("../common")), {
1068
- getMigrationFiles: jest.fn(),
1069
- createSchemaMigrations: jest.fn()
1070
- }));
1071
- const options = { connectionString: "postgres://user@localhost/dbname" };
1072
- const files = [
1073
- { path: "file1", version: "1" },
1074
- { path: "file2", version: "2" },
1075
- { path: "file3", version: "3" }
1076
- ];
1077
- const getMigratedVersionsArrayMock = jest.fn();
1078
- Adapter.prototype.arrays = getMigratedVersionsArrayMock;
1079
- const queryMock = jest.fn();
1080
- Adapter.prototype.query = queryMock;
1081
- Adapter.prototype.transaction = (cb) => {
1082
- return cb({});
1083
- };
1084
- const transactionQueryMock = jest.fn();
1085
- Migration.prototype.query = transactionQueryMock;
1086
- const requireTsMock = jest.fn();
1087
- const config = __spreadProps(__spreadValues({}, migrationConfigDefaults), {
1088
- requireTs: requireTsMock
1089
- });
1090
- describe("migrateOrRollback", () => {
1091
- beforeEach(() => {
1092
- jest.clearAllMocks();
1093
- });
1094
- describe("migrate", () => {
1095
- it("should work properly", async () => {
1096
- getMigrationFiles.mockReturnValueOnce(files);
1097
- getMigratedVersionsArrayMock.mockResolvedValueOnce({ rows: [["1"]] });
1098
- queryMock.mockReturnValueOnce(void 0);
1099
- requireTsMock.mockResolvedValue(void 0);
1100
- await migrate(options, config);
1101
- expect(getMigrationFiles).toBeCalledWith(config, true);
1102
- expect(requireTsMock).toBeCalledWith("file2");
1103
- expect(requireTsMock).toBeCalledWith("file3");
1104
- expect(transactionQueryMock).toBeCalledWith(
1105
- `INSERT INTO "schemaMigrations" VALUES ('2')`
1106
- );
1107
- expect(transactionQueryMock).toBeCalledWith(
1108
- `INSERT INTO "schemaMigrations" VALUES ('3')`
1109
- );
1110
- });
1111
- it("should create migrations table if it not exist", async () => {
1112
- getMigrationFiles.mockReturnValueOnce([]);
1113
- getMigratedVersionsArrayMock.mockRejectedValueOnce({ code: "42P01" });
1114
- createSchemaMigrations.mockResolvedValueOnce(void 0);
1115
- await migrate(options, config);
1116
- expect(getMigrationFiles).toBeCalledWith(config, true);
1117
- expect(createSchemaMigrations).toBeCalled();
1118
- expect(requireTsMock).not.toBeCalled();
1119
- expect(transactionQueryMock).not.toBeCalled();
1120
- });
1121
- });
1122
- describe("rollback", () => {
1123
- it("should work properly", async () => {
1124
- getMigrationFiles.mockReturnValueOnce(files.reverse());
1125
- getMigratedVersionsArrayMock.mockResolvedValueOnce({
1126
- rows: [["1"], ["2"]]
1127
- });
1128
- queryMock.mockReturnValueOnce(void 0);
1129
- requireTsMock.mockResolvedValue(void 0);
1130
- await rollback(options, config);
1131
- expect(getMigrationFiles).toBeCalledWith(config, false);
1132
- expect(requireTsMock).toBeCalledWith("file2");
1133
- expect(requireTsMock).toBeCalledWith("file1");
1134
- expect(transactionQueryMock).toBeCalledWith(
1135
- `DELETE FROM "schemaMigrations" WHERE version = '2'`
1136
- );
1137
- expect(transactionQueryMock).toBeCalledWith(
1138
- `DELETE FROM "schemaMigrations" WHERE version = '1'`
1139
- );
1140
- });
1141
- it("should create migrations table if it not exist", async () => {
1142
- getMigrationFiles.mockReturnValueOnce([]);
1143
- getMigratedVersionsArrayMock.mockRejectedValueOnce({ code: "42P01" });
1144
- createSchemaMigrations.mockResolvedValueOnce(void 0);
1145
- await rollback(options, config);
1146
- expect(getMigrationFiles).toBeCalledWith(config, false);
1147
- expect(createSchemaMigrations).toBeCalled();
1148
- expect(requireTsMock).not.toBeCalled();
1149
- expect(transactionQueryMock).not.toBeCalled();
1150
- });
1151
- });
1152
- });
1153
1158
 
1154
- export { Migration, change, createDb, dropDb, generate };
1159
+ export { Migration, change, createDb, dropDb, generate, migrate, rakeDb, rollback };
1155
1160
  //# sourceMappingURL=index.esm.js.map