masterrecord 1.1.3 → 1.1.5

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.
@@ -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
- });