masterrecord 1.0.0 → 1.0.2

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.
@@ -108,7 +108,14 @@ class EntityTrackerModel {
108
108
  }
109
109
 
110
110
  modelClass.__state = "modified";
111
- modelClass.__dirtyFields.push(modelField);
111
+ // Deduplicate: setting the same field twice used to push
112
+ // the name twice, producing duplicate assignments in the
113
+ // UPDATE SET clause (`SET col = ?, col = ?`) which is a
114
+ // hard error in Postgres and may silently take-last in
115
+ // MySQL/SQLite.
116
+ if (!modelClass.__dirtyFields.includes(modelField)) {
117
+ modelClass.__dirtyFields.push(modelField);
118
+ }
112
119
  // ensure this entity is tracked on any modification
113
120
  if(modelClass.__context && typeof modelClass.__context.__track === 'function'){
114
121
  modelClass.__context.__track(modelClass);
@@ -609,7 +609,15 @@ class queryMethods{
609
609
  }
610
610
  }
611
611
 
612
- this.__proto__["_" + fname] = value;
612
+ // Apply fieldDef.set transform if the entity defines one — the
613
+ // tracker-entity setter (entityTrackerModel.build) already does
614
+ // this on UPDATE; we need the same behavior on INSERT so values
615
+ // normalize consistently regardless of which path created them.
616
+ if (fieldDef && typeof fieldDef.set === 'function') {
617
+ this.__proto__["_" + fname] = fieldDef.set(value);
618
+ } else {
619
+ this.__proto__["_" + fname] = value;
620
+ }
613
621
  if(!this.__dirtyFields.includes(fname)){
614
622
  this.__dirtyFields.push(fname);
615
623
  }
package/SQLLiteEngine.js CHANGED
@@ -180,7 +180,10 @@ class SQLLiteEngine {
180
180
  query.count = "none";
181
181
  }
182
182
  queryString.entity = this.getEntity(entity.__name, query.entityMap);
183
- queryString.query = `SELECT ${this.buildCount(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)}`
183
+ // Include buildAnd so chained .and() calls (separate from
184
+ // .where()) survive into the COUNT SQL. Without this they
185
+ // were silently dropped.
186
+ queryString.query = `SELECT ${this.buildCount(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)}`
184
187
  }
185
188
  if(queryString.query){
186
189
  var queryCount = queryString.query
package/context.js CHANGED
@@ -1699,9 +1699,14 @@ class context {
1699
1699
  }
1700
1700
 
1701
1701
  if (entities.length === 1) {
1702
- // Single update - use existing logic
1702
+ // Single update - use existing logic.
1703
+ // NOTE: the second argument must be `__entity` (double underscore).
1704
+ // The previous code used `_entity` which is undefined, so
1705
+ // `removePrimarykeyandVirtual` received `undefined` and stripped
1706
+ // nothing — a latent bug that left primary-key/virtual fields in
1707
+ // the UPDATE SET clause if they ever landed in __dirtyFields.
1703
1708
  const currentModel = entities[0];
1704
- const cleanCurrentModel = tools.removePrimarykeyandVirtual(currentModel, currentModel._entity);
1709
+ const cleanCurrentModel = tools.removePrimarykeyandVirtual(currentModel, currentModel.__entity);
1705
1710
  const argu = this._SQLEngine._buildSQLEqualToParameterized(cleanCurrentModel);
1706
1711
 
1707
1712
  if (argu !== -1) {
@@ -1721,7 +1726,7 @@ class context {
1721
1726
  const updateQueries = [];
1722
1727
 
1723
1728
  for (const currentModel of entities) {
1724
- const cleanCurrentModel = tools.removePrimarykeyandVirtual(currentModel, currentModel._entity);
1729
+ const cleanCurrentModel = tools.removePrimarykeyandVirtual(currentModel, currentModel.__entity);
1725
1730
  const argu = this._SQLEngine._buildSQLEqualToParameterized(cleanCurrentModel);
1726
1731
 
1727
1732
  if (argu !== -1) {
@@ -1754,6 +1759,18 @@ class context {
1754
1759
  await entity.afterSave.call(entity);
1755
1760
  }
1756
1761
  }
1762
+
1763
+ // Reset tracker state on the entity itself so a subsequent
1764
+ // saveChanges() doesn't re-emit the same UPDATE for the same fields.
1765
+ // Previously only _processBatchInserts did this, not updates —
1766
+ // leaving __state="modified" and __dirtyFields populated. On the
1767
+ // next modification of a different field, the stale fields would
1768
+ // be re-written, silently overwriting any concurrent external
1769
+ // changes to those columns.
1770
+ for (const entity of entities) {
1771
+ entity.__state = 'track';
1772
+ entity.__dirtyFields = [];
1773
+ }
1757
1774
  }
1758
1775
 
1759
1776
  /**
package/mySQLEngine.js CHANGED
@@ -156,26 +156,32 @@ class MySQLEngine {
156
156
  }
157
157
 
158
158
  /**
159
- * SELECT COUNT
159
+ * SELECT COUNT. Builds the SQL inline (like SQLite/Postgres do) instead
160
+ * of trying to regex-wrap the full SELECT from buildQuery — the old code
161
+ * called `queryObject.count(sqlString)` which is a queryScript builder
162
+ * method (expects a lambda), not a SQL wrapper; the return value was the
163
+ * queryScript object and running it as SQL produced "[object Object]".
160
164
  */
161
165
  async getCount(queryObject, entity, context) {
162
166
  const query = queryObject.script;
163
167
  try {
164
- let queryString;
168
+ let sql;
165
169
  if (query.raw) {
166
- queryString = { query: query.raw };
170
+ sql = query.raw;
167
171
  } else {
168
- queryString = this.buildQuery(query, entity, context);
172
+ if (query.count === undefined) {
173
+ query.count = "none";
174
+ }
175
+ sql = `SELECT ${this.buildCount(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)}`;
169
176
  }
170
177
 
171
- if (queryString.query) {
172
- const queryCount = queryObject.count(queryString.query);
178
+ if (sql) {
173
179
  const params = query.parameters ? query.parameters.getParams() : [];
174
180
  if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
175
- console.debug("[SQL]", queryCount);
181
+ console.debug("[SQL]", sql);
176
182
  console.debug("[Params]", params);
177
183
  }
178
- const result = await this._runWithParams(queryCount, params);
184
+ const result = await this._runWithParams(sql, params);
179
185
  return result[0] || null;
180
186
  }
181
187
  return null;
@@ -185,6 +191,20 @@ class MySQLEngine {
185
191
  }
186
192
  }
187
193
 
194
+ /**
195
+ * Build COUNT(...) fragment for SELECT ... COUNT(...) FROM ...
196
+ * Matches the SQLite/Postgres engine contract.
197
+ */
198
+ buildCount(query, entity) {
199
+ const alias = this.getEntity(query.parentName || entity.__name, query.entityMap);
200
+ if (!query.count) return "";
201
+ if (query.count === "none") return `COUNT(*)`;
202
+ // query.count is a cachedExpr with selectFields when set via `.count(l => l.field)`.
203
+ const field = query.count.selectFields && query.count.selectFields[0];
204
+ if (!field) return `COUNT(*)`;
205
+ return `COUNT(${alias}.\`${field}\`)`;
206
+ }
207
+
188
208
  /**
189
209
  * SELECT multiple records
190
210
  */
@@ -260,16 +280,121 @@ class MySQLEngine {
260
280
  select: this.buildSelect(query, entity),
261
281
  from: this.buildFrom(query, entity),
262
282
  include: this.buildInclude(query, entity, context, {}),
263
- where: this.buildWhere(query, entity)
283
+ where: this.buildWhere(query, entity),
284
+ and: this.buildAnd(query, entity),
285
+ orderBy: this.buildOrderBy(query, entity),
286
+ take: this.buildTake(query),
287
+ skip: this.buildSkip(query)
264
288
  };
265
289
 
266
- const queryString = `${queryObject.select} ${queryObject.from} ${queryObject.include} ${queryObject.where}`;
290
+ const queryString = `${queryObject.select} ${queryObject.from} ${queryObject.include} ${queryObject.where} ${queryObject.and} ${queryObject.orderBy} ${queryObject.take} ${queryObject.skip}`;
267
291
  return {
268
292
  query: queryString,
269
293
  entity: this.getEntity(entity.__name, query.entityMap)
270
294
  };
271
295
  }
272
296
 
297
+ /**
298
+ * Build ORDER BY clause from query.orderBy or query.orderByDesc.
299
+ * Both are objects shaped like `{ selectFields: ['col1', 'col2'], ... }`
300
+ * (see QueryLanguage/queryScript.js buildScript()).
301
+ */
302
+ buildOrderBy(query, entity) {
303
+ let orderByType = "ASC";
304
+ let orderByEntity = query.orderBy;
305
+ if (orderByEntity === false || orderByEntity === undefined) {
306
+ orderByType = "DESC";
307
+ orderByEntity = query.orderByDesc;
308
+ }
309
+ if (!orderByEntity) return "";
310
+
311
+ // Security: Validate field exists in entity before interpolating into SQL.
312
+ if (entity && orderByEntity.selectFields) {
313
+ for (const item in orderByEntity.selectFields) {
314
+ const field = orderByEntity.selectFields[item];
315
+ if (!entity[field]) {
316
+ throw new Error(`Invalid ORDER BY field: ${field} not found in ${entity.__name || 'entity'}`);
317
+ }
318
+ }
319
+ }
320
+
321
+ const entityAlias = this.getEntity(query.parentName, query.entityMap);
322
+ const fieldList = [];
323
+ for (const item in orderByEntity.selectFields) {
324
+ fieldList.push(`${entityAlias}.\`${orderByEntity.selectFields[item]}\``);
325
+ }
326
+ if (fieldList.length === 0) return "";
327
+ return `ORDER BY ${fieldList.join(', ')} ${orderByType}`;
328
+ }
329
+
330
+ buildTake(query) {
331
+ if (query.take) {
332
+ return `LIMIT ${Number(query.take)}`;
333
+ }
334
+ return "";
335
+ }
336
+
337
+ buildSkip(query) {
338
+ if (query.skip) {
339
+ return `OFFSET ${Number(query.skip)}`;
340
+ }
341
+ return "";
342
+ }
343
+
344
+ /**
345
+ * Build chained AND clause from query.and (array of cachedExpr objects).
346
+ * Produces "AND <expr> AND <expr>" that appends to the WHERE clause.
347
+ */
348
+ buildAnd(query, mainQuery) {
349
+ const andEntity = query.and;
350
+ const $that = this;
351
+ if (!andEntity) return "";
352
+
353
+ let entity = this.getEntity(query.parentName, query.entityMap);
354
+ const andList = [];
355
+
356
+ for (const entityPart in andEntity) {
357
+ const itemEntity = andEntity[entityPart];
358
+ for (const table in itemEntity[query.parentName]) {
359
+ const item = itemEntity[query.parentName][table];
360
+ const expressions = [];
361
+ for (const exp in item.expressions) {
362
+ let field = tools.capitalizeFirstLetter(item.expressions[exp].field);
363
+ if (mainQuery[field] && mainQuery[field].isNavigational) {
364
+ entity = $that.getEntity(field, query.entityMap);
365
+ field = item.fields[1];
366
+ }
367
+
368
+ let func = item.expressions[exp].func;
369
+ const arg = item.expressions[exp].arg;
370
+
371
+ if (arg === "null") {
372
+ if (func === "=") func = "IS";
373
+ if (func === "!=") func = "IS NOT";
374
+ expressions.push(`${entity}.\`${field}\` ${func} ${arg}`);
375
+ } else {
376
+ // arg may be a parameterized placeholder (?, $1, (?, ?, ?))
377
+ // or a literal value quoted with single quotes.
378
+ const isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg) || /^\(.*\)$/.test(arg));
379
+ if (isPlaceholder || func === "IN") {
380
+ expressions.push(`${entity}.\`${field}\` ${func} ${arg}`);
381
+ } else {
382
+ expressions.push(`${entity}.\`${field}\` ${func} '${arg}'`);
383
+ }
384
+ }
385
+ }
386
+ if (expressions.length > 0) {
387
+ andList.push(expressions.join(" AND "));
388
+ }
389
+ }
390
+ }
391
+
392
+ if (andList.length > 0) {
393
+ return `AND ${andList.join(" AND ")}`;
394
+ }
395
+ return "";
396
+ }
397
+
273
398
  buildSelect(query, entity) {
274
399
  const select = "SELECT";
275
400
  const arr = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.0.000",
3
+ "version": "1.0.002",
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
@@ -198,8 +198,10 @@ class postgresEngine {
198
198
  query.count = "none";
199
199
  }
200
200
  const entityAlias = this.getEntity(entity.__name, query.entityMap);
201
+ // Include buildAnd so chained .and() calls survive into the
202
+ // COUNT SQL. Without this they were silently dropped.
201
203
  queryString = {
202
- query: `SELECT ${this.buildCount(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)}`,
204
+ query: `SELECT ${this.buildCount(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)}`,
203
205
  params: query.parameters ? query.parameters.getParams() : []
204
206
  };
205
207
  }
@@ -260,7 +262,9 @@ class postgresEngine {
260
262
  const entityStr = this.getEntity(entity.__name, query.entityMap);
261
263
  const params = query.parameters ? query.parameters.getParams() : [];
262
264
 
263
- const sql = `SELECT ${this.buildSelectString(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)} ${this.buildLimit(query)} ${this.buildSkip(query)} ${this.buildOrderBy(query, entity)}`;
265
+ // Standard SQL clause order: SELECT ... FROM ... WHERE ... AND ... ORDER BY ... LIMIT ... OFFSET ...
266
+ // The previous order placed LIMIT/OFFSET before ORDER BY, which Postgres rejects as a syntax error.
267
+ const sql = `SELECT ${this.buildSelectString(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)} ${this.buildOrderBy(query, entity)} ${this.buildLimit(query)} ${this.buildSkip(query)}`;
264
268
 
265
269
  return {
266
270
  query: sql,
@@ -268,9 +272,16 @@ class postgresEngine {
268
272
  };
269
273
  }
270
274
 
275
+ /**
276
+ * Build the column list after SELECT. If the user called `.select()`,
277
+ * `query.select` is a cachedExpr object with `selectFields` (not a string)
278
+ * — the previous implementation returned the object directly, which
279
+ * stringified to "[object Object]" and broke the query.
280
+ */
271
281
  buildSelectString(query, entity) {
272
- if (query.select) {
273
- return query.select;
282
+ if (query.select && query.select.selectFields && query.select.selectFields.length > 0) {
283
+ const alias = this.getEntity(query.parentName || entity.__name, query.entityMap);
284
+ return query.select.selectFields.map(f => `${alias}.${f}`).join(', ');
274
285
  }
275
286
  return `${tools.convertEntityToSelectParameterString(entity)}`;
276
287
  }
@@ -414,23 +425,39 @@ class postgresEngine {
414
425
  return "";
415
426
  }
416
427
 
428
+ /**
429
+ * Build ORDER BY clause from query.orderBy or query.orderByDesc.
430
+ * Both are objects shaped like `{ selectFields: ['col1', 'col2'], ... }`
431
+ * (see QueryLanguage/queryScript.js buildScript()). The previous
432
+ * implementation treated `query.orderBy` as a plain string and silently
433
+ * dropped the clause because the fluent API never produces that shape.
434
+ */
417
435
  buildOrderBy(query, entity) {
418
- if (query.orderBy) {
419
- // Security: Validate field exists in entity
420
- if (entity && !entity[query.orderBy]) {
421
- throw new Error(`Invalid ORDER BY field: ${query.orderBy} not found in ${entity.__name || 'entity'}`);
422
- }
423
- const entityStr = this.getEntity(query.parentName, query.entityMap);
424
- return `ORDER BY ${entityStr}.${query.orderBy} ASC`;
425
- } else if (query.orderByDescending) {
426
- // Security: Validate field exists in entity
427
- if (entity && !entity[query.orderByDescending]) {
428
- throw new Error(`Invalid ORDER BY field: ${query.orderByDescending} not found in ${entity.__name || 'entity'}`);
436
+ let orderByType = "ASC";
437
+ let orderByEntity = query.orderBy;
438
+ if (orderByEntity === false || orderByEntity === undefined) {
439
+ orderByType = "DESC";
440
+ orderByEntity = query.orderByDesc;
441
+ }
442
+ if (!orderByEntity) return "";
443
+
444
+ // Security: Validate field exists in entity before interpolating into SQL.
445
+ if (entity && orderByEntity.selectFields) {
446
+ for (const item in orderByEntity.selectFields) {
447
+ const field = orderByEntity.selectFields[item];
448
+ if (!entity[field]) {
449
+ throw new Error(`Invalid ORDER BY field: ${field} not found in ${entity.__name || 'entity'}`);
450
+ }
429
451
  }
430
- const entityStr = this.getEntity(query.parentName, query.entityMap);
431
- return `ORDER BY ${entityStr}.${query.orderByDescending} DESC`;
432
452
  }
433
- return "";
453
+
454
+ const entityStr = this.getEntity(query.parentName, query.entityMap);
455
+ const fieldList = [];
456
+ for (const item in orderByEntity.selectFields) {
457
+ fieldList.push(`${entityStr}.${orderByEntity.selectFields[item]}`);
458
+ }
459
+ if (fieldList.length === 0) return "";
460
+ return `ORDER BY ${fieldList.join(', ')} ${orderByType}`;
434
461
  }
435
462
 
436
463
  getEntity(name, list) {
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Verifies chained .where() calls are actually applied to COUNT queries,
3
+ * not silently dropped. Related to the "missing AND clause" family of bugs.
4
+ */
5
+
6
+ import { test } from 'node:test';
7
+ import assert from 'node:assert/strict';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ process.env.master = 'countchained';
13
+
14
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
+ const fixturesDir = path.join(__dirname, 'fixtures', 'count-chained-where');
16
+ const envDir = path.join(fixturesDir, 'config', 'environments');
17
+ const dbDir = path.join(fixturesDir, 'db');
18
+ const dbFile = path.join(dbDir, 'countctx.sqlite');
19
+
20
+ fs.mkdirSync(envDir, { recursive: true });
21
+ fs.mkdirSync(dbDir, { recursive: true });
22
+ if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
23
+
24
+ fs.writeFileSync(
25
+ path.join(envDir, 'env.countchained.json'),
26
+ JSON.stringify({
27
+ CountCtx: {
28
+ type: 'better-sqlite3',
29
+ connection: dbDir + path.sep,
30
+ },
31
+ })
32
+ );
33
+
34
+ const { default: context } = await import('../context.js');
35
+ const { default: MySQLEngine } = await import('../mySQLEngine.js');
36
+ const { default: PostgresEngine } = await import('../postgresEngine.js');
37
+
38
+ class Lead {
39
+ id(db) { db.integer().primary().auto(); }
40
+ stage(db) { db.string(); }
41
+ score(db) { db.integer(); }
42
+ }
43
+
44
+ class CountCtx extends context {
45
+ constructor() {
46
+ super();
47
+ this.env(envDir);
48
+ this.dbset(Lead);
49
+ }
50
+ }
51
+
52
+ // Seed 5 rows: 3 stage="New", 2 stage="Won". Of the 3 New, 2 have score > 10.
53
+ {
54
+ const ctx = new CountCtx();
55
+ ctx._SQLEngine.db.exec(`
56
+ CREATE TABLE IF NOT EXISTS Lead (
57
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
58
+ stage TEXT,
59
+ score INTEGER
60
+ );
61
+ `);
62
+ const insert = ctx._SQLEngine.db.prepare('INSERT INTO Lead (stage, score) VALUES (?, ?)');
63
+ insert.run('New', 5);
64
+ insert.run('New', 15);
65
+ insert.run('New', 20);
66
+ insert.run('Won', 30);
67
+ insert.run('Won', 40);
68
+ await ctx.close();
69
+ }
70
+
71
+ test('SQLite: chained .where() before .count() applies both conditions', async () => {
72
+ const ctx = new CountCtx();
73
+ // stage == 'New' AND score > 10 → rows 2 and 3 → count 2
74
+ const n = await ctx.Lead
75
+ .where('l => l.stage == $$', 'New')
76
+ .where('l => l.score > $$', 10)
77
+ .count();
78
+ assert.equal(n, 2, 'only Leads with stage=New AND score>10 counted');
79
+ await ctx.close();
80
+ });
81
+
82
+ test('SQLite: single .where() before .count() still works (sanity)', async () => {
83
+ const ctx = new CountCtx();
84
+ const n = await ctx.Lead.where('l => l.stage == $$', 'New').count();
85
+ assert.equal(n, 3);
86
+ await ctx.close();
87
+ });
88
+
89
+ function buildScript(chainFn) {
90
+ const ctx = new CountCtx();
91
+ const builder = chainFn(ctx.Lead);
92
+ const script = builder.__queryObject.script;
93
+ const entity = ctx.Lead.__entity;
94
+ ctx.close();
95
+ return { script, entity };
96
+ }
97
+
98
+ // Smoke test MySQL/Postgres engines' count query path — we can't run them
99
+ // against a real DB, but we can verify the generated SQL contains both
100
+ // predicate columns when chained .where() is used.
101
+ //
102
+ // NOTE: MySQL's getCount and Postgres's getCount build the COUNT SQL inline
103
+ // (they don't delegate to buildQuery), so these are separate code paths that
104
+ // also need to emit the AND clause.
105
+ test('MySQL engine should emit chained-AND predicate columns in count SQL', async () => {
106
+ const { script, entity } = buildScript((Lead) =>
107
+ Lead.where('l => l.stage == $$', 'New').where('l => l.score > $$', 10)
108
+ );
109
+ script.count = 'none';
110
+ const engine = new MySQLEngine();
111
+ // Emulate what getCount now builds inline.
112
+ const sql = `SELECT ${engine.buildCount(script, entity)} ${engine.buildFrom(script, entity)} ${engine.buildWhere(script, entity)} ${engine.buildAnd(script, entity)}`;
113
+ assert.match(sql, /\bstage\b/i, 'first predicate column present');
114
+ assert.match(sql, /\bscore\b/i, 'second predicate column present');
115
+ assert.match(sql, /^SELECT COUNT\(\*\)/, 'starts with SELECT COUNT(*)');
116
+ });
117
+
118
+ test('MySQL buildCount: SELECT COUNT(*) when no column specified', () => {
119
+ const { script, entity } = buildScript((Lead) =>
120
+ Lead.where('l => l.stage == $$', 'New')
121
+ );
122
+ script.count = 'none';
123
+ const engine = new MySQLEngine();
124
+ assert.equal(engine.buildCount(script, entity), 'COUNT(*)');
125
+ });
126
+
127
+ test('Postgres engine COUNT path should include chained-AND predicate columns', () => {
128
+ const { script, entity } = buildScript((Lead) =>
129
+ Lead.where('l => l.stage == $$', 'New').where('l => l.score > $$', 10)
130
+ );
131
+ script.count = 'none';
132
+ const engine = new PostgresEngine();
133
+ const sql = `SELECT ${engine.buildCount(script, entity)} ${engine.buildFrom(script, entity)} ${engine.buildWhere(script, entity)} ${engine.buildAnd(script, entity)}`;
134
+ assert.match(sql, /\bstage\b/i);
135
+ assert.match(sql, /\bscore\b/i, 'second .where() predicate must survive into the COUNT SQL');
136
+ });
@@ -0,0 +1 @@
1
+ {"CountCtx":{"type":"better-sqlite3","connection":"/Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/test/fixtures/count-chained-where/db/"}}
@@ -0,0 +1 @@
1
+ {"ParityCtx":{"type":"better-sqlite3","connection":"/Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/test/fixtures/query-builder-parity/db/"}}
@@ -0,0 +1 @@
1
+ {"SetDropCtx":{"type":"better-sqlite3","connection":"/Users/alexanderrich/Documents/development/opensourceHQ/MasterRecord/test/fixtures/setter-and-update-drop/db/"}}
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Regression tests for cross-engine query-builder feature parity.
3
+ *
4
+ * Covers bug report `mySQLEngine.buildQuery() silently drops ORDER BY /
5
+ * LIMIT / OFFSET / chained AND`, plus the equivalent Postgres bug where
6
+ * `buildOrderBy` treated `query.orderBy` as a string (never matching the
7
+ * object shape the fluent API actually produces).
8
+ *
9
+ * Strategy:
10
+ * - Use the fluent `.orderBy()` / `.orderByDescending()` / `.skip()` /
11
+ * `.take()` / chained `.where()` APIs to build up a query against a
12
+ * real SQLite database (which exercises end-to-end).
13
+ * - Snapshot the internal `queryScript` state at that point.
14
+ * - Feed the same state into MySQL and Postgres engine `buildQuery()`
15
+ * methods (no connection needed — the builders are pure functions)
16
+ * and assert the generated SQL contains the expected clauses.
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 = 'parity';
26
+
27
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
28
+ const fixturesDir = path.join(__dirname, 'fixtures', 'query-builder-parity');
29
+ const envDir = path.join(fixturesDir, 'config', 'environments');
30
+ const dbDir = path.join(fixturesDir, 'db');
31
+ const dbFile = path.join(dbDir, 'parityctx.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.parity.json'),
39
+ JSON.stringify({
40
+ ParityCtx: {
41
+ type: 'better-sqlite3',
42
+ connection: dbDir + path.sep,
43
+ },
44
+ })
45
+ );
46
+
47
+ const { default: context } = await import('../context.js');
48
+ const { default: MySQLEngine } = await import('../mySQLEngine.js');
49
+ const { default: PostgresEngine } = await import('../postgresEngine.js');
50
+
51
+ class Lead {
52
+ id(db) { db.integer().primary().auto(); }
53
+ stage(db) { db.string(); }
54
+ updatedAt(db) { db.integer(); }
55
+ }
56
+
57
+ class ParityCtx extends context {
58
+ constructor() {
59
+ super();
60
+ this.env(envDir);
61
+ this.dbset(Lead);
62
+ }
63
+ }
64
+
65
+ // Seed the SQLite DB with 5 rows — distinct updatedAt values so ordering is unambiguous.
66
+ {
67
+ const ctx = new ParityCtx();
68
+ ctx._SQLEngine.db.exec(`
69
+ CREATE TABLE IF NOT EXISTS Lead (
70
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
71
+ stage TEXT,
72
+ updatedAt INTEGER
73
+ );
74
+ `);
75
+ const rows = [
76
+ { stage: 'New', updatedAt: 1000 },
77
+ { stage: 'New', updatedAt: 5000 },
78
+ { stage: 'New', updatedAt: 3000 },
79
+ { stage: 'New', updatedAt: 2000 },
80
+ { stage: 'Won', updatedAt: 4000 },
81
+ ];
82
+ const insert = ctx._SQLEngine.db.prepare('INSERT INTO Lead (stage, updatedAt) VALUES (?, ?)');
83
+ for (const r of rows) insert.run(r.stage, r.updatedAt);
84
+ await ctx.close();
85
+ }
86
+
87
+ //
88
+ // SQLite — end-to-end: the query actually hits the DB.
89
+ // These confirm the fluent API itself is wired correctly and that the
90
+ // SQLite engine applies the clauses (prior behavior; regression guard).
91
+ //
92
+ test('SQLite: orderBy(updatedAt) returns rows in ascending order', async () => {
93
+ const ctx = new ParityCtx();
94
+ const rows = await ctx.Lead
95
+ .where('l => l.stage == $$', 'New')
96
+ .orderBy('l => l.updatedAt')
97
+ .toList();
98
+ const ts = rows.map(r => r.updatedAt);
99
+ assert.deepEqual(ts, [1000, 2000, 3000, 5000], 'ascending updatedAt');
100
+ await ctx.close();
101
+ });
102
+
103
+ test('SQLite: orderByDescending(updatedAt) returns rows in descending order', async () => {
104
+ const ctx = new ParityCtx();
105
+ const rows = await ctx.Lead
106
+ .where('l => l.stage == $$', 'New')
107
+ .orderByDescending('l => l.updatedAt')
108
+ .toList();
109
+ const ts = rows.map(r => r.updatedAt);
110
+ assert.deepEqual(ts, [5000, 3000, 2000, 1000], 'descending updatedAt');
111
+ await ctx.close();
112
+ });
113
+
114
+ test('SQLite: skip/take paginates correctly', async () => {
115
+ const ctx = new ParityCtx();
116
+ const rows = await ctx.Lead
117
+ .orderBy('l => l.updatedAt')
118
+ .skip(1).take(2)
119
+ .toList();
120
+ const ts = rows.map(r => r.updatedAt);
121
+ assert.deepEqual(ts, [2000, 3000], 'pagination skips first row, takes next two');
122
+ await ctx.close();
123
+ });
124
+
125
+ test('SQLite: chained where() calls AND together', async () => {
126
+ const ctx = new ParityCtx();
127
+ const rows = await ctx.Lead
128
+ .where('l => l.stage == $$', 'New')
129
+ .where('l => l.updatedAt > $$', 1500)
130
+ .orderBy('l => l.updatedAt')
131
+ .toList();
132
+ const ts = rows.map(r => r.updatedAt);
133
+ assert.deepEqual(ts, [2000, 3000, 5000], 'chained where filters correctly');
134
+ await ctx.close();
135
+ });
136
+
137
+ //
138
+ // Helper: build a query state with the fluent API, return the script.
139
+ // We don't execute it — we just need the internal `script` that gets
140
+ // handed to an engine's buildQuery().
141
+ //
142
+ function buildScript(chainFn) {
143
+ // Use the SQLite context to drive the fluent API, then snapshot the script.
144
+ const ctx = new ParityCtx();
145
+ const builder = chainFn(ctx.Lead);
146
+ const script = builder.__queryObject.script;
147
+ // Ensure the entity we pass matches what the engine expects
148
+ const entity = ctx.Lead.__entity;
149
+ ctx.close();
150
+ return { script, entity };
151
+ }
152
+
153
+ //
154
+ // MySQL — string-output tests. Engine builders are pure functions; no
155
+ // connection is required to call buildQuery().
156
+ //
157
+ test('MySQL buildQuery emits ORDER BY ... ASC for .orderBy()', () => {
158
+ const { script, entity } = buildScript((Lead) =>
159
+ Lead.where('l => l.stage == $$', 'New').orderBy('l => l.updatedAt')
160
+ );
161
+ const engine = new MySQLEngine();
162
+ const out = engine.buildQuery(script, entity, {});
163
+ assert.match(out.query, /ORDER BY\s+\w+\.`updatedAt`\s+ASC/, 'ORDER BY updatedAt ASC with backtick-quoted column');
164
+ });
165
+
166
+ test('MySQL buildQuery emits ORDER BY ... DESC for .orderByDescending()', () => {
167
+ const { script, entity } = buildScript((Lead) =>
168
+ Lead.where('l => l.stage == $$', 'New').orderByDescending('l => l.updatedAt')
169
+ );
170
+ const engine = new MySQLEngine();
171
+ const out = engine.buildQuery(script, entity, {});
172
+ assert.match(out.query, /ORDER BY\s+\w+\.`updatedAt`\s+DESC/, 'ORDER BY updatedAt DESC');
173
+ });
174
+
175
+ test('MySQL buildQuery emits LIMIT and OFFSET for .take()/.skip()', () => {
176
+ const { script, entity } = buildScript((Lead) =>
177
+ Lead.orderBy('l => l.updatedAt').skip(10).take(5)
178
+ );
179
+ const engine = new MySQLEngine();
180
+ const out = engine.buildQuery(script, entity, {});
181
+ assert.match(out.query, /LIMIT\s+5/, 'LIMIT 5 present');
182
+ assert.match(out.query, /OFFSET\s+10/, 'OFFSET 10 present');
183
+ });
184
+
185
+ test('MySQL buildQuery emits AND for chained .where()', () => {
186
+ const { script, entity } = buildScript((Lead) =>
187
+ Lead.where('l => l.stage == $$', 'New').where('l => l.updatedAt > $$', 1500)
188
+ );
189
+ const engine = new MySQLEngine();
190
+ const out = engine.buildQuery(script, entity, {});
191
+ // Chained .where() can merge into a single WHERE in some engines; either
192
+ // an explicit "AND <expr>" or a WHERE clause that contains the second
193
+ // column is acceptable as long as both conditions land in the SQL.
194
+ assert.match(out.query, /\bstage\b/, 'first predicate column present');
195
+ assert.match(out.query, /\bupdatedAt\b/, 'second predicate column present');
196
+ });
197
+
198
+ test('MySQL buildQuery clauses appear in correct SQL order (WHERE before ORDER BY before LIMIT before OFFSET)', () => {
199
+ const { script, entity } = buildScript((Lead) =>
200
+ Lead.where('l => l.stage == $$', 'New')
201
+ .orderBy('l => l.updatedAt')
202
+ .skip(2).take(3)
203
+ );
204
+ const engine = new MySQLEngine();
205
+ const out = engine.buildQuery(script, entity, {});
206
+ const whereIdx = out.query.indexOf('WHERE');
207
+ const orderIdx = out.query.indexOf('ORDER BY');
208
+ const limitIdx = out.query.indexOf('LIMIT');
209
+ const offsetIdx = out.query.indexOf('OFFSET');
210
+ assert.ok(whereIdx >= 0 && whereIdx < orderIdx, 'WHERE before ORDER BY');
211
+ assert.ok(orderIdx < limitIdx, 'ORDER BY before LIMIT');
212
+ assert.ok(limitIdx < offsetIdx, 'LIMIT before OFFSET');
213
+ });
214
+
215
+ //
216
+ // Postgres — same string-output tests.
217
+ //
218
+ test('Postgres buildQuery emits ORDER BY ... ASC for .orderBy()', () => {
219
+ const { script, entity } = buildScript((Lead) =>
220
+ Lead.where('l => l.stage == $$', 'New').orderBy('l => l.updatedAt')
221
+ );
222
+ const engine = new PostgresEngine();
223
+ const out = engine.buildQuery(script, entity, {});
224
+ assert.match(out.query, /ORDER BY\s+\w+\.updatedAt\s+ASC/);
225
+ });
226
+
227
+ test('Postgres buildQuery emits ORDER BY ... DESC for .orderByDescending()', () => {
228
+ const { script, entity } = buildScript((Lead) =>
229
+ Lead.where('l => l.stage == $$', 'New').orderByDescending('l => l.updatedAt')
230
+ );
231
+ const engine = new PostgresEngine();
232
+ const out = engine.buildQuery(script, entity, {});
233
+ assert.match(out.query, /ORDER BY\s+\w+\.updatedAt\s+DESC/);
234
+ });
235
+
236
+ test('Postgres buildQuery emits LIMIT and OFFSET', () => {
237
+ const { script, entity } = buildScript((Lead) =>
238
+ Lead.orderBy('l => l.updatedAt').skip(10).take(5)
239
+ );
240
+ const engine = new PostgresEngine();
241
+ const out = engine.buildQuery(script, entity, {});
242
+ assert.match(out.query, /LIMIT\s+5/);
243
+ assert.match(out.query, /OFFSET\s+10/);
244
+ });
245
+
246
+ test('Postgres buildQuery clauses appear in correct SQL order (ORDER BY before LIMIT before OFFSET)', () => {
247
+ const { script, entity } = buildScript((Lead) =>
248
+ Lead.where('l => l.stage == $$', 'New')
249
+ .orderBy('l => l.updatedAt')
250
+ .skip(2).take(3)
251
+ );
252
+ const engine = new PostgresEngine();
253
+ const out = engine.buildQuery(script, entity, {});
254
+ const orderIdx = out.query.indexOf('ORDER BY');
255
+ const limitIdx = out.query.indexOf('LIMIT');
256
+ const offsetIdx = out.query.indexOf('OFFSET');
257
+ assert.ok(orderIdx >= 0, 'ORDER BY emitted');
258
+ assert.ok(orderIdx < limitIdx, 'ORDER BY before LIMIT');
259
+ assert.ok(limitIdx < offsetIdx, 'LIMIT before OFFSET');
260
+ });
@@ -0,0 +1,168 @@
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
+ });