masterrecord 1.0.6 → 1.0.8

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 (59) hide show
  1. package/.claude/settings.local.json +4 -1
  2. package/Migrations/migrationMySQLQuery.js +8 -1
  3. package/Migrations/migrationPostgresQuery.js +5 -2
  4. package/Migrations/migrationSQLiteQuery.js +6 -5
  5. package/Migrations/schema.js +14 -4
  6. package/QueryLanguage/queryMethods.js +8 -0
  7. package/QueryLanguage/queryScript.js +18 -8
  8. package/SQLLiteEngine.js +17 -7
  9. package/context.js +34 -7
  10. package/mySQLEngine.js +23 -7
  11. package/package.json +1 -1
  12. package/postgresEngine.js +155 -35
  13. package/test/count-no-from-audit.test.js +1 -1
  14. package/test/ctx-dollar-placeholder.test.js +142 -0
  15. package/test/drop-column-idempotent.test.js +181 -0
  16. package/test/postgres-camelcase-quoting.test.js +249 -0
  17. package/test/query-builder-parity.test.js +2 -2
  18. package/test/fixtures/broad-audit/config/environments/env.audit.json +0 -1
  19. package/test/fixtures/broad-audit/db/auditctx.sqlite +0 -0
  20. package/test/fixtures/count-chained-where/config/environments/env.countchained.json +0 -1
  21. package/test/fixtures/count-chained-where/db/countctx.sqlite +0 -0
  22. package/test/fixtures/count-no-from/config/environments/env.countfrom.json +0 -1
  23. package/test/fixtures/count-no-from/db/countfromctx.sqlite +0 -0
  24. package/test/fixtures/edge-cases-audit/config/environments/env.edgeaudit.json +0 -1
  25. package/test/fixtures/edge-cases-audit/db/edgectx.sqlite +0 -0
  26. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
  27. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
  28. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
  29. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -96
  30. package/test/fixtures/multi-migration-N4bUYy/app/models/multimigctx.js +0 -26
  31. package/test/fixtures/multi-migration-N4bUYy/config/environments/env.multimig.json +0 -1
  32. package/test/fixtures/multi-migration-N4bUYy/db/multimigctx.sqlite +0 -0
  33. package/test/fixtures/multi-migration-N4bUYy/package.json +0 -1
  34. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
  35. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
  36. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
  37. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -96
  38. package/test/fixtures/multi-migration-Qu42ZE/app/models/multimigctx.js +0 -26
  39. package/test/fixtures/multi-migration-Qu42ZE/config/environments/env.multimig.json +0 -1
  40. package/test/fixtures/multi-migration-Qu42ZE/db/multimigctx.sqlite +0 -0
  41. package/test/fixtures/multi-migration-Qu42ZE/package.json +0 -1
  42. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
  43. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
  44. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
  45. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -104
  46. package/test/fixtures/multi-migration-xDfXbJ/app/models/multimigctx.js +0 -26
  47. package/test/fixtures/multi-migration-xDfXbJ/config/environments/env.multimig.json +0 -1
  48. package/test/fixtures/multi-migration-xDfXbJ/db/multimigctx.sqlite +0 -0
  49. package/test/fixtures/multi-migration-xDfXbJ/package.json +0 -1
  50. package/test/fixtures/new-setter-large-string/config/environments/env.newsetter.json +0 -1
  51. package/test/fixtures/new-setter-large-string/db/newsettercontext.sqlite +0 -0
  52. package/test/fixtures/query-builder-parity/config/environments/env.parity.json +0 -1
  53. package/test/fixtures/query-builder-parity/db/parityctx.sqlite +0 -0
  54. package/test/fixtures/setter-and-update-drop/config/environments/env.setterdrop.json +0 -1
  55. package/test/fixtures/setter-and-update-drop/db/setdropctx.sqlite +0 -0
  56. package/test/fixtures/sqlite-lifecycle/config/environments/env.test.json +0 -1
  57. package/test/fixtures/sqlite-lifecycle/db/lifecyclecontext.sqlite +0 -0
  58. package/test/fixtures/text-types/config/environments/env.texttypes.json +0 -1
  59. package/test/fixtures/text-types/db/textctx.sqlite +0 -0
package/postgresEngine.js CHANGED
@@ -14,6 +14,29 @@ class postgresEngine {
14
14
  this.unsupportedWords = ["order"];
15
15
  }
16
16
 
17
+ /**
18
+ * Quote a Postgres identifier (table or column name).
19
+ *
20
+ * Postgres folds unquoted identifiers to lowercase, so `SELECT id FROM Foo`
21
+ * becomes `SELECT id FROM foo` at parse time. For CamelCase entities like
22
+ * `Agent`, `SchedulerLeader`, `MemoryDoc` the DDL creates the table with
23
+ * preserved case (because masterrecord's DDL quotes), but unquoted SELECTs
24
+ * fail with `relation "schedulerleader" does not exist`.
25
+ *
26
+ * This helper wraps every identifier in double-quotes and escapes any
27
+ * embedded double-quotes per the Postgres standard (`"` → `""`).
28
+ *
29
+ * Safe for `*` (returns `*` unwrapped) so `COUNT(alias.*)` still works.
30
+ */
31
+ _q(ident) {
32
+ if (ident === '*') return '*';
33
+ if (ident === null || ident === undefined) return ident;
34
+ const s = String(ident);
35
+ // Already-quoted identifiers pass through unchanged.
36
+ if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) return s;
37
+ return `"${s.replace(/"/g, '""')}"`;
38
+ }
39
+
17
40
  /**
18
41
  * Initialize PostgreSQL connection pool
19
42
  * @param {Object} config - PostgreSQL connection config
@@ -51,7 +74,9 @@ class postgresEngine {
51
74
  throw new Error('UPDATE failed: Invalid parameterized query structure. Check entity definition.');
52
75
  }
53
76
 
54
- const sqlQuery = `UPDATE ${query.tableName} SET ${query.arg.query} WHERE ${query.tableName}.${query.primaryKey} = $${query.arg.params.length + 1}`;
77
+ const t = this._q(query.tableName);
78
+ const pk = this._q(query.primaryKey);
79
+ const sqlQuery = `UPDATE ${t} SET ${query.arg.query} WHERE ${t}.${pk} = $${query.arg.params.length + 1}`;
55
80
  // Add primaryKeyValue to params array
56
81
  const params = [...query.arg.params, query.primaryKeyValue];
57
82
  return await this._runWithParams(sqlQuery, params);
@@ -62,7 +87,9 @@ class postgresEngine {
62
87
  */
63
88
  async delete(queryObject) {
64
89
  const sqlObject = this._buildDeleteObject(queryObject);
65
- const sqlQuery = `DELETE FROM ${sqlObject.tableName} WHERE ${sqlObject.tableName}.${sqlObject.primaryKey} = $1`;
90
+ const t = this._q(sqlObject.tableName);
91
+ const pk = this._q(sqlObject.primaryKey);
92
+ const sqlQuery = `DELETE FROM ${t} WHERE ${t}.${pk} = $1`;
66
93
  return await this._runWithParams(sqlQuery, [sqlObject.value]);
67
94
  }
68
95
 
@@ -78,12 +105,12 @@ class postgresEngine {
78
105
 
79
106
  // Get primary key name for RETURNING clause
80
107
  const primaryKey = tools.getPrimaryKeyObject(queryObject.__entity);
81
- const query = `INSERT INTO ${sqlObject.tableName} (${sqlObject.columns}) VALUES (${sqlObject.placeholders}) RETURNING ${primaryKey}`;
108
+ const query = `INSERT INTO ${this._q(sqlObject.tableName)} (${sqlObject.columns}) VALUES (${sqlObject.placeholders}) RETURNING ${this._q(primaryKey)}`;
82
109
 
83
110
  const result = await this._runWithParams(query, sqlObject.params);
84
111
 
85
112
  return {
86
- id: result.rows[0][primaryKey]
113
+ id: result.rows[0] ? result.rows[0][primaryKey] : undefined
87
114
  };
88
115
  }
89
116
 
@@ -120,7 +147,7 @@ class postgresEngine {
120
147
  allParams.push(...sqlObj.params);
121
148
  }
122
149
 
123
- const query = `INSERT INTO "${first.tableName}" (${first.columns}) VALUES ${valueGroups.join(', ')} RETURNING ${primaryKey}`;
150
+ const query = `INSERT INTO ${this._q(first.tableName)} (${first.columns}) VALUES ${valueGroups.join(', ')} RETURNING ${this._q(primaryKey)}`;
124
151
  const result = await this._runWithParams(query, allParams);
125
152
 
126
153
  // PostgreSQL returns rows with the primary key values
@@ -145,13 +172,18 @@ class postgresEngine {
145
172
  }
146
173
 
147
174
  /**
148
- * Batch delete using WHERE IN
175
+ * Batch delete using WHERE IN.
176
+ * @param {string} tableName
177
+ * @param {Array} ids
178
+ * @param {string} [primaryKey='id'] - Primary-key column name. Defaults to
179
+ * 'id' for back-compat, but callers should pass the entity's actual PK
180
+ * to support custom primary-key names.
149
181
  */
150
- async bulkDelete(tableName, ids) {
182
+ async bulkDelete(tableName, ids, primaryKey = 'id') {
151
183
  if (!ids || ids.length === 0) return;
152
184
 
153
185
  const placeholders = ids.map((_, i) => `$${i + 1}`).join(', ');
154
- const query = `DELETE FROM "${tableName}" WHERE id IN (${placeholders})`;
186
+ const query = `DELETE FROM ${this._q(tableName)} WHERE ${this._q(primaryKey)} IN (${placeholders})`;
155
187
  return await this._runWithParams(query, ids);
156
188
  }
157
189
 
@@ -258,6 +290,38 @@ class postgresEngine {
258
290
  }
259
291
  }
260
292
 
293
+ /**
294
+ * Introspection: Get column information for a table.
295
+ *
296
+ * Used by `schema.syncTable()` to diff the existing database schema
297
+ * against the entity definition so migrations can add only the
298
+ * missing columns. Without this method on Postgres, syncTable
299
+ * couldn't detect existing columns and re-ran migrations failed
300
+ * with `column "X" already exists`.
301
+ *
302
+ * Returns rows shaped like the SQLite/MySQL counterparts:
303
+ * { name, dflt_value, is_nullable, data_type }
304
+ */
305
+ async getTableInfo(tableName) {
306
+ try {
307
+ const sql = `
308
+ SELECT
309
+ column_name AS name,
310
+ column_default AS dflt_value,
311
+ is_nullable AS is_nullable,
312
+ data_type AS data_type
313
+ FROM information_schema.columns
314
+ WHERE table_schema = ANY(current_schemas(false))
315
+ AND table_name = $1
316
+ ORDER BY ordinal_position
317
+ `;
318
+ const result = await this._runWithParams(sql, [tableName]);
319
+ return (result && result.rows) ? result.rows : [];
320
+ } catch (_) {
321
+ return [];
322
+ }
323
+ }
324
+
261
325
  /**
262
326
  * Build complete SELECT query with parameters
263
327
  */
@@ -284,21 +348,58 @@ class postgresEngine {
284
348
  buildSelectString(query, entity) {
285
349
  if (query.select && query.select.selectFields && query.select.selectFields.length > 0) {
286
350
  const alias = this.getEntity(query.parentName || entity.__name, query.entityMap);
287
- return query.select.selectFields.map(f => `${alias}.${f}`).join(', ');
351
+ // Alias is a generated short string (e.g. "a", "p") so does not need quoting,
352
+ // but the user-defined column names CAN be camelCase and MUST be quoted.
353
+ return query.select.selectFields.map(f => `${alias}.${this._q(f)}`).join(', ');
354
+ }
355
+ // Fall back to a fully-qualified column list quoted per-identifier.
356
+ // tools.convertEntityToSelectParameterString returns "alias.col, alias.col"
357
+ // built off entity field names; rebuild it here with quoting since the
358
+ // helper itself is engine-agnostic and can't know our quoting rules.
359
+ const alias = this.getEntity(entity.__name, query.entityMap);
360
+ const cols = [];
361
+ for (const key in entity) {
362
+ if (key.startsWith('_')) continue;
363
+ const def = entity[key];
364
+ if (!def || typeof def !== 'object') continue;
365
+ if (def.type === 'hasMany' || def.type === 'hasOne' || def.type === 'hasManyThrough') continue;
366
+ if (def.lifecycle === true) continue;
367
+ // Use foreignKey for belongsTo, otherwise the column's declared name.
368
+ const colName = (def.relationshipType === 'belongsTo' && def.foreignKey)
369
+ ? def.foreignKey
370
+ : def.name;
371
+ if (!colName) continue;
372
+ cols.push(`${alias}.${this._q(colName)}`);
288
373
  }
289
- return `${tools.convertEntityToSelectParameterString(entity)}`;
374
+ return cols.join(', ');
290
375
  }
291
376
 
292
377
  buildCount(query, entity) {
293
378
  const entityStr = this.getEntity(entity.__name, query.entityMap);
294
379
  if (query.count === "none") {
295
- return `COUNT(${entityStr}.*)`;
380
+ // `alias.*` is not standard Postgres syntax — use COUNT(*) instead.
381
+ return `COUNT(*)`;
296
382
  }
297
- return `COUNT(${entityStr}.${query.count})`;
383
+ // query.count is a cachedExpr with selectFields when set via `.count(p => p.field)`.
384
+ let field;
385
+ if (query.count && query.count.selectFields && query.count.selectFields[0]) {
386
+ field = query.count.selectFields[0];
387
+ } else if (typeof query.count === 'string') {
388
+ field = query.count;
389
+ }
390
+ if (!field) return `COUNT(*)`;
391
+ return `COUNT(${entityStr}.${this._q(field)})`;
298
392
  }
299
393
 
300
394
  buildFrom(query, entity) {
301
- return `FROM ${entity.__name}`;
395
+ // Quote the table name AND alias the table so downstream
396
+ // `alias.column` references in SELECT/WHERE/ORDER BY resolve against
397
+ // the alias rather than the bare CamelCase name.
398
+ const alias = this.getEntity(entity.__name, query.entityMap);
399
+ if (alias && alias !== entity.__name) {
400
+ return `FROM ${this._q(entity.__name)} AS ${alias}`;
401
+ }
402
+ return `FROM ${this._q(entity.__name)}`;
302
403
  }
303
404
 
304
405
  /**
@@ -318,11 +419,18 @@ class postgresEngine {
318
419
  const item = itemEntity[query.parentName][table];
319
420
  const expressions = [];
320
421
  for (let exp in item.expressions) {
321
- let field = tools.capitalizeFirstLetter(item.expressions[exp].field);
422
+ // Use the field name verbatim for SQL emission so it
423
+ // matches the actual column case. The capitalized form
424
+ // is only useful for the navigational-relationship
425
+ // lookup (relationships are stored with PascalCase keys
426
+ // like `User`, `Profile` on the entity).
427
+ const originalField = item.expressions[exp].field;
428
+ const capitalized = tools.capitalizeFirstLetter(originalField);
429
+ let field = originalField;
322
430
  let entityRef = entity;
323
431
 
324
- if (mainQuery[field] && mainQuery[field].isNavigational) {
325
- entityRef = $that.getEntity(field, query.entityMap);
432
+ if (mainQuery[capitalized] && mainQuery[capitalized].isNavigational) {
433
+ entityRef = $that.getEntity(capitalized, query.entityMap);
326
434
  field = item.fields[1];
327
435
  }
328
436
 
@@ -336,14 +444,14 @@ class postgresEngine {
336
444
  }
337
445
 
338
446
  if (arg === "null") {
339
- expressions.push(`${entityRef}.${field} ${func} ${arg}`);
447
+ expressions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
340
448
  } else {
341
449
  // Check if arg is a parameterized placeholder
342
450
  const isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg));
343
451
  if (isPlaceholder || func === "IN") {
344
- expressions.push(`${entityRef}.${field} ${func} ${arg}`);
452
+ expressions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
345
453
  } else {
346
- expressions.push(`${entityRef}.${field} ${func} '${arg}'`);
454
+ expressions.push(`${entityRef}.${$that._q(field)} ${func} '${arg}'`);
347
455
  }
348
456
  }
349
457
  }
@@ -374,11 +482,14 @@ class postgresEngine {
374
482
  const conditions = [];
375
483
 
376
484
  for (let exp in item.expressions) {
377
- let field = tools.capitalizeFirstLetter(item.expressions[exp].field);
485
+ // Use the field name verbatim for SQL emission. See buildAnd for full rationale.
486
+ const originalField = item.expressions[exp].field;
487
+ const capitalized = tools.capitalizeFirstLetter(originalField);
488
+ let field = originalField;
378
489
  let entityRef = entity;
379
490
 
380
- if (mainQuery[field] && mainQuery[field].isNavigational) {
381
- entityRef = $that.getEntity(field, query.entityMap);
491
+ if (mainQuery[capitalized] && mainQuery[capitalized].isNavigational) {
492
+ entityRef = $that.getEntity(capitalized, query.entityMap);
382
493
  field = item.fields[1];
383
494
  }
384
495
 
@@ -392,16 +503,16 @@ class postgresEngine {
392
503
  }
393
504
 
394
505
  if (arg === "null") {
395
- conditions.push(`${entityRef}.${field} ${func} ${arg}`);
506
+ conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
396
507
  } else if (func === "IN") {
397
- conditions.push(`${entityRef}.${field} ${func} ${arg}`);
508
+ conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
398
509
  } else {
399
510
  // Check if arg is a parameterized placeholder ($1, $2, etc.)
400
511
  const isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg));
401
512
  if (isPlaceholder) {
402
- conditions.push(`${entityRef}.${field} ${func} ${arg}`);
513
+ conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
403
514
  } else {
404
- conditions.push(`${entityRef}.${field} ${func} '${arg}'`);
515
+ conditions.push(`${entityRef}.${$that._q(field)} ${func} '${arg}'`);
405
516
  }
406
517
  }
407
518
  }
@@ -457,7 +568,7 @@ class postgresEngine {
457
568
  const entityStr = this.getEntity(query.parentName, query.entityMap);
458
569
  const fieldList = [];
459
570
  for (const item in orderByEntity.selectFields) {
460
- fieldList.push(`${entityStr}.${orderByEntity.selectFields[item]}`);
571
+ fieldList.push(`${entityStr}.${this._q(orderByEntity.selectFields[item])}`);
461
572
  }
462
573
  if (fieldList.length === 0) return "";
463
574
  return `ORDER BY ${fieldList.join(', ')} ${orderByType}`;
@@ -523,7 +634,7 @@ class postgresEngine {
523
634
  }
524
635
  fkValue = $that._convertValueForDatabase(fkValue, model.__entity[dirtyFields[column]].type);
525
636
  const fore = `_${dirtyFields[column]}`;
526
- sqlParts.push(`${foreignKey} = $${paramIndex++}`);
637
+ sqlParts.push(`${$that._q(foreignKey)} = $${paramIndex++}`);
527
638
  params.push(model[fore]);
528
639
  break;
529
640
 
@@ -541,7 +652,7 @@ class postgresEngine {
541
652
  throw new Error(`UPDATE failed: ${typeError.message}`);
542
653
  }
543
654
  intValue = $that._convertValueForDatabase(intValue, model.__entity[dirtyFields[column]].type);
544
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
655
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
545
656
  params.push(intValue);
546
657
  break;
547
658
 
@@ -559,7 +670,7 @@ class postgresEngine {
559
670
  throw new Error(`UPDATE failed: ${typeError.message}`);
560
671
  }
561
672
  strValue = $that._convertValueForDatabase(strValue, model.__entity[dirtyFields[column]].type);
562
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
673
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
563
674
  params.push(strValue);
564
675
  break;
565
676
 
@@ -577,7 +688,7 @@ class postgresEngine {
577
688
  throw new Error(`UPDATE failed: ${typeError.message}`);
578
689
  }
579
690
  boolValue = $that._convertValueForDatabase(boolValue, model.__entity[dirtyFields[column]].type);
580
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
691
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
581
692
  params.push(boolValue);
582
693
  break;
583
694
 
@@ -595,12 +706,12 @@ class postgresEngine {
595
706
  throw new Error(`UPDATE failed: ${typeError.message}`);
596
707
  }
597
708
  timeValue = $that._convertValueForDatabase(timeValue, model.__entity[dirtyFields[column]].type);
598
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
709
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
599
710
  params.push(timeValue);
600
711
  break;
601
712
 
602
713
  case "hasMany":
603
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
714
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
604
715
  params.push(model["_" + dirtyFields[column]]);
605
716
  break;
606
717
 
@@ -618,7 +729,7 @@ class postgresEngine {
618
729
  } catch (transformError) {
619
730
  throw new Error(`UPDATE failed: ${transformError.message}`);
620
731
  }
621
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
732
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
622
733
  params.push(rawValue);
623
734
  }
624
735
  }
@@ -674,7 +785,16 @@ class postgresEngine {
674
785
 
675
786
  // Skip auto-increment primary keys
676
787
  if (modelEntity[column].auto !== true) {
677
- columnNames.push(column);
788
+ // For belongsTo relationships, the actual SQL column is
789
+ // the foreignKey (e.g. `user_id`), not the relationship
790
+ // property name (`User`). MySQL handles this; Postgres
791
+ // used to push the relationship name and emit invalid
792
+ // INSERT column lists.
793
+ const relationship = modelEntity[column].relationshipType;
794
+ const actualColumn = relationship === "belongsTo" && modelEntity[column].foreignKey
795
+ ? modelEntity[column].foreignKey
796
+ : column;
797
+ columnNames.push($that._q(actualColumn));
678
798
  params.push(fieldColumn);
679
799
  }
680
800
  }
@@ -112,7 +112,7 @@ test('Postgres: COUNT SQL has a FROM clause even with no prior .where()', () =>
112
112
  // accept either shape here since the bug under test is about FROM, not
113
113
  // the exact COUNT expression.
114
114
  assert.match(sql, /SELECT\s+COUNT\(/, 'emits SELECT COUNT(...)');
115
- assert.match(sql, /FROM\s+Thing/, 'has FROM clause naming the table');
115
+ assert.match(sql, /FROM\s+"?Thing"?/, 'has FROM clause naming the table (quoted or unquoted)');
116
116
  });
117
117
 
118
118
  test('SQLite engine directly: buildFrom on empty entityMap now produces a valid FROM', () => {
@@ -0,0 +1,142 @@
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
+ });