rake-db 2.10.24 → 2.10.26

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.d.ts CHANGED
@@ -968,21 +968,23 @@ type RakeDbConfig<CT extends ColumnTypesBase = DefaultColumnTypes> = {
968
968
  basePath: string;
969
969
  dbScript: string;
970
970
  migrationsPath: string;
971
+ migrations?: ModuleExportsRecord;
971
972
  recurrentPath: string;
972
973
  migrationsTable: string;
973
974
  snakeCase: boolean;
974
975
  language?: string;
975
976
  commands: Record<string, (options: AdapterOptions[], config: RakeDbConfig<CT>, args: string[]) => Promise<void>>;
976
- import(path: string): Promise<unknown>;
977
977
  noPrimaryKey?: NoPrimaryKeyOption;
978
978
  baseTable?: BaseTable<CT>;
979
979
  appCodeUpdater?: AppCodeUpdater;
980
980
  useCodeUpdater?: boolean;
981
+ import(path: string): Promise<unknown>;
981
982
  beforeMigrate?(db: Db): Promise<void>;
982
983
  afterMigrate?(db: Db): Promise<void>;
983
984
  beforeRollback?(db: Db): Promise<void>;
984
985
  afterRollback?(db: Db): Promise<void>;
985
986
  } & QueryLogOptions;
987
+ type ModuleExportsRecord = Record<string, () => Promise<unknown>>;
986
988
  type AppCodeUpdaterParams = {
987
989
  options: AdapterOptions;
988
990
  basePath: string;
package/dist/index.js CHANGED
@@ -7,25 +7,6 @@ var promises = require('fs/promises');
7
7
  var prompts = require('prompts');
8
8
  var url = require('url');
9
9
 
10
- function _interopNamespaceDefault(e) {
11
- var n = Object.create(null);
12
- if (e) {
13
- Object.keys(e).forEach(function (k) {
14
- if (k !== 'default') {
15
- var d = Object.getOwnPropertyDescriptor(e, k);
16
- Object.defineProperty(n, k, d.get ? d : {
17
- enumerable: true,
18
- get: function () { return e[k]; }
19
- });
20
- }
21
- });
22
- }
23
- n.default = e;
24
- return Object.freeze(n);
25
- }
26
-
27
- var url__namespace = /*#__PURE__*/_interopNamespaceDefault(url);
28
-
29
10
  var __defProp$6 = Object.defineProperty;
30
11
  var __defProps$5 = Object.defineProperties;
31
12
  var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
@@ -66,8 +47,9 @@ const migrationConfigDefaults = {
66
47
  const processRakeDbConfig = (config) => {
67
48
  var _a;
68
49
  const result = __spreadValues$6(__spreadValues$6({}, migrationConfigDefaults), config);
69
- if (!result.recurrentPath)
50
+ if (!result.recurrentPath) {
70
51
  result.recurrentPath = path.join(result.migrationsPath, "recurrent");
52
+ }
71
53
  if (config.appCodeUpdater && (!("baseTable" in config) || !config.baseTable)) {
72
54
  throw new Error(
73
55
  "`baseTable` option is required in `rakeDb` for `appCodeUpdater`"
@@ -86,13 +68,13 @@ const processRakeDbConfig = (config) => {
86
68
  result.basePath = path.dirname(filePath);
87
69
  result.dbScript = path.basename(filePath);
88
70
  }
89
- if (!path.isAbsolute(result.migrationsPath)) {
71
+ if ("migrationsPath" in result && !path.isAbsolute(result.migrationsPath)) {
90
72
  result.migrationsPath = path.resolve(
91
73
  result.basePath,
92
74
  result.migrationsPath
93
75
  );
94
76
  }
95
- if (!path.isAbsolute(result.recurrentPath)) {
77
+ if ("recurrentPath" in result && !path.isAbsolute(result.recurrentPath)) {
96
78
  result.recurrentPath = path.resolve(result.basePath, result.recurrentPath);
97
79
  }
98
80
  if ("baseTable" in config) {
@@ -169,17 +151,28 @@ const setAdminCredentialsToOptions = async (options, create) => {
169
151
  }));
170
152
  };
171
153
  const createSchemaMigrations = async (db, config) => {
172
- var _a, _b;
154
+ var _a, _b, _c;
155
+ const { schema } = db;
156
+ if (schema && schema !== "public") {
157
+ try {
158
+ await db.query(`CREATE SCHEMA "${schema}"`);
159
+ (_a = config.logger) == null ? void 0 : _a.log(`Created schema ${schema}`);
160
+ } catch (err) {
161
+ if (err.code !== "42P06") {
162
+ throw err;
163
+ }
164
+ }
165
+ }
173
166
  try {
174
167
  await db.query(
175
168
  `CREATE TABLE ${quoteWithSchema({
176
169
  name: config.migrationsTable
177
170
  })} ( version TEXT NOT NULL )`
178
171
  );
179
- (_a = config.logger) == null ? void 0 : _a.log("Created versions table");
172
+ (_b = config.logger) == null ? void 0 : _b.log("Created versions table");
180
173
  } catch (err) {
181
174
  if (err.code === "42P07") {
182
- (_b = config.logger) == null ? void 0 : _b.log("Versions table exists");
175
+ (_c = config.logger) == null ? void 0 : _c.log("Versions table exists");
183
176
  } else {
184
177
  throw err;
185
178
  }
@@ -212,35 +205,63 @@ const getTextAfterTo = (input) => {
212
205
  const getTextAfterFrom = (input) => {
213
206
  return getTextAfterRegExp(input, /(From|-from|_from)[A-Z-_]/, 4);
214
207
  };
215
- const getMigrationFiles = async (config, up) => {
216
- const { migrationsPath } = config;
208
+ const getMigrations = async (config, up) => {
209
+ if ("migrations" in config) {
210
+ const result = [];
211
+ const { migrations, basePath } = config;
212
+ for (const key in migrations) {
213
+ result.push({
214
+ path: path.resolve(basePath, key),
215
+ version: getVersion(path.basename(key)),
216
+ change: migrations[key]
217
+ });
218
+ }
219
+ return result;
220
+ }
221
+ const { migrationsPath, import: imp } = config;
217
222
  let files;
218
223
  try {
219
224
  files = await promises.readdir(migrationsPath);
220
225
  } catch (_) {
221
226
  return [];
222
227
  }
223
- const sort = up ? sortAsc : sortDesc;
224
- return sort(files.filter((file) => path.basename(file).includes("."))).map(
225
- (file) => {
226
- if (!file.endsWith(".ts")) {
227
- throw new Error(
228
- `Only .ts files are supported for migration, received: ${file}`
229
- );
230
- }
231
- const timestampMatch = file.match(/^(\d{14})\D/);
232
- if (!timestampMatch) {
233
- throw new Error(
234
- `Migration file name should start with 14 digit version, received ${file}`
235
- );
228
+ files = files.filter((file) => path.basename(file).includes("."));
229
+ files = (up ? sortAsc : sortDesc)(files);
230
+ return files.map((file) => {
231
+ checkExt(file);
232
+ const filePath = path.resolve(migrationsPath, file);
233
+ return {
234
+ path: filePath,
235
+ version: getVersion(file),
236
+ async change() {
237
+ try {
238
+ await imp(filePath);
239
+ } catch (err) {
240
+ if (err.code !== "ERR_UNSUPPORTED_ESM_URL_SCHEME")
241
+ throw err;
242
+ await imp(url.pathToFileURL(filePath).pathname);
243
+ }
236
244
  }
237
- return {
238
- path: path.resolve(migrationsPath, file),
239
- version: timestampMatch[1]
240
- };
241
- }
242
- );
245
+ };
246
+ });
243
247
  };
248
+ function checkExt(path2) {
249
+ const ext = path2.slice(-3);
250
+ if (ext !== ".ts" && ext !== ".js") {
251
+ throw new Error(
252
+ `Only .ts and .js files are supported for migration, received: ${path2}`
253
+ );
254
+ }
255
+ }
256
+ function getVersion(path2) {
257
+ const timestampMatch = path2.match(/^(\d{14})\D/);
258
+ if (!timestampMatch) {
259
+ throw new Error(
260
+ `Migration file name should start with 14 digit version, received ${path2}`
261
+ );
262
+ }
263
+ return timestampMatch[1];
264
+ }
244
265
  const sortAsc = (arr) => arr.sort();
245
266
  const sortDesc = (arr) => arr.sort((a, b) => a > b ? -1 : 1);
246
267
  const joinColumns = (columns) => {
@@ -2178,7 +2199,7 @@ const getDb = (adapter) => pqb.createDb({ adapter });
2178
2199
  const migrateOrRollback = async (options, config, args, up) => {
2179
2200
  var _a, _b, _c, _d, _e, _f;
2180
2201
  config = __spreadValues$1({}, config);
2181
- const files = await getMigrationFiles(config, up);
2202
+ const files = await getMigrations(config, up);
2182
2203
  let count = up ? Infinity : 1;
2183
2204
  let argI = 0;
2184
2205
  const num = args[0] === "all" ? Infinity : parseInt(args[0]);
@@ -2252,13 +2273,7 @@ const processMigration = async (db, up, file, config, options, appCodeUpdaterCac
2252
2273
  clearChanges();
2253
2274
  let changes = changeCache[file.path];
2254
2275
  if (!changes) {
2255
- try {
2256
- await config.import(file.path);
2257
- } catch (err) {
2258
- if (err.code !== "ERR_UNSUPPORTED_ESM_URL_SCHEME")
2259
- throw err;
2260
- await config.import(url__namespace.pathToFileURL(file.path).pathname);
2261
- }
2276
+ await file.change();
2262
2277
  changes = getCurrentChanges();
2263
2278
  changeCache[file.path] = changes;
2264
2279
  }
@@ -2315,7 +2330,7 @@ const execute = async (options, sql) => {
2315
2330
  }
2316
2331
  };
2317
2332
  const createOrDrop = async (options, adminOptions, config, args) => {
2318
- var _a, _b, _c, _d, _e, _f;
2333
+ var _a, _b, _c, _d;
2319
2334
  const params = getDatabaseAndUserFromOptions(options);
2320
2335
  const result = await execute(
2321
2336
  setAdapterOptions(adminOptions, { database: "postgres" }),
@@ -2353,21 +2368,6 @@ Don't use this command for database service providers, only for a local db.`;
2353
2368
  if (!args.create)
2354
2369
  return;
2355
2370
  const db = new pqb.Adapter(options);
2356
- const { schema } = db;
2357
- if (schema) {
2358
- db.schema = void 0;
2359
- try {
2360
- await db.query(`CREATE SCHEMA "${schema}"`);
2361
- (_e = config.logger) == null ? void 0 : _e.log(`Created schema ${schema}`);
2362
- } catch (err) {
2363
- if (err.code === "42P06") {
2364
- (_f = config.logger) == null ? void 0 : _f.log(`Schema ${schema} already exists`);
2365
- } else {
2366
- throw err;
2367
- }
2368
- }
2369
- db.schema = schema;
2370
- }
2371
2371
  await createSchemaMigrations(db, config);
2372
2372
  await db.close();
2373
2373
  };