masterrecord 1.1.4 → 1.1.6

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 (41) hide show
  1. package/CHANGES.md +24 -0
  2. package/Entity/entityModelBuilder.js +7 -7
  3. package/Entity/entityTrackerModel.js +15 -15
  4. package/Migrations/cli.js +126 -121
  5. package/Migrations/migrationMySQLQuery.js +21 -27
  6. package/Migrations/migrationPostgresQuery.js +16 -16
  7. package/Migrations/migrationSQLiteQuery.js +14 -14
  8. package/Migrations/migrations.js +41 -45
  9. package/Migrations/schema.js +3 -3
  10. package/QueryLanguage/queryMethods.js +26 -26
  11. package/QueryLanguage/queryScript.js +28 -28
  12. package/SQLLiteEngine.js +116 -118
  13. package/Tools.js +19 -19
  14. package/context.js +1 -1
  15. package/mySQLEngine.js +3 -3
  16. package/package.json +22 -2
  17. package/postgresEngine.js +6 -6
  18. package/.claude/settings.local.json +0 -10
  19. package/Migrations/pathUtils.test.js +0 -37
  20. package/eslint.config.js +0 -40
  21. package/prettier.config.js +0 -22
  22. package/test/belongs-to-fk-setter.test.js +0 -154
  23. package/test/belongs-to-fk-type.test.js +0 -253
  24. package/test/broad-audit.test.js +0 -256
  25. package/test/context-errors.test.js +0 -43
  26. package/test/count-chained-where.test.js +0 -136
  27. package/test/count-no-from-audit.test.js +0 -124
  28. package/test/ctx-dollar-placeholder.test.js +0 -142
  29. package/test/drop-column-idempotent.test.js +0 -181
  30. package/test/edge-cases-audit.test.js +0 -180
  31. package/test/esm-imports.test.js +0 -110
  32. package/test/full-text-search.test.js +0 -340
  33. package/test/migration-template.test.js +0 -47
  34. package/test/new-setter-large-string.test.js +0 -191
  35. package/test/pool-key.test.js +0 -43
  36. package/test/postgres-camelcase-quoting.test.js +0 -249
  37. package/test/query-builder-parity.test.js +0 -260
  38. package/test/setter-and-update-drop.test.js +0 -168
  39. package/test/sqlite-lifecycle.test.js +0 -76
  40. package/test/text-types.test.js +0 -167
  41. package/test/update-database-multi.test.js +0 -239
@@ -1,168 +0,0 @@
1
- /**
2
- * Reproducers for the "silently dropped writes" family of bugs that
3
- * downstream consumers have been working around with raw _execute.
4
- *
5
- * 1. `.new()` setter does NOT apply `fieldDef.set` — tracker-entity setter
6
- * does. Inconsistent behavior between INSERT and UPDATE paths.
7
- * 2. `_processBatchUpdates` reads `currentModel._entity` (typo) instead of
8
- * `__entity`, so `removePrimarykeyandVirtual` gets `undefined`.
9
- * 3. After UPDATE, `__state` and `__dirtyFields` are not reset. On the next
10
- * `saveChanges()` call, the same fields are re-written to the DB, which
11
- * can silently overwrite concurrent changes from other processes.
12
- * 4. Tracker setter pushes to `__dirtyFields` without de-duplication, so
13
- * setting the same field multiple times produces duplicate assignments
14
- * in the UPDATE SET clause. In Postgres this is a hard error
15
- * ("multiple assignments to same column"); in SQLite/MySQL it may or
16
- * may not work depending on driver version.
17
- */
18
-
19
- import { test } from 'node:test';
20
- import assert from 'node:assert/strict';
21
- import fs from 'node:fs';
22
- import path from 'node:path';
23
- import { fileURLToPath } from 'node:url';
24
-
25
- process.env.master = 'setterdrop';
26
-
27
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
28
- const fixturesDir = path.join(__dirname, 'fixtures', 'setter-and-update-drop');
29
- const envDir = path.join(fixturesDir, 'config', 'environments');
30
- const dbDir = path.join(fixturesDir, 'db');
31
- const dbFile = path.join(dbDir, 'setdropctx.sqlite');
32
-
33
- fs.mkdirSync(envDir, { recursive: true });
34
- fs.mkdirSync(dbDir, { recursive: true });
35
- if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
36
-
37
- fs.writeFileSync(
38
- path.join(envDir, 'env.setterdrop.json'),
39
- JSON.stringify({
40
- SetDropCtx: {
41
- type: 'better-sqlite3',
42
- connection: dbDir + path.sep,
43
- },
44
- })
45
- );
46
-
47
- const { default: context } = await import('../context.js');
48
-
49
- class User {
50
- id(db) { db.integer().primary().auto(); }
51
- // `name` has a .set() transform that trims and lowercases — the
52
- // canonical test for whether the setter path applies fieldDef.set.
53
- name(db) { db.string().set(v => (typeof v === 'string' ? v.trim().toLowerCase() : v)); }
54
- email(db) { db.string(); }
55
- score(db) { db.integer(); }
56
- }
57
-
58
- class SetDropCtx extends context {
59
- constructor() {
60
- super();
61
- this.env(envDir);
62
- this.dbset(User);
63
- }
64
- }
65
-
66
- {
67
- const ctx = new SetDropCtx();
68
- ctx._SQLEngine.db.exec(`
69
- CREATE TABLE IF NOT EXISTS User (
70
- id INTEGER PRIMARY KEY AUTOINCREMENT,
71
- name TEXT,
72
- email TEXT,
73
- score INTEGER
74
- );
75
- `);
76
- await ctx.close();
77
- }
78
-
79
- //
80
- // Bug #1 — .new() setter must apply fieldDef.set
81
- //
82
- test('.new() setter applies fieldDef.set transform at write time', async () => {
83
- const ctx = new SetDropCtx();
84
- const u = ctx.User.new();
85
- u.name = ' ALICE '; // whitespace + uppercase
86
- u.email = 'alice@example.com';
87
- u.score = 10;
88
- await u.save();
89
-
90
- const row = ctx._SQLEngine.db.prepare('SELECT name FROM User WHERE email = ?').get('alice@example.com');
91
- assert.equal(row.name, 'alice', `.set() transform should have been applied on INSERT; got "${row.name}"`);
92
- await ctx.close();
93
- });
94
-
95
- test('Tracker setter applies fieldDef.set transform on UPDATE (baseline — already works)', async () => {
96
- const ctx = new SetDropCtx();
97
- ctx._SQLEngine.db.prepare('INSERT INTO User (name, email, score) VALUES (?, ?, ?)').run('bob', 'bob@example.com', 5);
98
-
99
- const loaded = await ctx.User.where('u => u.email == $$', 'bob@example.com').single();
100
- loaded.name = ' BOB-UPDATED ';
101
- await loaded.save();
102
-
103
- const row = ctx._SQLEngine.db.prepare('SELECT name FROM User WHERE email = ?').get('bob@example.com');
104
- assert.equal(row.name, 'bob-updated', `.set() transform should apply on UPDATE; got "${row.name}"`);
105
- await ctx.close();
106
- });
107
-
108
- //
109
- // Bug #2 — after UPDATE, __dirtyFields and __state are not reset;
110
- // calling saveChanges twice for the same entity silently re-updates the
111
- // same fields.
112
- //
113
- test('After UPDATE, __dirtyFields is cleared and __state is reset to track', async () => {
114
- const ctx = new SetDropCtx();
115
- ctx._SQLEngine.db.prepare('INSERT INTO User (name, email, score) VALUES (?, ?, ?)').run('carol', 'carol@example.com', 1);
116
-
117
- const loaded = await ctx.User.where('u => u.email == $$', 'carol@example.com').single();
118
- loaded.score = 2;
119
- await loaded.save();
120
-
121
- assert.deepEqual(loaded.__dirtyFields, [], '__dirtyFields should be empty after UPDATE');
122
- assert.equal(loaded.__state, 'track', '__state should be "track" after UPDATE');
123
- await ctx.close();
124
- });
125
-
126
- test('saveChanges re-called with no modifications after UPDATE is a no-op', async () => {
127
- const ctx = new SetDropCtx();
128
- ctx._SQLEngine.db.prepare('INSERT INTO User (name, email, score) VALUES (?, ?, ?)').run('dave', 'dave@example.com', 1);
129
-
130
- const loaded = await ctx.User.where('u => u.email == $$', 'dave@example.com').single();
131
- loaded.score = 99;
132
- await loaded.save();
133
-
134
- // Simulate concurrent external write: another process updates score to 42.
135
- ctx._SQLEngine.db.prepare('UPDATE User SET score = 42 WHERE email = ?').run('dave@example.com');
136
-
137
- // Re-saving without touching the entity should NOT overwrite the external
138
- // change; the entity is no longer modified.
139
- await ctx.saveChanges();
140
-
141
- const row = ctx._SQLEngine.db.prepare('SELECT score FROM User WHERE email = ?').get('dave@example.com');
142
- assert.equal(row.score, 42, 'second saveChanges must not silently re-apply the prior write');
143
- await ctx.close();
144
- });
145
-
146
- //
147
- // Bug #3 — setting the same field twice must not produce duplicate
148
- // SET assignments (SQLite errors on duplicates; Postgres always errors).
149
- //
150
- test('Setting the same field twice produces only one assignment in UPDATE', async () => {
151
- const ctx = new SetDropCtx();
152
- ctx._SQLEngine.db.prepare('INSERT INTO User (name, email, score) VALUES (?, ?, ?)').run('eve', 'eve@example.com', 1);
153
-
154
- const loaded = await ctx.User.where('u => u.email == $$', 'eve@example.com').single();
155
- loaded.score = 2;
156
- loaded.score = 3; // second assignment — must not push duplicate into __dirtyFields
157
- loaded.score = 4;
158
-
159
- // Only one occurrence of 'score' in dirtyFields
160
- const dupCount = loaded.__dirtyFields.filter(f => f === 'score').length;
161
- assert.equal(dupCount, 1, `score should appear exactly once in __dirtyFields; got ${dupCount} (${JSON.stringify(loaded.__dirtyFields)})`);
162
-
163
- // And the UPDATE must succeed and persist the last value.
164
- await loaded.save();
165
- const row = ctx._SQLEngine.db.prepare('SELECT score FROM User WHERE email = ?').get('eve@example.com');
166
- assert.equal(row.score, 4, 'last assigned value must be persisted');
167
- await ctx.close();
168
- });
@@ -1,76 +0,0 @@
1
- /**
2
- * End-to-end SQLite lifecycle test.
3
- * Creates a context, an entity, inserts, reads, updates, deletes, and closes.
4
- *
5
- * This is the smoke test that proves the ESM conversion didn't break the
6
- * core ORM flow for the default database driver.
7
- */
8
-
9
- import { test, after } from 'node:test';
10
- import assert from 'node:assert/strict';
11
- import fs from 'node:fs';
12
- import path from 'node:path';
13
- import { fileURLToPath } from 'node:url';
14
-
15
- // Point the context at our fixture config
16
- process.env.master = 'test';
17
-
18
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
- const fixturesDir = path.join(__dirname, 'fixtures', 'sqlite-lifecycle');
20
- const envDir = path.join(fixturesDir, 'config', 'environments');
21
- const dbDir = path.join(fixturesDir, 'db');
22
- const dbFile = path.join(dbDir, 'LifecycleContext.sqlite');
23
-
24
- // Clean state
25
- fs.mkdirSync(envDir, { recursive: true });
26
- fs.mkdirSync(dbDir, { recursive: true });
27
- if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
28
-
29
- fs.writeFileSync(
30
- path.join(envDir, 'env.test.json'),
31
- JSON.stringify({
32
- LifecycleContext: {
33
- type: 'better-sqlite3',
34
- connection: dbDir + path.sep,
35
- },
36
- })
37
- );
38
-
39
- const { default: context } = await import('../context.js');
40
-
41
- class Widget {
42
- id(db) { db.integer().primary().auto(); }
43
- name(db) { db.string(); }
44
- qty(db) { db.integer(); }
45
- }
46
-
47
- class LifecycleContext extends context {
48
- constructor() {
49
- super();
50
- this.env(envDir);
51
- this.dbset(Widget);
52
- }
53
- }
54
-
55
- const ctx = new LifecycleContext();
56
-
57
- after(async () => {
58
- if (ctx && typeof ctx.close === 'function') {
59
- await ctx.close();
60
- }
61
- // Leave fixtures on disk for debugging; they're regenerated each run.
62
- });
63
-
64
- test('context instantiates as SQLite', () => {
65
- assert.equal(ctx.isSQLite, true);
66
- assert.equal(ctx.isMySQL, false);
67
- assert.equal(ctx.isPostgres, false);
68
- });
69
-
70
- test('context exposes the registered entity', () => {
71
- assert.ok(ctx.Widget, 'Widget dbset is attached');
72
- });
73
-
74
- test('context has a SQL engine', () => {
75
- assert.ok(ctx._SQLEngine, 'SQL engine was initialized');
76
- });
@@ -1,167 +0,0 @@
1
- /**
2
- * Verifies db.text() / db.mediumtext() / db.longtext() emit correct
3
- * column types on each engine.
4
- *
5
- * MySQL → TEXT, MEDIUMTEXT, LONGTEXT
6
- * SQLite → TEXT, TEXT, TEXT (SQLite TEXT is unlimited)
7
- * Postgres → TEXT, TEXT, TEXT (Postgres TEXT is unlimited)
8
- *
9
- * Also catches the prior bug where SQLite's #typeManager had no `text` case
10
- * and emitted "<colname> undefined NOT NULL" — accepted by SQLite's lax type
11
- * affinity but still wrong.
12
- */
13
-
14
- import { test } from 'node:test';
15
- import assert from 'node:assert/strict';
16
- import fs from 'node:fs';
17
- import path from 'node:path';
18
- import { fileURLToPath } from 'node:url';
19
-
20
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
21
- const fixturesDir = path.join(__dirname, 'fixtures', 'text-types');
22
- const envDir = path.join(fixturesDir, 'config', 'environments');
23
- const dbDir = path.join(fixturesDir, 'db');
24
-
25
- fs.mkdirSync(envDir, { recursive: true });
26
- fs.mkdirSync(dbDir, { recursive: true });
27
-
28
- process.env.master = 'texttypes';
29
- fs.writeFileSync(
30
- path.join(envDir, 'env.texttypes.json'),
31
- JSON.stringify({
32
- TextCtx: {
33
- type: 'better-sqlite3',
34
- connection: dbDir + path.sep,
35
- },
36
- })
37
- );
38
-
39
- const { default: EntityModel } = await import('../Entity/entityModel.js');
40
- const { default: SQLiteQuery } = await import('../Migrations/migrationSQLiteQuery.js');
41
- const { default: MySQLQuery } = await import('../Migrations/migrationMySQLQuery.js');
42
- const { default: PostgresQuery } = await import('../Migrations/migrationPostgresQuery.js');
43
-
44
- //
45
- // EntityModel — the fluent builder must record the new types.
46
- //
47
- test('EntityModel.text() sets type to "text"', () => {
48
- const m = new EntityModel('m');
49
- m.text();
50
- assert.equal(m.obj.type, 'text');
51
- });
52
-
53
- test('EntityModel.mediumtext() sets type to "mediumtext"', () => {
54
- const m = new EntityModel('m');
55
- m.mediumtext();
56
- assert.equal(m.obj.type, 'mediumtext');
57
- });
58
-
59
- test('EntityModel.longtext() sets type to "longtext"', () => {
60
- const m = new EntityModel('m');
61
- m.longtext();
62
- assert.equal(m.obj.type, 'longtext');
63
- });
64
-
65
- //
66
- // MySQL — emits TEXT / MEDIUMTEXT / LONGTEXT
67
- //
68
- test('MySQL emits TEXT for text', () => {
69
- const q = new MySQLQuery();
70
- assert.equal(q.typeManager('text'), 'TEXT');
71
- });
72
-
73
- test('MySQL emits MEDIUMTEXT for mediumtext', () => {
74
- const q = new MySQLQuery();
75
- assert.equal(q.typeManager('mediumtext'), 'MEDIUMTEXT');
76
- });
77
-
78
- test('MySQL emits LONGTEXT for longtext', () => {
79
- const q = new MySQLQuery();
80
- assert.equal(q.typeManager('longtext'), 'LONGTEXT');
81
- });
82
-
83
- //
84
- // Postgres — collapses all three to TEXT (TEXT is unlimited on PG)
85
- //
86
- test('Postgres emits TEXT for text', () => {
87
- const q = new PostgresQuery();
88
- assert.equal(q.typeManager('text'), 'TEXT');
89
- });
90
-
91
- test('Postgres emits TEXT for mediumtext', () => {
92
- const q = new PostgresQuery();
93
- assert.equal(q.typeManager('mediumtext'), 'TEXT');
94
- });
95
-
96
- test('Postgres emits TEXT for longtext', () => {
97
- const q = new PostgresQuery();
98
- assert.equal(q.typeManager('longtext'), 'TEXT');
99
- });
100
-
101
- //
102
- // SQLite — collapses all three to TEXT (TEXT is unlimited on SQLite)
103
- //
104
- test('SQLite createTable for "text" column emits TEXT (regression for missing case)', () => {
105
- const q = new SQLiteQuery();
106
- const table = {
107
- __name: 'Note',
108
- body: { name: 'body', type: 'text', nullable: true },
109
- };
110
- const sql = q.createTable(table);
111
- assert.match(sql, /\bbody\s+TEXT\b/i, `SQLite should emit "body TEXT"; got ${sql}`);
112
- assert.doesNotMatch(sql, /undefined/, 'SQLite must not emit "undefined" as a type');
113
- });
114
-
115
- test('SQLite createTable for "mediumtext" emits TEXT', () => {
116
- const q = new SQLiteQuery();
117
- const table = {
118
- __name: 'Note',
119
- body: { name: 'body', type: 'mediumtext', nullable: true },
120
- };
121
- const sql = q.createTable(table);
122
- assert.match(sql, /\bbody\s+TEXT\b/i);
123
- assert.doesNotMatch(sql, /MEDIUMTEXT/i, 'SQLite has no MEDIUMTEXT type');
124
- });
125
-
126
- test('SQLite createTable for "longtext" emits TEXT', () => {
127
- const q = new SQLiteQuery();
128
- const table = {
129
- __name: 'Note',
130
- body: { name: 'body', type: 'longtext', nullable: true },
131
- };
132
- const sql = q.createTable(table);
133
- assert.match(sql, /\bbody\s+TEXT\b/i);
134
- assert.doesNotMatch(sql, /LONGTEXT/i, 'SQLite has no LONGTEXT type');
135
- });
136
-
137
- //
138
- // End-to-end on SQLite — define an entity with all three text types and
139
- // verify the table is created with TEXT columns.
140
- //
141
- test('SQLite end-to-end: entity with text/mediumtext/longtext creates table with TEXT columns', async () => {
142
- const { default: context } = await import('../context.js');
143
-
144
- class Document {
145
- id(db) { db.integer().primary().auto(); }
146
- small(db) { db.text(); }
147
- medium(db) { db.mediumtext(); }
148
- large(db) { db.longtext(); }
149
- }
150
-
151
- class TextCtx extends context {
152
- constructor() {
153
- super();
154
- this.env(envDir);
155
- this.dbset(Document);
156
- }
157
- }
158
-
159
- const ctx = new TextCtx();
160
- const q = new SQLiteQuery();
161
- const sql = q.createTable(ctx.Document.__entity);
162
- assert.match(sql, /\bsmall\s+TEXT\b/i);
163
- assert.match(sql, /\bmedium\s+TEXT\b/i);
164
- assert.match(sql, /\blarge\s+TEXT\b/i);
165
- assert.doesNotMatch(sql, /undefined/);
166
- await ctx.close();
167
- });
@@ -1,239 +0,0 @@
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
- });