rake-db 2.4.2 → 2.4.4

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
@@ -1,4 +1,4 @@
1
- import { ColumnType, EnumColumn, ColumnTypes, ColumnsShape, DbResult, DefaultColumnTypes, TransactionAdapter, AdapterOptions, QueryLogObject, IndexColumnOptions, IndexOptions, ForeignKeyOptions, TextColumn, NoPrimaryKeyOption, TableData, SingleColumnIndexOptions, QueryLogOptions } from 'pqb';
1
+ import { ColumnType, EnumColumn, ColumnTypes, ColumnsShape, DbResult, DefaultColumnTypes, TransactionAdapter, QueryLogObject, IndexColumnOptions, IndexOptions, ForeignKeyOptions, TextColumn, NoPrimaryKeyOption, TableData, SingleColumnIndexOptions, AdapterOptions, QueryLogOptions } from 'pqb';
2
2
  import { EmptyObject, RawExpression, ColumnTypesBase, raw, MaybeArray } from 'orchid-core';
3
3
 
4
4
  declare function add(this: ColumnTypesBase, item: ColumnType, options?: {
@@ -52,14 +52,13 @@ declare type ColumnComment = {
52
52
  comment: string | null;
53
53
  };
54
54
  declare type Migration = DbResult<DefaultColumnTypes> & MigrationBase;
55
- declare const createMigrationInterface: (tx: TransactionAdapter, up: boolean, options: RakeDbConfig, adapterOptions: AdapterOptions, appCodeUpdaterCache: object) => Migration;
55
+ declare const createMigrationInterface: (tx: TransactionAdapter, up: boolean, options: RakeDbConfig) => Migration;
56
56
  declare class MigrationBase {
57
57
  adapter: TransactionAdapter;
58
58
  log?: QueryLogObject;
59
59
  up: boolean;
60
60
  options: RakeDbConfig;
61
- adapterOptions: AdapterOptions;
62
- appCodeUpdaterCache: object;
61
+ migratedAsts: RakeDbAst[];
63
62
  createTable(tableName: string, options: TableOptions, fn: ColumnsShapeCallback): Promise<void>;
64
63
  createTable(tableName: string, fn: ColumnsShapeCallback): Promise<void>;
65
64
  dropTable(tableName: string, options: TableOptions, fn: ColumnsShapeCallback): Promise<void>;
@@ -84,13 +83,12 @@ declare class MigrationBase {
84
83
  dropSchema(schemaName: string): Promise<void>;
85
84
  createExtension(name: string, options?: Omit<RakeDbAst.Extension, 'type' | 'action' | 'name'>): Promise<void>;
86
85
  dropExtension(name: string, options?: Omit<RakeDbAst.Extension, 'type' | 'action' | 'name' | 'values'>): Promise<void>;
87
- createEnum(name: string, values: string[], options?: Omit<RakeDbAst.Enum, 'type' | 'action' | 'name' | 'values'>): Promise<void>;
88
- dropEnum(name: string, values: string[], options?: Omit<RakeDbAst.Enum, 'type' | 'action' | 'name' | 'values'>): Promise<void>;
86
+ createEnum(name: string, values: [string, ...string[]], options?: Omit<RakeDbAst.Enum, 'type' | 'action' | 'name' | 'values'>): Promise<void>;
87
+ dropEnum(name: string, values: [string, ...string[]], options?: Omit<RakeDbAst.Enum, 'type' | 'action' | 'name' | 'values'>): Promise<void>;
89
88
  tableExists(tableName: string): Promise<boolean>;
90
89
  columnExists(tableName: string, columnName: string): Promise<boolean>;
91
90
  constraintExists(constraintName: string): Promise<boolean>;
92
91
  }
93
- declare const runCodeUpdater: (migration: MigrationBase, ast: RakeDbAst) => Promise<void> | undefined;
94
92
 
95
93
  declare type RakeDbAst = RakeDbAst.Table | RakeDbAst.ChangeTable | RakeDbAst.RenameTable | RakeDbAst.Schema | RakeDbAst.Extension | RakeDbAst.Enum | RakeDbAst.ForeignKey;
96
94
  declare namespace RakeDbAst {
@@ -174,7 +172,7 @@ declare namespace RakeDbAst {
174
172
  action: 'create' | 'drop';
175
173
  schema?: string;
176
174
  name: string;
177
- values: string[];
175
+ values: [string, ...string[]];
178
176
  cascade?: boolean;
179
177
  dropIfExists?: boolean;
180
178
  };
@@ -211,6 +209,7 @@ declare type AppCodeUpdater = (params: {
211
209
  options: AdapterOptions;
212
210
  basePath: string;
213
211
  cache: object;
212
+ logger: QueryLogOptions['logger'];
214
213
  }) => Promise<void>;
215
214
 
216
215
  declare const createDb: (arg: MaybeArray<AdapterOptions>, config: RakeDbConfig) => Promise<void>;
@@ -230,4 +229,4 @@ declare const rollback: (options: MaybeArray<AdapterOptions>, config: RakeDbConf
230
229
 
231
230
  declare const rakeDb: (options: MaybeArray<AdapterOptions>, partialConfig?: Partial<RakeDbConfig>, args?: string[]) => Promise<void>;
232
231
 
233
- export { AppCodeUpdater, ChangeTableCallback, ChangeTableOptions, ColumnComment, ColumnsShapeCallback, DropMode, Migration, MigrationBase, MigrationColumnTypes, RakeDbAst, RakeDbConfig, TableOptions, change, changeCache, createDb, createMigrationInterface, dropDb, generate, migrate, migrateOrRollback, rakeDb, resetDb, rollback, runCodeUpdater, writeMigrationFile };
232
+ export { AppCodeUpdater, ChangeTableCallback, ChangeTableOptions, ColumnComment, ColumnsShapeCallback, DropMode, Migration, MigrationBase, MigrationColumnTypes, RakeDbAst, RakeDbConfig, TableOptions, change, changeCache, createDb, createMigrationInterface, dropDb, generate, migrate, migrateOrRollback, rakeDb, resetDb, rollback, writeMigrationFile };
package/dist/index.js CHANGED
@@ -65,10 +65,15 @@ const migrationConfigDefaults = {
65
65
  const processRakeDbConfig = (config) => {
66
66
  var _a;
67
67
  const result = __spreadValues$6(__spreadValues$6({}, migrationConfigDefaults), config);
68
+ if (!result.log) {
69
+ delete result.logger;
70
+ }
68
71
  if (!result.basePath) {
69
72
  let stack;
73
+ const original = Error.prepareStackTrace;
70
74
  Error.prepareStackTrace = (_, s) => stack = s;
71
75
  new Error().stack;
76
+ Error.prepareStackTrace = original;
72
77
  if (stack) {
73
78
  const thisFile = (_a = stack[0]) == null ? void 0 : _a.getFileName();
74
79
  const thisDir = thisFile && path__default["default"].dirname(thisFile);
@@ -165,16 +170,17 @@ const setAdminCredentialsToOptions = async (options, create) => {
165
170
  }));
166
171
  };
167
172
  const createSchemaMigrations = async (db, config) => {
173
+ var _a, _b;
168
174
  try {
169
175
  await db.query(
170
176
  `CREATE TABLE ${quoteWithSchema({
171
177
  name: config.migrationsTable
172
178
  })} ( version TEXT NOT NULL )`
173
179
  );
174
- console.log("Created versions table");
180
+ (_a = config.logger) == null ? void 0 : _a.log("Created versions table");
175
181
  } catch (err) {
176
182
  if (err.code === "42P07") {
177
- console.log("Versions table exists");
183
+ (_b = config.logger) == null ? void 0 : _b.log("Versions table exists");
178
184
  } else {
179
185
  throw err;
180
186
  }
@@ -528,7 +534,7 @@ const createTable$1 = async (migration, up, tableName, options, fn) => {
528
534
  const result = await migration.adapter.arrays(query);
529
535
  then == null ? void 0 : then(result);
530
536
  }
531
- await runCodeUpdater(migration, ast);
537
+ migration.migratedAsts.push(ast);
532
538
  };
533
539
  const makeAst$1 = (up, tableName, shape, tableData, options, noPrimaryKey) => {
534
540
  const shapePKeys = [];
@@ -786,7 +792,7 @@ const changeTable = async (migration, up, tableName, options, fn) => {
786
792
  const result = await migration.adapter.arrays(query);
787
793
  (_a = query.then) == null ? void 0 : _a.call(query, result);
788
794
  }
789
- await runCodeUpdater(migration, ast);
795
+ migration.migratedAsts.push(ast);
790
796
  };
791
797
  const makeAst = (up, name, changeData, changeTableData2, options) => {
792
798
  const { comment } = options;
@@ -1024,7 +1030,7 @@ var __spreadValues$2 = (a, b) => {
1024
1030
  return a;
1025
1031
  };
1026
1032
  var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
1027
- const createMigrationInterface = (tx, up, options, adapterOptions, appCodeUpdaterCache) => {
1033
+ const createMigrationInterface = (tx, up, options) => {
1028
1034
  const adapter = new pqb.TransactionAdapter(tx, tx.client, tx.types);
1029
1035
  const { query, arrays } = adapter;
1030
1036
  const log = pqb.logParamToLogObject(options.logger || console, options.log);
@@ -1039,13 +1045,12 @@ const createMigrationInterface = (tx, up, options, adapterOptions, appCodeUpdate
1039
1045
  for (const key of Object.getOwnPropertyNames(proto)) {
1040
1046
  db[key] = proto[key];
1041
1047
  }
1048
+ db.migratedAsts = [];
1042
1049
  return Object.assign(db, {
1043
1050
  adapter,
1044
1051
  log,
1045
1052
  up,
1046
- options,
1047
- adapterOptions,
1048
- appCodeUpdaterCache
1053
+ options
1049
1054
  });
1050
1055
  };
1051
1056
  class MigrationBase {
@@ -1082,7 +1087,7 @@ class MigrationBase {
1082
1087
  name: ast.to
1083
1088
  })}`
1084
1089
  );
1085
- await runCodeUpdater(this, ast);
1090
+ this.migratedAsts.push(ast);
1086
1091
  }
1087
1092
  addColumn(tableName, columnName, fn) {
1088
1093
  return addColumn(this, this.up, tableName, columnName, fn);
@@ -1205,7 +1210,7 @@ const createSchema$1 = async (migration, up, name) => {
1205
1210
  await migration.adapter.query(
1206
1211
  `${ast.action === "create" ? "CREATE" : "DROP"} SCHEMA "${name}"`
1207
1212
  );
1208
- await runCodeUpdater(migration, ast);
1213
+ migration.migratedAsts.push(ast);
1209
1214
  };
1210
1215
  const createExtension$1 = async (migration, up, name, options) => {
1211
1216
  const ast = __spreadValues$2({
@@ -1220,7 +1225,7 @@ const createExtension$1 = async (migration, up, name, options) => {
1220
1225
  query = `CREATE EXTENSION${ast.createIfNotExists ? " IF NOT EXISTS" : ""} "${ast.name}"${ast.schema ? ` SCHEMA "${ast.schema}"` : ""}${ast.version ? ` VERSION '${ast.version}'` : ""}${ast.cascade ? " CASCADE" : ""}`;
1221
1226
  }
1222
1227
  await migration.adapter.query(query);
1223
- await runCodeUpdater(migration, ast);
1228
+ migration.migratedAsts.push(ast);
1224
1229
  };
1225
1230
  const createEnum$1 = async (migration, up, name, values, options = {}) => {
1226
1231
  const [schema, enumName] = getSchemaAndTableFromName(name);
@@ -1239,20 +1244,11 @@ const createEnum$1 = async (migration, up, name, values, options = {}) => {
1239
1244
  query = `DROP TYPE${ast.dropIfExists ? " IF EXISTS" : ""} ${quotedName}${ast.cascade ? " CASCADE" : ""}`;
1240
1245
  }
1241
1246
  await migration.adapter.query(query);
1242
- await runCodeUpdater(migration, ast);
1247
+ migration.migratedAsts.push(ast);
1243
1248
  };
1244
1249
  const queryExists = (db, sql) => {
1245
1250
  return db.adapter.query(sql).then(({ rowCount }) => rowCount > 0);
1246
1251
  };
1247
- const runCodeUpdater = (migration, ast) => {
1248
- var _a, _b;
1249
- return (_b = (_a = migration.options).appCodeUpdater) == null ? void 0 : _b.call(_a, {
1250
- ast,
1251
- options: migration.adapterOptions,
1252
- basePath: migration.options.basePath,
1253
- cache: migration.appCodeUpdaterCache
1254
- });
1255
- };
1256
1252
 
1257
1253
  var __defProp$1 = Object.defineProperty;
1258
1254
  var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
@@ -1313,7 +1309,9 @@ const migrateOrRollback = async (options, config, args, up) => {
1313
1309
  opts,
1314
1310
  appCodeUpdaterCache
1315
1311
  );
1316
- (_c = config.logger) == null ? void 0 : _c.log(`${file.path} ${up ? "migrated" : "rolled back"}`);
1312
+ (_c = config.logger) == null ? void 0 : _c.log(
1313
+ `${up ? "Migrated" : "Rolled back"} ${orchidCore.pathToLog(file.path)}`
1314
+ );
1317
1315
  }
1318
1316
  if (up) {
1319
1317
  await ((_d = config.afterMigrate) == null ? void 0 : _d.call(config, db != null ? db : db = getDb(adapter)));
@@ -1328,14 +1326,9 @@ const migrateOrRollback = async (options, config, args, up) => {
1328
1326
  };
1329
1327
  const changeCache = {};
1330
1328
  const processMigration = async (db, up, file, config, options, appCodeUpdaterCache) => {
1331
- await db.transaction(async (tx) => {
1332
- const db2 = createMigrationInterface(
1333
- tx,
1334
- up,
1335
- config,
1336
- options,
1337
- appCodeUpdaterCache
1338
- );
1329
+ var _a;
1330
+ const asts = await db.transaction(async (tx) => {
1331
+ const db2 = createMigrationInterface(tx, up, config);
1339
1332
  clearChanges();
1340
1333
  let changes = changeCache[file.path];
1341
1334
  if (!changes) {
@@ -1357,7 +1350,17 @@ const processMigration = async (db, up, file, config, options, appCodeUpdaterCac
1357
1350
  file.version,
1358
1351
  config
1359
1352
  );
1353
+ return db2.migratedAsts;
1360
1354
  });
1355
+ for (const ast of asts) {
1356
+ await ((_a = config.appCodeUpdater) == null ? void 0 : _a.call(config, {
1357
+ ast,
1358
+ options,
1359
+ basePath: config.basePath,
1360
+ cache: appCodeUpdaterCache,
1361
+ logger: config.logger
1362
+ }));
1363
+ }
1361
1364
  };
1362
1365
  const saveMigratedVersion = async (db, version, config) => {
1363
1366
  await db.query(
@@ -1412,17 +1415,20 @@ const execute = async (options, sql) => {
1412
1415
  }
1413
1416
  };
1414
1417
  const createOrDrop = async (options, adminOptions, config, args) => {
1418
+ var _a, _b, _c, _d;
1415
1419
  const params = getDatabaseAndUserFromOptions(options);
1416
1420
  const result = await execute(
1417
1421
  setAdapterOptions(adminOptions, { database: "postgres" }),
1418
1422
  args.sql(params)
1419
1423
  );
1420
1424
  if (result === "ok") {
1421
- console.log(args.successMessage(params));
1425
+ (_a = config.logger) == null ? void 0 : _a.log(args.successMessage(params));
1422
1426
  } else if (result === "already") {
1423
- console.log(args.alreadyMessage(params));
1427
+ (_b = config.logger) == null ? void 0 : _b.log(args.alreadyMessage(params));
1424
1428
  } else if (result === "ssl required") {
1425
- console.log("SSL is required: append ?ssl=true to the database url string");
1429
+ (_c = config.logger) == null ? void 0 : _c.log(
1430
+ "SSL is required: append ?ssl=true to the database url string"
1431
+ );
1426
1432
  return;
1427
1433
  } else if (result === "forbidden") {
1428
1434
  let message = `Permission denied to ${args.create ? "create" : "drop"} database.`;
@@ -1432,7 +1438,7 @@ const createOrDrop = async (options, adminOptions, config, args) => {
1432
1438
  message += `
1433
1439
  Don't use this command for database service providers, only for a local db.`;
1434
1440
  }
1435
- console.log(message);
1441
+ (_d = config.logger) == null ? void 0 : _d.log(message);
1436
1442
  const updatedOptions = await setAdminCredentialsToOptions(
1437
1443
  options,
1438
1444
  args.create
@@ -1488,13 +1494,14 @@ const resetDb = async (arg, config) => {
1488
1494
  };
1489
1495
 
1490
1496
  const writeMigrationFile = async (config, name, content) => {
1497
+ var _a;
1491
1498
  await promises.mkdir(config.migrationsPath, { recursive: true });
1492
1499
  const filePath = path__default["default"].resolve(
1493
1500
  config.migrationsPath,
1494
1501
  `${makeFileTimeStamp()}_${name}.ts`
1495
1502
  );
1496
1503
  await promises.writeFile(filePath, content);
1497
- console.log(`Created ${filePath}`);
1504
+ (_a = config.logger) == null ? void 0 : _a.log(`Created ${orchidCore.pathToLog(filePath)}`);
1498
1505
  };
1499
1506
  const generate = async (config, args) => {
1500
1507
  const name = args[0];
@@ -1632,6 +1639,8 @@ WHERE ${filterSchema("n.nspname")}`
1632
1639
  table_name "tableName",
1633
1640
  column_name "name",
1634
1641
  udt_name "type",
1642
+ udt_schema "typeSchema",
1643
+ data_type "dataType",
1635
1644
  character_maximum_length AS "maxChars",
1636
1645
  numeric_precision AS "numericPrecision",
1637
1646
  numeric_scale AS "numericScale",
@@ -1871,6 +1880,11 @@ var __spreadValues = (a, b) => {
1871
1880
  return a;
1872
1881
  };
1873
1882
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1883
+ class RakeDbEnumColumn extends pqb.EnumColumn {
1884
+ toCode(t) {
1885
+ return pqb.columnCode(this, t, `enum('${this.enumName}')`);
1886
+ }
1887
+ }
1874
1888
  const matchMap = {
1875
1889
  s: void 0,
1876
1890
  f: "FULL",
@@ -2001,11 +2015,10 @@ const getIsSerial = (item) => {
2001
2015
  }
2002
2016
  return false;
2003
2017
  };
2004
- const getColumnType = (item, isSerial) => {
2005
- if (isSerial) {
2006
- return item.type === "int2" ? "smallserial" : item.type === "int4" ? "serial" : "bigserial";
2007
- }
2008
- return item.type;
2018
+ const getColumnType = (type, isSerial) => {
2019
+ if (!isSerial)
2020
+ return type;
2021
+ return type === "int2" ? "smallserial" : type === "int4" ? "serial" : "bigserial";
2009
2022
  };
2010
2023
  const pushTableAst = (ast, data, table, pendingTables, innerFKeys = data.foreignKeys) => {
2011
2024
  const { schemaName, name } = table;
@@ -2024,11 +2037,26 @@ const pushTableAst = (ast, data, table, pendingTables, innerFKeys = data.foreign
2024
2037
  if (isSerial) {
2025
2038
  item = __spreadProps(__spreadValues({}, item), { default: void 0 });
2026
2039
  }
2027
- const klass = pqb.columnsByType[getColumnType(item, isSerial)];
2028
- if (!klass) {
2029
- throw new Error(`Column type \`${item.type}\` is not supported`);
2040
+ let column;
2041
+ const isArray = item.dataType === "ARRAY";
2042
+ const type = isArray ? item.type.slice(1) : item.type;
2043
+ const klass = pqb.columnsByType[getColumnType(type, isSerial)];
2044
+ if (klass) {
2045
+ column = pqb.instantiateColumn(klass, item);
2046
+ } else {
2047
+ const { type: type2, typeSchema } = item;
2048
+ const enumType = data.enums.find(
2049
+ (item2) => item2.name === type2 && item2.schemaName === typeSchema
2050
+ );
2051
+ if (!enumType) {
2052
+ throw new Error(
2053
+ `Cannot handle column ${item.schemaName}.${item.tableName}.${item.name}: column type \`${item.type}\` is not supported`
2054
+ );
2055
+ }
2056
+ column = new RakeDbEnumColumn({}, type2, enumType.values);
2030
2057
  }
2031
- let column = pqb.instantiateColumn(klass, item);
2058
+ if (isArray)
2059
+ column = new pqb.ArrayColumn({}, column);
2032
2060
  if ((primaryKey == null ? void 0 : primaryKey.columnNames.length) === 1 && (primaryKey == null ? void 0 : primaryKey.columnNames[0]) === item.name) {
2033
2061
  column = column.primaryKey();
2034
2062
  }
@@ -2268,7 +2296,7 @@ const pullDbStructure = async (options, config) => {
2268
2296
  };
2269
2297
 
2270
2298
  const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2)) => {
2271
- var _a;
2299
+ var _a, _b, _c;
2272
2300
  const config = processRakeDbConfig(partialConfig);
2273
2301
  const command = (_a = args[0]) == null ? void 0 : _a.split(":")[0];
2274
2302
  try {
@@ -2289,18 +2317,17 @@ const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2))
2289
2317
  } else if (config.commands[command]) {
2290
2318
  await config.commands[command](orchidCore.toArray(options), config, args.slice(1));
2291
2319
  } else {
2292
- printHelp();
2320
+ (_b = config.logger) == null ? void 0 : _b.log(help);
2293
2321
  }
2294
2322
  } catch (err) {
2295
2323
  if (err instanceof RakeDbError) {
2296
- console.error(err.message);
2324
+ (_c = config.logger) == null ? void 0 : _c.error(err.message);
2297
2325
  process.exit(1);
2298
2326
  }
2299
2327
  throw err;
2300
2328
  }
2301
2329
  };
2302
- const printHelp = () => console.log(
2303
- `Usage: rake-db [command] [arguments]
2330
+ const help = `Usage: rake-db [command] [arguments]
2304
2331
 
2305
2332
  Commands:
2306
2333
  create create databases
@@ -2334,8 +2361,7 @@ Generate arguments:
2334
2361
 
2335
2362
  - other arguments considered as columns with types and optional methods:
2336
2363
  rake-db g createTable id:serial.primaryKey name:text.nullable
2337
- `
2338
- );
2364
+ `;
2339
2365
 
2340
2366
  exports.MigrationBase = MigrationBase;
2341
2367
  exports.change = change;
@@ -2349,6 +2375,5 @@ exports.migrateOrRollback = migrateOrRollback;
2349
2375
  exports.rakeDb = rakeDb;
2350
2376
  exports.resetDb = resetDb;
2351
2377
  exports.rollback = rollback;
2352
- exports.runCodeUpdater = runCodeUpdater;
2353
2378
  exports.writeMigrationFile = writeMigrationFile;
2354
2379
  //# sourceMappingURL=index.js.map