masterrecord 1.0.2 → 1.0.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.
Files changed (28) hide show
  1. package/Migrations/cli.js +155 -23
  2. package/package.json +1 -1
  3. package/postgresEngine.js +15 -0
  4. package/test/fixtures/multi-migration-MFc2cl/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +14 -0
  5. package/test/fixtures/multi-migration-MFc2cl/app/models/db/migrations/1700000002000_CreateBook_migration.js +14 -0
  6. package/test/fixtures/multi-migration-MFc2cl/app/models/db/migrations/1700000003000_CreateReview_migration.js +14 -0
  7. package/test/fixtures/multi-migration-MFc2cl/app/models/db/migrations/multimigctx_contextSnapShot.json +104 -0
  8. package/test/fixtures/multi-migration-MFc2cl/app/models/multimigctx.js +26 -0
  9. package/test/fixtures/multi-migration-MFc2cl/config/environments/env.multimig.json +1 -0
  10. package/test/fixtures/multi-migration-MFc2cl/db/multimigctx.sqlite +0 -0
  11. package/test/fixtures/multi-migration-MFc2cl/package.json +1 -0
  12. package/test/fixtures/multi-migration-gWKaXD/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +14 -0
  13. package/test/fixtures/multi-migration-gWKaXD/app/models/db/migrations/1700000002000_CreateBook_migration.js +14 -0
  14. package/test/fixtures/multi-migration-gWKaXD/app/models/db/migrations/1700000003000_CreateReview_migration.js +14 -0
  15. package/test/fixtures/multi-migration-gWKaXD/app/models/db/migrations/multimigctx_contextSnapShot.json +96 -0
  16. package/test/fixtures/multi-migration-gWKaXD/app/models/multimigctx.js +26 -0
  17. package/test/fixtures/multi-migration-gWKaXD/config/environments/env.multimig.json +1 -0
  18. package/test/fixtures/multi-migration-gWKaXD/db/multimigctx.sqlite +0 -0
  19. package/test/fixtures/multi-migration-gWKaXD/package.json +1 -0
  20. package/test/fixtures/multi-migration-vsWfKD/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +14 -0
  21. package/test/fixtures/multi-migration-vsWfKD/app/models/db/migrations/1700000002000_CreateBook_migration.js +14 -0
  22. package/test/fixtures/multi-migration-vsWfKD/app/models/db/migrations/1700000003000_CreateReview_migration.js +14 -0
  23. package/test/fixtures/multi-migration-vsWfKD/app/models/db/migrations/multimigctx_contextSnapShot.json +96 -0
  24. package/test/fixtures/multi-migration-vsWfKD/app/models/multimigctx.js +26 -0
  25. package/test/fixtures/multi-migration-vsWfKD/config/environments/env.multimig.json +1 -0
  26. package/test/fixtures/multi-migration-vsWfKD/db/multimigctx.sqlite +0 -0
  27. package/test/fixtures/multi-migration-vsWfKD/package.json +1 -0
  28. package/test/update-database-multi.test.js +239 -0
package/Migrations/cli.js CHANGED
@@ -42,6 +42,77 @@ function __getMigrationTimestamp(file){
42
42
  }
43
43
  }
44
44
 
45
+ // ============================================================================
46
+ // Migration tracking — one row per applied migration filename.
47
+ // Without this, update-database cannot tell which files are pending, so it
48
+ // used to run only the last one and silently skip the rest.
49
+ // ============================================================================
50
+
51
+ const __MIGRATIONS_TABLE__ = '_masterrecord_migrations';
52
+
53
+ async function __ensureMigrationsTable(ctx){
54
+ const engine = ctx._SQLEngine;
55
+ if (ctx.isSQLite) {
56
+ await ctx._execute(`CREATE TABLE IF NOT EXISTS [${__MIGRATIONS_TABLE__}] (
57
+ migration_name TEXT PRIMARY KEY,
58
+ applied_at TEXT NOT NULL
59
+ )`);
60
+ } else if (ctx.isMySQL) {
61
+ await ctx._execute(`CREATE TABLE IF NOT EXISTS \`${__MIGRATIONS_TABLE__}\` (
62
+ migration_name VARCHAR(255) PRIMARY KEY,
63
+ applied_at VARCHAR(64) NOT NULL
64
+ )`);
65
+ } else if (ctx.isPostgres) {
66
+ await ctx._execute(`CREATE TABLE IF NOT EXISTS "${__MIGRATIONS_TABLE__}" (
67
+ migration_name VARCHAR(255) PRIMARY KEY,
68
+ applied_at VARCHAR(64) NOT NULL
69
+ )`);
70
+ }
71
+ }
72
+
73
+ async function __getAppliedMigrations(ctx){
74
+ const applied = new Set();
75
+ const engine = ctx._SQLEngine;
76
+ let rows;
77
+ try {
78
+ if (ctx.isSQLite) {
79
+ rows = engine.db.prepare(`SELECT migration_name FROM [${__MIGRATIONS_TABLE__}]`).all();
80
+ } else if (ctx.isMySQL) {
81
+ rows = await engine._runWithParams(`SELECT migration_name FROM \`${__MIGRATIONS_TABLE__}\``, []);
82
+ } else if (ctx.isPostgres) {
83
+ const r = await engine._runWithParams(`SELECT migration_name FROM "${__MIGRATIONS_TABLE__}"`, []);
84
+ rows = r && r.rows ? r.rows : [];
85
+ }
86
+ } catch (_) {
87
+ rows = [];
88
+ }
89
+ for (const r of (rows || [])) {
90
+ if (r && r.migration_name) applied.add(r.migration_name);
91
+ }
92
+ return applied;
93
+ }
94
+
95
+ async function __recordMigrationApplied(ctx, migrationName){
96
+ const appliedAt = new Date().toISOString();
97
+ if (ctx.isSQLite) {
98
+ await ctx._execute(`INSERT INTO [${__MIGRATIONS_TABLE__}] (migration_name, applied_at) VALUES (?, ?)`, [migrationName, appliedAt]);
99
+ } else if (ctx.isMySQL) {
100
+ await ctx._execute(`INSERT INTO \`${__MIGRATIONS_TABLE__}\` (migration_name, applied_at) VALUES (?, ?)`, [migrationName, appliedAt]);
101
+ } else if (ctx.isPostgres) {
102
+ await ctx._execute(`INSERT INTO "${__MIGRATIONS_TABLE__}" (migration_name, applied_at) VALUES ($1, $2)`, [migrationName, appliedAt]);
103
+ }
104
+ }
105
+
106
+ async function __removeMigrationApplied(ctx, migrationName){
107
+ if (ctx.isSQLite) {
108
+ await ctx._execute(`DELETE FROM [${__MIGRATIONS_TABLE__}] WHERE migration_name = ?`, [migrationName]);
109
+ } else if (ctx.isMySQL) {
110
+ await ctx._execute(`DELETE FROM \`${__MIGRATIONS_TABLE__}\` WHERE migration_name = ?`, [migrationName]);
111
+ } else if (ctx.isPostgres) {
112
+ await ctx._execute(`DELETE FROM "${__MIGRATIONS_TABLE__}" WHERE migration_name = $1`, [migrationName]);
113
+ }
114
+ }
115
+
45
116
  // Helper to cleanup context and exit
46
117
  async function __cleanupAndExit(contextInstance, exitCode = 0) {
47
118
  try {
@@ -360,23 +431,22 @@ program.option('-V', 'output the version');
360
431
  await __cleanupAndExit(contextInstance, 1);
361
432
  }
362
433
 
363
- // sort by timestamp prefix or file mtime as fallback
434
+ // Sort by timestamp prefix (filename convention) or file mtime as fallback.
435
+ // Then run EVERY pending migration in order, not just the last one —
436
+ // the old behavior silently skipped earlier pending migrations when a
437
+ // user had stacked multiple add-migration calls before deploying.
364
438
  var mFiles = migrationFiles.slice().sort(function(a, b){
365
439
  return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
366
440
  });
367
- var mFile = mFiles[mFiles.length -1];
368
- console.log(`✓ Found ${mFiles.length} migration file(s), using latest: ${path.basename(mFile)}`);
441
+ console.log(`✓ Found ${mFiles.length} migration file(s)`);
369
442
 
370
443
  console.log(`\n🔍 Loading Context file from: ${contextAbs}`);
371
- var migrationProjectFile;
372
444
  var ContextCtor;
373
445
  try{
374
- migrationProjectFile = await __loadUserModule(mFile);
375
446
  ContextCtor = await __loadUserModule(contextAbs);
376
447
  }catch(err){
377
- console.error(`\n❌ Error - Cannot load Context or migration file`);
448
+ console.error(`\n❌ Error - Cannot load Context file`);
378
449
  console.error(`\nContext file: ${contextAbs}`);
379
- console.error(`Migration file: ${mFile}`);
380
450
  console.error(`\nDetails: ${err.message}`);
381
451
  if(err.stack){
382
452
  console.error(`\nStack trace:`);
@@ -390,6 +460,11 @@ program.option('-V', 'output the version');
390
460
 
391
461
  try{
392
462
  contextInstance = new ContextCtor();
463
+ // MySQL/Postgres initialize asynchronously — wait for the pool
464
+ // before we can run any migration queries against it.
465
+ if (contextInstance && contextInstance._initPromise) {
466
+ await contextInstance._initPromise;
467
+ }
393
468
  }catch(err){
394
469
  console.error(`\n❌ Error - Failed to instantiate Context`);
395
470
  console.error(`\nContext file: ${contextAbs}`);
@@ -425,6 +500,8 @@ program.option('-V', 'output the version');
425
500
  }
426
501
  }else if(contextInstance.isMySQL){
427
502
  console.log(`\n📊 Database Type: MySQL`);
503
+ }else if(contextInstance.isPostgres){
504
+ console.log(`\n📊 Database Type: PostgreSQL`);
428
505
  }
429
506
 
430
507
  console.log(`\n🔍 Loading entities from context...`);
@@ -439,22 +516,54 @@ program.option('-V', 'output the version');
439
516
  console.error(` this.dbset(Post, 'Post');`);
440
517
  }
441
518
 
442
- console.log(`\n🚀 Running migration...`);
443
- try{
444
- var newMigrationProjectInstance = new migrationProjectFile(ContextCtor);
445
- var tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
446
- await newMigrationProjectInstance.up(tableObj);
447
- }catch(err){
448
- console.error(`\n❌ Error - Migration failed during execution`);
449
- console.error(`\nMigration file: ${mFile}`);
519
+ // Build tableObj once from the current entity state. All pending
520
+ // migrations share this object — the old design assumed a single
521
+ // migration, so there's no historical per-migration tableObj.
522
+ // Idempotent helpers (createTable checks tableExists; addColumn
523
+ // no-ops on undefined `table.col`) make this safe in practice.
524
+ var tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
525
+
526
+ // Bootstrap the migrations tracking table, then filter out any
527
+ // migrations already applied so re-running update-database is a
528
+ // no-op. Must run before any migration's `up()`.
529
+ try {
530
+ await __ensureMigrationsTable(contextInstance);
531
+ } catch (err) {
532
+ console.error(`\n❌ Error - Could not create migration tracking table`);
450
533
  console.error(`\nDetails: ${err.message}`);
451
- if(err.stack){
452
- console.error(`\nStack trace:`);
453
- console.error(err.stack);
454
- }
455
534
  await __cleanupAndExit(contextInstance, 1);
456
535
  }
457
536
 
537
+ const appliedMigrations = await __getAppliedMigrations(contextInstance);
538
+ const pending = mFiles.filter(f => !appliedMigrations.has(path.basename(f)));
539
+
540
+ if (pending.length === 0) {
541
+ console.log(`\n✓ All migrations already applied (${appliedMigrations.size} on record). Database is up to date.`);
542
+ } else {
543
+ console.log(`\n🚀 Running ${pending.length} pending migration(s)...`);
544
+ }
545
+
546
+ for (const mFile of pending) {
547
+ const migrationName = path.basename(mFile);
548
+ console.log(`\n → ${migrationName}`);
549
+ try {
550
+ const MigrationCtor = await __loadUserModule(mFile);
551
+ const instance = new MigrationCtor(ContextCtor);
552
+ await instance.up(tableObj);
553
+ await __recordMigrationApplied(contextInstance, migrationName);
554
+ console.log(` ✓ applied`);
555
+ } catch (err) {
556
+ console.error(`\n❌ Error - Migration '${migrationName}' failed during execution`);
557
+ console.error(`\nDetails: ${err.message}`);
558
+ if (err.stack) {
559
+ console.error(`\nStack trace:`);
560
+ console.error(err.stack);
561
+ }
562
+ console.error(`\n💡 Earlier migrations (if any) were already applied and recorded. Fix the failing migration and re-run update-database to resume from this point.`);
563
+ await __cleanupAndExit(contextInstance, 1);
564
+ }
565
+ }
566
+
458
567
  console.log(`\n💾 Updating snapshot...`);
459
568
  var snap = {
460
569
  file : contextAbs,
@@ -525,11 +634,11 @@ program.option('-V', 'output the version');
525
634
  console.log("Error - Cannot read or find migration file");
526
635
  return;
527
636
  }
528
- // Sort and select latest
637
+ // Sort so we can find the latest APPLIED migration (not just the
638
+ // latest on disk) using the tracking table.
529
639
  var mFiles = migrationFiles.slice().sort(function(a, b){
530
640
  return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
531
641
  });
532
- var latestFile = mFiles[mFiles.length - 1];
533
642
 
534
643
  // Prepare context and table object
535
644
  let ContextCtor;
@@ -548,6 +657,9 @@ program.option('-V', 'output the version');
548
657
  var contextInstance;
549
658
  try{
550
659
  contextInstance = new ContextCtor();
660
+ if (contextInstance && contextInstance._initPromise) {
661
+ await contextInstance._initPromise;
662
+ }
551
663
  }catch(err){
552
664
  console.error(`\n❌ Error - Failed to construct Context from '${contextAbs}'`);
553
665
  console.error(`\nThis usually happens when:`);
@@ -565,12 +677,32 @@ program.option('-V', 'output the version');
565
677
  var cleanEntities = migration.cleanEntities(contextInstance.__entities);
566
678
  var tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
567
679
 
568
- var MigCtor = await __loadUserModule(latestFile);
680
+ // Roll back the most recently APPLIED migration. Falls back to the
681
+ // latest migration file on disk if the tracking table is missing or
682
+ // empty (preserves legacy behavior for users who haven't run
683
+ // update-database under the tracked system yet).
684
+ await __ensureMigrationsTable(contextInstance);
685
+ const applied = await __getAppliedMigrations(contextInstance);
686
+ let rollbackFile;
687
+ let rollbackName;
688
+ if (applied.size > 0) {
689
+ // Pick the applied file with the latest timestamp prefix.
690
+ const appliedFiles = mFiles.filter(f => applied.has(path.basename(f)));
691
+ rollbackFile = appliedFiles[appliedFiles.length - 1];
692
+ rollbackName = path.basename(rollbackFile || mFiles[mFiles.length - 1]);
693
+ } else {
694
+ rollbackFile = mFiles[mFiles.length - 1];
695
+ rollbackName = path.basename(rollbackFile);
696
+ console.log(`⚠️ No applied-migration record found; falling back to latest file on disk: ${rollbackName}`);
697
+ }
698
+
699
+ var MigCtor = await __loadUserModule(rollbackFile);
569
700
  var migInstance = new MigCtor(ContextCtor);
570
701
  if(typeof migInstance.down === 'function'){
571
702
  await migInstance.down(tableObj);
703
+ await __removeMigrationApplied(contextInstance, rollbackName);
572
704
  }else{
573
- console.log(`Warning - Migration '${path.basename(latestFile)}' has no down method; skipping.`);
705
+ console.log(`Warning - Migration '${rollbackName}' has no down method; skipping.`);
574
706
  }
575
707
 
576
708
  // Update snapshot
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.0.002",
3
+ "version": "1.0.003",
4
4
  "description": "An Object-relational mapping for the Master framework. Master Record connects classes to relational database tables to establish a database with almost zero-configuration ",
5
5
  "type": "module",
6
6
  "main": "./MasterRecord.js",
package/postgresEngine.js CHANGED
@@ -255,6 +255,21 @@ class postgresEngine {
255
255
  return await this._runWithParams(query, params);
256
256
  }
257
257
 
258
+ /**
259
+ * Introspection: Check if a table exists in the current Postgres schema.
260
+ * Mirrors the SQLite/MySQL engines so migration code and the CLI's
261
+ * migration tracker can call it uniformly across all three drivers.
262
+ */
263
+ async tableExists(tableName) {
264
+ try {
265
+ const sql = `SELECT 1 FROM information_schema.tables WHERE table_schema = ANY(current_schemas(false)) AND table_name = $1 LIMIT 1`;
266
+ const result = await this._runWithParams(sql, [tableName]);
267
+ return !!(result && result.rows && result.rows.length > 0);
268
+ } catch (_) {
269
+ return false;
270
+ }
271
+ }
272
+
258
273
  /**
259
274
  * Build complete SELECT query with parameters
260
275
  */
@@ -0,0 +1,14 @@
1
+
2
+ import masterrecord from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/MasterRecord.js";
3
+ class CreateAuthor extends masterrecord.schema {
4
+ constructor(context){ super(context); }
5
+ async up(table){
6
+ await this.init(table);
7
+ await this.createTable(table.Author);
8
+ }
9
+ async down(table){
10
+ await this.init(table);
11
+ await this.dropTable(table.Author);
12
+ }
13
+ }
14
+ export default CreateAuthor;
@@ -0,0 +1,14 @@
1
+
2
+ import masterrecord from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/MasterRecord.js";
3
+ class CreateBook extends masterrecord.schema {
4
+ constructor(context){ super(context); }
5
+ async up(table){
6
+ await this.init(table);
7
+ await this.createTable(table.Book);
8
+ }
9
+ async down(table){
10
+ await this.init(table);
11
+ await this.dropTable(table.Book);
12
+ }
13
+ }
14
+ export default CreateBook;
@@ -0,0 +1,14 @@
1
+
2
+ import masterrecord from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/MasterRecord.js";
3
+ class CreateReview extends masterrecord.schema {
4
+ constructor(context){ super(context); }
5
+ async up(table){
6
+ await this.init(table);
7
+ await this.createTable(table.Review);
8
+ }
9
+ async down(table){
10
+ await this.init(table);
11
+ await this.dropTable(table.Review);
12
+ }
13
+ }
14
+ export default CreateReview;
@@ -0,0 +1,104 @@
1
+ {
2
+ "contextLocation": "../../multimigctx.js",
3
+ "migrationFolder": ".",
4
+ "snapShotLocation": "multimigctx_contextSnapShot.json",
5
+ "schema": [
6
+ {
7
+ "id": {
8
+ "name": "id",
9
+ "type": "integer",
10
+ "primary": true,
11
+ "nullable": false,
12
+ "unique": true,
13
+ "auto": true,
14
+ "cascadeOnDelete": true,
15
+ "lazyLoading": true,
16
+ "isNavigational": false,
17
+ "skipGetFunction": false,
18
+ "valueConversion": true
19
+ },
20
+ "name": {
21
+ "name": "name",
22
+ "type": "string",
23
+ "nullable": true,
24
+ "unique": false,
25
+ "auto": false,
26
+ "cascadeOnDelete": true,
27
+ "lazyLoading": true,
28
+ "isNavigational": false,
29
+ "skipGetFunction": false,
30
+ "valueConversion": true
31
+ },
32
+ "__compositeIndexes": [],
33
+ "__name": "Author"
34
+ },
35
+ {
36
+ "id": {
37
+ "name": "id",
38
+ "type": "integer",
39
+ "primary": true,
40
+ "nullable": false,
41
+ "unique": true,
42
+ "auto": true,
43
+ "cascadeOnDelete": true,
44
+ "lazyLoading": true,
45
+ "isNavigational": false,
46
+ "skipGetFunction": false,
47
+ "valueConversion": true
48
+ },
49
+ "title": {
50
+ "name": "title",
51
+ "type": "string",
52
+ "nullable": true,
53
+ "unique": false,
54
+ "auto": false,
55
+ "cascadeOnDelete": true,
56
+ "lazyLoading": true,
57
+ "isNavigational": false,
58
+ "skipGetFunction": false,
59
+ "valueConversion": true
60
+ },
61
+ "__compositeIndexes": [],
62
+ "__name": "Book"
63
+ },
64
+ {
65
+ "id": {
66
+ "name": "id",
67
+ "type": "integer",
68
+ "primary": true,
69
+ "nullable": false,
70
+ "unique": true,
71
+ "auto": true,
72
+ "cascadeOnDelete": true,
73
+ "lazyLoading": true,
74
+ "isNavigational": false,
75
+ "skipGetFunction": false,
76
+ "valueConversion": true
77
+ },
78
+ "body": {
79
+ "name": "body",
80
+ "type": "string",
81
+ "nullable": true,
82
+ "unique": false,
83
+ "auto": false,
84
+ "cascadeOnDelete": true,
85
+ "lazyLoading": true,
86
+ "isNavigational": false,
87
+ "skipGetFunction": false,
88
+ "valueConversion": true
89
+ },
90
+ "__compositeIndexes": [],
91
+ "__name": "Review"
92
+ }
93
+ ],
94
+ "seedData": {},
95
+ "seedConfig": {
96
+ "generateDownMigrations": false,
97
+ "downStrategy": "delete",
98
+ "deleteByPrimaryKey": true,
99
+ "onRollbackError": "warn",
100
+ "detectCircularDependencies": true,
101
+ "circularStrategy": "warn",
102
+ "defaultStrategy": "insert"
103
+ }
104
+ }
@@ -0,0 +1,26 @@
1
+
2
+ import context from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/context.js";
3
+
4
+ class Author {
5
+ id(db) { db.integer().primary().auto(); }
6
+ name(db) { db.string(); }
7
+ }
8
+ class Book {
9
+ id(db) { db.integer().primary().auto(); }
10
+ title(db) { db.string(); }
11
+ }
12
+ class Review {
13
+ id(db) { db.integer().primary().auto(); }
14
+ body(db) { db.string(); }
15
+ }
16
+
17
+ class multimigctx extends context {
18
+ constructor() {
19
+ super();
20
+ this.env("/Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/test/fixtures/multi-migration-MFc2cl/config/environments");
21
+ this.dbset(Author);
22
+ this.dbset(Book);
23
+ this.dbset(Review);
24
+ }
25
+ }
26
+ export default multimigctx;
@@ -0,0 +1 @@
1
+ {"multimigctx":{"type":"better-sqlite3","connection":"/Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/test/fixtures/multi-migration-MFc2cl/db/"}}
@@ -0,0 +1 @@
1
+ {"name":"multi-migration-fixture","type":"module"}
@@ -0,0 +1,14 @@
1
+
2
+ import masterrecord from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/MasterRecord.js";
3
+ class CreateAuthor extends masterrecord.schema {
4
+ constructor(context){ super(context); }
5
+ async up(table){
6
+ await this.init(table);
7
+ await this.createTable(table.Author);
8
+ }
9
+ async down(table){
10
+ await this.init(table);
11
+ await this.dropTable(table.Author);
12
+ }
13
+ }
14
+ export default CreateAuthor;
@@ -0,0 +1,14 @@
1
+
2
+ import masterrecord from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/MasterRecord.js";
3
+ class CreateBook extends masterrecord.schema {
4
+ constructor(context){ super(context); }
5
+ async up(table){
6
+ await this.init(table);
7
+ await this.createTable(table.Book);
8
+ }
9
+ async down(table){
10
+ await this.init(table);
11
+ await this.dropTable(table.Book);
12
+ }
13
+ }
14
+ export default CreateBook;
@@ -0,0 +1,14 @@
1
+
2
+ import masterrecord from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/MasterRecord.js";
3
+ class CreateReview extends masterrecord.schema {
4
+ constructor(context){ super(context); }
5
+ async up(table){
6
+ await this.init(table);
7
+ await this.createTable(table.Review);
8
+ }
9
+ async down(table){
10
+ await this.init(table);
11
+ await this.dropTable(table.Review);
12
+ }
13
+ }
14
+ export default CreateReview;
@@ -0,0 +1,96 @@
1
+ {
2
+ "contextLocation": "../../multimigctx.js",
3
+ "migrationFolder": ".",
4
+ "snapShotLocation": "multimigctx_contextSnapShot.json",
5
+ "schema": [
6
+ {
7
+ "id": {
8
+ "name": "id",
9
+ "type": "integer",
10
+ "primary": true,
11
+ "nullable": false,
12
+ "unique": true,
13
+ "auto": true,
14
+ "cascadeOnDelete": true,
15
+ "lazyLoading": true,
16
+ "isNavigational": false,
17
+ "skipGetFunction": false,
18
+ "valueConversion": true
19
+ },
20
+ "name": {
21
+ "name": "name",
22
+ "type": "string",
23
+ "nullable": true,
24
+ "unique": false,
25
+ "auto": false,
26
+ "cascadeOnDelete": true,
27
+ "lazyLoading": true,
28
+ "isNavigational": false,
29
+ "skipGetFunction": false,
30
+ "valueConversion": true
31
+ },
32
+ "__compositeIndexes": [],
33
+ "__name": "Author"
34
+ },
35
+ {
36
+ "id": {
37
+ "name": "id",
38
+ "type": "integer",
39
+ "primary": true,
40
+ "nullable": false,
41
+ "unique": true,
42
+ "auto": true,
43
+ "cascadeOnDelete": true,
44
+ "lazyLoading": true,
45
+ "isNavigational": false,
46
+ "skipGetFunction": false,
47
+ "valueConversion": true
48
+ },
49
+ "title": {
50
+ "name": "title",
51
+ "type": "string",
52
+ "nullable": true,
53
+ "unique": false,
54
+ "auto": false,
55
+ "cascadeOnDelete": true,
56
+ "lazyLoading": true,
57
+ "isNavigational": false,
58
+ "skipGetFunction": false,
59
+ "valueConversion": true
60
+ },
61
+ "__compositeIndexes": [],
62
+ "__name": "Book"
63
+ },
64
+ {
65
+ "id": {
66
+ "name": "id",
67
+ "type": "integer",
68
+ "primary": true,
69
+ "nullable": false,
70
+ "unique": true,
71
+ "auto": true,
72
+ "cascadeOnDelete": true,
73
+ "lazyLoading": true,
74
+ "isNavigational": false,
75
+ "skipGetFunction": false,
76
+ "valueConversion": true
77
+ },
78
+ "body": {
79
+ "name": "body",
80
+ "type": "string",
81
+ "nullable": true,
82
+ "unique": false,
83
+ "auto": false,
84
+ "cascadeOnDelete": true,
85
+ "lazyLoading": true,
86
+ "isNavigational": false,
87
+ "skipGetFunction": false,
88
+ "valueConversion": true
89
+ },
90
+ "__compositeIndexes": [],
91
+ "__name": "Review"
92
+ }
93
+ ],
94
+ "seedData": {},
95
+ "seedConfig": {}
96
+ }
@@ -0,0 +1,26 @@
1
+
2
+ import context from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/context.js";
3
+
4
+ class Author {
5
+ id(db) { db.integer().primary().auto(); }
6
+ name(db) { db.string(); }
7
+ }
8
+ class Book {
9
+ id(db) { db.integer().primary().auto(); }
10
+ title(db) { db.string(); }
11
+ }
12
+ class Review {
13
+ id(db) { db.integer().primary().auto(); }
14
+ body(db) { db.string(); }
15
+ }
16
+
17
+ class multimigctx extends context {
18
+ constructor() {
19
+ super();
20
+ this.env("/Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/test/fixtures/multi-migration-gWKaXD/config/environments");
21
+ this.dbset(Author);
22
+ this.dbset(Book);
23
+ this.dbset(Review);
24
+ }
25
+ }
26
+ export default multimigctx;
@@ -0,0 +1 @@
1
+ {"multimigctx":{"type":"better-sqlite3","connection":"/Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/test/fixtures/multi-migration-gWKaXD/db/"}}
@@ -0,0 +1 @@
1
+ {"name":"multi-migration-fixture","type":"module"}
@@ -0,0 +1,14 @@
1
+
2
+ import masterrecord from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/MasterRecord.js";
3
+ class CreateAuthor extends masterrecord.schema {
4
+ constructor(context){ super(context); }
5
+ async up(table){
6
+ await this.init(table);
7
+ await this.createTable(table.Author);
8
+ }
9
+ async down(table){
10
+ await this.init(table);
11
+ await this.dropTable(table.Author);
12
+ }
13
+ }
14
+ export default CreateAuthor;
@@ -0,0 +1,14 @@
1
+
2
+ import masterrecord from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/MasterRecord.js";
3
+ class CreateBook extends masterrecord.schema {
4
+ constructor(context){ super(context); }
5
+ async up(table){
6
+ await this.init(table);
7
+ await this.createTable(table.Book);
8
+ }
9
+ async down(table){
10
+ await this.init(table);
11
+ await this.dropTable(table.Book);
12
+ }
13
+ }
14
+ export default CreateBook;
@@ -0,0 +1,14 @@
1
+
2
+ import masterrecord from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/MasterRecord.js";
3
+ class CreateReview extends masterrecord.schema {
4
+ constructor(context){ super(context); }
5
+ async up(table){
6
+ await this.init(table);
7
+ await this.createTable(table.Review);
8
+ }
9
+ async down(table){
10
+ await this.init(table);
11
+ await this.dropTable(table.Review);
12
+ }
13
+ }
14
+ export default CreateReview;
@@ -0,0 +1,96 @@
1
+ {
2
+ "contextLocation": "../../multimigctx.js",
3
+ "migrationFolder": ".",
4
+ "snapShotLocation": "multimigctx_contextSnapShot.json",
5
+ "schema": [
6
+ {
7
+ "id": {
8
+ "name": "id",
9
+ "type": "integer",
10
+ "primary": true,
11
+ "nullable": false,
12
+ "unique": true,
13
+ "auto": true,
14
+ "cascadeOnDelete": true,
15
+ "lazyLoading": true,
16
+ "isNavigational": false,
17
+ "skipGetFunction": false,
18
+ "valueConversion": true
19
+ },
20
+ "name": {
21
+ "name": "name",
22
+ "type": "string",
23
+ "nullable": true,
24
+ "unique": false,
25
+ "auto": false,
26
+ "cascadeOnDelete": true,
27
+ "lazyLoading": true,
28
+ "isNavigational": false,
29
+ "skipGetFunction": false,
30
+ "valueConversion": true
31
+ },
32
+ "__compositeIndexes": [],
33
+ "__name": "Author"
34
+ },
35
+ {
36
+ "id": {
37
+ "name": "id",
38
+ "type": "integer",
39
+ "primary": true,
40
+ "nullable": false,
41
+ "unique": true,
42
+ "auto": true,
43
+ "cascadeOnDelete": true,
44
+ "lazyLoading": true,
45
+ "isNavigational": false,
46
+ "skipGetFunction": false,
47
+ "valueConversion": true
48
+ },
49
+ "title": {
50
+ "name": "title",
51
+ "type": "string",
52
+ "nullable": true,
53
+ "unique": false,
54
+ "auto": false,
55
+ "cascadeOnDelete": true,
56
+ "lazyLoading": true,
57
+ "isNavigational": false,
58
+ "skipGetFunction": false,
59
+ "valueConversion": true
60
+ },
61
+ "__compositeIndexes": [],
62
+ "__name": "Book"
63
+ },
64
+ {
65
+ "id": {
66
+ "name": "id",
67
+ "type": "integer",
68
+ "primary": true,
69
+ "nullable": false,
70
+ "unique": true,
71
+ "auto": true,
72
+ "cascadeOnDelete": true,
73
+ "lazyLoading": true,
74
+ "isNavigational": false,
75
+ "skipGetFunction": false,
76
+ "valueConversion": true
77
+ },
78
+ "body": {
79
+ "name": "body",
80
+ "type": "string",
81
+ "nullable": true,
82
+ "unique": false,
83
+ "auto": false,
84
+ "cascadeOnDelete": true,
85
+ "lazyLoading": true,
86
+ "isNavigational": false,
87
+ "skipGetFunction": false,
88
+ "valueConversion": true
89
+ },
90
+ "__compositeIndexes": [],
91
+ "__name": "Review"
92
+ }
93
+ ],
94
+ "seedData": {},
95
+ "seedConfig": {}
96
+ }
@@ -0,0 +1,26 @@
1
+
2
+ import context from "file:///Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/context.js";
3
+
4
+ class Author {
5
+ id(db) { db.integer().primary().auto(); }
6
+ name(db) { db.string(); }
7
+ }
8
+ class Book {
9
+ id(db) { db.integer().primary().auto(); }
10
+ title(db) { db.string(); }
11
+ }
12
+ class Review {
13
+ id(db) { db.integer().primary().auto(); }
14
+ body(db) { db.string(); }
15
+ }
16
+
17
+ class multimigctx extends context {
18
+ constructor() {
19
+ super();
20
+ this.env("/Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/test/fixtures/multi-migration-vsWfKD/config/environments");
21
+ this.dbset(Author);
22
+ this.dbset(Book);
23
+ this.dbset(Review);
24
+ }
25
+ }
26
+ export default multimigctx;
@@ -0,0 +1 @@
1
+ {"multimigctx":{"type":"better-sqlite3","connection":"/Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/test/fixtures/multi-migration-vsWfKD/db/"}}
@@ -0,0 +1 @@
1
+ {"name":"multi-migration-fixture","type":"module"}
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Regression for the "update-database only runs the latest migration file"
3
+ * bug. Spawns the real CLI against SQLite and asserts that:
4
+ * 1. With THREE pending migrations, all three are applied.
5
+ * 2. A second `update-database` run is a no-op (the tracking table filters
6
+ * out already-applied migrations).
7
+ * 3. `update-database-down` rolls back only the MOST RECENTLY APPLIED
8
+ * migration, not just the latest file on disk.
9
+ */
10
+
11
+ import { test } from 'node:test';
12
+ import assert from 'node:assert/strict';
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+ import { spawnSync } from 'node:child_process';
17
+ import Database from 'better-sqlite3';
18
+
19
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
20
+ const masterRecordRoot = path.resolve(__dirname, '..');
21
+ const cliEntry = path.join(masterRecordRoot, 'Migrations', 'cli.js');
22
+
23
+ // Each test sets up an isolated project directory with:
24
+ // - package.json (ESM)
25
+ // - config/environments/env.multimigctx.json
26
+ // - app/models/multimigctx.js (context)
27
+ // - app/models/db/migrations/<ts>_<name>_migration.js (3 files)
28
+ // - app/models/db/migrations/multimigctx_contextSnapShot.json
29
+ // - db/ (destination for SQLite file)
30
+
31
+ function makeProject() {
32
+ const projectDir = fs.mkdtempSync(path.join(masterRecordRoot, 'test', 'fixtures', 'multi-migration-'));
33
+ const envDir = path.join(projectDir, 'config', 'environments');
34
+ const modelsDir = path.join(projectDir, 'app', 'models');
35
+ const migrationsDir = path.join(modelsDir, 'db', 'migrations');
36
+ const dbDir = path.join(projectDir, 'db');
37
+
38
+ fs.mkdirSync(envDir, { recursive: true });
39
+ fs.mkdirSync(modelsDir, { recursive: true });
40
+ fs.mkdirSync(migrationsDir, { recursive: true });
41
+ fs.mkdirSync(dbDir, { recursive: true });
42
+
43
+ fs.writeFileSync(
44
+ path.join(projectDir, 'package.json'),
45
+ JSON.stringify({ name: 'multi-migration-fixture', type: 'module' })
46
+ );
47
+
48
+ fs.writeFileSync(
49
+ path.join(envDir, 'env.multimig.json'),
50
+ JSON.stringify({
51
+ multimigctx: {
52
+ type: 'better-sqlite3',
53
+ connection: dbDir + path.sep,
54
+ },
55
+ })
56
+ );
57
+
58
+ // Context file — 3 entities: Author, Book, Review
59
+ const mrPath = pathToImportSpecifier(path.join(masterRecordRoot, 'MasterRecord.js'));
60
+ const ctxPath = pathToImportSpecifier(path.join(masterRecordRoot, 'context.js'));
61
+ fs.writeFileSync(
62
+ path.join(modelsDir, 'multimigctx.js'),
63
+ `
64
+ import context from ${JSON.stringify(ctxPath)};
65
+
66
+ class Author {
67
+ id(db) { db.integer().primary().auto(); }
68
+ name(db) { db.string(); }
69
+ }
70
+ class Book {
71
+ id(db) { db.integer().primary().auto(); }
72
+ title(db) { db.string(); }
73
+ }
74
+ class Review {
75
+ id(db) { db.integer().primary().auto(); }
76
+ body(db) { db.string(); }
77
+ }
78
+
79
+ class multimigctx extends context {
80
+ constructor() {
81
+ super();
82
+ this.env(${JSON.stringify(envDir)});
83
+ this.dbset(Author);
84
+ this.dbset(Book);
85
+ this.dbset(Review);
86
+ }
87
+ }
88
+ export default multimigctx;
89
+ `
90
+ );
91
+
92
+ // Snapshot — lists all three entities as the current schema.
93
+ // The `schema` field must match what buildUpObject expects. Since this
94
+ // is an integration smoke test we construct it manually to reflect the
95
+ // current entity shape the context produces.
96
+ const entityShape = (name, cols) => {
97
+ const obj = { __name: name, __compositeIndexes: [] };
98
+ for (const [cname, def] of Object.entries(cols)) {
99
+ obj[cname] = { ...def, name: cname };
100
+ }
101
+ return obj;
102
+ };
103
+ const schema = [
104
+ entityShape('Author', {
105
+ id: { type: 'integer', primary: true, auto: true, nullable: false, unique: true },
106
+ name: { type: 'string', nullable: true },
107
+ }),
108
+ entityShape('Book', {
109
+ id: { type: 'integer', primary: true, auto: true, nullable: false, unique: true },
110
+ title: { type: 'string', nullable: true },
111
+ }),
112
+ entityShape('Review', {
113
+ id: { type: 'integer', primary: true, auto: true, nullable: false, unique: true },
114
+ body: { type: 'string', nullable: true },
115
+ }),
116
+ ];
117
+
118
+ fs.writeFileSync(
119
+ path.join(migrationsDir, 'multimigctx_contextSnapShot.json'),
120
+ JSON.stringify({
121
+ contextLocation: path.relative(migrationsDir, path.join(modelsDir, 'multimigctx.js')),
122
+ migrationFolder: '.',
123
+ snapShotLocation: 'multimigctx_contextSnapShot.json',
124
+ schema,
125
+ seedData: {},
126
+ seedConfig: {},
127
+ }, null, 2)
128
+ );
129
+
130
+ // Three migration files with ascending timestamps. Each creates one table.
131
+ // createTable is idempotent so running them all in sequence on a fresh DB
132
+ // produces all three tables.
133
+ const migFor = (ts, className, entityKey) => `
134
+ import masterrecord from ${JSON.stringify(mrPath)};
135
+ class ${className} extends masterrecord.schema {
136
+ constructor(context){ super(context); }
137
+ async up(table){
138
+ await this.init(table);
139
+ await this.createTable(table.${entityKey});
140
+ }
141
+ async down(table){
142
+ await this.init(table);
143
+ await this.dropTable(table.${entityKey});
144
+ }
145
+ }
146
+ export default ${className};
147
+ `;
148
+ const ts = [1700000001000, 1700000002000, 1700000003000];
149
+ fs.writeFileSync(path.join(migrationsDir, `${ts[0]}_CreateAuthor_migration.js`), migFor(ts[0], 'CreateAuthor', 'Author'));
150
+ fs.writeFileSync(path.join(migrationsDir, `${ts[1]}_CreateBook_migration.js`), migFor(ts[1], 'CreateBook', 'Book'));
151
+ fs.writeFileSync(path.join(migrationsDir, `${ts[2]}_CreateReview_migration.js`), migFor(ts[2], 'CreateReview', 'Review'));
152
+
153
+ return { projectDir, dbDir, migrationsDir, envDir };
154
+ }
155
+
156
+ function pathToImportSpecifier(absPath) {
157
+ // Import via absolute file URL so the fixture does not need node_modules.
158
+ return 'file://' + absPath;
159
+ }
160
+
161
+ function runCli(args, cwd) {
162
+ return spawnSync(process.execPath, [cliEntry, ...args], {
163
+ cwd,
164
+ env: { ...process.env, master: 'multimig' },
165
+ encoding: 'utf8',
166
+ });
167
+ }
168
+
169
+ function dbPath(dbDir) {
170
+ return path.join(dbDir, 'multimigctx.sqlite');
171
+ }
172
+
173
+ function tableNames(dbFile) {
174
+ const db = new Database(dbFile);
175
+ const rows = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' ORDER BY name`).all();
176
+ db.close();
177
+ return rows.map(r => r.name);
178
+ }
179
+
180
+ function appliedMigrationRows(dbFile) {
181
+ const db = new Database(dbFile);
182
+ const rows = db.prepare(`SELECT migration_name FROM _masterrecord_migrations ORDER BY migration_name`).all();
183
+ db.close();
184
+ return rows.map(r => r.migration_name);
185
+ }
186
+
187
+ test('update-database applies ALL pending migrations, not just the latest', () => {
188
+ const { projectDir, dbDir } = makeProject();
189
+ const result = runCli(['update-database', 'multimigctx'], projectDir);
190
+
191
+ assert.equal(result.status, 0, `CLI exited non-zero. stderr:\n${result.stderr}\nstdout:\n${result.stdout}`);
192
+
193
+ const file = dbPath(dbDir);
194
+ assert.ok(fs.existsSync(file), 'SQLite DB file should be created');
195
+
196
+ const tables = tableNames(file);
197
+ assert.ok(tables.includes('Author'), 'Author table should exist (from migration 1)');
198
+ assert.ok(tables.includes('Book'), 'Book table should exist (from migration 2)');
199
+ assert.ok(tables.includes('Review'), 'Review table should exist (from migration 3)');
200
+ assert.ok(tables.includes('_masterrecord_migrations'), 'migration tracking table should exist');
201
+
202
+ const applied = appliedMigrationRows(file);
203
+ assert.equal(applied.length, 3, `all three migrations should be recorded; got ${applied.length}: ${applied.join(', ')}`);
204
+ });
205
+
206
+ test('update-database is a no-op on the second run (tracking table filters)', () => {
207
+ const { projectDir, dbDir } = makeProject();
208
+ const first = runCli(['update-database', 'multimigctx'], projectDir);
209
+ assert.equal(first.status, 0, `first run failed. stderr:\n${first.stderr}`);
210
+
211
+ const second = runCli(['update-database', 'multimigctx'], projectDir);
212
+ assert.equal(second.status, 0, `second run failed. stderr:\n${second.stderr}`);
213
+ assert.match(second.stdout, /already applied|up to date/i, `expected no-op message on second run; got:\n${second.stdout}`);
214
+
215
+ const applied = appliedMigrationRows(dbPath(dbDir));
216
+ assert.equal(applied.length, 3, 'still exactly 3 applied rows after second run');
217
+ });
218
+
219
+ test('update-database-down rolls back the MOST RECENTLY APPLIED migration', () => {
220
+ const { projectDir, dbDir } = makeProject();
221
+ const up = runCli(['update-database', 'multimigctx'], projectDir);
222
+ assert.equal(up.status, 0, `up failed. stderr:\n${up.stderr}`);
223
+
224
+ assert.deepEqual(tableNames(dbPath(dbDir)).filter(n => !n.startsWith('_') && !n.startsWith('sqlite_')).sort(),
225
+ ['Author', 'Book', 'Review']);
226
+
227
+ const down = runCli(['update-database-down', 'multimigctx'], projectDir);
228
+ assert.equal(down.status, 0, `down failed. stderr:\n${down.stderr}`);
229
+
230
+ // Review was the latest migration; after down, Review should be gone,
231
+ // Author and Book should remain.
232
+ const tables = tableNames(dbPath(dbDir)).filter(n => !n.startsWith('_') && !n.startsWith('sqlite_'));
233
+ assert.ok(tables.includes('Author'), 'Author should still exist');
234
+ assert.ok(tables.includes('Book'), 'Book should still exist');
235
+ assert.ok(!tables.includes('Review'), 'Review should have been dropped by down()');
236
+
237
+ const applied = appliedMigrationRows(dbPath(dbDir));
238
+ assert.equal(applied.length, 2, `after down, 2 migrations should remain applied; got ${applied.join(', ')}`);
239
+ });