rake-db 2.25.17 → 2.26.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,8 +1,10 @@
1
- import { DomainColumn, escapeForMigration, ArrayColumn, EnumColumn, defaultSchemaConfig, getColumnTypes, parseTableData, escapeString, tableDataMethods, ColumnType, parseTableDataInput, UnknownColumn, raw, TransactionAdapter, logParamToLogObject, createDb as createDb$1, Adapter, makeColumnTypes, makeColumnsByType, RawSQL, CustomTypeColumn, assignDbDataToColumn, PostgisGeographyPointColumn, pushTableDataCode, primaryKeyInnerToCode, indexInnerToCode, excludeInnerToCode, constraintInnerToCode, referencesArgsToCode, TimestampTZColumn, TimestampColumn } from 'pqb';
2
- import { singleQuote, toSnakeCase, isRawSQL, toCamelCase, toArray, snakeCaseKey, emptyObject, setCurrentColumnName, consumeColumnName, ColumnTypeBase, setDefaultLanguage, deepCompare, getImportPath, pathToLog, emptyArray, getStackTrace, codeToString, addCode, quoteObjectKey, backtickQuote } from 'orchid-core';
1
+ import { singleQuote, isRawSQL, toSnakeCase, toCamelCase, toArray, snakeCaseKey, emptyObject, setCurrentColumnName, consumeColumnName, ColumnTypeBase, setDefaultLanguage, deepCompare, getImportPath, pathToLog, emptyArray, getStackTrace, codeToString, addCode, quoteObjectKey, backtickQuote } from 'orchid-core';
2
+ import { escapeForMigration, ArrayColumn, DomainColumn, EnumColumn, defaultSchemaConfig, getColumnTypes, parseTableData, escapeString, tableDataMethods, ColumnType, parseTableDataInput, UnknownColumn, raw, TransactionAdapter, logParamToLogObject, createDb as createDb$1, Adapter, makeColumnTypes, makeColumnsByType, RawSQL, CustomTypeColumn, assignDbDataToColumn, PostgisGeographyPointColumn, pushTableDataCode, primaryKeyInnerToCode, indexInnerToCode, excludeInnerToCode, constraintInnerToCode, referencesArgsToCode, TimestampTZColumn, TimestampColumn } from 'pqb';
3
3
  import path, { join } from 'path';
4
4
  import { pathToFileURL, fileURLToPath } from 'node:url';
5
5
  import fs, { mkdir, writeFile, readdir, stat, readFile } from 'fs/promises';
6
+ import 'url';
7
+ import 'node:path';
6
8
 
7
9
  const getFirstWordAndRest = (input) => {
8
10
  const i = input.search(/(?=[A-Z])|[-_ ]/);
@@ -29,12 +31,6 @@ const getTextAfterTo = (input) => {
29
31
  const getTextAfterFrom = (input) => {
30
32
  return getTextAfterRegExp(input, /(From|-from|_from| from)[A-Z-_ ]/, 4);
31
33
  };
32
- const joinWords = (...words) => {
33
- return words.slice(1).reduce(
34
- (acc, word) => acc + word[0].toUpperCase() + word.slice(1),
35
- words[0]
36
- );
37
- };
38
34
  const joinColumns = (columns) => {
39
35
  return columns.map((column) => `"${column}"`).join(", ");
40
36
  };
@@ -79,19 +75,13 @@ const transaction = (adapter, fn) => {
79
75
  return adapter.transaction(begin, fn);
80
76
  };
81
77
  const queryLock = (trx) => trx.query(`SELECT pg_advisory_xact_lock('${RAKE_DB_LOCK_KEY}')`);
82
- const exhaustive = (_) => {
83
- throw new Error("Condition was not exhaustive");
84
- };
85
- const pluralize = (w, count, append = "s") => {
86
- return count === 1 ? w : w + append;
87
- };
88
78
 
89
79
  let currentChanges = [];
90
80
  const clearChanges = () => {
91
81
  currentChanges = [];
92
82
  };
93
83
  const getCurrentChanges = () => currentChanges;
94
- const pushChange = (fn) => currentChanges.push(fn);
84
+ const pushChange = (change) => currentChanges.push(change);
95
85
 
96
86
  const versionToString = (config, version) => config.migrationId === "timestamp" ? `${version}` : `${version}`.padStart(config.migrationId.serial, "0");
97
87
  const columnTypeToSql = (item) => {
@@ -3062,17 +3052,17 @@ function makeMigrateFn(defaultCount, up, fn) {
3062
3052
  return adapters;
3063
3053
  };
3064
3054
  }
3065
- const migrate = makeMigrateFn(
3055
+ const fullMigrate = makeMigrateFn(
3066
3056
  Infinity,
3067
3057
  true,
3068
3058
  (trx, config, set, versions, count, force) => migrateOrRollback(trx, config, set, versions, count, true, false, force)
3069
3059
  );
3070
- const rollback = makeMigrateFn(
3060
+ const fullRollback = makeMigrateFn(
3071
3061
  1,
3072
3062
  false,
3073
3063
  (trx, config, set, versions, count, force) => migrateOrRollback(trx, config, set, versions, count, false, false, force)
3074
3064
  );
3075
- const redo = makeMigrateFn(
3065
+ const fullRedo = makeMigrateFn(
3076
3066
  1,
3077
3067
  true,
3078
3068
  async (trx, config, set, versions, count, force) => {
@@ -3093,7 +3083,7 @@ const redo = makeMigrateFn(
3093
3083
  }
3094
3084
  );
3095
3085
  const getDb = (adapter) => createDb$1({ adapter });
3096
- const migrateOrRollback = async (trx, config, set, versions, count, up, redo2, force, skipLock) => {
3086
+ const migrateOrRollback = async (trx, config, set, versions, count, up, redo, force, skipLock) => {
3097
3087
  const { sequence, map: versionsMap } = versions;
3098
3088
  if (up) {
3099
3089
  const rollbackTo = checkMigrationOrder(config, set, versions, force);
@@ -3114,7 +3104,7 @@ const migrateOrRollback = async (trx, config, set, versions, count, up, redo2, f
3114
3104
  versions,
3115
3105
  sequence.length - i,
3116
3106
  false,
3117
- redo2
3107
+ redo
3118
3108
  );
3119
3109
  set.migrations.reverse();
3120
3110
  }
@@ -3126,7 +3116,7 @@ const migrateOrRollback = async (trx, config, set, versions, count, up, redo2, f
3126
3116
  db ?? (db = getDb(trx));
3127
3117
  const { migrations: migrations2 } = set;
3128
3118
  await beforeMigrate?.({ db, migrations: migrations2 });
3129
- await config.beforeChange?.({ db, migrations: migrations2, up, redo: redo2 });
3119
+ await config.beforeChange?.({ db, migrations: migrations2, up, redo });
3130
3120
  }
3131
3121
  let loggedAboutStarting = false;
3132
3122
  let migrations;
@@ -3135,14 +3125,16 @@ const migrateOrRollback = async (trx, config, set, versions, count, up, redo2, f
3135
3125
  continue;
3136
3126
  }
3137
3127
  if (count-- <= 0) break;
3138
- if (!loggedAboutStarting && (!redo2 || !up)) {
3128
+ if (!loggedAboutStarting && (!redo || !up)) {
3139
3129
  loggedAboutStarting = true;
3140
3130
  config.logger?.log(
3141
- `${redo2 ? "Reapplying migrations for" : up ? "Migrating" : "Rolling back"} database ${trx.config.connectionString ? new URL(trx.config.connectionString).pathname.slice(1) : trx.config.database}
3131
+ `${redo ? "Reapplying migrations for" : up ? "Migrating" : "Rolling back"} database ${trx.config.connectionString ? new URL(trx.config.connectionString).pathname.slice(1) : trx.config.database}
3142
3132
  `
3143
3133
  );
3144
3134
  }
3145
- await runMigration(trx, up, file, config);
3135
+ const changes = await getChanges(file, config);
3136
+ const adapter = await runMigration(trx, up, changes, config);
3137
+ await changeMigratedVersion(adapter, up, file, config);
3146
3138
  (migrations ?? (migrations = [])).push(file);
3147
3139
  if (up) {
3148
3140
  const name = path.basename(file.path);
@@ -3161,7 +3153,7 @@ const migrateOrRollback = async (trx, config, set, versions, count, up, redo2, f
3161
3153
  const afterMigrate = config[up ? "afterMigrate" : "afterRollback"];
3162
3154
  if (config.afterChange || afterMigrate) {
3163
3155
  db ?? (db = getDb(trx));
3164
- await config.afterChange?.({ db, up, redo: redo2, migrations });
3156
+ await config.afterChange?.({ db, up, redo, migrations });
3165
3157
  await afterMigrate?.({ db, migrations });
3166
3158
  }
3167
3159
  return migrations;
@@ -3204,31 +3196,37 @@ Run \`**db command** up force\` to rollback the above migrations and migrate all
3204
3196
  return;
3205
3197
  };
3206
3198
  const changeCache = {};
3207
- const runMigration = async (trx, up, file, config) => {
3199
+ const getChanges = async (file, config) => {
3208
3200
  clearChanges();
3209
- let changes = changeCache[file.path];
3201
+ let changes = file.path ? changeCache[file.path] : void 0;
3210
3202
  if (!changes) {
3211
3203
  const module = await file.load();
3212
3204
  const exported = module?.default && toArray(module.default);
3213
- if (config.forceDefaultExports && !exported) {
3205
+ if (config?.forceDefaultExports && !exported) {
3214
3206
  throw new RakeDbError(
3215
3207
  `Missing a default export in ${file.path} migration`
3216
3208
  );
3217
3209
  }
3218
3210
  changes = exported || getCurrentChanges();
3219
- changeCache[file.path] = changes;
3211
+ if (file.path) changeCache[file.path] = changes;
3220
3212
  }
3213
+ return changes;
3214
+ };
3215
+ const runMigration = async (trx, up, changes, config) => {
3221
3216
  const db = createMigrationInterface(trx, up, config);
3222
3217
  if (changes.length) {
3223
3218
  const from = up ? 0 : changes.length - 1;
3224
3219
  const to = up ? changes.length : -1;
3225
3220
  const step = up ? 1 : -1;
3226
3221
  for (let i = from; i !== to; i += step) {
3227
- await changes[i](db, up);
3222
+ await changes[i].fn(db, up);
3228
3223
  }
3229
3224
  }
3225
+ return db.adapter;
3226
+ };
3227
+ const changeMigratedVersion = async (adapter, up, file, config) => {
3230
3228
  await (up ? saveMigratedVersion : deleteMigratedVersion)(
3231
- db.adapter,
3229
+ adapter,
3232
3230
  file.version,
3233
3231
  path.basename(file.path).slice(file.version.length + 1),
3234
3232
  config
@@ -3638,7 +3636,7 @@ const dropDb = async (options, config) => {
3638
3636
  const resetDb = async (options, config) => {
3639
3637
  await dropDb(options, config);
3640
3638
  await createDb(options, config);
3641
- await migrate({}, options, config);
3639
+ await fullMigrate({}, options, config);
3642
3640
  };
3643
3641
 
3644
3642
  const filterSchema = (table) => `${table} !~ '^pg_' AND ${table} != 'information_schema'`;
@@ -4602,6 +4600,10 @@ const checkIfIsOuterRecursiveFkey = (data, table, references) => {
4602
4600
  return false;
4603
4601
  };
4604
4602
 
4603
+ const exhaustive = (_) => {
4604
+ throw new Error("Condition was not exhaustive");
4605
+ };
4606
+
4605
4607
  const astToGenerateItems = (config, asts, currentSchema) => {
4606
4608
  return asts.map((ast) => astToGenerateItem(config, ast, currentSchema));
4607
4609
  };
@@ -5642,7 +5644,7 @@ const rebase = async (options, config) => {
5642
5644
  return files2;
5643
5645
  }, []).sort((a, b) => +b.version - +a.version);
5644
5646
  set.migrations = migrationsDown;
5645
- await redo(
5647
+ await fullRedo(
5646
5648
  ctx,
5647
5649
  options,
5648
5650
  {
@@ -5682,25 +5684,26 @@ const rakeDb = (options, partialConfig, args = process.argv.slice(2)) => {
5682
5684
  }
5683
5685
  throw err;
5684
5686
  });
5685
- return Object.assign(change, {
5687
+ return Object.assign(makeChange(config), {
5686
5688
  promise
5687
5689
  });
5688
5690
  };
5689
5691
  rakeDb.lazy = (options, partialConfig) => {
5690
5692
  const config = processRakeDbConfig(partialConfig);
5691
5693
  return {
5692
- change,
5694
+ change: makeChange(config),
5693
5695
  run(args, conf) {
5694
5696
  return runCommand(options, conf ? { ...config, ...conf } : config, args);
5695
5697
  }
5696
5698
  };
5697
5699
  };
5698
- function change(fn) {
5699
- pushChange(fn);
5700
- return fn;
5701
- }
5700
+ const makeChange = (config) => (fn) => {
5701
+ const change = { fn, config };
5702
+ pushChange(change);
5703
+ return change;
5704
+ };
5702
5705
  const rakeDbAliases = {
5703
- migrate: "up",
5706
+ fullMigrate: "up",
5704
5707
  rollback: "down",
5705
5708
  s: "status",
5706
5709
  rec: "recurrent"
@@ -5776,7 +5779,7 @@ ${Object.entries(helpArguments).map(
5776
5779
  };
5777
5780
  };
5778
5781
  const upCommand = {
5779
- run: (options, config, args) => migrate({}, options, config, args).then(
5782
+ run: (options, config, args) => fullMigrate({}, options, config, args).then(
5780
5783
  () => runRecurrentMigrations(options, config)
5781
5784
  ),
5782
5785
  help: "migrate pending migrations",
@@ -5787,7 +5790,7 @@ const upCommand = {
5787
5790
  }
5788
5791
  };
5789
5792
  const downCommand = {
5790
- run: (options, config, args) => rollback({}, options, config, args),
5793
+ run: (options, config, args) => fullRollback({}, options, config, args),
5791
5794
  help: "rollback migrated migrations",
5792
5795
  helpArguments: {
5793
5796
  "no arguments": "rollback one last migration",
@@ -5827,7 +5830,7 @@ const rakeDbCommands = {
5827
5830
  down: downCommand,
5828
5831
  rollback: downCommand,
5829
5832
  redo: {
5830
- run: (options, config, args) => redo({}, options, config, args).then(
5833
+ run: (options, config, args) => fullRedo({}, options, config, args).then(
5831
5834
  () => runRecurrentMigrations(options, config)
5832
5835
  ),
5833
5836
  help: "rollback and migrate, run recurrent"
@@ -5859,5 +5862,18 @@ const rakeDbCommands = {
5859
5862
  }
5860
5863
  };
5861
5864
 
5862
- export { Migration, NoMigrationsTableError, RAKE_DB_LOCK_KEY, addColumnComment, addColumnExclude, addColumnIndex, addOrDropEnumValues, astToMigration, changeCache, changeEnumValues, clearChanges, cmpRawSql, colors, columnToSql, columnTypeToSql, commentsToQuery, concatSchemaAndName, constraintToSql, createDb, createMigrationInterface, dbColumnToAst, deleteMigratedVersion, dropDb, encodeColumnDefault, excludesToQuery, exhaustive, generateTimeStamp, getColumnName, getConstraintName, getCurrentChanges, getDatabaseAndUserFromOptions, getDbStructureTableData, getDbTableColumnsChecks, getExcludeName, getFirstWordAndRest, getForeignKeyTable, getIndexName, getMigratedVersionsMap, getSchemaAndTableFromName, getTextAfterFrom, getTextAfterTo, identityToSql, indexesToQuery, instantiateDbColumn, interpolateSqlValues, introspectDbSchema, joinColumns, joinWords, makeDbStructureColumnsShape, makeDomainsMap, makeFileVersion, makePopulateEnumQuery, makeStructureToAstCtx, migrate, migrateOrRollback, migrationConfigDefaults, nameColumnChecks, newMigration, pluralize, primaryKeyToSql, processRakeDbConfig, promptConfirm, promptSelect, promptText, pushChange, queryLock, quoteCustomType, quoteNameFromString, quoteSchemaTable, quoteTable, quoteWithSchema, rakeDb, rakeDbAliases, rakeDbCommands, redo, referencesToSql, renameType, resetDb, rollback, saveMigratedVersion, structureToAst, tableToAst, transaction, versionToString, writeMigrationFile };
5865
+ const migrateFiles = async (db, files) => {
5866
+ const qb = db.$qb;
5867
+ await qb.ensureTransaction(async () => {
5868
+ const adapter = qb.internal.transactionStorage.getStore()?.adapter;
5869
+ for (const load of files) {
5870
+ clearChanges();
5871
+ const changes = await getChanges({ load });
5872
+ const config = changes[0]?.config;
5873
+ await runMigration(adapter, true, changes, config);
5874
+ }
5875
+ });
5876
+ };
5877
+
5878
+ export { astToMigration, concatSchemaAndName, createMigrationInterface, dbColumnToAst, encodeColumnDefault, fullMigrate, getConstraintName, getDbStructureTableData, getDbTableColumnsChecks, getExcludeName, getIndexName, getSchemaAndTableFromName, instantiateDbColumn, introspectDbSchema, makeDomainsMap, makeFileVersion, makeStructureToAstCtx, migrateFiles, migrationConfigDefaults, promptSelect, rakeDb, rakeDbCommands, saveMigratedVersion, structureToAst, tableToAst, writeMigrationFile };
5863
5879
  //# sourceMappingURL=index.mjs.map