rake-db 2.4.2 → 2.4.3

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,5 +1,5 @@
1
- import { quote, getRaw, EnumColumn, columnTypes, getColumnTypes, getTableData, ColumnType, resetTableData, TransactionAdapter, logParamToLogObject, createDb as createDb$1, Adapter, columnsByType, instantiateColumn, codeToString, primaryKeyToCode, indexToCode, foreignKeyToCode, TimestampColumn, foreignKeyArgsToCode } from 'pqb';
2
- import { singleQuote, isRaw, toArray, snakeCaseKey, nameKey, emptyObject, addCode, quoteObjectKey } from 'orchid-core';
1
+ import { quote, getRaw, EnumColumn, columnTypes, getColumnTypes, getTableData, ColumnType, resetTableData, TransactionAdapter, logParamToLogObject, createDb as createDb$1, Adapter, columnsByType, instantiateColumn, ArrayColumn, columnCode, codeToString, primaryKeyToCode, indexToCode, foreignKeyToCode, TimestampColumn, foreignKeyArgsToCode } from 'pqb';
2
+ import { singleQuote, isRaw, toArray, snakeCaseKey, nameKey, emptyObject, pathToLog, addCode, quoteObjectKey } from 'orchid-core';
3
3
  import path from 'path';
4
4
  import { readdir, mkdir, writeFile } from 'fs/promises';
5
5
  import prompts from 'prompts';
@@ -37,10 +37,15 @@ const migrationConfigDefaults = {
37
37
  const processRakeDbConfig = (config) => {
38
38
  var _a;
39
39
  const result = __spreadValues$6(__spreadValues$6({}, migrationConfigDefaults), config);
40
+ if (!result.log) {
41
+ delete result.logger;
42
+ }
40
43
  if (!result.basePath) {
41
44
  let stack;
45
+ const original = Error.prepareStackTrace;
42
46
  Error.prepareStackTrace = (_, s) => stack = s;
43
47
  new Error().stack;
48
+ Error.prepareStackTrace = original;
44
49
  if (stack) {
45
50
  const thisFile = (_a = stack[0]) == null ? void 0 : _a.getFileName();
46
51
  const thisDir = thisFile && path.dirname(thisFile);
@@ -137,16 +142,17 @@ const setAdminCredentialsToOptions = async (options, create) => {
137
142
  }));
138
143
  };
139
144
  const createSchemaMigrations = async (db, config) => {
145
+ var _a, _b;
140
146
  try {
141
147
  await db.query(
142
148
  `CREATE TABLE ${quoteWithSchema({
143
149
  name: config.migrationsTable
144
150
  })} ( version TEXT NOT NULL )`
145
151
  );
146
- console.log("Created versions table");
152
+ (_a = config.logger) == null ? void 0 : _a.log("Created versions table");
147
153
  } catch (err) {
148
154
  if (err.code === "42P07") {
149
- console.log("Versions table exists");
155
+ (_b = config.logger) == null ? void 0 : _b.log("Versions table exists");
150
156
  } else {
151
157
  throw err;
152
158
  }
@@ -500,7 +506,7 @@ const createTable$1 = async (migration, up, tableName, options, fn) => {
500
506
  const result = await migration.adapter.arrays(query);
501
507
  then == null ? void 0 : then(result);
502
508
  }
503
- await runCodeUpdater(migration, ast);
509
+ migration.migratedAsts.push(ast);
504
510
  };
505
511
  const makeAst$1 = (up, tableName, shape, tableData, options, noPrimaryKey) => {
506
512
  const shapePKeys = [];
@@ -758,7 +764,7 @@ const changeTable = async (migration, up, tableName, options, fn) => {
758
764
  const result = await migration.adapter.arrays(query);
759
765
  (_a = query.then) == null ? void 0 : _a.call(query, result);
760
766
  }
761
- await runCodeUpdater(migration, ast);
767
+ migration.migratedAsts.push(ast);
762
768
  };
763
769
  const makeAst = (up, name, changeData, changeTableData2, options) => {
764
770
  const { comment } = options;
@@ -996,7 +1002,7 @@ var __spreadValues$2 = (a, b) => {
996
1002
  return a;
997
1003
  };
998
1004
  var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
999
- const createMigrationInterface = (tx, up, options, adapterOptions, appCodeUpdaterCache) => {
1005
+ const createMigrationInterface = (tx, up, options) => {
1000
1006
  const adapter = new TransactionAdapter(tx, tx.client, tx.types);
1001
1007
  const { query, arrays } = adapter;
1002
1008
  const log = logParamToLogObject(options.logger || console, options.log);
@@ -1011,13 +1017,12 @@ const createMigrationInterface = (tx, up, options, adapterOptions, appCodeUpdate
1011
1017
  for (const key of Object.getOwnPropertyNames(proto)) {
1012
1018
  db[key] = proto[key];
1013
1019
  }
1020
+ db.migratedAsts = [];
1014
1021
  return Object.assign(db, {
1015
1022
  adapter,
1016
1023
  log,
1017
1024
  up,
1018
- options,
1019
- adapterOptions,
1020
- appCodeUpdaterCache
1025
+ options
1021
1026
  });
1022
1027
  };
1023
1028
  class MigrationBase {
@@ -1054,7 +1059,7 @@ class MigrationBase {
1054
1059
  name: ast.to
1055
1060
  })}`
1056
1061
  );
1057
- await runCodeUpdater(this, ast);
1062
+ this.migratedAsts.push(ast);
1058
1063
  }
1059
1064
  addColumn(tableName, columnName, fn) {
1060
1065
  return addColumn(this, this.up, tableName, columnName, fn);
@@ -1177,7 +1182,7 @@ const createSchema$1 = async (migration, up, name) => {
1177
1182
  await migration.adapter.query(
1178
1183
  `${ast.action === "create" ? "CREATE" : "DROP"} SCHEMA "${name}"`
1179
1184
  );
1180
- await runCodeUpdater(migration, ast);
1185
+ migration.migratedAsts.push(ast);
1181
1186
  };
1182
1187
  const createExtension$1 = async (migration, up, name, options) => {
1183
1188
  const ast = __spreadValues$2({
@@ -1192,7 +1197,7 @@ const createExtension$1 = async (migration, up, name, options) => {
1192
1197
  query = `CREATE EXTENSION${ast.createIfNotExists ? " IF NOT EXISTS" : ""} "${ast.name}"${ast.schema ? ` SCHEMA "${ast.schema}"` : ""}${ast.version ? ` VERSION '${ast.version}'` : ""}${ast.cascade ? " CASCADE" : ""}`;
1193
1198
  }
1194
1199
  await migration.adapter.query(query);
1195
- await runCodeUpdater(migration, ast);
1200
+ migration.migratedAsts.push(ast);
1196
1201
  };
1197
1202
  const createEnum$1 = async (migration, up, name, values, options = {}) => {
1198
1203
  const [schema, enumName] = getSchemaAndTableFromName(name);
@@ -1211,20 +1216,11 @@ const createEnum$1 = async (migration, up, name, values, options = {}) => {
1211
1216
  query = `DROP TYPE${ast.dropIfExists ? " IF EXISTS" : ""} ${quotedName}${ast.cascade ? " CASCADE" : ""}`;
1212
1217
  }
1213
1218
  await migration.adapter.query(query);
1214
- await runCodeUpdater(migration, ast);
1219
+ migration.migratedAsts.push(ast);
1215
1220
  };
1216
1221
  const queryExists = (db, sql) => {
1217
1222
  return db.adapter.query(sql).then(({ rowCount }) => rowCount > 0);
1218
1223
  };
1219
- const runCodeUpdater = (migration, ast) => {
1220
- var _a, _b;
1221
- return (_b = (_a = migration.options).appCodeUpdater) == null ? void 0 : _b.call(_a, {
1222
- ast,
1223
- options: migration.adapterOptions,
1224
- basePath: migration.options.basePath,
1225
- cache: migration.appCodeUpdaterCache
1226
- });
1227
- };
1228
1224
 
1229
1225
  var __defProp$1 = Object.defineProperty;
1230
1226
  var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
@@ -1285,7 +1281,9 @@ const migrateOrRollback = async (options, config, args, up) => {
1285
1281
  opts,
1286
1282
  appCodeUpdaterCache
1287
1283
  );
1288
- (_c = config.logger) == null ? void 0 : _c.log(`${file.path} ${up ? "migrated" : "rolled back"}`);
1284
+ (_c = config.logger) == null ? void 0 : _c.log(
1285
+ `${up ? "Migrated" : "Rolled back"} ${pathToLog(file.path)}`
1286
+ );
1289
1287
  }
1290
1288
  if (up) {
1291
1289
  await ((_d = config.afterMigrate) == null ? void 0 : _d.call(config, db != null ? db : db = getDb(adapter)));
@@ -1300,14 +1298,9 @@ const migrateOrRollback = async (options, config, args, up) => {
1300
1298
  };
1301
1299
  const changeCache = {};
1302
1300
  const processMigration = async (db, up, file, config, options, appCodeUpdaterCache) => {
1303
- await db.transaction(async (tx) => {
1304
- const db2 = createMigrationInterface(
1305
- tx,
1306
- up,
1307
- config,
1308
- options,
1309
- appCodeUpdaterCache
1310
- );
1301
+ var _a;
1302
+ const asts = await db.transaction(async (tx) => {
1303
+ const db2 = createMigrationInterface(tx, up, config);
1311
1304
  clearChanges();
1312
1305
  let changes = changeCache[file.path];
1313
1306
  if (!changes) {
@@ -1329,7 +1322,17 @@ const processMigration = async (db, up, file, config, options, appCodeUpdaterCac
1329
1322
  file.version,
1330
1323
  config
1331
1324
  );
1325
+ return db2.migratedAsts;
1332
1326
  });
1327
+ for (const ast of asts) {
1328
+ await ((_a = config.appCodeUpdater) == null ? void 0 : _a.call(config, {
1329
+ ast,
1330
+ options,
1331
+ basePath: config.basePath,
1332
+ cache: appCodeUpdaterCache,
1333
+ logger: config.logger
1334
+ }));
1335
+ }
1333
1336
  };
1334
1337
  const saveMigratedVersion = async (db, version, config) => {
1335
1338
  await db.query(
@@ -1384,17 +1387,20 @@ const execute = async (options, sql) => {
1384
1387
  }
1385
1388
  };
1386
1389
  const createOrDrop = async (options, adminOptions, config, args) => {
1390
+ var _a, _b, _c, _d;
1387
1391
  const params = getDatabaseAndUserFromOptions(options);
1388
1392
  const result = await execute(
1389
1393
  setAdapterOptions(adminOptions, { database: "postgres" }),
1390
1394
  args.sql(params)
1391
1395
  );
1392
1396
  if (result === "ok") {
1393
- console.log(args.successMessage(params));
1397
+ (_a = config.logger) == null ? void 0 : _a.log(args.successMessage(params));
1394
1398
  } else if (result === "already") {
1395
- console.log(args.alreadyMessage(params));
1399
+ (_b = config.logger) == null ? void 0 : _b.log(args.alreadyMessage(params));
1396
1400
  } else if (result === "ssl required") {
1397
- console.log("SSL is required: append ?ssl=true to the database url string");
1401
+ (_c = config.logger) == null ? void 0 : _c.log(
1402
+ "SSL is required: append ?ssl=true to the database url string"
1403
+ );
1398
1404
  return;
1399
1405
  } else if (result === "forbidden") {
1400
1406
  let message = `Permission denied to ${args.create ? "create" : "drop"} database.`;
@@ -1404,7 +1410,7 @@ const createOrDrop = async (options, adminOptions, config, args) => {
1404
1410
  message += `
1405
1411
  Don't use this command for database service providers, only for a local db.`;
1406
1412
  }
1407
- console.log(message);
1413
+ (_d = config.logger) == null ? void 0 : _d.log(message);
1408
1414
  const updatedOptions = await setAdminCredentialsToOptions(
1409
1415
  options,
1410
1416
  args.create
@@ -1460,13 +1466,14 @@ const resetDb = async (arg, config) => {
1460
1466
  };
1461
1467
 
1462
1468
  const writeMigrationFile = async (config, name, content) => {
1469
+ var _a;
1463
1470
  await mkdir(config.migrationsPath, { recursive: true });
1464
1471
  const filePath = path.resolve(
1465
1472
  config.migrationsPath,
1466
1473
  `${makeFileTimeStamp()}_${name}.ts`
1467
1474
  );
1468
1475
  await writeFile(filePath, content);
1469
- console.log(`Created ${filePath}`);
1476
+ (_a = config.logger) == null ? void 0 : _a.log(`Created ${pathToLog(filePath)}`);
1470
1477
  };
1471
1478
  const generate = async (config, args) => {
1472
1479
  const name = args[0];
@@ -1604,6 +1611,8 @@ WHERE ${filterSchema("n.nspname")}`
1604
1611
  table_name "tableName",
1605
1612
  column_name "name",
1606
1613
  udt_name "type",
1614
+ udt_schema "typeSchema",
1615
+ data_type "dataType",
1607
1616
  character_maximum_length AS "maxChars",
1608
1617
  numeric_precision AS "numericPrecision",
1609
1618
  numeric_scale AS "numericScale",
@@ -1843,6 +1852,11 @@ var __spreadValues = (a, b) => {
1843
1852
  return a;
1844
1853
  };
1845
1854
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1855
+ class RakeDbEnumColumn extends EnumColumn {
1856
+ toCode(t) {
1857
+ return columnCode(this, t, `enum('${this.enumName}')`);
1858
+ }
1859
+ }
1846
1860
  const matchMap = {
1847
1861
  s: void 0,
1848
1862
  f: "FULL",
@@ -1973,11 +1987,10 @@ const getIsSerial = (item) => {
1973
1987
  }
1974
1988
  return false;
1975
1989
  };
1976
- const getColumnType = (item, isSerial) => {
1977
- if (isSerial) {
1978
- return item.type === "int2" ? "smallserial" : item.type === "int4" ? "serial" : "bigserial";
1979
- }
1980
- return item.type;
1990
+ const getColumnType = (type, isSerial) => {
1991
+ if (!isSerial)
1992
+ return type;
1993
+ return type === "int2" ? "smallserial" : type === "int4" ? "serial" : "bigserial";
1981
1994
  };
1982
1995
  const pushTableAst = (ast, data, table, pendingTables, innerFKeys = data.foreignKeys) => {
1983
1996
  const { schemaName, name } = table;
@@ -1996,11 +2009,26 @@ const pushTableAst = (ast, data, table, pendingTables, innerFKeys = data.foreign
1996
2009
  if (isSerial) {
1997
2010
  item = __spreadProps(__spreadValues({}, item), { default: void 0 });
1998
2011
  }
1999
- const klass = columnsByType[getColumnType(item, isSerial)];
2000
- if (!klass) {
2001
- throw new Error(`Column type \`${item.type}\` is not supported`);
2012
+ let column;
2013
+ const isArray = item.dataType === "ARRAY";
2014
+ const type = isArray ? item.type.slice(1) : item.type;
2015
+ const klass = columnsByType[getColumnType(type, isSerial)];
2016
+ if (klass) {
2017
+ column = instantiateColumn(klass, item);
2018
+ } else {
2019
+ const { type: type2, typeSchema } = item;
2020
+ const enumType = data.enums.find(
2021
+ (item2) => item2.name === type2 && item2.schemaName === typeSchema
2022
+ );
2023
+ if (!enumType) {
2024
+ throw new Error(
2025
+ `Cannot handle column ${item.schemaName}.${item.tableName}.${item.name}: column type \`${item.type}\` is not supported`
2026
+ );
2027
+ }
2028
+ column = new RakeDbEnumColumn({}, type2, enumType.values);
2002
2029
  }
2003
- let column = instantiateColumn(klass, item);
2030
+ if (isArray)
2031
+ column = new ArrayColumn({}, column);
2004
2032
  if ((primaryKey == null ? void 0 : primaryKey.columnNames.length) === 1 && (primaryKey == null ? void 0 : primaryKey.columnNames[0]) === item.name) {
2005
2033
  column = column.primaryKey();
2006
2034
  }
@@ -2240,7 +2268,7 @@ const pullDbStructure = async (options, config) => {
2240
2268
  };
2241
2269
 
2242
2270
  const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2)) => {
2243
- var _a;
2271
+ var _a, _b, _c;
2244
2272
  const config = processRakeDbConfig(partialConfig);
2245
2273
  const command = (_a = args[0]) == null ? void 0 : _a.split(":")[0];
2246
2274
  try {
@@ -2261,18 +2289,17 @@ const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2))
2261
2289
  } else if (config.commands[command]) {
2262
2290
  await config.commands[command](toArray(options), config, args.slice(1));
2263
2291
  } else {
2264
- printHelp();
2292
+ (_b = config.logger) == null ? void 0 : _b.log(help);
2265
2293
  }
2266
2294
  } catch (err) {
2267
2295
  if (err instanceof RakeDbError) {
2268
- console.error(err.message);
2296
+ (_c = config.logger) == null ? void 0 : _c.error(err.message);
2269
2297
  process.exit(1);
2270
2298
  }
2271
2299
  throw err;
2272
2300
  }
2273
2301
  };
2274
- const printHelp = () => console.log(
2275
- `Usage: rake-db [command] [arguments]
2302
+ const help = `Usage: rake-db [command] [arguments]
2276
2303
 
2277
2304
  Commands:
2278
2305
  create create databases
@@ -2306,8 +2333,7 @@ Generate arguments:
2306
2333
 
2307
2334
  - other arguments considered as columns with types and optional methods:
2308
2335
  rake-db g createTable id:serial.primaryKey name:text.nullable
2309
- `
2310
- );
2336
+ `;
2311
2337
 
2312
- export { MigrationBase, change, changeCache, createDb, createMigrationInterface, dropDb, generate, migrate, migrateOrRollback, rakeDb, resetDb, rollback, runCodeUpdater, writeMigrationFile };
2338
+ export { MigrationBase, change, changeCache, createDb, createMigrationInterface, dropDb, generate, migrate, migrateOrRollback, rakeDb, resetDb, rollback, writeMigrationFile };
2313
2339
  //# sourceMappingURL=index.mjs.map