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,124 +0,0 @@
1
- /**
2
- * Verifies the `.count()` without-prior-`.where()` bug is resolved on
3
- * all three engines. The SQLite bug manifested because SQLite's getEntity
4
- * returned "" on fallthrough (MySQL/Postgres returned the name), plus
5
- * queryMethods.count() didn't bootstrap the entityMap like single()/toList()
6
- * did. Both fixes are engine-agnostic; this test verifies no engine
7
- * regresses.
8
- *
9
- * Strategy: build a query state via the real fluent API, then feed it to
10
- * each engine's COUNT path. Assert the generated SQL has a FROM clause
11
- * and includes COUNT(*).
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
- process.env.master = 'countfrom';
21
-
22
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
23
- const fixturesDir = path.join(__dirname, 'fixtures', 'count-no-from');
24
- const envDir = path.join(fixturesDir, 'config', 'environments');
25
- const dbDir = path.join(fixturesDir, 'db');
26
- const dbFile = path.join(dbDir, 'countctx.sqlite');
27
-
28
- fs.mkdirSync(envDir, { recursive: true });
29
- fs.mkdirSync(dbDir, { recursive: true });
30
- if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
31
-
32
- fs.writeFileSync(
33
- path.join(envDir, 'env.countfrom.json'),
34
- JSON.stringify({
35
- CountFromCtx: {
36
- type: 'better-sqlite3',
37
- connection: dbDir + path.sep,
38
- },
39
- })
40
- );
41
-
42
- const { default: context } = await import('../context.js');
43
- const { default: SQLiteEngine } = await import('../SQLLiteEngine.js');
44
- const { default: MySQLEngine } = await import('../mySQLEngine.js');
45
- const { default: PostgresEngine } = await import('../postgresEngine.js');
46
-
47
- class Thing {
48
- id(db) { db.integer().primary().auto(); }
49
- label(db) { db.string(); }
50
- }
51
-
52
- class CountFromCtx extends context {
53
- constructor() {
54
- super();
55
- this.env(envDir);
56
- this.dbset(Thing);
57
- }
58
- }
59
-
60
- {
61
- const ctx = new CountFromCtx();
62
- ctx._SQLEngine.db.exec(`
63
- CREATE TABLE IF NOT EXISTS Thing (
64
- id INTEGER PRIMARY KEY AUTOINCREMENT,
65
- label TEXT
66
- );
67
- `);
68
- const insert = ctx._SQLEngine.db.prepare('INSERT INTO Thing (label) VALUES (?)');
69
- insert.run('a'); insert.run('b'); insert.run('c'); insert.run('d');
70
- await ctx.close();
71
- }
72
-
73
- // End-to-end SQLite test — the only engine we can actually run.
74
- test('SQLite: .count() with no prior .where() returns the correct row count (not 1)', async () => {
75
- const db = new CountFromCtx();
76
- const n = await db.Thing.count();
77
- assert.equal(n, 4, 'count() must reflect actual row count, not silently return 1');
78
- await db.close();
79
- });
80
-
81
- // For MySQL and Postgres, we snapshot the SQL that getCount would build.
82
- // We can't run them without a connection, but the string output is enough
83
- // to prove the FROM clause and COUNT(*) are present.
84
- function snapshotFluentState() {
85
- const ctx = new CountFromCtx();
86
- // Mirror what `.count()` does internally: bootstrap entityMap via skipClause
87
- // when the user calls count() without a prior .where().
88
- const builder = ctx.Thing;
89
- if (builder.__queryObject.script.entityMap.length === 0) {
90
- builder.__queryObject.skipClause(ctx.Thing.__entity.__name);
91
- }
92
- const script = builder.__queryObject.script;
93
- script.count = 'none'; // matches what getCount sets when count is undefined
94
- const entity = ctx.Thing.__entity;
95
- ctx.close();
96
- return { script, entity };
97
- }
98
-
99
- test('MySQL: COUNT SQL has a FROM clause even with no prior .where()', () => {
100
- const { script, entity } = snapshotFluentState();
101
- const engine = new MySQLEngine();
102
- const sql = `SELECT ${engine.buildCount(script, entity)} ${engine.buildFrom(script, entity)} ${engine.buildWhere(script, entity)} ${engine.buildAnd(script, entity)}`;
103
- assert.match(sql, /SELECT\s+COUNT\(\*\)/, 'emits COUNT(*)');
104
- assert.match(sql, /FROM\s+`Thing`/, 'has FROM clause with backtick-quoted table');
105
- });
106
-
107
- test('Postgres: COUNT SQL has a FROM clause even with no prior .where()', () => {
108
- const { script, entity } = snapshotFluentState();
109
- const engine = new PostgresEngine();
110
- const sql = `SELECT ${engine.buildCount(script, entity)} ${engine.buildFrom(script, entity)} ${engine.buildWhere(script, entity)} ${engine.buildAnd(script, entity)}`;
111
- // Postgres buildCount emits COUNT(alias.*) when count is 'none' — we
112
- // accept either shape here since the bug under test is about FROM, not
113
- // the exact COUNT expression.
114
- assert.match(sql, /SELECT\s+COUNT\(/, 'emits SELECT COUNT(...)');
115
- assert.match(sql, /FROM\s+"?Thing"?/, 'has FROM clause naming the table (quoted or unquoted)');
116
- });
117
-
118
- test('SQLite engine directly: buildFrom on empty entityMap now produces a valid FROM', () => {
119
- const engine = new SQLiteEngine();
120
- const fakeScript = { entityMap: [], parentName: '' };
121
- const fakeEntity = { __name: 'Thing' };
122
- const from = engine.buildFrom(fakeScript, fakeEntity);
123
- assert.match(from, /^FROM\s+Thing\b/, `empty entityMap should now produce a FROM clause; got "${from}"`);
124
- });
@@ -1,142 +0,0 @@
1
- /**
2
- * Verifies `ctx.$$` (and `this.$$` from inside a context method) work as
3
- * a TypeScript/ESLint-clean alias for the bare `$$` placeholder.
4
- *
5
- * ctx.User.where(u => u.id == ctx.$$, 42)
6
- * ctx.User.where(u => u.id == this.$$, 42)
7
- * ctx.User.where('u => u.id == $$', 42) // legacy bare form still works
8
- *
9
- * All three must produce the same SQL parameters and return the same rows.
10
- */
11
-
12
- import { test } from 'node:test';
13
- import assert from 'node:assert/strict';
14
- import fs from 'node:fs';
15
- import path from 'node:path';
16
- import { fileURLToPath } from 'node:url';
17
-
18
- process.env.master = 'ctxdollar';
19
-
20
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
21
- const fixturesDir = path.join(__dirname, 'fixtures', 'ctx-dollar');
22
- const envDir = path.join(fixturesDir, 'config', 'environments');
23
- const dbDir = path.join(fixturesDir, 'db');
24
- const dbFile = path.join(dbDir, 'dollarctx.sqlite');
25
-
26
- fs.mkdirSync(envDir, { recursive: true });
27
- fs.mkdirSync(dbDir, { recursive: true });
28
- if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
29
-
30
- fs.writeFileSync(
31
- path.join(envDir, 'env.ctxdollar.json'),
32
- JSON.stringify({
33
- DollarCtx: {
34
- type: 'better-sqlite3',
35
- connection: dbDir + path.sep,
36
- },
37
- })
38
- );
39
-
40
- const { default: context } = await import('../context.js');
41
-
42
- class Plugin {
43
- id(db) { db.integer().primary().auto(); }
44
- name(db) { db.string(); }
45
- version(db) { db.string(); }
46
- }
47
-
48
- class DollarCtx extends context {
49
- constructor() {
50
- super();
51
- this.env(envDir);
52
- this.dbset(Plugin);
53
- }
54
- }
55
-
56
- {
57
- const ctx = new DollarCtx();
58
- ctx._SQLEngine.db.exec(`
59
- CREATE TABLE IF NOT EXISTS Plugin (
60
- id INTEGER PRIMARY KEY AUTOINCREMENT,
61
- name TEXT,
62
- version TEXT
63
- );
64
- `);
65
- const insert = ctx._SQLEngine.db.prepare('INSERT INTO Plugin (name, version) VALUES (?, ?)');
66
- insert.run('provider-openai', '1.0');
67
- insert.run('provider-anthropic', '1.2');
68
- insert.run('provider-google', '0.9');
69
- await ctx.close();
70
- }
71
-
72
- test('context.$$ getter returns the literal "$$" string', () => {
73
- const ctx = new DollarCtx();
74
- assert.equal(ctx.$$, '$$');
75
- });
76
-
77
- test('bare $$ in a string lambda still works (legacy form)', async () => {
78
- const ctx = new DollarCtx();
79
- const row = await ctx.Plugin
80
- .where('p => p.name == $$', 'provider-openai')
81
- .single();
82
- assert.ok(row);
83
- assert.equal(row.name, 'provider-openai');
84
- await ctx.close();
85
- });
86
-
87
- test('ctx.$$ in an arrow lambda matches the same row', async () => {
88
- const ctx = new DollarCtx();
89
- const row = await ctx.Plugin
90
- .where((p) => p.name == ctx.$$, 'provider-openai')
91
- .single();
92
- assert.ok(row);
93
- assert.equal(row.name, 'provider-openai');
94
- await ctx.close();
95
- });
96
-
97
- test('this.$$ inside a context method works the same way', async () => {
98
- const ctx = new DollarCtx();
99
- // Bind `this` to the context. This mirrors what user code looks like
100
- // when `findByName` is defined as an instance method on the context
101
- // class itself.
102
- const findByName = async function (name) {
103
- return this.Plugin.where((p) => p.name == this.$$, name).single();
104
- };
105
- const row = await findByName.call(ctx, 'provider-anthropic');
106
- assert.ok(row);
107
- assert.equal(row.name, 'provider-anthropic');
108
- await ctx.close();
109
- });
110
-
111
- test('multiple ctx.$$ placeholders in one lambda', async () => {
112
- const ctx = new DollarCtx();
113
- const rows = await ctx.Plugin
114
- .where((p) => p.name == ctx.$$ || p.name == ctx.$$, 'provider-openai', 'provider-google')
115
- .toList();
116
- const names = rows.map(r => r.name).sort();
117
- assert.deepEqual(names, ['provider-google', 'provider-openai']);
118
- await ctx.close();
119
- });
120
-
121
- test('mixing ctx.$$ and bare $$ in the same lambda', async () => {
122
- const ctx = new DollarCtx();
123
- // First placeholder uses ctx.$$, second uses bare $$
124
- const rows = await ctx.Plugin
125
- .where(`p => p.name == ctx.$$ || p.version == $$`, 'provider-openai', '1.2')
126
- .toList();
127
- const names = rows.map(r => r.name).sort();
128
- assert.deepEqual(names, ['provider-anthropic', 'provider-openai']);
129
- await ctx.close();
130
- });
131
-
132
- test('orderBy and other clauses also accept ctx.$$', async () => {
133
- const ctx = new DollarCtx();
134
- // orderBy doesn't take placeholders, but where chained with orderBy should still work
135
- const rows = await ctx.Plugin
136
- .where((p) => p.version != ctx.$$, '0.9')
137
- .orderBy('p => p.name')
138
- .toList();
139
- assert.equal(rows.length, 2);
140
- assert.deepEqual(rows.map(r => r.name), ['provider-anthropic', 'provider-openai']);
141
- await ctx.close();
142
- });
@@ -1,181 +0,0 @@
1
- /**
2
- * Regression for two related 1.0.8 fixes:
3
- *
4
- * 1. postgresEngine was missing getTableInfo() — schema.syncTable() couldn't
5
- * diff against the existing schema, so re-running migrations failed with
6
- * `column "X" already exists`.
7
- *
8
- * 2. DROP COLUMN DDL was not idempotent — Postgres/MySQL didn't emit
9
- * `IF EXISTS` and SQLite had no runtime guard, so re-running a
10
- * drop-column migration after a failed/partial run errored with
11
- * `column "X" does not exist`.
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
- process.env.master = 'dropcol';
21
-
22
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
23
- const fixturesDir = path.join(__dirname, 'fixtures', 'drop-col');
24
- const envDir = path.join(fixturesDir, 'config', 'environments');
25
- const dbDir = path.join(fixturesDir, 'db');
26
- const dbFile = path.join(dbDir, 'dropcolctx.sqlite');
27
-
28
- fs.mkdirSync(envDir, { recursive: true });
29
- fs.mkdirSync(dbDir, { recursive: true });
30
- if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
31
-
32
- fs.writeFileSync(
33
- path.join(envDir, 'env.dropcol.json'),
34
- JSON.stringify({
35
- DropColCtx: {
36
- type: 'better-sqlite3',
37
- connection: dbDir + path.sep,
38
- },
39
- })
40
- );
41
-
42
- const { default: context } = await import('../context.js');
43
- const { default: schema } = await import('../Migrations/schema.js');
44
- const { default: PostgresEngine } = await import('../postgresEngine.js');
45
- const { default: MySQLEngine } = await import('../mySQLEngine.js');
46
- const { default: SQLiteQuery } = await import('../Migrations/migrationSQLiteQuery.js');
47
- const { default: MySQLQuery } = await import('../Migrations/migrationMySQLQuery.js');
48
- const { default: PostgresQuery } = await import('../Migrations/migrationPostgresQuery.js');
49
-
50
- // ---- DDL string-level checks (no DB connection required) ----
51
-
52
- test('Postgres dropColumn emits IF EXISTS with quoted identifiers', () => {
53
- const q = new PostgresQuery();
54
- const sql = q.dropColumn({ tableName: 'SchedulerLeader', name: 'staleField' });
55
- assert.match(sql, /ALTER TABLE "SchedulerLeader" DROP COLUMN IF EXISTS "staleField"/);
56
- });
57
-
58
- test('MySQL dropColumn emits IF EXISTS with backtick quotes', () => {
59
- const q = new MySQLQuery();
60
- const sql = q.dropColumn({ tableName: 'User', name: 'legacyField' });
61
- assert.match(sql, /ALTER TABLE `User` DROP COLUMN IF EXISTS `legacyField`/);
62
- });
63
-
64
- test('SQLite dropColumn quotes identifiers with square brackets', () => {
65
- const q = new SQLiteQuery();
66
- const sql = q.dropColumn({ tableName: 'User', name: 'legacyField' });
67
- assert.match(sql, /ALTER TABLE \[User\] DROP COLUMN \[legacyField\]/);
68
- // SQLite has no `IF EXISTS` on DROP COLUMN; the guard lives in schema.dropColumn().
69
- assert.doesNotMatch(sql, /IF EXISTS/);
70
- });
71
-
72
- // ---- Postgres getTableInfo presence ----
73
-
74
- test('Postgres engine exposes getTableInfo()', () => {
75
- const engine = new PostgresEngine();
76
- assert.equal(typeof engine.getTableInfo, 'function');
77
- });
78
-
79
- test('Postgres getTableInfo returns rows shaped like SQLite/MySQL counterparts', async () => {
80
- const engine = new PostgresEngine();
81
- // Stub _runWithParams so we can verify the SQL without a live Postgres.
82
- let capturedSql;
83
- let capturedParams;
84
- engine._runWithParams = async (sql, params) => {
85
- capturedSql = sql;
86
- capturedParams = params;
87
- return {
88
- rows: [
89
- { name: 'id', dflt_value: null, is_nullable: 'NO', data_type: 'integer' },
90
- { name: 'createdAt', dflt_value: null, is_nullable: 'YES', data_type: 'timestamp without time zone' },
91
- ],
92
- };
93
- };
94
- const rows = await engine.getTableInfo('SchedulerLeader');
95
- assert.match(capturedSql, /information_schema\.columns/);
96
- assert.match(capturedSql, /table_name\s*=\s*\$1/);
97
- assert.deepEqual(capturedParams, ['SchedulerLeader']);
98
- assert.equal(rows.length, 2);
99
- assert.equal(rows[0].name, 'id');
100
- assert.equal(rows[1].name, 'createdAt');
101
- // Field names mirror SQLite's PRAGMA table_info / MySQL's INFORMATION_SCHEMA query.
102
- for (const key of ['name', 'dflt_value', 'is_nullable', 'data_type']) {
103
- assert.ok(key in rows[0], `expected '${key}' in row`);
104
- }
105
- });
106
-
107
- test('Postgres getTableInfo returns [] on error', async () => {
108
- const engine = new PostgresEngine();
109
- engine._runWithParams = async () => { throw new Error('boom'); };
110
- assert.deepEqual(await engine.getTableInfo('Whatever'), []);
111
- });
112
-
113
- // ---- SQLite end-to-end: dropColumn twice in a row must not throw ----
114
-
115
- class Widget {
116
- id(db) { db.integer().primary().auto(); }
117
- name(db) { db.string(); }
118
- legacyField(db) { db.string(); }
119
- }
120
-
121
- class DropColCtx extends context {
122
- constructor() {
123
- super();
124
- this.env(envDir);
125
- this.dbset(Widget);
126
- }
127
- }
128
-
129
- {
130
- // Seed the schema using raw SQL so we don't depend on the rest of the
131
- // migration pipeline for setup.
132
- const ctx = new DropColCtx();
133
- ctx._SQLEngine.db.exec(`
134
- CREATE TABLE IF NOT EXISTS Widget (
135
- id INTEGER PRIMARY KEY AUTOINCREMENT,
136
- name TEXT,
137
- legacyField TEXT
138
- );
139
- `);
140
- await ctx.close();
141
- }
142
-
143
- test('SQLite schema.dropColumn() is idempotent (re-running does not throw)', async () => {
144
- const ctx = new DropColCtx();
145
- const sch = new schema(DropColCtx);
146
- await sch._ensureReady();
147
- // schema.dropColumn() gates on `this.fullTable` being truthy as a "did
148
- // init run" sentinel. Real migrations get a real tableObj here; tests
149
- // just need a truthy value to pass the gate.
150
- sch.fullTable = { __name: 'Widget' };
151
-
152
- // Confirm the column exists initially.
153
- const before = await ctx._SQLEngine.getTableInfo('Widget');
154
- assert.ok(before.some(c => c.name === 'legacyField'), 'precondition: legacyField column exists');
155
-
156
- // First drop: removes the column.
157
- await sch.dropColumn({ tableName: 'Widget', name: 'legacyField' });
158
- const afterFirst = await ctx._SQLEngine.getTableInfo('Widget');
159
- assert.ok(!afterFirst.some(c => c.name === 'legacyField'), 'column was dropped');
160
-
161
- // Second drop: must be a no-op, not an error. This is the regression
162
- // that 1.0.8 fixes — without the runtime guard in schema.dropColumn(),
163
- // SQLite would have thrown "no such column: legacyField".
164
- await assert.doesNotReject(
165
- sch.dropColumn({ tableName: 'Widget', name: 'legacyField' }),
166
- 'second dropColumn must be idempotent'
167
- );
168
-
169
- await ctx.close();
170
- });
171
-
172
- test('SQLite schema.dropColumn() on a never-existed column is also a no-op', async () => {
173
- const ctx = new DropColCtx();
174
- const sch = new schema(DropColCtx);
175
- await sch._ensureReady();
176
- sch.fullTable = { __name: 'Widget' };
177
- await assert.doesNotReject(
178
- sch.dropColumn({ tableName: 'Widget', name: 'neverExisted' })
179
- );
180
- await ctx.close();
181
- });
@@ -1,180 +0,0 @@
1
- /**
2
- * Second-pass audit: edge cases and less-common API surfaces.
3
- */
4
-
5
- import { test } from 'node:test';
6
- import assert from 'node:assert/strict';
7
- import fs from 'node:fs';
8
- import path from 'node:path';
9
- import { fileURLToPath } from 'node:url';
10
-
11
- process.env.master = 'edgeaudit';
12
-
13
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
- const fixturesDir = path.join(__dirname, 'fixtures', 'edge-cases-audit');
15
- const envDir = path.join(fixturesDir, 'config', 'environments');
16
- const dbDir = path.join(fixturesDir, 'db');
17
- const dbFile = path.join(dbDir, 'edgectx.sqlite');
18
-
19
- fs.mkdirSync(envDir, { recursive: true });
20
- fs.mkdirSync(dbDir, { recursive: true });
21
- if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
22
-
23
- fs.writeFileSync(
24
- path.join(envDir, 'env.edgeaudit.json'),
25
- JSON.stringify({
26
- EdgeCtx: {
27
- type: 'better-sqlite3',
28
- connection: dbDir + path.sep,
29
- },
30
- })
31
- );
32
-
33
- const { default: context } = await import('../context.js');
34
-
35
- class Widget {
36
- id(db) { db.integer().primary().auto(); }
37
- sku(db) { db.string(); }
38
- price(db) { db.integer(); }
39
- tags(db) {
40
- db.text().transform({
41
- toDatabase: v => (typeof v === 'string' ? v : JSON.stringify(v)),
42
- fromDatabase: v => { try { return JSON.parse(v); } catch { return v; } },
43
- });
44
- }
45
- }
46
-
47
- class EdgeCtx extends context {
48
- constructor() {
49
- super();
50
- this.env(envDir);
51
- this.dbset(Widget);
52
- }
53
- }
54
-
55
- {
56
- const ctx = new EdgeCtx();
57
- ctx._SQLEngine.db.exec(`
58
- CREATE TABLE IF NOT EXISTS Widget (
59
- id INTEGER PRIMARY KEY AUTOINCREMENT,
60
- sku TEXT,
61
- price INTEGER,
62
- tags TEXT
63
- );
64
- `);
65
- const insert = ctx._SQLEngine.db.prepare('INSERT INTO Widget (sku, price, tags) VALUES (?, ?, ?)');
66
- insert.run('A-1', 10, '["red"]');
67
- insert.run('A-2', 20, '["red","blue"]');
68
- insert.run('B-1', 30, '["green"]');
69
- insert.run('B-2', 40, '[]');
70
- insert.run('C-1', 50, null);
71
- await ctx.close();
72
- }
73
-
74
- test('count with specific field: .count(w => w.id)', async () => {
75
- const db = new EdgeCtx();
76
- const n = await db.Widget.count('w => w.id');
77
- assert.equal(n, 5);
78
- await db.close();
79
- });
80
-
81
- test('first() returns a single row', async () => {
82
- const db = new EdgeCtx();
83
- const row = await db.Widget.first();
84
- assert.ok(row, 'first() should return a row');
85
- assert.equal(row.id, 1, 'first() should return the first by primary key');
86
- await db.close();
87
- });
88
-
89
- test('first() on empty result returns null/undefined without throwing', async () => {
90
- const db = new EdgeCtx();
91
- const row = await db.Widget.where('w => w.sku == $$', '__nonexistent__').first();
92
- assert.ok(row == null, 'first() on empty result should return null');
93
- await db.close();
94
- });
95
-
96
- test('.select() narrows returned columns', async () => {
97
- const db = new EdgeCtx();
98
- const rows = await db.Widget.select('w => w.sku').orderBy('w => w.id').toList();
99
- assert.ok(rows.length > 0);
100
- // .select() is a projection — `price` should not be set on returned rows
101
- // (though whether it's strictly absent vs undefined depends on the ORM).
102
- // At minimum sku should be present.
103
- for (const r of rows) {
104
- assert.ok(r.sku, 'sku should be present in selected rows');
105
- }
106
- await db.close();
107
- });
108
-
109
- test('NULL handling in WHERE: == null should match null rows', async () => {
110
- const db = new EdgeCtx();
111
- const rows = await db.Widget.where('w => w.tags == null').toList();
112
- // C-1 has tags=null
113
- assert.equal(rows.length, 1, `expected exactly 1 row with tags=null, got ${rows.length}`);
114
- assert.equal(rows[0].sku, 'C-1');
115
- await db.close();
116
- });
117
-
118
- test('NULL handling in WHERE: != null should match non-null rows', async () => {
119
- const db = new EdgeCtx();
120
- const rows = await db.Widget.where('w => w.tags != null').toList();
121
- // A-1, A-2, B-1, B-2 have non-null tags
122
- assert.equal(rows.length, 4, `expected 4 rows with tags != null, got ${rows.length}`);
123
- await db.close();
124
- });
125
-
126
- test('transformer roundtrip: array saved as JSON and parsed back', async () => {
127
- const db = new EdgeCtx();
128
- const a1 = await db.Widget.where('w => w.sku == $$', 'A-1').single();
129
- assert.ok(Array.isArray(a1.tags), `tags should be parsed to array, got ${typeof a1.tags}`);
130
- assert.deepEqual(a1.tags, ['red']);
131
- await db.close();
132
- });
133
-
134
- test('update with transformer: modify array, save, reload, array shape preserved', async () => {
135
- const db = new EdgeCtx();
136
- const a2 = await db.Widget.where('w => w.sku == $$', 'A-2').single();
137
- a2.tags = ['yellow', 'purple'];
138
- await a2.save();
139
-
140
- const reloaded = await db.Widget.where('w => w.sku == $$', 'A-2').single();
141
- assert.ok(Array.isArray(reloaded.tags));
142
- assert.deepEqual(reloaded.tags, ['yellow', 'purple']);
143
- await db.close();
144
- });
145
-
146
- test('chained queries do not leak parameters across calls on the same context', async () => {
147
- const db = new EdgeCtx();
148
- const a = await db.Widget.where('w => w.price > $$', 25).toList();
149
- assert.equal(a.length, 3, 'price > 25 → B-1, B-2, C-1');
150
-
151
- // Issue a second unrelated query — parameters from the first must not leak
152
- const b = await db.Widget.where('w => w.price < $$', 15).toList();
153
- assert.equal(b.length, 1, 'price < 15 → A-1 only; parameters from prev call must not leak');
154
- await db.close();
155
- });
156
-
157
- test('raw() produces the expected rows', async () => {
158
- const db = new EdgeCtx();
159
- const rows = await db.Widget.raw('SELECT id, sku FROM Widget WHERE price > 20 ORDER BY id').toList();
160
- assert.ok(rows.length >= 3);
161
- await db.close();
162
- });
163
-
164
- test('save() on tracked entity that was already deleted does not throw obscure error', async () => {
165
- const db = new EdgeCtx();
166
- const w = await db.Widget.where('w => w.sku == $$', 'A-1').single();
167
- // Manually delete the row behind MasterRecord's back
168
- db._SQLEngine.db.prepare('DELETE FROM Widget WHERE id = ?').run(w.id);
169
-
170
- // Attempt to save a modification — expected: either a clean error or a no-op (0 rows affected)
171
- w.price = 11;
172
- try {
173
- await w.save();
174
- // No error — that's fine, SQLite UPDATE on nonexistent row affects 0 rows silently
175
- } catch (err) {
176
- // Also fine, as long as it's a clear error
177
- assert.ok(err instanceof Error, 'if thrown, must be an Error');
178
- }
179
- await db.close();
180
- });