masterrecord 1.5.17 → 1.22.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.
@@ -43,6 +43,21 @@ class EntityTrackerModel {
43
43
  }
44
44
  }
45
45
 
46
+ // Snapshot ORIGINAL values as loaded from the database (EF's
47
+ // EntityEntry.OriginalValues). Used for optimistic concurrency — the
48
+ // original value of a concurrency token goes into the UPDATE/DELETE
49
+ // WHERE clause — and for conflict resolution / entry() introspection.
50
+ // Non-enumerable so it never leaks into spreads/JSON.
51
+ const originals = {};
52
+ for (const [modelField, modelFieldValue] of modelFields) {
53
+ if (!$that._isRelationship(currentEntity[modelField])) {
54
+ originals[modelField] = modelFieldValue;
55
+ }
56
+ }
57
+ Object.defineProperty(modelClass, '__originalValues', {
58
+ value: originals, enumerable: false, writable: true, configurable: true,
59
+ });
60
+
46
61
  // Add Active Record-style .save() method
47
62
  modelClass.save = async function() {
48
63
  if (!this.__context) {
@@ -169,20 +184,20 @@ class EntityTrackerModel {
169
184
  throw new Error('Cannot reload: entity is not attached to a context');
170
185
  }
171
186
 
172
- // Get primary key
173
- const primaryKey = tools.getPrimaryKeyObject(this.__entity);
174
- const primaryKeyValue = this[primaryKey];
187
+ // Get primary key (all columns of a composite key — EF HasKey(a, b))
188
+ const keys = tools.primaryKeys(this.__entity);
189
+ const keyValues = keys.map(k => this[k]);
175
190
 
176
- if (!primaryKeyValue) {
191
+ if (!keys.length || keyValues.some(v => v === undefined || v === null || v === '')) {
177
192
  throw new Error('Cannot reload: entity has no primary key value');
178
193
  }
179
194
 
180
195
  // Fetch fresh from database
181
196
  const EntityClass = this.__context[this.__name];
182
- const fresh = await EntityClass.findById(primaryKeyValue);
197
+ const fresh = await EntityClass.findById(...keyValues);
183
198
  if (!fresh) {
184
199
  throw new Error(
185
- `Cannot reload: ${this.__name} with ${primaryKey}=${primaryKeyValue} not found`
200
+ `Cannot reload: ${this.__name} with ${keys.map((k, i) => `${k}=${keyValues[i]}`).join(', ')} not found`
186
201
  );
187
202
  }
188
203
 
@@ -204,6 +219,17 @@ class EntityTrackerModel {
204
219
  // Reset dirty fields and state
205
220
  this.__dirtyFields = [];
206
221
  this.__state = 'track';
222
+ // Reload resets ORIGINAL values to the database state (EF's
223
+ // Reload()), so a later concurrency check compares against what
224
+ // is now in the row — this is what makes "reload and retry" work.
225
+ if (typeof this.__context._refreshOriginalValues === 'function') {
226
+ this.__context._refreshOriginalValues(this);
227
+ }
228
+ // findById tracked a second instance of this row; drop it so the
229
+ // identity map holds only this entity (EF never tracks two copies).
230
+ if (typeof this.__context.__untrack === 'function') {
231
+ this.__context.__untrack([fresh]);
232
+ }
207
233
 
208
234
  return this;
209
235
  };
@@ -407,7 +433,15 @@ class EntityTrackerModel {
407
433
  }
408
434
  this["__proto__"]["_" + modelField] = storedValue;
409
435
  if (navNameForFk) {
410
- this["__proto__"]["_" + navNameForFk] = storedValue;
436
+ // FK -> navigation fix-up (EF): changing the FK column invalidates
437
+ // a previously loaded/assigned navigation so the next read
438
+ // re-resolves it (lazy) instead of returning a stale parent.
439
+ // The engines persist the FK via tools.foreignKeyValue(), which
440
+ // falls back to this column when the navigation slot is unset.
441
+ const proto = this["__proto__"];
442
+ const nav = proto["_" + navNameForFk];
443
+ if (nav !== undefined && nav !== storedValue) delete proto["_" + navNameForFk];
444
+ delete proto["__loading_" + navNameForFk];
411
445
  }
412
446
  },
413
447
  get: function() {
@@ -486,6 +520,12 @@ class EntityTrackerModel {
486
520
  // the user set and that the INSERT persisted — not a raw DB row.
487
521
  this._defineTrackedColumn(target, modelField, captured[modelField], currentEntity, fkToNavName, false);
488
522
  }
523
+ // Original values for a just-inserted (or attached) entity are its
524
+ // current values — exactly what was written. (EF: originals equal
525
+ // current for attached entities.)
526
+ Object.defineProperty(target, '__originalValues', {
527
+ value: { ...captured }, enumerable: false, writable: true, configurable: true,
528
+ });
489
529
  return target;
490
530
  }
491
531
 
@@ -530,7 +570,7 @@ class EntityTrackerModel {
530
570
 
531
571
  Object.defineProperty(modelClass, entityField, {
532
572
  set: function(value) {
533
- if(typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" ){
573
+ if(typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value === null){
534
574
  modelClass.__state = "modified";
535
575
  modelClass.__version = (modelClass.__version || 0) + 1;
536
576
  modelClass.__dirtyFields.push(entityField);
@@ -540,125 +580,53 @@ class EntityTrackerModel {
540
580
  modelClass.__context.__track(modelClass);
541
581
  }
542
582
  }
543
- this["__proto__"]["_" + entityField] = value;
544
- },
545
- get : function(){
546
- let ent = tools.findEntity(entityField, this.__context);
547
- if(!ent){
548
- const parentEntity = tools.findEntity(this.__name, this.__context);
549
- if(parentEntity){
550
- ent = tools.findEntity(parentEntity.__entity[entityField].foreignTable, this.__context);
551
- if(!ent){
552
- return `Error - Entity ${parentEntity.__entity[entityField].foreignTable} not found. Please check your context for proper name.`
553
- }
554
- }
555
- else{
556
- return `Error - Entity ${parentEntity} not found. Please check your context for proper name.`
557
- }
558
- }
559
-
560
-
561
- if(currentEntity[entityField].relationshipType === "belongsTo"){
562
- if(currentEntity[entityField].lazyLoading){
563
- // TODO: UPDATE THIS CODE TO USE SOMETHING ELSE - THIS WILL NOT WORK WHEN USING DIFFERENT DATABASES BECAUSE THIS IS USING SQLITE CODE.
564
-
565
- const name = currentEntity[entityField].foreignKey;
566
- var priKey = tools.getPrimaryKeyObject(ent.__entity);
567
-
568
- //var idValue = currentEntity[entityField].foreignKey;
569
- const currentValue = this.__proto__[`_${name}`];
570
- const val = this["__proto__"]["_"+entityField];
571
- var modelValue = null;
572
- if(!val){
573
- modelValue = ent.where(`r => r.${priKey} == ${ currentValue }`).single();
574
-
575
- }
576
- else{
577
- modelValue = val;
578
- }
579
-
580
- this[entityField] = modelValue;
581
- }
582
- else{
583
- return this["__proto__"]["_" + entityField];
584
- }
585
- }
586
- else{
587
- // user.tags = gets all tags related to user
588
- // tag.users = get all users related to tags
589
- if(currentEntity[entityField].lazyLoading){
590
- var priKey = tools.getPrimaryKeyObject(this.__entity);
591
- var entityName = currentEntity[entityField].foreignTable === undefined ? entityField : currentEntity[entityField].foreignTable;
592
- let tableName = "";
593
- if(entityName){
594
- switch(currentEntity[entityField].type){
595
- // TODO: move the SQL generation part to the SQL builder so that we can later on use many diffrent types of SQL databases.
596
- case "hasManyThrough" :
597
- try{
598
- const joiningEntity = this.__context[tools.capitalize(entityName)];
599
- const entityFieldJoinName = currentEntity[entityField].foreignTable === undefined? entityField : currentEntity[entityField].foreignTable;
600
- const _thirdEntity = this.__context[tools.capitalize(entityFieldJoinName)];
601
- const firstJoiningID = joiningEntity.__entity[this.__entity.__name].foreignTable;
602
- const secondJoiningID = Object.values(joiningEntity.__entity).find(e => e.foreignTable === ent.__name);
603
- if(firstJoiningID && secondJoiningID )
604
- {
605
- var modelValue = ent.include(`p => p.${entityFieldJoinName}.select(j => j.${joiningEntity.__entity[this.__entity.__name].foreignKey})`).include(`p =>p.${this.__entity.__name}`).where(`r =>r.${this.__entity.__name}.${priKey} = ${this[priKey]}`).toList();
606
- // var modelQuery = `select ${selectParameter} from ${this.__entity.__name} INNER JOIN ${entityName} ON ${this.__entity.__name}.${priKey} = ${entityName}.${firstJoiningID} INNER JOIN ${entityField} ON ${entityField}.${joinTablePriKey} = ${entityName}.${secondJoiningID} WHERE ${this.__entity.__name}.${priKey} = ${ this[priKey]}`;
607
- // var modelValue = ent.raw(modelQuery).toList();
608
- this[entityField] = modelValue;
609
- }
610
- else{
611
- return "Joining table must declaire joining table names"
612
- }
613
- }
614
- catch(error){
615
- return error;
616
- }
617
- /*
618
- select * from User
619
- INNER JOIN Tagging ON User.id = Tagging.user_id
620
- INNER JOIN Tag ON Tag.id = Tagging.tag_id
621
- WHERE Tagging.user_id = 13
622
- */
623
- break;
624
- case "hasOne" :
625
- var entityName = tools.findForeignTable(this.__entity.__name, ent.__entity);
626
- if(entityName){
627
- tableName = entityName.foreignKey;
628
- }
629
- else{
630
- return `Error - Entity ${ent.__entity.__name} has no property named ${this.__entity.__name}`;
631
- }
632
-
633
- //var jj = ent.raw(`select * from ${entityName} where ${tableName} = ${ this[priKey] }`).single();
634
- var modelValue = ent.where(`r => r.${tableName} == ${this[priKey]}`).single();
635
- this[entityField] = modelValue;
636
- break;
637
- case "hasMany" :
638
- var entityName = tools.findForeignTable(this.__entity.__name, ent.__entity);
639
- if(entityName){
640
- tableName = entityName.foreignKey;
641
- }
642
- else{
643
- return `Error - Entity ${ent.__entity.__name} has no property named ${this.__entity.__name}`;
644
- }
645
- //var modelValue = ent.raw(`select * from ${entityName} where ${tableName} = ${ this[priKey] }`).toList();
646
- var modelValue = ent.where(`r => r.${tableName} == ${this[priKey]}`).toList();
647
- this[entityField] = modelValue;
648
- break;
649
- }
650
- }
651
- else{
652
- return "Entity name must be defined"
653
- }
654
- }
655
- else{
656
- return this["__proto__"]["_" + entityField];
583
+ // Relationship fix-up (EF): assigning a parent ENTITY to a
584
+ // belongsTo navigation also sets the foreign-key column, so
585
+ // `post.author = someAuthor` persists author_id on save.
586
+ const def = currentEntity[entityField];
587
+ const proto = Object.getPrototypeOf(modelClass); // accessor owner's slot, never `this`
588
+ if (value && typeof value === 'object' && value.__entity && def && def.relationshipType === 'belongsTo' && def.foreignKey) {
589
+ const parentPk = tools.getPrimaryKeyObject(value.__entity);
590
+ const fkVal = parentPk ? value[parentPk] : undefined;
591
+ if (fkVal !== undefined && fkVal !== null && typeof fkVal !== 'function' && tools.dataValue(modelClass, def.foreignKey) !== fkVal) {
592
+ // Tracked entity: the FK column's accessor marks the entity dirty
593
+ // (and invalidates the old navigation); plain object: data property.
594
+ modelClass[def.foreignKey] = fkVal;
657
595
  }
596
+ } else if ((value === null || typeof value !== 'object') && def && def.relationshipType === 'belongsTo' && def.foreignKey && ('_' + def.foreignKey) in proto) {
597
+ proto['_' + def.foreignKey] = value; // legacy idiom `post.author = authorId`
658
598
  }
659
-
660
-
661
- return this["__proto__"]["_" + entityField];
599
+ delete proto['__loading_' + entityField];
600
+ proto["_" + entityField] = value;
601
+ },
602
+ get : function(){
603
+ // Navigation getter (EF semantics, adapted to async JS drivers):
604
+ // - already loaded (via include() or a previous load) -> the value, synchronously;
605
+ // - lazyLoadingOff() and not loaded -> null (EF: null when not loaded);
606
+ // - otherwise -> a Promise that loads it ONCE via the engine-agnostic,
607
+ // parameterized context.loadNavigation() and caches the result, so
608
+ // `await post.author` works on every engine. (The old getter issued
609
+ // SQLite-shaped SQL with the key VALUE interpolated into the lambda.)
610
+ // Resolve the backing slot from the accessor OWNER, never from
611
+ // `this`: a derived object (Object.create(entity), used by the
612
+ // engines) must not end up with its own shadowing `_<nav>`.
613
+ const proto = Object.getPrototypeOf(modelClass);
614
+ const loaded = proto['_' + entityField];
615
+ // undefined = not loaded; null = loaded, no related row (EF); a thenable = in flight
616
+ if (loaded !== undefined && !(loaded && typeof loaded.then === 'function')) return loaded;
617
+ const def = currentEntity[entityField];
618
+ if (!def || def.lazyLoading === false) return (loaded === undefined) ? null : loaded;
619
+ const ctx = modelClass.__context;
620
+ if (!ctx || typeof ctx.loadNavigation !== 'function') return (loaded === undefined) ? null : loaded;
621
+ const inflightKey = '__loading_' + entityField;
622
+ if (proto[inflightKey] && typeof proto[inflightKey].then === 'function') return proto[inflightKey];
623
+ const p = ctx.loadNavigation(modelClass, entityField).then(
624
+ (v) => { proto['_' + entityField] = v; delete proto[inflightKey]; return v; },
625
+ (err) => { delete proto[inflightKey]; throw err; }
626
+ );
627
+ proto[inflightKey] = p;
628
+ p.catch(() => {}); // awaiters still see the rejection; avoids an unhandled-rejection crash when un-awaited
629
+ return p;
662
630
  }
663
631
  });
664
632
 
package/MasterRecord.js CHANGED
@@ -2,12 +2,23 @@
2
2
  import context from './context.js';
3
3
  import schema from './Migrations/schema.js';
4
4
  import ContextPool from './ContextPool.js';
5
+ import { sql, RawSql } from './QueryLanguage/rawSql.js';
6
+ import { ConcurrencyError } from './errors.js';
7
+ import { configureLogging, getLoggingConfig } from './logging.js';
8
+ import { isTransientError } from './resilience.js';
5
9
 
6
10
  class masterrecord {
7
11
  constructor() {
8
12
  this.context = context;
9
13
  this.schema = schema;
10
14
  this.ContextPool = ContextPool; // EF AddDbContextPool equivalent
15
+ this.sql = sql; // raw SET fragment for executeUpdate (EF SetProperty(b => b.X + 1))
16
+ this.RawSql = RawSql;
17
+ this.ConcurrencyError = ConcurrencyError;
18
+ this.configureLogging = configureLogging; // EF LogTo / EnableSensitiveDataLogging
19
+ this.getLoggingConfig = getLoggingConfig;
20
+ this.configureRetry = (opts) => context.configureRetry(opts); // EF EnableRetryOnFailure (global default)
21
+ this.isTransientError = isTransientError;
11
22
  }
12
23
  }
13
24
 
package/Migrations/cli.js CHANGED
@@ -152,6 +152,82 @@ async function __removeMigrationApplied(ctx, migrationName){
152
152
  }
153
153
  }
154
154
 
155
+ /** Applied migrations with timestamps: [{ migration_name, applied_at }] (EF `migrations list`). */
156
+ async function __getAppliedMigrationRows(ctx){
157
+ const engine = ctx._SQLEngine;
158
+ try {
159
+ if (ctx.isSQLite) {
160
+ return engine.db.prepare(`SELECT migration_name, applied_at FROM [${__MIGRATIONS_TABLE__}] ORDER BY applied_at`).all();
161
+ } else if (ctx.isMySQL) {
162
+ return await engine._runWithParams(`SELECT migration_name, applied_at FROM \`${__MIGRATIONS_TABLE__}\` ORDER BY applied_at`, []);
163
+ } else if (ctx.isPostgres) {
164
+ const r = await engine._runWithParams(`SELECT migration_name, applied_at FROM "${__MIGRATIONS_TABLE__}" ORDER BY applied_at`, []);
165
+ return r && r.rows ? r.rows : [];
166
+ }
167
+ } catch (_) { /* table may not exist yet */ }
168
+ return [];
169
+ }
170
+
171
+ /**
172
+ * Apply ONE migration step atomically (EF Core: each migration runs in its own
173
+ * transaction). The migration's DDL/DML and its tracking-table row commit or
174
+ * roll back together, so a failure can never leave a half-applied schema that
175
+ * is (or isn't) recorded.
176
+ * - PostgreSQL: transactional DDL -> BEGIN ... COMMIT.
177
+ * - SQLite: transactional DDL too, but `PRAGMA foreign_keys` is a no-op inside
178
+ * a transaction and the table-rebuild path relies on toggling it, so FK
179
+ * enforcement is switched off BEFORE the transaction and restored after
180
+ * (exactly what EF does for SQLite rebuilds).
181
+ * - MySQL: DDL implicitly commits, so a migration cannot be made atomic there
182
+ * (EF documents the same limitation); statements run directly.
183
+ * Runs on the migration's own context (it shares the engine/connection with
184
+ * `contextInstance`), so the tracking row is written inside the same transaction.
185
+ */
186
+ async function __applyMigrationStep(contextInstance, instance, tableObj, migrationName, direction = 'up'){
187
+ const ctx = (instance && instance.context) ? instance.context : contextInstance;
188
+ const run = async () => {
189
+ if (direction === 'down') await instance.down(tableObj); else await instance.up(tableObj);
190
+ if (typeof instance.finalize === 'function') await instance.finalize();
191
+ if (direction === 'down') await __removeMigrationApplied(ctx, migrationName);
192
+ else await __recordMigrationApplied(ctx, migrationName);
193
+ };
194
+ if (ctx.isMySQL || typeof ctx.transaction !== 'function') { await run(); return 'autocommit'; }
195
+
196
+ let fkWasOn = false;
197
+ if (ctx.isSQLite) {
198
+ await ctx._ensureReady();
199
+ try { fkWasOn = ctx._SQLEngine.db.pragma('foreign_keys', { simple: true }) === 1; } catch (_) { /* older driver */ }
200
+ if (fkWasOn) { try { ctx._SQLEngine.db.pragma('foreign_keys = OFF'); } catch (_) { /* ignore */ } }
201
+ }
202
+ try {
203
+ await ctx.transaction(run);
204
+ return 'transaction';
205
+ } finally {
206
+ if (ctx.isSQLite && fkWasOn) { try { ctx._SQLEngine.db.pragma('foreign_keys = ON'); } catch (_) { /* ignore */ } }
207
+ }
208
+ }
209
+
210
+ /** Resolve everything a migration command needs for a context (snapshot, files, constructor). */
211
+ async function __resolveMigrationPlan(contextFileName){
212
+ const executedLocation = process.cwd();
213
+ contextFileName = String(contextFileName).toLowerCase();
214
+ const files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
215
+ const file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
216
+ if (!file) {
217
+ throw new Error(`Cannot find Context snapshot '${contextFileName}_contextSnapShot.json' in '${executedLocation}'. Run 'masterrecord enable-migrations ${contextFileName}' first.`);
218
+ }
219
+ const contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
220
+ const snapDir = path.dirname(file);
221
+ const contextAbs = path.resolve(snapDir, contextSnapshot.contextLocation || '');
222
+ let migBase = path.resolve(snapDir, contextSnapshot.migrationFolder || '.');
223
+ if (!fs.existsSync(migBase)) migBase = snapDir;
224
+ const migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true }) || [];
225
+ const mFiles = migrationFiles.map(f => path.resolve(migBase, f))
226
+ .sort((a, b) => __getMigrationTimestamp(a) - __getMigrationTimestamp(b));
227
+ const ContextCtor = await __loadUserModule(contextAbs);
228
+ return { executedLocation, contextFileName, file, contextSnapshot, contextAbs, migBase, mFiles, ContextCtor };
229
+ }
230
+
155
231
  // Helper to cleanup context and exit
156
232
  async function __cleanupAndExit(contextInstance, exitCode = 0) {
157
233
  try {
@@ -177,6 +253,15 @@ program
177
253
  // Support legacy '-V' as an alias to print version
178
254
  program.option('-V', 'output the version');
179
255
 
256
+ // EF `--connection`: override the env-file connection for this run with a JSON
257
+ // config (optionally keyed by context name), e.g.
258
+ // masterrecord update-database AppContext --connection '{"type":"sqlite","connection":"./tmp/"}'
259
+ program.option('--connection <json>', 'JSON connection config that overrides the environment file for this run');
260
+ program.hook('preAction', () => {
261
+ const opts = program.opts();
262
+ if (opts.connection) process.env.MASTERRECORD_CONNECTION_OVERRIDE = String(opts.connection);
263
+ });
264
+
180
265
  // Instructions : to run command you must go to main project folder is located and run the command using the context file name.
181
266
  program
182
267
  .command('enable-migrations <contextFileName>')
@@ -594,9 +679,10 @@ program.option('-V', 'output the version');
594
679
  try {
595
680
  const MigrationCtor = await __loadUserModule(mFile);
596
681
  const instance = new MigrationCtor(ContextCtor);
597
- await instance.up(tableObj);
598
- await __recordMigrationApplied(contextInstance, migrationName);
599
- console.log(` ✓ applied`);
682
+ // Atomic: DDL + tracking row commit/roll back together (EF: one
683
+ // transaction per migration; MySQL DDL autocommits — see helper).
684
+ const mode = await __applyMigrationStep(contextInstance, instance, tableObj, migrationName, 'up');
685
+ console.log(` ✓ applied${mode === 'transaction' ? ' (transactional)' : ''}`);
600
686
  } catch (err) {
601
687
  console.error(`\n❌ Error - Migration '${migrationName}' failed during execution`);
602
688
  console.error(`\nDetails: ${err.message}`);
@@ -616,7 +702,8 @@ program.option('-V', 'output the version');
616
702
  context : contextInstance,
617
703
  contextEntities : cleanEntities,
618
704
  contextSeedData: contextInstance.__contextSeedData || {},
619
- contextFileName: contextFileName
705
+ contextFileName: contextFileName,
706
+ latestMigration: mFiles.length ? path.basename(mFiles[mFiles.length - 1]) : null
620
707
  }
621
708
 
622
709
  migration.createSnapShot(snap);
@@ -745,6 +832,7 @@ program.option('-V', 'output the version');
745
832
  const migInstance = new MigCtor(ContextCtor);
746
833
  if(typeof migInstance.down === 'function'){
747
834
  await migInstance.down(tableObj);
835
+ if (typeof migInstance.finalize === 'function') await migInstance.finalize();
748
836
  await __removeMigrationApplied(contextInstance, rollbackName);
749
837
  }else{
750
838
  console.log(`Warning - Migration '${rollbackName}' has no down method; skipping.`);
@@ -847,6 +935,7 @@ program.option('-V', 'output the version');
847
935
  const newMigrationProjectInstance = new migrationProjectFile(ContextCtor);
848
936
  const tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
849
937
  await newMigrationProjectInstance.up(tableObj);
938
+ if (typeof newMigrationProjectInstance.finalize === 'function') await newMigrationProjectInstance.finalize();
850
939
  }
851
940
  const snap = {
852
941
  file : contextAbs,
@@ -868,6 +957,163 @@ program.option('-V', 'output the version');
868
957
  });
869
958
 
870
959
 
960
+ // EF `dotnet ef migrations list`: applied (with timestamps) vs pending.
961
+ program
962
+ .command('migrations-status <contextFileName>')
963
+ .alias('ms')
964
+ .description('Show applied and pending migrations for a context against the database')
965
+ .action(async function(contextFileName){
966
+ let contextInstance = null;
967
+ try {
968
+ const plan = await __resolveMigrationPlan(contextFileName);
969
+ contextInstance = await instantiateReadyContext(plan.ContextCtor);
970
+ const rows = await __getAppliedMigrationRows(contextInstance);
971
+ const appliedMap = new Map(rows.map(r => [r.migration_name, r.applied_at]));
972
+ const names = plan.mFiles.map(f => path.basename(f));
973
+ const pending = names.filter(n => !appliedMap.has(n));
974
+ const orphans = [...appliedMap.keys()].filter(n => !names.includes(n));
975
+ console.log(`Context: ${plan.contextFileName}`);
976
+ console.log(`Migrations folder: ${plan.migBase}`);
977
+ console.log(`\nApplied (${appliedMap.size}):`);
978
+ for (const n of names) if (appliedMap.has(n)) console.log(` ✓ ${n} ${appliedMap.get(n)}`);
979
+ for (const n of orphans) console.log(` ✓ ${n} ${appliedMap.get(n)} [recorded, file missing]`);
980
+ console.log(`\nPending (${pending.length}):`);
981
+ for (const n of pending) console.log(` • ${n}`);
982
+ if (plan.contextSnapshot.latestMigration) console.log(`\nSnapshot latest migration: ${plan.contextSnapshot.latestMigration}`);
983
+ await __cleanupAndExit(contextInstance, 0);
984
+ } catch (e) {
985
+ console.error(`❌ migrations-status failed: ${e.message}`);
986
+ await __cleanupAndExit(contextInstance, 1);
987
+ }
988
+ });
989
+
990
+ // EF `dotnet ef migrations remove`: delete the LATEST migration file. Like EF
991
+ // it refuses when that migration has been applied to the database, unless
992
+ // `--force`, which reverts it (down, in its own transaction) first. The
993
+ // snapshot needs no rewrite for a pending migration: masterrecord's snapshot
994
+ // reflects the APPLIED database state (it is updated by update-database).
995
+ program
996
+ .command('remove-migration <contextFileName>')
997
+ .alias('rm')
998
+ .option('-f, --force', 'revert the migration if it has been applied, then remove it')
999
+ .description('Remove the latest migration file (EF: migrations remove); refuses an applied migration unless --force')
1000
+ .action(async function(contextFileName, cmdOpts){
1001
+ let contextInstance = null;
1002
+ try {
1003
+ const plan = await __resolveMigrationPlan(contextFileName);
1004
+ if (!plan.mFiles.length) {
1005
+ console.log(`No migration files found in ${plan.migBase}.`);
1006
+ process.exit(0);
1007
+ }
1008
+ const latest = plan.mFiles[plan.mFiles.length - 1];
1009
+ const name = path.basename(latest);
1010
+ contextInstance = await instantiateReadyContext(plan.ContextCtor);
1011
+ const rows = await __getAppliedMigrationRows(contextInstance);
1012
+ const appliedNames = new Set(rows.map(r => r.migration_name));
1013
+ if (appliedNames.has(name)) {
1014
+ if (!(cmdOpts && cmdOpts.force)) {
1015
+ console.error(`❌ Migration '${name}' has been applied to the database. Revert it first with 'masterrecord update-database-down ${plan.contextFileName}', or pass --force to revert and remove it.`);
1016
+ await __cleanupAndExit(contextInstance, 1);
1017
+ return;
1018
+ }
1019
+ // --force: revert (down) atomically, then remove.
1020
+ const migration = new Migration();
1021
+ const cleanEntities = migration.cleanEntities(contextInstance.__entities);
1022
+ const tableObj = migration.buildUpObject(plan.contextSnapshot.schema, cleanEntities);
1023
+ const MigCtor = await __loadUserModule(latest);
1024
+ const instance = new MigCtor(plan.ContextCtor);
1025
+ if (typeof instance.down !== 'function') throw new Error(`Migration '${name}' has no down() method; cannot revert it.`);
1026
+ const mode = await __applyMigrationStep(contextInstance, instance, tableObj, name, 'down');
1027
+ console.log(`↩ Reverted '${name}' (${mode})`);
1028
+ try { if (instance.context && instance.context !== contextInstance && typeof instance.context.close === 'function') await instance.context.close(); } catch (_) { /* best-effort */ }
1029
+ // Snapshot follows the applied state: previous applied migration becomes the latest.
1030
+ const remaining = plan.mFiles.filter(f => path.basename(f) !== name && appliedNames.has(path.basename(f)));
1031
+ migration.createSnapShot({
1032
+ file: plan.contextAbs, executedLocation: plan.executedLocation, context: contextInstance,
1033
+ contextEntities: cleanEntities,
1034
+ contextSeedData: contextInstance.__contextSeedData || {},
1035
+ contextSeedConfig: contextInstance.__contextSeedConfig || {},
1036
+ contextFileName: plan.contextFileName,
1037
+ latestMigration: remaining.length ? path.basename(remaining[remaining.length - 1]) : null,
1038
+ });
1039
+ }
1040
+ fs.unlinkSync(latest);
1041
+ console.log(`✓ Removed migration '${name}'`);
1042
+ await __cleanupAndExit(contextInstance, 0);
1043
+ } catch (e) {
1044
+ console.error(`❌ remove-migration failed: ${e.message}`);
1045
+ await __cleanupAndExit(contextInstance, 1);
1046
+ }
1047
+ });
1048
+
1049
+ // EF `dotnet ef migrations script`: the SQL for pending migrations, NOT applied.
1050
+ program
1051
+ .command('script <contextFileName>')
1052
+ .option('-o, --output <file>', 'write the SQL to a file instead of stdout')
1053
+ .description('Generate the SQL for pending migrations without applying them (for DBA review)')
1054
+ .action(async function(contextFileName, cmdOpts){
1055
+ let contextInstance = null;
1056
+ try {
1057
+ const plan = await __resolveMigrationPlan(contextFileName);
1058
+ contextInstance = await instantiateReadyContext(plan.ContextCtor);
1059
+ const applied = await __getAppliedMigrations(contextInstance);
1060
+ const pending = plan.mFiles.filter(f => !applied.has(path.basename(f)));
1061
+ const migration = new Migration();
1062
+ const cleanEntities = migration.cleanEntities(contextInstance.__entities);
1063
+ const tableObj = migration.buildUpObject(plan.contextSnapshot.schema, cleanEntities);
1064
+ const lines = [
1065
+ `-- masterrecord migration script for '${plan.contextFileName}'`,
1066
+ `-- generated ${new Date().toISOString()} — ${pending.length} pending migration(s). This script was NOT applied.`,
1067
+ `-- Introspection (table/column checks) ran against the live database; statements below are what update-database would execute.`,
1068
+ '',
1069
+ ];
1070
+ const fmt = (q, p) => {
1071
+ const s = String(q).replace(/\s+/g, ' ').trim().replace(/;$/, '');
1072
+ return (p && p.length) ? `${s}; -- params: ${JSON.stringify(p)}` : `${s};`;
1073
+ };
1074
+ for (const mFile of pending) {
1075
+ const name = path.basename(mFile);
1076
+ const MigrationCtor = await __loadUserModule(mFile);
1077
+ const instance = new MigrationCtor(plan.ContextCtor);
1078
+ const mctx = instance.context || contextInstance;
1079
+ const captured = [];
1080
+ // Capture instead of execute: schema.js issues all DDL/DML through
1081
+ // context._execute; engine-level introspection (tableExists/getTableInfo)
1082
+ // is untouched so the plan reflects the real database state.
1083
+ const patch = (c) => {
1084
+ const orig = c._execute;
1085
+ c._execute = (q, p) => { captured.push(fmt(q, p)); return Promise.resolve({ changes: 0, rowCount: 0, affectedRows: 0 }); };
1086
+ return () => { c._execute = orig; };
1087
+ };
1088
+ const restores = [patch(mctx)];
1089
+ if (mctx !== contextInstance) restores.push(patch(contextInstance));
1090
+ try {
1091
+ await instance.up(tableObj);
1092
+ if (typeof instance.finalize === 'function') await instance.finalize();
1093
+ await __recordMigrationApplied(mctx, name); // captured, not executed
1094
+ } finally {
1095
+ for (const r of restores) r();
1096
+ }
1097
+ lines.push(`-- Migration: ${name}`);
1098
+ lines.push(...captured);
1099
+ lines.push('');
1100
+ try { if (mctx !== contextInstance && typeof mctx.close === 'function') await mctx.close(); } catch (_) { /* best-effort */ }
1101
+ }
1102
+ const out = lines.join('\n');
1103
+ if (cmdOpts && cmdOpts.output) {
1104
+ const target = path.resolve(cmdOpts.output);
1105
+ fs.writeFileSync(target, out, 'utf8');
1106
+ console.log(`✓ SQL script for ${pending.length} pending migration(s) written to ${target}`);
1107
+ } else {
1108
+ process.stdout.write(out + '\n');
1109
+ }
1110
+ await __cleanupAndExit(contextInstance, 0);
1111
+ } catch (e) {
1112
+ console.error(`❌ script failed: ${e.message}`);
1113
+ await __cleanupAndExit(contextInstance, 1);
1114
+ }
1115
+ });
1116
+
871
1117
  program
872
1118
  .command('get-migrations <contextFileName>')
873
1119
  .alias('gm')
@@ -1004,6 +1250,7 @@ program.option('-V', 'output the version');
1004
1250
  const migInstance = new MigCtor(ContextCtor);
1005
1251
  if(typeof migInstance.down === 'function'){
1006
1252
  await migInstance.down(tableObj);
1253
+ if (typeof migInstance.finalize === 'function') await migInstance.finalize();
1007
1254
  } else {
1008
1255
  console.log(`Warning - Migration '${path.basename(migFile)}' has no down method; skipping.`);
1009
1256
  }
@@ -1234,8 +1481,7 @@ program.option('-V', 'output the version');
1234
1481
  try {
1235
1482
  const MigrationCtor = await __loadUserModule(mFile);
1236
1483
  const inst = new MigrationCtor(ContextCtor);
1237
- await inst.up(tableObj);
1238
- await __recordMigrationApplied(contextInstance, migrationName);
1484
+ await __applyMigrationStep(contextInstance, inst, tableObj, migrationName, 'up');
1239
1485
  appliedCount++;
1240
1486
  // Release the migration's own context (opened by its schema
1241
1487
  // constructor) so connections don't accumulate across the batch.