rake-db 2.14.4 → 2.15.0

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.mjs CHANGED
@@ -1,206 +1,11 @@
1
- import { defaultSchemaConfig, makeColumnTypes, quote, EnumColumn, getColumnTypes, getTableData, ColumnType, resetTableData, UnknownColumn, raw, TransactionAdapter, logParamToLogObject, createDb as createDb$1, Adapter, simplifyColumnDefault, instantiateColumn, DomainColumn, CustomTypeColumn, ArrayColumn, getConstraintKind, primaryKeyToCode, indexToCode, constraintToCode, referencesArgsToCode, constraintPropsToCode, TimestampTZColumn, makeColumnsByType } from 'pqb';
2
- import { getStackTrace, singleQuote, toSnakeCase, isRawSQL, toArray, snakeCaseKey, emptyObject, setCurrentColumnName, consumeColumnName, setDefaultLanguage, ColumnTypeBase, deepCompare, pathToLog, emptyArray, getImportPath, toCamelCase, codeToString, addCode, quoteObjectKey, backtickQuote } from 'orchid-core';
1
+ import { quote, EnumColumn, defaultSchemaConfig, getColumnTypes, getTableData, ColumnType, resetTableData, UnknownColumn, raw, TransactionAdapter, logParamToLogObject, createDb as createDb$1, Adapter, makeColumnTypes, simplifyColumnDefault, instantiateColumn, DomainColumn, CustomTypeColumn, ArrayColumn, getConstraintKind, primaryKeyToCode, indexToCode, constraintToCode, referencesArgsToCode, constraintPropsToCode, TimestampTZColumn, makeColumnsByType } from 'pqb';
2
+ import { singleQuote, emptyArray, toSnakeCase, isRawSQL, toArray, snakeCaseKey, emptyObject, setCurrentColumnName, consumeColumnName, setDefaultLanguage, ColumnTypeBase, deepCompare, getImportPath, pathToLog, getStackTrace, toCamelCase, codeToString, addCode, quoteObjectKey, backtickQuote } from 'orchid-core';
3
3
  import path, { join } from 'path';
4
- import { readdir, mkdir, writeFile, stat, readFile } from 'fs/promises';
4
+ import { pathToFileURL, fileURLToPath } from 'node:url';
5
+ import fs, { mkdir, writeFile, readdir, stat, readFile } from 'fs/promises';
5
6
  import prompts from 'prompts';
6
- import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { redo as redo$1 } from 'rake-db';
7
8
 
8
- var __defProp$7 = Object.defineProperty;
9
- var __defProps$5 = Object.defineProperties;
10
- var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
11
- var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
12
- var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
13
- var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
14
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
15
- var __spreadValues$7 = (a, b) => {
16
- for (var prop in b || (b = {}))
17
- if (__hasOwnProp$7.call(b, prop))
18
- __defNormalProp$7(a, prop, b[prop]);
19
- if (__getOwnPropSymbols$7)
20
- for (var prop of __getOwnPropSymbols$7(b)) {
21
- if (__propIsEnum$7.call(b, prop))
22
- __defNormalProp$7(a, prop, b[prop]);
23
- }
24
- return a;
25
- };
26
- var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
27
- var __objRest$2 = (source, exclude) => {
28
- var target = {};
29
- for (var prop in source)
30
- if (__hasOwnProp$7.call(source, prop) && exclude.indexOf(prop) < 0)
31
- target[prop] = source[prop];
32
- if (source != null && __getOwnPropSymbols$7)
33
- for (var prop of __getOwnPropSymbols$7(source)) {
34
- if (exclude.indexOf(prop) < 0 && __propIsEnum$7.call(source, prop))
35
- target[prop] = source[prop];
36
- }
37
- return target;
38
- };
39
- const migrationConfigDefaults = {
40
- schemaConfig: defaultSchemaConfig,
41
- migrationsPath: path.join("src", "db", "migrations"),
42
- migrationsTable: "schemaMigrations",
43
- snakeCase: false,
44
- commands: {},
45
- import: (path2) => {
46
- return import(path2).catch((err) => {
47
- if (err.code === "ERR_UNKNOWN_FILE_EXTENSION") {
48
- require(path2);
49
- } else {
50
- throw err;
51
- }
52
- });
53
- },
54
- log: true,
55
- logger: console,
56
- useCodeUpdater: true
57
- };
58
- const processRakeDbConfig = (config) => {
59
- var _a, _b;
60
- const result = __spreadValues$7(__spreadValues$7({}, migrationConfigDefaults), config);
61
- if (!result.recurrentPath) {
62
- result.recurrentPath = path.join(result.migrationsPath, "recurrent");
63
- }
64
- if (config.appCodeUpdater && (!("baseTable" in config) || !config.baseTable)) {
65
- throw new Error(
66
- "`baseTable` option is required in `rakeDb` for `appCodeUpdater`"
67
- );
68
- }
69
- if (!result.log) {
70
- delete result.logger;
71
- }
72
- if (!result.basePath || !result.dbScript) {
73
- let filePath = (_a = getStackTrace()) == null ? void 0 : _a[3].getFileName();
74
- if (!filePath) {
75
- throw new Error(
76
- "Failed to determine path to db script. Please set basePath option of rakeDb"
77
- );
78
- }
79
- if (filePath.startsWith("file://")) {
80
- filePath = fileURLToPath(filePath);
81
- }
82
- const ext = path.extname(filePath);
83
- if (ext !== ".ts" && ext !== ".js" && ext !== ".mjs") {
84
- throw new Error(
85
- `Add a .ts suffix to the "${path.basename(filePath)}" when calling it`
86
- );
87
- }
88
- result.basePath = path.dirname(filePath);
89
- result.dbScript = path.basename(filePath);
90
- }
91
- if ("migrationsPath" in result && !path.isAbsolute(result.migrationsPath)) {
92
- result.migrationsPath = path.resolve(
93
- result.basePath,
94
- result.migrationsPath
95
- );
96
- }
97
- if ("recurrentPath" in result && !path.isAbsolute(result.recurrentPath)) {
98
- result.recurrentPath = path.resolve(result.basePath, result.recurrentPath);
99
- }
100
- if ("baseTable" in config) {
101
- const proto = (_b = config.baseTable) == null ? void 0 : _b.prototype;
102
- result.columnTypes = proto.types || makeColumnTypes(defaultSchemaConfig);
103
- if (proto.snakeCase)
104
- result.snakeCase = true;
105
- if (proto.language)
106
- result.language = proto.language;
107
- } else {
108
- const ct = "columnTypes" in config && config.columnTypes;
109
- result.columnTypes = (typeof ct === "function" ? ct(
110
- makeColumnTypes(defaultSchemaConfig)
111
- ) : ct) || makeColumnTypes;
112
- }
113
- return result;
114
- };
115
- const getDatabaseAndUserFromOptions = (options) => {
116
- if (options.databaseURL) {
117
- const url = new URL(options.databaseURL);
118
- return {
119
- database: url.pathname.slice(1),
120
- user: url.username
121
- };
122
- } else {
123
- return {
124
- database: options.database,
125
- user: options.user
126
- };
127
- }
128
- };
129
- const setAdapterOptions = (options, set) => {
130
- if (options.databaseURL) {
131
- const url = new URL(options.databaseURL);
132
- if ("database" in set) {
133
- url.pathname = `/${set.database}`;
134
- }
135
- if (set.user !== void 0) {
136
- url.username = set.user;
137
- }
138
- if (set.password !== void 0) {
139
- url.password = set.password;
140
- }
141
- return __spreadProps$5(__spreadValues$7({}, options), { databaseURL: url.toString() });
142
- } else {
143
- return __spreadValues$7(__spreadValues$7({}, options), set);
144
- }
145
- };
146
- const setAdminCredentialsToOptions = async (options, create) => {
147
- const confirm = await prompts([
148
- {
149
- message: `Would you like to share admin credentials to ${create ? "create" : "drop"} a database`,
150
- type: "confirm",
151
- name: "confirm",
152
- initial: true
153
- }
154
- ]);
155
- if (!confirm.confirm) {
156
- return;
157
- }
158
- const values = await prompts([
159
- {
160
- message: "Enter admin user:",
161
- type: "text",
162
- name: "user",
163
- initial: "postgres",
164
- min: 1
165
- },
166
- {
167
- message: "Enter admin password:",
168
- type: "password",
169
- name: "password"
170
- }
171
- ]);
172
- return setAdapterOptions(options, __spreadProps$5(__spreadValues$7({}, values), {
173
- password: values.password || void 0
174
- }));
175
- };
176
- const createSchemaMigrations = async (db, config) => {
177
- var _a, _b, _c;
178
- const { schema } = db;
179
- if (schema && schema !== "public") {
180
- try {
181
- await db.query(`CREATE SCHEMA "${schema}"`);
182
- (_a = config.logger) == null ? void 0 : _a.log(`Created schema ${schema}`);
183
- } catch (err) {
184
- if (err.code !== "42P06") {
185
- throw err;
186
- }
187
- }
188
- }
189
- try {
190
- await db.query(
191
- `CREATE TABLE ${quoteWithSchema({
192
- name: config.migrationsTable
193
- })} ( version TEXT NOT NULL )`
194
- );
195
- (_b = config.logger) == null ? void 0 : _b.log("Created versions table");
196
- } catch (err) {
197
- if (err.code === "42P07") {
198
- (_c = config.logger) == null ? void 0 : _c.log("Versions table exists");
199
- } else {
200
- throw err;
201
- }
202
- }
203
- };
204
9
  const getFirstWordAndRest = (input) => {
205
10
  const index = input.search(/(?=[A-Z])|[-_]/);
206
11
  if (index !== -1) {
@@ -228,73 +33,6 @@ const getTextAfterTo = (input) => {
228
33
  const getTextAfterFrom = (input) => {
229
34
  return getTextAfterRegExp(input, /(From|-from|_from)[A-Z-_]/, 4);
230
35
  };
231
- const getMigrations = async (_a, up) => {
232
- var _b = _a, {
233
- migrations
234
- } = _b, config = __objRest$2(_b, [
235
- "migrations"
236
- ]);
237
- return migrations ? getMigrationsFromConfig(__spreadProps$5(__spreadValues$7({}, config), { migrations }), up) : getMigrationsFromFiles(config, up);
238
- };
239
- function getMigrationsFromConfig(config, up) {
240
- const result = [];
241
- const { migrations, basePath } = config;
242
- for (const key in migrations) {
243
- result.push({
244
- path: path.resolve(basePath, key),
245
- version: getVersion(path.basename(key)),
246
- load: migrations[key]
247
- });
248
- }
249
- return up ? result : result.reverse();
250
- }
251
- async function getMigrationsFromFiles(config, up) {
252
- const { migrationsPath, import: imp } = config;
253
- let files;
254
- try {
255
- files = await readdir(migrationsPath);
256
- } catch (_) {
257
- return [];
258
- }
259
- files = files.filter((file) => path.basename(file).includes("."));
260
- files = (up ? sortAsc : sortDesc)(files);
261
- return files.map((file) => {
262
- checkExt(file);
263
- const filePath = path.resolve(migrationsPath, file);
264
- return {
265
- path: filePath,
266
- version: getVersion(file),
267
- async load() {
268
- try {
269
- await imp(filePath);
270
- } catch (err) {
271
- if (err.code !== "ERR_UNSUPPORTED_ESM_URL_SCHEME")
272
- throw err;
273
- await imp(pathToFileURL(filePath).pathname);
274
- }
275
- }
276
- };
277
- });
278
- }
279
- function checkExt(filePath) {
280
- const ext = path.extname(filePath);
281
- if (ext !== ".ts" && ext !== ".js" && ext !== ".mjs") {
282
- throw new Error(
283
- `Only .ts, .js, and .mjs files are supported for migration, received: ${path}`
284
- );
285
- }
286
- }
287
- function getVersion(path2) {
288
- const timestampMatch = path2.match(/^(\d{14})\D/);
289
- if (!timestampMatch) {
290
- throw new Error(
291
- `Migration file name should start with 14 digit version, received ${path2}`
292
- );
293
- }
294
- return timestampMatch[1];
295
- }
296
- const sortAsc = (arr) => arr.sort();
297
- const sortDesc = (arr) => arr.sort((a, b) => a > b ? -1 : 1);
298
36
  const joinColumns = (columns) => {
299
37
  return columns.map((column) => `"${column}"`).join(", ");
300
38
  };
@@ -330,6 +68,14 @@ const makePopulateEnumQuery = (item) => {
330
68
  }
331
69
  };
332
70
  };
71
+ const begin = {
72
+ text: "BEGIN",
73
+ values: emptyArray
74
+ };
75
+ const transaction = (adapter, fn) => {
76
+ return adapter.transaction(begin, fn);
77
+ };
78
+ const queryLock = (trx) => trx.query(`SELECT pg_advisory_xact_lock('${RAKE_DB_LOCK_KEY}')`);
333
79
 
334
80
  let currentChanges = [];
335
81
  const clearChanges = () => {
@@ -338,25 +84,25 @@ const clearChanges = () => {
338
84
  const getCurrentChanges = () => currentChanges;
339
85
  const pushChange = (fn) => currentChanges.push(fn);
340
86
 
341
- var __defProp$6 = Object.defineProperty;
342
- var __defProps$4 = Object.defineProperties;
343
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
344
- var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
345
- var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
346
- var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
347
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
348
- var __spreadValues$6 = (a, b) => {
87
+ var __defProp$a = Object.defineProperty;
88
+ var __defProps$7 = Object.defineProperties;
89
+ var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
90
+ var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
91
+ var __hasOwnProp$a = Object.prototype.hasOwnProperty;
92
+ var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
93
+ var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
94
+ var __spreadValues$a = (a, b) => {
349
95
  for (var prop in b || (b = {}))
350
- if (__hasOwnProp$6.call(b, prop))
351
- __defNormalProp$6(a, prop, b[prop]);
352
- if (__getOwnPropSymbols$6)
353
- for (var prop of __getOwnPropSymbols$6(b)) {
354
- if (__propIsEnum$6.call(b, prop))
355
- __defNormalProp$6(a, prop, b[prop]);
96
+ if (__hasOwnProp$a.call(b, prop))
97
+ __defNormalProp$a(a, prop, b[prop]);
98
+ if (__getOwnPropSymbols$a)
99
+ for (var prop of __getOwnPropSymbols$a(b)) {
100
+ if (__propIsEnum$a.call(b, prop))
101
+ __defNormalProp$a(a, prop, b[prop]);
356
102
  }
357
103
  return a;
358
104
  };
359
- var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
105
+ var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
360
106
  const columnTypeToSql = (item) => {
361
107
  return item.data.isOfCustomType ? `"${item.toSQL()}"` : item.toSQL();
362
108
  };
@@ -450,7 +196,7 @@ const addColumnIndex = (indexes, name, item) => {
450
196
  if (item.data.indexes) {
451
197
  indexes.push(
452
198
  ...item.data.indexes.map((index) => ({
453
- columns: [__spreadProps$4(__spreadValues$6({}, index), { column: name })],
199
+ columns: [__spreadProps$7(__spreadValues$a({}, index), { column: name })],
454
200
  options: index
455
201
  }))
456
202
  );
@@ -632,33 +378,33 @@ class RakeDbError extends Error {
632
378
  class NoPrimaryKey extends RakeDbError {
633
379
  }
634
380
 
635
- var __defProp$5 = Object.defineProperty;
636
- var __defProps$3 = Object.defineProperties;
637
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
638
- var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
639
- var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
640
- var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
641
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
642
- var __spreadValues$5 = (a, b) => {
381
+ var __defProp$9 = Object.defineProperty;
382
+ var __defProps$6 = Object.defineProperties;
383
+ var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
384
+ var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
385
+ var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
386
+ var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
387
+ var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
388
+ var __spreadValues$9 = (a, b) => {
643
389
  for (var prop in b || (b = {}))
644
- if (__hasOwnProp$5.call(b, prop))
645
- __defNormalProp$5(a, prop, b[prop]);
646
- if (__getOwnPropSymbols$5)
647
- for (var prop of __getOwnPropSymbols$5(b)) {
648
- if (__propIsEnum$5.call(b, prop))
649
- __defNormalProp$5(a, prop, b[prop]);
390
+ if (__hasOwnProp$9.call(b, prop))
391
+ __defNormalProp$9(a, prop, b[prop]);
392
+ if (__getOwnPropSymbols$9)
393
+ for (var prop of __getOwnPropSymbols$9(b)) {
394
+ if (__propIsEnum$9.call(b, prop))
395
+ __defNormalProp$9(a, prop, b[prop]);
650
396
  }
651
397
  return a;
652
398
  };
653
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
399
+ var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
654
400
  var __objRest$1 = (source, exclude) => {
655
401
  var target = {};
656
402
  for (var prop in source)
657
- if (__hasOwnProp$5.call(source, prop) && exclude.indexOf(prop) < 0)
403
+ if (__hasOwnProp$9.call(source, prop) && exclude.indexOf(prop) < 0)
658
404
  target[prop] = source[prop];
659
- if (source != null && __getOwnPropSymbols$5)
660
- for (var prop of __getOwnPropSymbols$5(source)) {
661
- if (exclude.indexOf(prop) < 0 && __propIsEnum$5.call(source, prop))
405
+ if (source != null && __getOwnPropSymbols$9)
406
+ for (var prop of __getOwnPropSymbols$9(source)) {
407
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$9.call(source, prop))
662
408
  target[prop] = source[prop];
663
409
  }
664
410
  return target;
@@ -710,14 +456,14 @@ const makeAst$2 = (up, tableName, shape, tableData, options, noPrimaryKey) => {
710
456
  }
711
457
  const { primaryKey } = tableData;
712
458
  const [schema, table] = getSchemaAndTableFromName(tableName);
713
- return __spreadProps$3(__spreadValues$5(__spreadProps$3(__spreadValues$5({
459
+ return __spreadProps$6(__spreadValues$9(__spreadProps$6(__spreadValues$9({
714
460
  type: "table",
715
461
  action: up ? "create" : "drop",
716
462
  schema,
717
463
  name: table,
718
464
  shape
719
465
  }, tableData), {
720
- primaryKey: shapePKeys.length <= 1 ? primaryKey : primaryKey ? __spreadProps$3(__spreadValues$5({}, primaryKey), { columns: [...shapePKeys, ...primaryKey.columns] }) : { columns: shapePKeys }
466
+ primaryKey: shapePKeys.length <= 1 ? primaryKey : primaryKey ? __spreadProps$6(__spreadValues$9({}, primaryKey), { columns: [...shapePKeys, ...primaryKey.columns] }) : { columns: shapePKeys }
721
467
  }), options), {
722
468
  noPrimaryKey: options.noPrimaryKey ? "ignore" : noPrimaryKey || "error"
723
469
  });
@@ -794,8 +540,8 @@ const astToQueries$1 = (ast, snakeCase, language) => {
794
540
  ${constraintToSql(
795
541
  ast,
796
542
  true,
797
- __spreadProps$3(__spreadValues$5({}, item), {
798
- references: item.references ? __spreadProps$3(__spreadValues$5({}, item.references), {
543
+ __spreadProps$6(__spreadValues$9({}, item), {
544
+ references: item.references ? __spreadProps$6(__spreadValues$9({}, item.references), {
799
545
  columns: item.references.columns.map(
800
546
  (column) => getColumnName(shape[column], column, snakeCase)
801
547
  )
@@ -807,8 +553,8 @@ const astToQueries$1 = (ast, snakeCase, language) => {
807
553
  );
808
554
  });
809
555
  indexes.push(
810
- ...((_b = ast.indexes) == null ? void 0 : _b.map((index) => __spreadProps$3(__spreadValues$5({}, index), {
811
- columns: index.columns.map((item) => __spreadValues$5(__spreadValues$5({}, item), "column" in item ? {
556
+ ...((_b = ast.indexes) == null ? void 0 : _b.map((index) => __spreadProps$6(__spreadValues$9({}, index), {
557
+ columns: index.columns.map((item) => __spreadValues$9(__spreadValues$9({}, item), "column" in item ? {
812
558
  column: getColumnName(shape[item.column], item.column, snakeCase)
813
559
  } : {}))
814
560
  }))) || []
@@ -830,25 +576,25 @@ const astToQueries$1 = (ast, snakeCase, language) => {
830
576
  return queries;
831
577
  };
832
578
 
833
- var __defProp$4 = Object.defineProperty;
834
- var __defProps$2 = Object.defineProperties;
835
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
836
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
837
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
838
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
839
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
840
- var __spreadValues$4 = (a, b) => {
579
+ var __defProp$8 = Object.defineProperty;
580
+ var __defProps$5 = Object.defineProperties;
581
+ var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
582
+ var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
583
+ var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
584
+ var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
585
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
586
+ var __spreadValues$8 = (a, b) => {
841
587
  for (var prop in b || (b = {}))
842
- if (__hasOwnProp$4.call(b, prop))
843
- __defNormalProp$4(a, prop, b[prop]);
844
- if (__getOwnPropSymbols$4)
845
- for (var prop of __getOwnPropSymbols$4(b)) {
846
- if (__propIsEnum$4.call(b, prop))
847
- __defNormalProp$4(a, prop, b[prop]);
588
+ if (__hasOwnProp$8.call(b, prop))
589
+ __defNormalProp$8(a, prop, b[prop]);
590
+ if (__getOwnPropSymbols$8)
591
+ for (var prop of __getOwnPropSymbols$8(b)) {
592
+ if (__propIsEnum$8.call(b, prop))
593
+ __defNormalProp$8(a, prop, b[prop]);
848
594
  }
849
595
  return a;
850
596
  };
851
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
597
+ var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
852
598
  const newChangeTableData = () => ({
853
599
  add: {},
854
600
  drop: {}
@@ -864,7 +610,7 @@ const mergeTableData = (a, b) => {
864
610
  } else {
865
611
  a.primaryKey = {
866
612
  columns: [...a.primaryKey.columns, ...b.primaryKey.columns],
867
- options: __spreadValues$4(__spreadValues$4({}, a.primaryKey.options), b.primaryKey.options)
613
+ options: __spreadValues$8(__spreadValues$8({}, a.primaryKey.options), b.primaryKey.options)
868
614
  };
869
615
  }
870
616
  }
@@ -927,7 +673,7 @@ const addOrDrop = (type, item, options) => {
927
673
  check: item.data.check
928
674
  }
929
675
  });
930
- return __spreadValues$4({
676
+ return __spreadValues$8({
931
677
  type: "change",
932
678
  from: type === "add" ? empty : add2,
933
679
  to: type === "add" ? add2 : empty
@@ -945,7 +691,7 @@ const columnTypeToColumnChange = (item) => {
945
691
  if (foreignKeys == null ? void 0 : foreignKeys.some((it) => "fn" in it)) {
946
692
  throw new Error("Callback in foreignKey is not allowed in migration");
947
693
  }
948
- return __spreadProps$2(__spreadValues$4({
694
+ return __spreadProps$5(__spreadValues$8({
949
695
  column: item,
950
696
  type: item.toSQL(),
951
697
  nullable: item.data.isNullable,
@@ -957,7 +703,7 @@ const columnTypeToColumnChange = (item) => {
957
703
  return item.to;
958
704
  };
959
705
  const nameKey = Symbol("name");
960
- const tableChangeMethods = __spreadProps$2(__spreadValues$4({}, tableMethods), {
706
+ const tableChangeMethods = __spreadProps$5(__spreadValues$8({}, tableMethods), {
961
707
  name(name) {
962
708
  setCurrentColumnName(name);
963
709
  const types = Object.create(this);
@@ -967,7 +713,7 @@ const tableChangeMethods = __spreadProps$2(__spreadValues$4({}, tableMethods), {
967
713
  add,
968
714
  drop,
969
715
  change(from, to, options) {
970
- return __spreadValues$4({
716
+ return __spreadValues$8({
971
717
  type: "change",
972
718
  name: this[nameKey],
973
719
  from: columnTypeToColumnChange(from),
@@ -1029,18 +775,18 @@ const makeAst$1 = (up, name, changeData, changeTableData2, options) => {
1029
775
  }
1030
776
  if ("type" in item) {
1031
777
  if (up) {
1032
- shape[key] = item.type === "change" && item.usingUp ? __spreadProps$2(__spreadValues$4({}, item), { using: item.usingUp }) : item;
778
+ shape[key] = item.type === "change" && item.usingUp ? __spreadProps$5(__spreadValues$8({}, item), { using: item.usingUp }) : item;
1033
779
  } else {
1034
780
  if (item.type === "rename") {
1035
- shape[item.name] = __spreadProps$2(__spreadValues$4({}, item), { name: key });
781
+ shape[item.name] = __spreadProps$5(__spreadValues$8({}, item), { name: key });
1036
782
  } else {
1037
- shape[key] = item.type === "add" ? __spreadProps$2(__spreadValues$4({}, item), { type: "drop" }) : item.type === "drop" ? __spreadProps$2(__spreadValues$4({}, item), { type: "add" }) : item.type === "change" ? __spreadProps$2(__spreadValues$4({}, item), { from: item.to, to: item.from, using: item.usingDown }) : item;
783
+ shape[key] = item.type === "add" ? __spreadProps$5(__spreadValues$8({}, item), { type: "drop" }) : item.type === "drop" ? __spreadProps$5(__spreadValues$8({}, item), { type: "add" }) : item.type === "change" ? __spreadProps$5(__spreadValues$8({}, item), { from: item.to, to: item.from, using: item.usingDown }) : item;
1038
784
  }
1039
785
  }
1040
786
  }
1041
787
  }
1042
788
  const [schema, table] = getSchemaAndTableFromName(name);
1043
- return __spreadValues$4({
789
+ return __spreadValues$8({
1044
790
  type: "changeTable",
1045
791
  schema,
1046
792
  name: table,
@@ -1234,7 +980,7 @@ const astToQueries = (ast, snakeCase, language) => {
1234
980
  if (fromIndex) {
1235
981
  dropIndexes.push({
1236
982
  columns: [
1237
- __spreadValues$4({
983
+ __spreadValues$8({
1238
984
  column: name
1239
985
  }, fromIndex)
1240
986
  ],
@@ -1244,7 +990,7 @@ const astToQueries = (ast, snakeCase, language) => {
1244
990
  if (toIndex) {
1245
991
  addIndexes.push({
1246
992
  columns: [
1247
- __spreadValues$4({
993
+ __spreadValues$8({
1248
994
  column: name
1249
995
  }, toIndex)
1250
996
  ],
@@ -1309,13 +1055,13 @@ const mapIndexesForSnakeCase = (indexes, snakeCase) => {
1309
1055
  return (indexes == null ? void 0 : indexes.map((index) => ({
1310
1056
  options: index.options,
1311
1057
  columns: snakeCase ? index.columns.map(
1312
- (item) => "column" in item ? __spreadProps$2(__spreadValues$4({}, item), { column: toSnakeCase(item.column) }) : item
1058
+ (item) => "column" in item ? __spreadProps$5(__spreadValues$8({}, item), { column: toSnakeCase(item.column) }) : item
1313
1059
  ) : index.columns
1314
1060
  }))) || [];
1315
1061
  };
1316
1062
  const mapConstraintsToSnakeCase = (foreignKeys, snakeCase) => {
1317
- return (foreignKeys == null ? void 0 : foreignKeys.map((item) => __spreadProps$2(__spreadValues$4({}, item), {
1318
- references: item.references ? snakeCase ? __spreadProps$2(__spreadValues$4({}, item.references), {
1063
+ return (foreignKeys == null ? void 0 : foreignKeys.map((item) => __spreadProps$5(__spreadValues$8({}, item), {
1064
+ references: item.references ? snakeCase ? __spreadProps$5(__spreadValues$8({}, item.references), {
1319
1065
  columns: item.references.columns.map(toSnakeCase)
1320
1066
  }) : item.references : void 0
1321
1067
  }))) || [];
@@ -1383,25 +1129,25 @@ const astToQuery = (ast) => {
1383
1129
  };
1384
1130
  };
1385
1131
 
1386
- var __defProp$3 = Object.defineProperty;
1387
- var __defProps$1 = Object.defineProperties;
1388
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
1389
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
1390
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
1391
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
1392
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1393
- var __spreadValues$3 = (a, b) => {
1132
+ var __defProp$7 = Object.defineProperty;
1133
+ var __defProps$4 = Object.defineProperties;
1134
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
1135
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
1136
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
1137
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
1138
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1139
+ var __spreadValues$7 = (a, b) => {
1394
1140
  for (var prop in b || (b = {}))
1395
- if (__hasOwnProp$3.call(b, prop))
1396
- __defNormalProp$3(a, prop, b[prop]);
1397
- if (__getOwnPropSymbols$3)
1398
- for (var prop of __getOwnPropSymbols$3(b)) {
1399
- if (__propIsEnum$3.call(b, prop))
1400
- __defNormalProp$3(a, prop, b[prop]);
1141
+ if (__hasOwnProp$7.call(b, prop))
1142
+ __defNormalProp$7(a, prop, b[prop]);
1143
+ if (__getOwnPropSymbols$7)
1144
+ for (var prop of __getOwnPropSymbols$7(b)) {
1145
+ if (__propIsEnum$7.call(b, prop))
1146
+ __defNormalProp$7(a, prop, b[prop]);
1401
1147
  }
1402
1148
  return a;
1403
1149
  };
1404
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
1150
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
1405
1151
  const createMigrationInterface = (tx, up, config, asts) => {
1406
1152
  const adapter = new TransactionAdapter(tx, tx.client, tx.types);
1407
1153
  const { query, arrays } = adapter;
@@ -2040,7 +1786,7 @@ const wrapWithLog = async (log, query, fn) => {
2040
1786
  if (!log) {
2041
1787
  return fn();
2042
1788
  } else {
2043
- const sql = typeof query === "string" ? { text: query, values: [] } : query.values ? query : __spreadProps$1(__spreadValues$3({}, query), { values: [] });
1789
+ const sql = typeof query === "string" ? { text: query, values: [] } : query.values ? query : __spreadProps$4(__spreadValues$7({}, query), { values: [] });
2044
1790
  const logData = log.beforeQuery(sql);
2045
1791
  try {
2046
1792
  const result = await fn();
@@ -2058,19 +1804,19 @@ const addColumn = (migration, up, tableName, columnName, fn) => {
2058
1804
  }));
2059
1805
  };
2060
1806
  const addIndex = (migration, up, tableName, columns, options) => {
2061
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$3({}, t.add(t.index(columns, options))));
1807
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$7({}, t.add(t.index(columns, options))));
2062
1808
  };
2063
1809
  const addForeignKey = (migration, up, tableName, columns, foreignTable, foreignColumns, options) => {
2064
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$3({}, t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))));
1810
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$7({}, t.add(t.foreignKey(columns, foreignTable, foreignColumns, options))));
2065
1811
  };
2066
1812
  const addPrimaryKey = (migration, up, tableName, columns, options) => {
2067
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$3({}, t.add(t.primaryKey(columns, options))));
1813
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$7({}, t.add(t.primaryKey(columns, options))));
2068
1814
  };
2069
1815
  const addCheck = (migration, up, tableName, check) => {
2070
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$3({}, t.add(t.check(check))));
1816
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$7({}, t.add(t.check(check))));
2071
1817
  };
2072
1818
  const addConstraint = (migration, up, tableName, constraint) => {
2073
- return changeTable(migration, up, tableName, {}, (t) => __spreadValues$3({}, t.add(t.constraint(constraint))));
1819
+ return changeTable(migration, up, tableName, {}, (t) => __spreadValues$7({}, t.add(t.constraint(constraint))));
2074
1820
  };
2075
1821
  const createSchema$1 = async (migration, up, name) => {
2076
1822
  const ast = {
@@ -2084,7 +1830,7 @@ const createSchema$1 = async (migration, up, name) => {
2084
1830
  migration.migratedAsts.push(ast);
2085
1831
  };
2086
1832
  const createExtension$1 = async (migration, up, name, options) => {
2087
- const ast = __spreadValues$3({
1833
+ const ast = __spreadValues$7({
2088
1834
  type: "extension",
2089
1835
  action: up ? "create" : "drop",
2090
1836
  name
@@ -2100,7 +1846,7 @@ const createExtension$1 = async (migration, up, name, options) => {
2100
1846
  };
2101
1847
  const createEnum$1 = async (migration, up, name, values, options = {}) => {
2102
1848
  const [schema, enumName] = getSchemaAndTableFromName(name);
2103
- const ast = __spreadValues$3({
1849
+ const ast = __spreadValues$7({
2104
1850
  type: "enum",
2105
1851
  action: up ? "create" : "drop",
2106
1852
  schema,
@@ -2119,7 +1865,7 @@ const createEnum$1 = async (migration, up, name, values, options = {}) => {
2119
1865
  };
2120
1866
  const createDomain$1 = async (migration, up, name, fn, options) => {
2121
1867
  const [schema, domainName] = getSchemaAndTableFromName(name);
2122
- const ast = __spreadValues$3({
1868
+ const ast = __spreadValues$7({
2123
1869
  type: "domain",
2124
1870
  action: up ? "create" : "drop",
2125
1871
  schema,
@@ -2147,7 +1893,7 @@ DEFAULT ${ast.default.toSQL({ values })}` : ""}${ast.notNull || ast.check ? "\n"
2147
1893
  };
2148
1894
  const createCollation$1 = async (migration, up, name, options) => {
2149
1895
  const [schema, collationName] = getSchemaAndTableFromName(name);
2150
- const ast = __spreadValues$3({
1896
+ const ast = __spreadValues$7({
2151
1897
  type: "collation",
2152
1898
  action: up ? "create" : "drop",
2153
1899
  schema,
@@ -2189,28 +1935,357 @@ const queryExists = (db, sql) => {
2189
1935
  return db.adapter.query(sql).then(({ rowCount }) => rowCount > 0);
2190
1936
  };
2191
1937
 
2192
- const saveMigratedVersion = async (db, version, config) => {
2193
- await db.silentArrays(
2194
- `INSERT INTO ${quoteWithSchema({
2195
- name: config.migrationsTable
2196
- })} VALUES ('${version}')`
1938
+ const writeMigrationFile = async (config, version, name, content) => {
1939
+ var _a;
1940
+ await mkdir(config.migrationsPath, { recursive: true });
1941
+ const filePath = path.resolve(config.migrationsPath, `${version}_${name}.ts`);
1942
+ const importPath = getImportPath(
1943
+ filePath,
1944
+ path.join(config.basePath, config.dbScript)
1945
+ );
1946
+ await writeFile(filePath, content(importPath, name));
1947
+ (_a = config.logger) == null ? void 0 : _a.log(`Created ${pathToLog(filePath)}`);
1948
+ };
1949
+ const generate = async (config, [name]) => {
1950
+ if (!name)
1951
+ throw new Error("Migration name is missing");
1952
+ const version = await makeFileVersion({}, config);
1953
+ await writeMigrationFile(config, version, name, makeContent);
1954
+ };
1955
+ const makeFileVersion = async (ctx, config) => {
1956
+ if (config.migrationId === "timestamp") {
1957
+ return generateTimeStamp();
1958
+ } else {
1959
+ const {
1960
+ migrations: [first]
1961
+ } = await getMigrations(ctx, config, false);
1962
+ return first ? String(parseInt(first.version) + 1).padStart(4, "0") : "0001";
1963
+ }
1964
+ };
1965
+ const generateTimeStamp = () => {
1966
+ const now = /* @__PURE__ */ new Date();
1967
+ return [
1968
+ now.getUTCFullYear(),
1969
+ now.getUTCMonth() + 1,
1970
+ now.getUTCDate(),
1971
+ now.getUTCHours(),
1972
+ now.getUTCMinutes(),
1973
+ now.getUTCSeconds()
1974
+ ].map((value) => value < 10 ? `0${value}` : value).join("");
1975
+ };
1976
+ const makeContent = (importPath, name) => {
1977
+ let content = `import { change } from '${importPath}';
1978
+
1979
+ change(async (db) => {`;
1980
+ const [first, rest] = getFirstWordAndRest(name);
1981
+ if (rest) {
1982
+ if (first === "create" || first === "drop") {
1983
+ content += `
1984
+ await db.${first === "create" ? "createTable" : "dropTable"}('${rest}', (t) => ({
1985
+
1986
+ }));`;
1987
+ } else if (first === "change") {
1988
+ content += `
1989
+ await db.changeTable('${rest}', (t) => ({
1990
+
1991
+ }));`;
1992
+ } else if (first === "add" || first === "remove") {
1993
+ const table = first === "add" ? getTextAfterTo(rest) : getTextAfterFrom(rest);
1994
+ content += `
1995
+ await db.changeTable(${table ? `'${table}'` : "tableName"}, (t) => ({
1996
+
1997
+ }));`;
1998
+ }
1999
+ }
2000
+ return content + "\n});\n";
2001
+ };
2002
+
2003
+ const fileNamesToChangeMigrationId = {
2004
+ serial: ".rename-to-serial.json",
2005
+ timestamp: ".rename-to-timestamp.json"
2006
+ };
2007
+ const fileNamesToChangeMigrationIdMap = Object.fromEntries(
2008
+ Object.entries(fileNamesToChangeMigrationId).map(([_, name]) => [name, true])
2009
+ );
2010
+ const changeIds = async (options, config, [arg]) => {
2011
+ var _a;
2012
+ if (arg !== "serial" && arg !== "timestamp") {
2013
+ throw new Error(
2014
+ `Pass "serial" or "timestamp" argument to the "change-ids" command`
2015
+ );
2016
+ }
2017
+ if (config.migrations) {
2018
+ throw new Error(
2019
+ `Cannot change migrations ids when migrations set is defined in the config`
2020
+ );
2021
+ }
2022
+ const data = await getMigrationsFromFiles(config, false, (_, filePath) => {
2023
+ const fileName = path.basename(filePath);
2024
+ const match = fileName.match(/^(\d+)\D/);
2025
+ if (!match) {
2026
+ throw new Error(
2027
+ `Migration file name should start digits, received ${fileName}`
2028
+ );
2029
+ }
2030
+ return match[1];
2031
+ });
2032
+ if (data.renameTo) {
2033
+ if (data.renameTo === arg) {
2034
+ (_a = config.logger) == null ? void 0 : _a.log(`${fileNamesToChangeMigrationId[arg]} already exists`);
2035
+ return;
2036
+ }
2037
+ await fs.unlink(
2038
+ path.join(
2039
+ config.migrationsPath,
2040
+ fileNamesToChangeMigrationId[data.renameTo]
2041
+ )
2042
+ );
2043
+ }
2044
+ const version = arg === "timestamp" ? parseInt(generateTimeStamp()) : 1;
2045
+ const rename = Object.fromEntries(
2046
+ data.migrations.map((item, i) => [path.basename(item.path), version + i])
2047
+ );
2048
+ await fs.writeFile(
2049
+ path.join(config.migrationsPath, fileNamesToChangeMigrationId[arg]),
2050
+ JSON.stringify(rename, null, 2)
2051
+ );
2052
+ const values = [];
2053
+ await Promise.all(
2054
+ data.migrations.map(async (item, i) => {
2055
+ let newVersion = String(version + i);
2056
+ if (arg === "serial")
2057
+ newVersion = newVersion.padStart(4, "0");
2058
+ const name = path.basename(item.path).slice(item.version.length + 1);
2059
+ await fs.rename(
2060
+ item.path,
2061
+ path.join(path.dirname(item.path), `${newVersion}_${name}`)
2062
+ );
2063
+ values.push([item.version, name, newVersion]);
2064
+ })
2197
2065
  );
2066
+ if (!values.length)
2067
+ return;
2068
+ await options.map((opts) => {
2069
+ const adapter = new Adapter(opts);
2070
+ renameMigrationVersionsInDb(config, adapter, values).then(
2071
+ () => adapter.close()
2072
+ );
2073
+ });
2198
2074
  };
2199
- const removeMigratedVersion = async (db, version, config) => {
2200
- await db.silentArrays(
2201
- `DELETE FROM ${quoteWithSchema({
2075
+ const renameMigrationVersionsInDb = async (config, adapter, values) => {
2076
+ await adapter.arrays({
2077
+ text: `UPDATE ${quoteWithSchema({
2202
2078
  name: config.migrationsTable
2203
- })} WHERE version = '${version}'`
2079
+ })} AS t SET version = v.version FROM (VALUES ${values.map(
2080
+ ([oldVersion, , newVersion], i) => `('${oldVersion}', $${i + 1}, '${newVersion}')`
2081
+ ).join(
2082
+ ", "
2083
+ )}) v(oldVersion, name, version) WHERE t.version = v.oldVersion`,
2084
+ values: values.map(([, name]) => name)
2085
+ });
2086
+ };
2087
+
2088
+ var __defProp$6 = Object.defineProperty;
2089
+ var __defProps$3 = Object.defineProperties;
2090
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
2091
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
2092
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
2093
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
2094
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2095
+ var __spreadValues$6 = (a, b) => {
2096
+ for (var prop in b || (b = {}))
2097
+ if (__hasOwnProp$6.call(b, prop))
2098
+ __defNormalProp$6(a, prop, b[prop]);
2099
+ if (__getOwnPropSymbols$6)
2100
+ for (var prop of __getOwnPropSymbols$6(b)) {
2101
+ if (__propIsEnum$6.call(b, prop))
2102
+ __defNormalProp$6(a, prop, b[prop]);
2103
+ }
2104
+ return a;
2105
+ };
2106
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
2107
+ const getMigrations = async (ctx, config, up, allowDuplicates) => {
2108
+ var _a;
2109
+ return ((_a = ctx.migrationsPromise) != null ? _a : ctx.migrationsPromise = config.migrations ? getMigrationsFromConfig(__spreadProps$3(__spreadValues$6({}, config), { migrations: config.migrations })) : getMigrationsFromFiles(config, allowDuplicates)).then(
2110
+ (data) => up ? data : { renameTo: data.renameTo, migrations: [...data.migrations].reverse() }
2204
2111
  );
2205
2112
  };
2113
+ function getMigrationsFromConfig(config, allowDuplicates) {
2114
+ const result = [];
2115
+ const versions = {};
2116
+ const { migrations, basePath } = config;
2117
+ for (const key in migrations) {
2118
+ const version = getMigrationVersionOrThrow(config, path.basename(key));
2119
+ if (versions[version] && !allowDuplicates) {
2120
+ throw new Error(
2121
+ `Migration ${key} has the same version as ${versions[version]}`
2122
+ );
2123
+ }
2124
+ versions[version] = key;
2125
+ result.push({
2126
+ path: path.resolve(basePath, key),
2127
+ version,
2128
+ load: migrations[key]
2129
+ });
2130
+ }
2131
+ return Promise.resolve({
2132
+ migrations: result
2133
+ });
2134
+ }
2135
+ const sortMigrationsAsc = (a, b) => +a.version - +b.version;
2136
+ async function getMigrationsFromFiles(config, allowDuplicates, getVersion = getMigrationVersionOrThrow) {
2137
+ const { migrationsPath, import: imp } = config;
2138
+ const entries = await readdir(migrationsPath, { withFileTypes: true }).catch(
2139
+ () => []
2140
+ );
2141
+ const versions = {};
2142
+ const result = entries.reduce(
2143
+ (data, file) => {
2144
+ if (!file.isFile())
2145
+ return data;
2146
+ if (fileNamesToChangeMigrationIdMap[file.name]) {
2147
+ if (data.renameTo) {
2148
+ throw new Error(
2149
+ `Both files for renaming to serial and timestamp found, only one must remain`
2150
+ );
2151
+ }
2152
+ data.renameTo = file.name === ".rename-to-serial.json" ? "serial" : "timestamp";
2153
+ return data;
2154
+ } else {
2155
+ checkExt(file.name);
2156
+ }
2157
+ const version = getVersion(config, file.name);
2158
+ const filePath = path.resolve(migrationsPath, file.name);
2159
+ if (versions[version] && !allowDuplicates) {
2160
+ throw new Error(
2161
+ `Migration ${pathToFileURL(
2162
+ filePath
2163
+ )} has the same version as ${pathToFileURL(
2164
+ versions[version]
2165
+ )}
2166
+ Run \`**db command** rebase\` to reorganize files with duplicated versions.`
2167
+ );
2168
+ }
2169
+ versions[version] = filePath;
2170
+ data.migrations.push({
2171
+ path: filePath,
2172
+ version,
2173
+ async load() {
2174
+ try {
2175
+ await imp(this.path);
2176
+ } catch (err) {
2177
+ if (err.code !== "ERR_UNSUPPORTED_ESM_URL_SCHEME")
2178
+ throw err;
2179
+ await imp(pathToFileURL(this.path).pathname);
2180
+ }
2181
+ }
2182
+ });
2183
+ return data;
2184
+ },
2185
+ { migrations: [] }
2186
+ );
2187
+ result.migrations.sort(sortMigrationsAsc);
2188
+ return result;
2189
+ }
2190
+ function checkExt(filePath) {
2191
+ const ext = path.extname(filePath);
2192
+ if (ext !== ".ts" && ext !== ".js" && ext !== ".mjs") {
2193
+ throw new Error(
2194
+ `Only .ts, .js, and .mjs files are supported for migration, received: ${filePath}`
2195
+ );
2196
+ }
2197
+ }
2198
+ function getMigrationVersionOrThrow(config, filePath) {
2199
+ const name = path.basename(filePath);
2200
+ const value = getMigrationVersion(config, name);
2201
+ if (value)
2202
+ return value;
2203
+ if (config.migrationId === "timestamp") {
2204
+ throw new Error(
2205
+ `Migration file name should start with 14 digit timestamp, received ${name}`
2206
+ );
2207
+ } else {
2208
+ throw new Error(
2209
+ `Migration file name should start with 4 digit serial number, received ${name}.
2210
+ You can automatically change migration ids to serial by running \`*db-command* change-ids serial\`.
2211
+ To keep using timestamp ids, set \`migrationId\` option of rake-db to 'timestamp'.`
2212
+ );
2213
+ }
2214
+ }
2215
+ function getMigrationVersion(config, name) {
2216
+ var _a;
2217
+ return (_a = config.migrationId === "timestamp" ? name.match(/^(\d{14})(_|\b)/) : name.match(/^(\d{4})(_|\b)/)) == null ? void 0 : _a[1];
2218
+ }
2219
+ function getDigitsPrefix(name) {
2220
+ var _a;
2221
+ const value = (_a = name.match(/^(\d+)\D/)) == null ? void 0 : _a[1];
2222
+ if (!value) {
2223
+ throw new Error(
2224
+ `Migration file should be prefixed with a serial number, received ${name}`
2225
+ );
2226
+ }
2227
+ return value;
2228
+ }
2229
+
2230
+ const saveMigratedVersion = async (db, version, name, config) => {
2231
+ await db.silentArrays({
2232
+ text: `INSERT INTO ${quoteWithSchema({
2233
+ name: config.migrationsTable
2234
+ })}(version, name) VALUES ($1, $2)`,
2235
+ values: [version, name]
2236
+ });
2237
+ };
2238
+ const removeMigratedVersion = async (db, version, name, config) => {
2239
+ const res = await db.silentArrays({
2240
+ text: `DELETE FROM ${quoteWithSchema({
2241
+ name: config.migrationsTable
2242
+ })} WHERE version = $1 AND name = $2`,
2243
+ values: [version, name]
2244
+ });
2245
+ if (res.rowCount === 0) {
2246
+ throw new Error(`Migration ${version}_${name} was not found in db`);
2247
+ }
2248
+ };
2206
2249
  class NoMigrationsTableError extends Error {
2207
2250
  }
2208
- const getMigratedVersionsMap = async (db, config) => {
2251
+ const getMigratedVersionsMap = async (ctx, adapter, config) => {
2209
2252
  try {
2210
- const result = await db.arrays(
2211
- `SELECT * FROM ${quoteWithSchema({ name: config.migrationsTable })}`
2212
- );
2213
- return Object.fromEntries(result.rows.map((row) => [row[0], true]));
2253
+ const table = quoteWithSchema({
2254
+ name: config.migrationsTable
2255
+ });
2256
+ const result = await adapter.arrays(`SELECT * FROM ${table}`);
2257
+ if (!result.fields[1]) {
2258
+ const { migrations } = await getMigrations(ctx, config, true);
2259
+ const map = {};
2260
+ for (const item of migrations) {
2261
+ const name = path.basename(item.path);
2262
+ map[item.version] = name.slice(getDigitsPrefix(name).length + 1);
2263
+ }
2264
+ const data = result.rows.map(
2265
+ ([version]) => {
2266
+ const name = map[version];
2267
+ if (!name) {
2268
+ throw new Error(
2269
+ `Migration for version ${version} is stored in db but is not found among available migrations`
2270
+ );
2271
+ }
2272
+ return { version, name };
2273
+ }
2274
+ );
2275
+ await adapter.arrays(`ALTER TABLE ${table} ADD COLUMN name TEXT`);
2276
+ await Promise.all(
2277
+ data.map(
2278
+ ({ version, name }) => adapter.arrays({
2279
+ text: `UPDATE ${table} SET name = $2 WHERE version = $1`,
2280
+ values: [version, name]
2281
+ })
2282
+ )
2283
+ );
2284
+ await adapter.arrays(
2285
+ `ALTER TABLE ${table} ALTER COLUMN name SET NOT NULL`
2286
+ );
2287
+ }
2288
+ return Object.fromEntries(result.rows);
2214
2289
  } catch (err) {
2215
2290
  if (err.code === "42P01") {
2216
2291
  throw new NoMigrationsTableError();
@@ -2220,26 +2295,55 @@ const getMigratedVersionsMap = async (db, config) => {
2220
2295
  }
2221
2296
  };
2222
2297
 
2223
- var __defProp$2 = Object.defineProperty;
2224
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
2225
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
2226
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
2227
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2228
- var __spreadValues$2 = (a, b) => {
2298
+ const createMigrationsTable = async (db, config) => {
2299
+ var _a, _b, _c;
2300
+ const { schema } = db;
2301
+ if (schema && schema !== "public") {
2302
+ try {
2303
+ await db.query(`CREATE SCHEMA "${schema}"`);
2304
+ (_a = config.logger) == null ? void 0 : _a.log(`Created schema ${schema}`);
2305
+ } catch (err) {
2306
+ if (err.code !== "42P06") {
2307
+ throw err;
2308
+ }
2309
+ }
2310
+ }
2311
+ try {
2312
+ await db.query(
2313
+ `CREATE TABLE ${quoteWithSchema({
2314
+ name: config.migrationsTable
2315
+ })} ( version TEXT NOT NULL, name TEXT NOT NULL )`
2316
+ );
2317
+ (_b = config.logger) == null ? void 0 : _b.log("Created versions table");
2318
+ } catch (err) {
2319
+ if (err.code === "42P07") {
2320
+ (_c = config.logger) == null ? void 0 : _c.log("Versions table exists");
2321
+ } else {
2322
+ throw err;
2323
+ }
2324
+ }
2325
+ };
2326
+
2327
+ var __defProp$5 = Object.defineProperty;
2328
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
2329
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
2330
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
2331
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2332
+ var __spreadValues$5 = (a, b) => {
2229
2333
  for (var prop in b || (b = {}))
2230
- if (__hasOwnProp$2.call(b, prop))
2231
- __defNormalProp$2(a, prop, b[prop]);
2232
- if (__getOwnPropSymbols$2)
2233
- for (var prop of __getOwnPropSymbols$2(b)) {
2234
- if (__propIsEnum$2.call(b, prop))
2235
- __defNormalProp$2(a, prop, b[prop]);
2334
+ if (__hasOwnProp$5.call(b, prop))
2335
+ __defNormalProp$5(a, prop, b[prop]);
2336
+ if (__getOwnPropSymbols$5)
2337
+ for (var prop of __getOwnPropSymbols$5(b)) {
2338
+ if (__propIsEnum$5.call(b, prop))
2339
+ __defNormalProp$5(a, prop, b[prop]);
2236
2340
  }
2237
2341
  return a;
2238
2342
  };
2239
2343
  const RAKE_DB_LOCK_KEY = "8582141715823621641";
2240
2344
  function makeMigrateFn(defaultCount, up, fn) {
2241
- return async (options, config, args = []) => {
2242
- const files = await getMigrations(config, up);
2345
+ return async (ctx, options, config, args = []) => {
2346
+ const set = await getMigrations(ctx, config, up);
2243
2347
  const count = getCount(args);
2244
2348
  const conf = prepareConfig(config, args, count);
2245
2349
  const asts = [];
@@ -2250,21 +2354,22 @@ function makeMigrateFn(defaultCount, up, fn) {
2250
2354
  for (const opts of arrOptions) {
2251
2355
  const adapter = new Adapter(opts);
2252
2356
  try {
2253
- await adapter.transaction(begin, async (trx) => {
2357
+ await transaction(adapter, async (trx) => {
2254
2358
  await fn(
2359
+ ctx,
2255
2360
  trx,
2256
2361
  conf,
2257
- files,
2362
+ set,
2258
2363
  count != null ? count : defaultCount,
2259
2364
  localAsts
2260
2365
  );
2261
2366
  });
2262
2367
  } catch (err) {
2263
2368
  if (err instanceof NoMigrationsTableError) {
2264
- await adapter.transaction(begin, async (trx) => {
2369
+ await transaction(adapter, async (trx) => {
2265
2370
  const config2 = conf;
2266
- await createSchemaMigrations(trx, config2);
2267
- await fn(trx, config2, files, count != null ? count : defaultCount, localAsts);
2371
+ await createMigrationsTable(trx, config2);
2372
+ await fn(ctx, trx, config2, set, count != null ? count : defaultCount, localAsts);
2268
2373
  });
2269
2374
  } else {
2270
2375
  throw err;
@@ -2286,21 +2391,21 @@ function makeMigrateFn(defaultCount, up, fn) {
2286
2391
  const migrate = makeMigrateFn(
2287
2392
  Infinity,
2288
2393
  true,
2289
- (trx, config, files, count, asts) => migrateOrRollback(trx, config, files, count, asts, true)
2394
+ (ctx, trx, config, migrations, count, asts) => migrateOrRollback(ctx, trx, config, migrations, count, asts, true)
2290
2395
  );
2291
2396
  const rollback = makeMigrateFn(
2292
2397
  1,
2293
2398
  false,
2294
- (trx, config, files, count, asts) => migrateOrRollback(trx, config, files, count, asts, false)
2399
+ (ctx, trx, config, migrations, count, asts) => migrateOrRollback(ctx, trx, config, migrations, count, asts, false)
2295
2400
  );
2296
2401
  const redo = makeMigrateFn(
2297
2402
  1,
2298
- false,
2299
- async (trx, config, files, count, asts) => {
2300
- await migrateOrRollback(trx, config, files, count, asts, false);
2301
- files.reverse();
2302
- await migrateOrRollback(trx, config, files, count, asts, true, true);
2303
- files.reverse();
2403
+ true,
2404
+ async (ctx, trx, config, set, count, asts) => {
2405
+ set.migrations.reverse();
2406
+ await migrateOrRollback(ctx, trx, config, set, count, asts, false);
2407
+ set.migrations.reverse();
2408
+ await migrateOrRollback(ctx, trx, config, set, count, asts, true, true);
2304
2409
  }
2305
2410
  );
2306
2411
  const getDb = (adapter) => createDb$1({ adapter });
@@ -2309,7 +2414,7 @@ const getCount = (args) => {
2309
2414
  return isNaN(num) ? void 0 : num;
2310
2415
  };
2311
2416
  function prepareConfig(config, args, count) {
2312
- config = __spreadValues$2({}, config);
2417
+ config = __spreadValues$5({}, config);
2313
2418
  const i = count === void 0 ? 0 : 1;
2314
2419
  const arg = args[i];
2315
2420
  if (arg === "--code") {
@@ -2319,83 +2424,303 @@ function prepareConfig(config, args, count) {
2319
2424
  delete config.appCodeUpdater;
2320
2425
  return config;
2321
2426
  }
2322
- const migrateOrRollback = async (trx, config, files, count, asts, up, skipLock) => {
2427
+ const migrateOrRollback = async (ctx, trx, config, set, count, asts, up, skipLock) => {
2323
2428
  var _a, _b, _c;
2324
- if (!skipLock) {
2325
- await trx.query(`SELECT pg_advisory_xact_lock('${RAKE_DB_LOCK_KEY}')`);
2326
- }
2429
+ if (!skipLock)
2430
+ await queryLock(trx);
2327
2431
  let db;
2328
2432
  await ((_a = config[up ? "beforeMigrate" : "beforeRollback"]) == null ? void 0 : _a.call(config, db != null ? db : db = getDb(trx)));
2329
- const migratedVersions = await getMigratedVersionsMap(trx, config);
2330
- for (const file of files) {
2433
+ let migratedVersions = await getMigratedVersionsMap(ctx, trx, config);
2434
+ if (set.renameTo) {
2435
+ migratedVersions = await renameMigrations(
2436
+ config,
2437
+ trx,
2438
+ migratedVersions,
2439
+ set.renameTo
2440
+ );
2441
+ }
2442
+ for (const file of set.migrations) {
2331
2443
  if (up && migratedVersions[file.version] || !up && !migratedVersions[file.version]) {
2332
2444
  continue;
2333
2445
  }
2334
- if (count-- <= 0)
2335
- break;
2336
- await runMigration(trx, up, file, config, asts);
2337
- (_b = config.logger) == null ? void 0 : _b.log(
2338
- `${up ? "Migrated" : "Rolled back"} ${pathToLog(file.path)}`
2339
- );
2340
- }
2341
- await ((_c = config[up ? "afterMigrate" : "afterRollback"]) == null ? void 0 : _c.call(config, db != null ? db : db = getDb(trx)));
2342
- };
2343
- async function runCodeUpdaterAfterAll(options, config, appCodeUpdater, asts, cache) {
2344
- for (const ast of asts) {
2345
- await (appCodeUpdater == null ? void 0 : appCodeUpdater.process({
2346
- ast,
2347
- options,
2348
- basePath: config.basePath,
2349
- cache,
2350
- logger: config.logger,
2351
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2352
- baseTable: config.baseTable,
2353
- import: config.import
2354
- }));
2446
+ if (count-- <= 0)
2447
+ break;
2448
+ await runMigration(trx, up, file, config, asts);
2449
+ (_b = config.logger) == null ? void 0 : _b.log(
2450
+ `${up ? "Migrated" : "Rolled back"} ${pathToLog(file.path)}`
2451
+ );
2452
+ }
2453
+ await ((_c = config[up ? "afterMigrate" : "afterRollback"]) == null ? void 0 : _c.call(config, db != null ? db : db = getDb(trx)));
2454
+ };
2455
+ async function renameMigrations(config, trx, migratedVersions, renameTo) {
2456
+ let first;
2457
+ for (const version in migratedVersions) {
2458
+ first = version;
2459
+ break;
2460
+ }
2461
+ if (!first || getMigrationVersion(config, first))
2462
+ return migratedVersions;
2463
+ const fileName = fileNamesToChangeMigrationId[renameTo];
2464
+ const filePath = path.join(config.migrationsPath, fileName);
2465
+ const json = await fs.readFile(filePath, "utf-8");
2466
+ let data;
2467
+ try {
2468
+ data = JSON.parse(json);
2469
+ if (typeof data !== "object")
2470
+ throw new Error("Config for renaming is not an object");
2471
+ } catch (err) {
2472
+ throw new Error(`Failed to read ${pathToFileURL(filePath)}`, {
2473
+ cause: err
2474
+ });
2475
+ }
2476
+ const values = [];
2477
+ const updatedVersions = {};
2478
+ for (const version in migratedVersions) {
2479
+ const name = migratedVersions[version];
2480
+ const key = `${version}_${name}`;
2481
+ let newVersion = data[key];
2482
+ if (!newVersion) {
2483
+ throw new Error(
2484
+ `Failed to find an entry for the migrated ${key} in the ${fileName} config`
2485
+ );
2486
+ }
2487
+ if (renameTo === "serial") {
2488
+ newVersion = String(newVersion).padStart(4, "0");
2489
+ }
2490
+ updatedVersions[newVersion] = name;
2491
+ values.push([version, name, newVersion]);
2492
+ }
2493
+ await renameMigrationVersionsInDb(config, trx, values);
2494
+ return updatedVersions;
2495
+ }
2496
+ async function runCodeUpdaterAfterAll(options, config, appCodeUpdater, asts, cache) {
2497
+ for (const ast of asts) {
2498
+ await (appCodeUpdater == null ? void 0 : appCodeUpdater.process({
2499
+ ast,
2500
+ options,
2501
+ basePath: config.basePath,
2502
+ cache,
2503
+ logger: config.logger,
2504
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2505
+ baseTable: config.baseTable,
2506
+ import: config.import
2507
+ }));
2508
+ }
2509
+ await (appCodeUpdater == null ? void 0 : appCodeUpdater.afterAll({
2510
+ options,
2511
+ basePath: config.basePath,
2512
+ cache,
2513
+ logger: config.logger,
2514
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2515
+ baseTable: config.baseTable,
2516
+ import: config.import
2517
+ }));
2518
+ }
2519
+ const changeCache = {};
2520
+ const runMigration = async (trx, up, file, config, asts) => {
2521
+ clearChanges();
2522
+ let changes = changeCache[file.path];
2523
+ if (!changes) {
2524
+ const module = await file.load();
2525
+ const exported = (module == null ? void 0 : module.default) && toArray(module.default);
2526
+ if (config.forceDefaultExports && !exported) {
2527
+ throw new RakeDbError(
2528
+ `Missing a default export in ${file.path} migration`
2529
+ );
2530
+ }
2531
+ changes = exported || getCurrentChanges();
2532
+ changeCache[file.path] = changes;
2533
+ }
2534
+ const db = createMigrationInterface(trx, up, config, asts);
2535
+ if (changes.length) {
2536
+ const from = up ? 0 : changes.length - 1;
2537
+ const to = up ? changes.length : -1;
2538
+ const step = up ? 1 : -1;
2539
+ for (let i = from; i !== to; i += step) {
2540
+ await changes[i](db, up);
2541
+ }
2542
+ }
2543
+ await (up ? saveMigratedVersion : removeMigratedVersion)(
2544
+ db.adapter,
2545
+ file.version,
2546
+ path.basename(file.path).slice(file.version.length + 1),
2547
+ config
2548
+ );
2549
+ };
2550
+
2551
+ var __defProp$4 = Object.defineProperty;
2552
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
2553
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
2554
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
2555
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2556
+ var __spreadValues$4 = (a, b) => {
2557
+ for (var prop in b || (b = {}))
2558
+ if (__hasOwnProp$4.call(b, prop))
2559
+ __defNormalProp$4(a, prop, b[prop]);
2560
+ if (__getOwnPropSymbols$4)
2561
+ for (var prop of __getOwnPropSymbols$4(b)) {
2562
+ if (__propIsEnum$4.call(b, prop))
2563
+ __defNormalProp$4(a, prop, b[prop]);
2564
+ }
2565
+ return a;
2566
+ };
2567
+ const migrationConfigDefaults = {
2568
+ schemaConfig: defaultSchemaConfig,
2569
+ migrationsPath: path.join("src", "db", "migrations"),
2570
+ migrationId: "serial",
2571
+ migrationsTable: "schemaMigrations",
2572
+ snakeCase: false,
2573
+ commands: {},
2574
+ import: (path2) => {
2575
+ return import(path2).catch((err) => {
2576
+ if (err.code === "ERR_UNKNOWN_FILE_EXTENSION") {
2577
+ require(path2);
2578
+ } else {
2579
+ throw err;
2580
+ }
2581
+ });
2582
+ },
2583
+ log: true,
2584
+ logger: console,
2585
+ useCodeUpdater: true
2586
+ };
2587
+ const processRakeDbConfig = (config) => {
2588
+ var _a, _b;
2589
+ const result = __spreadValues$4(__spreadValues$4({}, migrationConfigDefaults), config);
2590
+ if (!result.recurrentPath) {
2591
+ result.recurrentPath = path.join(result.migrationsPath, "recurrent");
2592
+ }
2593
+ if (config.appCodeUpdater && (!("baseTable" in config) || !config.baseTable)) {
2594
+ throw new Error(
2595
+ "`baseTable` option is required in `rakeDb` for `appCodeUpdater`"
2596
+ );
2597
+ }
2598
+ if (!result.log) {
2599
+ delete result.logger;
2600
+ }
2601
+ if (!result.basePath || !result.dbScript) {
2602
+ let filePath = (_a = getStackTrace()) == null ? void 0 : _a[3].getFileName();
2603
+ if (!filePath) {
2604
+ throw new Error(
2605
+ "Failed to determine path to db script. Please set basePath option of rakeDb"
2606
+ );
2607
+ }
2608
+ if (filePath.startsWith("file://")) {
2609
+ filePath = fileURLToPath(filePath);
2610
+ }
2611
+ const ext = path.extname(filePath);
2612
+ if (ext !== ".ts" && ext !== ".js" && ext !== ".mjs") {
2613
+ throw new Error(
2614
+ `Add a .ts suffix to the "${path.basename(filePath)}" when calling it`
2615
+ );
2616
+ }
2617
+ result.basePath = path.dirname(filePath);
2618
+ result.dbScript = path.basename(filePath);
2619
+ }
2620
+ if ("migrationsPath" in result && !path.isAbsolute(result.migrationsPath)) {
2621
+ result.migrationsPath = path.resolve(
2622
+ result.basePath,
2623
+ result.migrationsPath
2624
+ );
2625
+ }
2626
+ if ("recurrentPath" in result && !path.isAbsolute(result.recurrentPath)) {
2627
+ result.recurrentPath = path.resolve(result.basePath, result.recurrentPath);
2628
+ }
2629
+ if ("baseTable" in config) {
2630
+ const proto = (_b = config.baseTable) == null ? void 0 : _b.prototype;
2631
+ result.columnTypes = proto.types || makeColumnTypes(defaultSchemaConfig);
2632
+ if (proto.snakeCase)
2633
+ result.snakeCase = true;
2634
+ if (proto.language)
2635
+ result.language = proto.language;
2636
+ } else {
2637
+ const ct = "columnTypes" in config && config.columnTypes;
2638
+ result.columnTypes = (typeof ct === "function" ? ct(
2639
+ makeColumnTypes(defaultSchemaConfig)
2640
+ ) : ct) || makeColumnTypes;
2641
+ }
2642
+ return result;
2643
+ };
2644
+ const getDatabaseAndUserFromOptions = (options) => {
2645
+ if (options.databaseURL) {
2646
+ const url = new URL(options.databaseURL);
2647
+ return {
2648
+ database: url.pathname.slice(1),
2649
+ user: url.username
2650
+ };
2651
+ } else {
2652
+ return {
2653
+ database: options.database,
2654
+ user: options.user
2655
+ };
2656
+ }
2657
+ };
2658
+
2659
+ var __defProp$3 = Object.defineProperty;
2660
+ var __defProps$2 = Object.defineProperties;
2661
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
2662
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
2663
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
2664
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
2665
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2666
+ var __spreadValues$3 = (a, b) => {
2667
+ for (var prop in b || (b = {}))
2668
+ if (__hasOwnProp$3.call(b, prop))
2669
+ __defNormalProp$3(a, prop, b[prop]);
2670
+ if (__getOwnPropSymbols$3)
2671
+ for (var prop of __getOwnPropSymbols$3(b)) {
2672
+ if (__propIsEnum$3.call(b, prop))
2673
+ __defNormalProp$3(a, prop, b[prop]);
2674
+ }
2675
+ return a;
2676
+ };
2677
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
2678
+ const setAdapterOptions = (options, set) => {
2679
+ if (options.databaseURL) {
2680
+ const url = new URL(options.databaseURL);
2681
+ if ("database" in set) {
2682
+ url.pathname = `/${set.database}`;
2683
+ }
2684
+ if (set.user !== void 0) {
2685
+ url.username = set.user;
2686
+ }
2687
+ if (set.password !== void 0) {
2688
+ url.password = set.password;
2689
+ }
2690
+ return __spreadProps$2(__spreadValues$3({}, options), { databaseURL: url.toString() });
2691
+ } else {
2692
+ return __spreadValues$3(__spreadValues$3({}, options), set);
2355
2693
  }
2356
- await (appCodeUpdater == null ? void 0 : appCodeUpdater.afterAll({
2357
- options,
2358
- basePath: config.basePath,
2359
- cache,
2360
- logger: config.logger,
2361
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2362
- baseTable: config.baseTable,
2363
- import: config.import
2364
- }));
2365
- }
2366
- const changeCache = {};
2367
- const begin = {
2368
- text: "BEGIN",
2369
- values: emptyArray
2370
2694
  };
2371
- const runMigration = async (trx, up, file, config, asts) => {
2372
- clearChanges();
2373
- let changes = changeCache[file.path];
2374
- if (!changes) {
2375
- const module = await file.load();
2376
- const exported = (module == null ? void 0 : module.default) && toArray(module.default);
2377
- if (config.forceDefaultExports && !exported) {
2378
- throw new RakeDbError(
2379
- `Missing a default export in ${file.path} migration`
2380
- );
2695
+ const setAdminCredentialsToOptions = async (options, create) => {
2696
+ const confirm = await prompts([
2697
+ {
2698
+ message: `Would you like to share admin credentials to ${create ? "create" : "drop"} a database`,
2699
+ type: "confirm",
2700
+ name: "confirm",
2701
+ initial: true
2381
2702
  }
2382
- changes = exported || getCurrentChanges();
2383
- changeCache[file.path] = changes;
2703
+ ]);
2704
+ if (!confirm.confirm) {
2705
+ return;
2384
2706
  }
2385
- const db = createMigrationInterface(trx, up, config, asts);
2386
- if (changes.length) {
2387
- const from = up ? 0 : changes.length - 1;
2388
- const to = up ? changes.length : -1;
2389
- const step = up ? 1 : -1;
2390
- for (let i = from; i !== to; i += step) {
2391
- await changes[i](db, up);
2707
+ const values = await prompts([
2708
+ {
2709
+ message: "Enter admin user:",
2710
+ type: "text",
2711
+ name: "user",
2712
+ initial: "postgres",
2713
+ min: 1
2714
+ },
2715
+ {
2716
+ message: "Enter admin password:",
2717
+ type: "password",
2718
+ name: "password"
2392
2719
  }
2393
- }
2394
- await (up ? saveMigratedVersion : removeMigratedVersion)(
2395
- db.adapter,
2396
- file.version,
2397
- config
2398
- );
2720
+ ]);
2721
+ return setAdapterOptions(options, __spreadProps$2(__spreadValues$3({}, values), {
2722
+ password: values.password || void 0
2723
+ }));
2399
2724
  };
2400
2725
 
2401
2726
  const execute = async (options, sql) => {
@@ -2458,7 +2783,7 @@ Don't use this command for database service providers, only for a local db.`;
2458
2783
  if (!args.create)
2459
2784
  return;
2460
2785
  const db = new Adapter(options);
2461
- await createSchemaMigrations(db, config);
2786
+ await createMigrationsTable(db, config);
2462
2787
  await db.close();
2463
2788
  };
2464
2789
  const createDb = async (arg, config) => {
@@ -2495,62 +2820,7 @@ const dropDb = async (arg, config) => {
2495
2820
  const resetDb = async (arg, config) => {
2496
2821
  await dropDb(arg, config);
2497
2822
  await createDb(arg, config);
2498
- await migrate(arg, config);
2499
- };
2500
-
2501
- const writeMigrationFile = async (config, version, name, content) => {
2502
- var _a;
2503
- await mkdir(config.migrationsPath, { recursive: true });
2504
- const filePath = path.resolve(config.migrationsPath, `${version}_${name}.ts`);
2505
- const importPath = getImportPath(
2506
- filePath,
2507
- path.join(config.basePath, config.dbScript)
2508
- );
2509
- await writeFile(filePath, content(importPath, name));
2510
- (_a = config.logger) == null ? void 0 : _a.log(`Created ${pathToLog(filePath)}`);
2511
- };
2512
- const generate = async (config, [name]) => {
2513
- if (!name)
2514
- throw new Error("Migration name is missing");
2515
- const version = makeFileTimeStamp();
2516
- await writeMigrationFile(config, version, name, makeContent);
2517
- };
2518
- const makeFileTimeStamp = () => {
2519
- const now = /* @__PURE__ */ new Date();
2520
- return [
2521
- now.getUTCFullYear(),
2522
- now.getUTCMonth() + 1,
2523
- now.getUTCDate(),
2524
- now.getUTCHours(),
2525
- now.getUTCMinutes(),
2526
- now.getUTCSeconds()
2527
- ].map((value) => value < 10 ? `0${value}` : value).join("");
2528
- };
2529
- const makeContent = (importPath, name) => {
2530
- let content = `import { change } from '${importPath}';
2531
-
2532
- change(async (db) => {`;
2533
- const [first, rest] = getFirstWordAndRest(name);
2534
- if (rest) {
2535
- if (first === "create" || first === "drop") {
2536
- content += `
2537
- await db.${first === "create" ? "createTable" : "dropTable"}('${rest}', (t) => ({
2538
-
2539
- }));`;
2540
- } else if (first === "change") {
2541
- content += `
2542
- await db.changeTable('${rest}', (t) => ({
2543
-
2544
- }));`;
2545
- } else if (first === "add" || first === "remove") {
2546
- const table = first === "add" ? getTextAfterTo(rest) : getTextAfterFrom(rest);
2547
- content += `
2548
- await db.changeTable(${table ? `'${table}'` : "tableName"}, (t) => ({
2549
-
2550
- }));`;
2551
- }
2552
- }
2553
- return content + "\n});\n";
2823
+ await migrate({}, arg, config);
2554
2824
  };
2555
2825
 
2556
2826
  const filterSchema = (table) => `${table} !~ '^pg_' AND ${table} != 'information_schema'`;
@@ -2922,33 +3192,33 @@ async function introspectDbSchema(db) {
2922
3192
  return data.rows[0];
2923
3193
  }
2924
3194
 
2925
- var __defProp$1 = Object.defineProperty;
2926
- var __defProps = Object.defineProperties;
2927
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
2928
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
2929
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
2930
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
2931
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2932
- var __spreadValues$1 = (a, b) => {
3195
+ var __defProp$2 = Object.defineProperty;
3196
+ var __defProps$1 = Object.defineProperties;
3197
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
3198
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
3199
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
3200
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
3201
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3202
+ var __spreadValues$2 = (a, b) => {
2933
3203
  for (var prop in b || (b = {}))
2934
- if (__hasOwnProp$1.call(b, prop))
2935
- __defNormalProp$1(a, prop, b[prop]);
2936
- if (__getOwnPropSymbols$1)
2937
- for (var prop of __getOwnPropSymbols$1(b)) {
2938
- if (__propIsEnum$1.call(b, prop))
2939
- __defNormalProp$1(a, prop, b[prop]);
3204
+ if (__hasOwnProp$2.call(b, prop))
3205
+ __defNormalProp$2(a, prop, b[prop]);
3206
+ if (__getOwnPropSymbols$2)
3207
+ for (var prop of __getOwnPropSymbols$2(b)) {
3208
+ if (__propIsEnum$2.call(b, prop))
3209
+ __defNormalProp$2(a, prop, b[prop]);
2940
3210
  }
2941
3211
  return a;
2942
3212
  };
2943
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
3213
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
2944
3214
  var __objRest = (source, exclude) => {
2945
3215
  var target = {};
2946
3216
  for (var prop in source)
2947
- if (__hasOwnProp$1.call(source, prop) && exclude.indexOf(prop) < 0)
3217
+ if (__hasOwnProp$2.call(source, prop) && exclude.indexOf(prop) < 0)
2948
3218
  target[prop] = source[prop];
2949
- if (source != null && __getOwnPropSymbols$1)
2950
- for (var prop of __getOwnPropSymbols$1(source)) {
2951
- if (exclude.indexOf(prop) < 0 && __propIsEnum$1.call(source, prop))
3219
+ if (source != null && __getOwnPropSymbols$2)
3220
+ for (var prop of __getOwnPropSymbols$2(source)) {
3221
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$2.call(source, prop))
2952
3222
  target[prop] = source[prop];
2953
3223
  }
2954
3224
  return target;
@@ -2979,7 +3249,7 @@ const structureToAst = async (ctx, adapter) => {
2979
3249
  });
2980
3250
  }
2981
3251
  for (const it of data.collations) {
2982
- ast.push(__spreadProps(__spreadValues$1({
3252
+ ast.push(__spreadProps$1(__spreadValues$2({
2983
3253
  type: "collation",
2984
3254
  action: "create"
2985
3255
  }, it), {
@@ -3074,7 +3344,7 @@ const structureToAst = async (ctx, adapter) => {
3074
3344
  );
3075
3345
  }
3076
3346
  for (const [fkey, table] of outerConstraints) {
3077
- ast.push(__spreadProps(__spreadValues$1({}, constraintToAst(ctx, fkey)), {
3347
+ ast.push(__spreadProps$1(__spreadValues$2({}, constraintToAst(ctx, fkey)), {
3078
3348
  type: "constraint",
3079
3349
  action: "create",
3080
3350
  tableSchema: table.schemaName === ctx.currentSchema ? void 0 : table.schemaName,
@@ -3231,7 +3501,7 @@ const pushTableAst = (ctx, ast, data, domains, table, pendingTables, innerConstr
3231
3501
  indexes: tableIndexes.filter(
3232
3502
  (index) => index.columns.length > 1 || index.columns.some((it) => "expression" in it)
3233
3503
  ).map((index) => ({
3234
- columns: index.columns.map((it) => __spreadProps(__spreadValues$1({}, "column" in it ? { column: it.column } : { expression: it.expression }), {
3504
+ columns: index.columns.map((it) => __spreadProps$1(__spreadValues$2({}, "column" in it ? { column: it.column } : { expression: it.expression }), {
3235
3505
  collate: it.collate,
3236
3506
  opclass: it.opclass,
3237
3507
  order: it.order
@@ -3331,9 +3601,9 @@ const makeColumnsShape = (ctx, data, domains, tableName, columns, primaryKey, in
3331
3601
  for (let item of columns) {
3332
3602
  const isSerial = getIsSerial(item);
3333
3603
  if (isSerial) {
3334
- item = __spreadProps(__spreadValues$1({}, item), { default: void 0 });
3604
+ item = __spreadProps$1(__spreadValues$2({}, item), { default: void 0 });
3335
3605
  }
3336
- let column = getColumn(ctx, data, domains, __spreadProps(__spreadValues$1({}, item), {
3606
+ let column = getColumn(ctx, data, domains, __spreadProps$1(__spreadValues$2({}, item), {
3337
3607
  type: item.type,
3338
3608
  isArray: item.isArray,
3339
3609
  isSerial
@@ -3657,13 +3927,13 @@ const pullDbStructure = async (options, config) => {
3657
3927
  const result = astToMigration(config, ast);
3658
3928
  if (!result)
3659
3929
  return;
3660
- const version = makeFileTimeStamp();
3930
+ const version = await makeFileVersion({}, config);
3661
3931
  await writeMigrationFile(config, version, "pull", result);
3662
3932
  const silentQueries = Object.assign(adapter, {
3663
3933
  silentQuery: adapter.query,
3664
3934
  silentArrays: adapter.arrays
3665
3935
  });
3666
- await saveMigratedVersion(silentQueries, version, config);
3936
+ await saveMigratedVersion(silentQueries, version, "pull", config);
3667
3937
  const cache = {};
3668
3938
  for (const item of ast) {
3669
3939
  await ((_a = config == null ? void 0 : config.appCodeUpdater) == null ? void 0 : _a.process({
@@ -3749,6 +4019,290 @@ const readdirRecursive = async (dirPath, cb) => {
3749
4019
  );
3750
4020
  };
3751
4021
 
4022
+ const listMigrationsStatuses = async (options, config, args) => {
4023
+ var _a, _b;
4024
+ const adapters = options.map((opts) => new Adapter(opts));
4025
+ const ctx = {};
4026
+ const [{ migrations }, ...migrated] = await Promise.all([
4027
+ getMigrations(ctx, config, true),
4028
+ ...adapters.map((adapter) => getMigratedVersionsMap(ctx, adapter, config))
4029
+ ]);
4030
+ const map = {};
4031
+ let maxVersionLength = 12;
4032
+ let maxNameLength = 4;
4033
+ for (let i = 0; i < options.length; i++) {
4034
+ const list = migrated[i];
4035
+ const key = Object.entries(list).map(([version, up]) => `${version}${up ? "t" : "f"}`).join("");
4036
+ const database = options[i].database || new URL(options[i].databaseURL).pathname.slice(1);
4037
+ if (map[key]) {
4038
+ map[key].databases.push(database);
4039
+ continue;
4040
+ }
4041
+ map[key] = {
4042
+ databases: [database],
4043
+ migrations: migrations.map((item) => {
4044
+ if (item.version.length > maxVersionLength) {
4045
+ maxVersionLength = item.version.length;
4046
+ }
4047
+ const name = path.parse(item.path).name.slice(item.version.length + 1).replace(
4048
+ /([a-z])([A-Z])/g,
4049
+ (_, a, b) => `${a} ${b.toLocaleLowerCase()}`
4050
+ ).replace(/[-_](.)/g, (_, char) => ` ${char.toLocaleLowerCase()}`).replace(/^\w/, (match) => match.toLocaleUpperCase());
4051
+ if (name.length > maxNameLength) {
4052
+ maxNameLength = name.length;
4053
+ }
4054
+ return {
4055
+ up: !!list[item.version],
4056
+ version: item.version,
4057
+ name,
4058
+ url: pathToFileURL(item.path)
4059
+ };
4060
+ })
4061
+ };
4062
+ }
4063
+ const showUrl = args.includes("p") || args.includes("path");
4064
+ const colors = typeof config.log === "object" ? (_a = config.log.colors) != null ? _a : true : true;
4065
+ const yellow = colors ? (s) => `\x1B[33m${s}\x1B[0m` : (s) => s;
4066
+ const green = colors ? (s) => `\x1B[32m${s}\x1B[0m` : (s) => s;
4067
+ const red = colors ? (s) => `\x1B[31m${s}\x1B[0m` : (s) => s;
4068
+ const blue = colors ? (s) => `\x1B[34m${s}\x1B[0m` : (s) => s;
4069
+ const log = Object.values(map).map(({ databases, migrations: migrations2 }) => {
4070
+ let log2 = ` ${yellow("Database:")} ${databases.join(", ")}`;
4071
+ if (migrations2.length === 0) {
4072
+ return log2 + `
4073
+
4074
+ No migrations available`;
4075
+ }
4076
+ const lineSeparator = yellow(
4077
+ makeChars(14 + maxVersionLength + maxNameLength, "-")
4078
+ );
4079
+ const columnSeparator = yellow("|");
4080
+ log2 += "\n\n " + yellow(
4081
+ `Status | Migration ID${makeChars(
4082
+ maxVersionLength - 12,
4083
+ " "
4084
+ )} | Name
4085
+ ${lineSeparator}`
4086
+ );
4087
+ for (const migration of migrations2) {
4088
+ log2 += `
4089
+ ${migration.up ? ` ${green("Up")} ` : red("Down")} ${columnSeparator} ${blue(migration.version)}${makeChars(
4090
+ maxVersionLength - migration.version.length,
4091
+ " "
4092
+ )} ${columnSeparator} ${migration.name}`;
4093
+ if (showUrl) {
4094
+ log2 += `
4095
+ ${migration.url}
4096
+ `;
4097
+ }
4098
+ }
4099
+ return log2 += showUrl ? lineSeparator : `
4100
+ ${lineSeparator}`;
4101
+ }).join("\n\n");
4102
+ ((_b = config.logger) != null ? _b : console).log(log);
4103
+ await Promise.all(adapters.map((adapter) => adapter.close()));
4104
+ };
4105
+ const makeChars = (count, char) => {
4106
+ let chars = "";
4107
+ for (let i = 0; i < count; i++) {
4108
+ chars += char;
4109
+ }
4110
+ return chars;
4111
+ };
4112
+
4113
+ var __defProp$1 = Object.defineProperty;
4114
+ var __defProps = Object.defineProperties;
4115
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4116
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
4117
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
4118
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
4119
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4120
+ var __spreadValues$1 = (a, b) => {
4121
+ for (var prop in b || (b = {}))
4122
+ if (__hasOwnProp$1.call(b, prop))
4123
+ __defNormalProp$1(a, prop, b[prop]);
4124
+ if (__getOwnPropSymbols$1)
4125
+ for (var prop of __getOwnPropSymbols$1(b)) {
4126
+ if (__propIsEnum$1.call(b, prop))
4127
+ __defNormalProp$1(a, prop, b[prop]);
4128
+ }
4129
+ return a;
4130
+ };
4131
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
4132
+ const rebase = async (options, config) => {
4133
+ var _a, _b;
4134
+ if (config.migrations) {
4135
+ throw new Error("Cannot rebase migrations defined in the config");
4136
+ }
4137
+ if (config.migrationId !== "serial") {
4138
+ throw new Error(
4139
+ `Cannot rebase when the 'migrationId' is set to '${config.migrationId}' in the config`
4140
+ );
4141
+ }
4142
+ const adapters = options.map((opts) => new Adapter(opts));
4143
+ const ctx = {};
4144
+ const [set, ...versionMaps] = await Promise.all([
4145
+ await getMigrations(ctx, config, true, true),
4146
+ ...adapters.map((adapter) => getMigratedVersionsMap(ctx, adapter, config))
4147
+ ]);
4148
+ await Promise.all(adapters.map((adapter) => adapter.close()));
4149
+ const files = set.migrations.map((file) => __spreadProps(__spreadValues$1({}, file), {
4150
+ name: path.basename(file.path),
4151
+ serial: +file.version
4152
+ }));
4153
+ if (!files.length)
4154
+ return;
4155
+ const start = files.findIndex(
4156
+ (file, i) => i !== 0 && file.serial === files[i - 1].serial
4157
+ );
4158
+ if (start === -1)
4159
+ return;
4160
+ const combinedVersionsMap = {};
4161
+ for (const map of versionMaps) {
4162
+ Object.assign(combinedVersionsMap, map);
4163
+ }
4164
+ const renames = [];
4165
+ const renamesMap = {};
4166
+ let minVersionToMigrate = (_b = (_a = files.find((file) => !combinedVersionsMap[file.version])) == null ? void 0 : _a.serial) != null ? _b : Infinity;
4167
+ const migratedFiles = [];
4168
+ let maxNewVersion = 0;
4169
+ let move = 0;
4170
+ for (let i = start; i < files.length; i++) {
4171
+ const prev = files[i - 1];
4172
+ const file = files[i];
4173
+ let moveFile;
4174
+ const migratedName = combinedVersionsMap[file.version];
4175
+ if (prev.serial === file.serial) {
4176
+ if (migratedName) {
4177
+ if (prev.name === migratedName) {
4178
+ moveFile = prev;
4179
+ } else if (file.name === migratedName) {
4180
+ moveFile = file;
4181
+ }
4182
+ }
4183
+ if (moveFile) {
4184
+ if (moveFile.serial < minVersionToMigrate) {
4185
+ minVersionToMigrate = moveFile.serial;
4186
+ }
4187
+ migratedFiles.push(moveFile);
4188
+ } else if (!moveFile) {
4189
+ move++;
4190
+ const result = await prompts([
4191
+ {
4192
+ type: "select",
4193
+ name: "file",
4194
+ message: "Which should go first?",
4195
+ choices: [
4196
+ {
4197
+ title: prev.name,
4198
+ value: "prev"
4199
+ },
4200
+ {
4201
+ title: file.name,
4202
+ value: "current"
4203
+ }
4204
+ ]
4205
+ }
4206
+ ]);
4207
+ moveFile = result.file === "prev" ? prev : file;
4208
+ }
4209
+ }
4210
+ let newVersion = file.serial;
4211
+ if (move) {
4212
+ newVersion += move;
4213
+ if (moveFile === prev && !renamesMap[prev.path])
4214
+ newVersion--;
4215
+ if (file.serial !== newVersion) {
4216
+ if (newVersion < minVersionToMigrate)
4217
+ minVersionToMigrate = newVersion;
4218
+ const values = [file.path, newVersion];
4219
+ renames.push(values);
4220
+ renamesMap[file.path] = values;
4221
+ }
4222
+ if (moveFile === prev) {
4223
+ if (prev.serial < minVersionToMigrate)
4224
+ minVersionToMigrate = prev.serial;
4225
+ newVersion = prev.serial + move;
4226
+ let item = [prev.path, newVersion];
4227
+ if (renamesMap[prev.path]) {
4228
+ renamesMap[prev.path] = item;
4229
+ for (let i2 = renames.length - 1; i2 >= 0; i2--) {
4230
+ const rename = renames[i2];
4231
+ rename[1]--;
4232
+ renames[i2] = item;
4233
+ if (rename[0] === prev.path)
4234
+ break;
4235
+ renamesMap[item[0]] = item;
4236
+ item = rename;
4237
+ }
4238
+ } else {
4239
+ renames.push(item);
4240
+ renamesMap[prev.path] = item;
4241
+ }
4242
+ }
4243
+ }
4244
+ if (file.name !== migratedName && newVersion > maxNewVersion) {
4245
+ maxNewVersion = newVersion;
4246
+ }
4247
+ }
4248
+ if (!renames.length && !migratedFiles.length)
4249
+ return;
4250
+ maxNewVersion++;
4251
+ renames.push(
4252
+ ...migratedFiles.map((file, i) => {
4253
+ const rename = [file.path, maxNewVersion + i];
4254
+ renamesMap[file.path] = rename;
4255
+ return rename;
4256
+ })
4257
+ );
4258
+ if (!renames.length)
4259
+ return;
4260
+ const migrationsDown = files.filter(
4261
+ (file) => combinedVersionsMap[file.version] === file.name && file.serial >= minVersionToMigrate
4262
+ );
4263
+ const migrationsUp = files.reduce((files2, file) => {
4264
+ const rename = renamesMap[file.path];
4265
+ if (rename) {
4266
+ const version = String(rename[1]).padStart(4, "0");
4267
+ files2.push(__spreadProps(__spreadValues$1({}, file), {
4268
+ path: path.join(
4269
+ path.dirname(rename[0]),
4270
+ version + path.basename(rename[0]).slice(version.length)
4271
+ ),
4272
+ version
4273
+ }));
4274
+ } else if (!combinedVersionsMap[file.version] || file.serial >= minVersionToMigrate) {
4275
+ files2.push(file);
4276
+ }
4277
+ return files2;
4278
+ }, []).sort((a, b) => +b.version - +a.version);
4279
+ set.migrations = migrationsDown;
4280
+ await redo$1(
4281
+ ctx,
4282
+ options,
4283
+ __spreadProps(__spreadValues$1({}, config), {
4284
+ async afterRollback() {
4285
+ set.migrations = migrationsUp;
4286
+ },
4287
+ async afterMigrate() {
4288
+ set.migrations = migrationsDown;
4289
+ }
4290
+ }),
4291
+ ["all"]
4292
+ );
4293
+ for (let i = renames.length - 1; i >= 0; i--) {
4294
+ const [from, version] = renames[i];
4295
+ const prefix = String(version).padStart(4, "0");
4296
+ await fs.rename(
4297
+ from,
4298
+ path.join(
4299
+ path.dirname(from),
4300
+ prefix + path.basename(from).slice(prefix.length)
4301
+ )
4302
+ );
4303
+ }
4304
+ };
4305
+
3752
4306
  var __defProp = Object.defineProperty;
3753
4307
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3754
4308
  var __hasOwnProp = Object.prototype.hasOwnProperty;
@@ -3806,15 +4360,21 @@ const runCommand = async (options, config, args = process.argv.slice(2)) => {
3806
4360
  } else if (arg === "reset") {
3807
4361
  await resetDb(options, config);
3808
4362
  } else if (arg === "up" || arg === "migrate") {
3809
- await migrate(options, config, args.slice(1));
4363
+ await migrate({}, options, config, args.slice(1));
3810
4364
  } else if (arg === "down" || arg === "rollback") {
3811
- await rollback(options, config, args.slice(1));
4365
+ await rollback({}, options, config, args.slice(1));
3812
4366
  } else if (arg === "redo") {
3813
- await redo(options, config, args.slice(1));
4367
+ await redo({}, options, config, args.slice(1));
3814
4368
  } else if (arg === "new") {
3815
4369
  await generate(config, args.slice(1));
3816
4370
  } else if (arg === "pull") {
3817
4371
  await pullDbStructure(toArray(options)[0], config);
4372
+ } else if (arg === "status" || arg === "s") {
4373
+ await listMigrationsStatuses(toArray(options), config, args.slice(1));
4374
+ } else if (arg === "rebase") {
4375
+ await rebase(toArray(options), config);
4376
+ } else if (arg === "change-ids") {
4377
+ await changeIds(toArray(options), config, args.slice(1));
3818
4378
  } else if (config.commands[arg]) {
3819
4379
  await config.commands[arg](toArray(options), config, args.slice(1));
3820
4380
  } else if (arg !== "rec" && arg !== "recurrent") {
@@ -3839,7 +4399,12 @@ Commands:
3839
4399
  up migrate pending migrations, don't run recurrent
3840
4400
  rollback or down rollback the last migrated
3841
4401
  redo rollback and migrate, run recurrent
4402
+ status or s list migrations statuses
4403
+ status path or s p list migrations statuses and paths to files
3842
4404
  rec or recurrent run recurrent migrations
4405
+ change-ids serial change migrations ids to 4 digit serial
4406
+ change-ids serial 42 change migrations ids to custom digits serial
4407
+ change-ids timestamp change migrations ids to timestamps
3843
4408
  no or unknown command prints this message
3844
4409
 
3845
4410
  Migrate arguments:
@@ -3856,5 +4421,5 @@ Migrate and rollback common arguments:
3856
4421
  --code false do not run code updater
3857
4422
  `;
3858
4423
 
3859
- export { Migration, NoMigrationsTableError, RAKE_DB_LOCK_KEY, changeCache, createDb, createMigrationInterface, dropDb, generate, getMigratedVersionsMap, makeFileTimeStamp, migrate, migrateOrRollback, rakeDb, redo, removeMigratedVersion, resetDb, rollback, saveMigratedVersion, writeMigrationFile };
4424
+ export { Migration, NoMigrationsTableError, RAKE_DB_LOCK_KEY, changeCache, createDb, createMigrationInterface, dropDb, generate, generateTimeStamp, getDatabaseAndUserFromOptions, getMigratedVersionsMap, makeFileVersion, migrate, migrateOrRollback, migrationConfigDefaults, processRakeDbConfig, rakeDb, redo, removeMigratedVersion, resetDb, rollback, saveMigratedVersion, writeMigrationFile };
3860
4425
  //# sourceMappingURL=index.mjs.map