masterrecord 1.0.5 → 1.0.7

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 (54) hide show
  1. package/.claude/settings.local.json +4 -1
  2. package/QueryLanguage/queryMethods.js +8 -0
  3. package/QueryLanguage/queryScript.js +18 -8
  4. package/SQLLiteEngine.js +17 -7
  5. package/context.js +34 -7
  6. package/mySQLEngine.js +23 -19
  7. package/package.json +1 -1
  8. package/postgresEngine.js +123 -47
  9. package/test/count-no-from-audit.test.js +1 -1
  10. package/test/ctx-dollar-placeholder.test.js +142 -0
  11. package/test/postgres-camelcase-quoting.test.js +249 -0
  12. package/test/query-builder-parity.test.js +2 -2
  13. package/test/fixtures/broad-audit/config/environments/env.audit.json +0 -1
  14. package/test/fixtures/broad-audit/db/auditctx.sqlite +0 -0
  15. package/test/fixtures/count-chained-where/config/environments/env.countchained.json +0 -1
  16. package/test/fixtures/count-chained-where/db/countctx.sqlite +0 -0
  17. package/test/fixtures/count-no-from/config/environments/env.countfrom.json +0 -1
  18. package/test/fixtures/count-no-from/db/countfromctx.sqlite +0 -0
  19. package/test/fixtures/edge-cases-audit/config/environments/env.edgeaudit.json +0 -1
  20. package/test/fixtures/edge-cases-audit/db/edgectx.sqlite +0 -0
  21. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
  22. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
  23. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
  24. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -96
  25. package/test/fixtures/multi-migration-N4bUYy/app/models/multimigctx.js +0 -26
  26. package/test/fixtures/multi-migration-N4bUYy/config/environments/env.multimig.json +0 -1
  27. package/test/fixtures/multi-migration-N4bUYy/db/multimigctx.sqlite +0 -0
  28. package/test/fixtures/multi-migration-N4bUYy/package.json +0 -1
  29. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
  30. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
  31. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
  32. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -96
  33. package/test/fixtures/multi-migration-Qu42ZE/app/models/multimigctx.js +0 -26
  34. package/test/fixtures/multi-migration-Qu42ZE/config/environments/env.multimig.json +0 -1
  35. package/test/fixtures/multi-migration-Qu42ZE/db/multimigctx.sqlite +0 -0
  36. package/test/fixtures/multi-migration-Qu42ZE/package.json +0 -1
  37. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
  38. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
  39. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
  40. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -104
  41. package/test/fixtures/multi-migration-xDfXbJ/app/models/multimigctx.js +0 -26
  42. package/test/fixtures/multi-migration-xDfXbJ/config/environments/env.multimig.json +0 -1
  43. package/test/fixtures/multi-migration-xDfXbJ/db/multimigctx.sqlite +0 -0
  44. package/test/fixtures/multi-migration-xDfXbJ/package.json +0 -1
  45. package/test/fixtures/new-setter-large-string/config/environments/env.newsetter.json +0 -1
  46. package/test/fixtures/new-setter-large-string/db/newsettercontext.sqlite +0 -0
  47. package/test/fixtures/query-builder-parity/config/environments/env.parity.json +0 -1
  48. package/test/fixtures/query-builder-parity/db/parityctx.sqlite +0 -0
  49. package/test/fixtures/setter-and-update-drop/config/environments/env.setterdrop.json +0 -1
  50. package/test/fixtures/setter-and-update-drop/db/setdropctx.sqlite +0 -0
  51. package/test/fixtures/sqlite-lifecycle/config/environments/env.test.json +0 -1
  52. package/test/fixtures/sqlite-lifecycle/db/lifecyclecontext.sqlite +0 -0
  53. package/test/fixtures/text-types/config/environments/env.texttypes.json +0 -1
  54. package/test/fixtures/text-types/db/textctx.sqlite +0 -0
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "permissions": {
3
3
  "allow": [
4
- "Bash(node --test --test-timeout=20000 test/text-types.test.js)"
4
+ "Bash(node --test --test-timeout=20000 test/text-types.test.js)",
5
+ "Bash(node --check /Users/alexanderrich/Documents/development/opensourceHQ/MasterController/MasterActionFilters.js)",
6
+ "Bash(node --test test/action-filters-mixin.test.js)",
7
+ "Bash(npm test *)"
5
8
  ]
6
9
  }
7
10
  }
@@ -297,6 +297,14 @@ class queryMethods{
297
297
  }
298
298
 
299
299
  __validateAndCollectParameters(str, args, methodName){
300
+ // Normalize `<ident>.$$` (e.g. `ctx.$$`, `this.$$`) to bare `$$` so
301
+ // TypeScript/ESLint-clean lambdas like `(u) => u.id == ctx.$$` work
302
+ // identically to `'u => u.id == $$'`. The lambda is never evaluated
303
+ // at runtime — only stringified — so the property path doesn't matter.
304
+ // Note: `$$$$` in a String.prototype.replace replacement string means
305
+ // a literal `$$` (each `$$` escapes to a single `$`).
306
+ str = str.replace(/[A-Za-z_$][\w$]*\.\$\$/g, '$$$$');
307
+
300
308
  // Count placeholders - support both $$ (standard) and $ (backwards compatibility)
301
309
  // Match $$ first to avoid double-counting, then match remaining single $
302
310
  let placeholderCount = 0;
@@ -202,10 +202,16 @@ class queryScript{
202
202
 
203
203
  // look and grab all fields
204
204
  buildFields(text, desc){
205
- var match = text.match(/^([\w\d$_]+?)\s*=>((?:\{\sreturn\s)?[\s\S]*(?:\})?)/);
205
+ // Accept both `p => body` and `(p) => body` (and `(p, ...) => body`).
206
+ // JS Function.prototype.toString() preserves the parenthesized form
207
+ // for arrow functions, so when users pass a real lambda we receive
208
+ // `(p) => p.name == ...` — the previous regex only matched bare
209
+ // identifiers and silently mis-parsed parens as the entity name,
210
+ // producing SQL like `SELECT (.id, (.name FROM Plugin AS (`.
211
+ var match = text.match(/^\s*(?:\(\s*([\w\d$_]+)[^)]*\)|([\w\d$_]+))\s*=>((?:\{\sreturn\s)?[\s\S]*(?:\})?)/);
206
212
  if(match){
207
- const entity = match[1];
208
- let exprStr = match[2];
213
+ const entity = match[1] || match[2];
214
+ let exprStr = match[3];
209
215
  const fields = [];
210
216
 
211
217
  exprStr.replace(new RegExp(entity + "\\.([\\w_]+)", "g"), function (_, field) {
@@ -465,13 +471,17 @@ class queryScript{
465
471
  }
466
472
 
467
473
  getEntity(str){
468
- // Prefer parsing the lambda parameter (e.g., 'uc' in 'uc => uc.user_id == $$')
469
- const m = str.match(/^\s*([\w\d$_]+?)\s*=>/);
470
- if(m && m[1]){
471
- return m[1];
474
+ // Prefer parsing the lambda parameter. Accept both bare-arg and
475
+ // parenthesized-arg forms — JS `.toString()` preserves parens.
476
+ // uc => uc.user_id == $$
477
+ // (uc) => uc.user_id == $$
478
+ // (uc, idx) => ...
479
+ const m = str.match(/^\s*(?:\(\s*([\w\d$_]+)[^)]*\)|([\w\d$_]+))\s*=>/);
480
+ if(m){
481
+ return m[1] || m[2];
472
482
  }
473
483
  // Fallback to previous behavior: first non-space char
474
- var clean = str.replace(/\s/g, '');
484
+ var clean = str.replace(/\s/g, '');
475
485
  return clean.substring(0, 1);
476
486
  }
477
487
 
package/SQLLiteEngine.js CHANGED
@@ -102,11 +102,11 @@ class SQLLiteEngine {
102
102
  /**
103
103
  * Batch delete multiple entities using WHERE IN
104
104
  */
105
- async bulkDelete(tableName, ids) {
105
+ async bulkDelete(tableName, ids, primaryKey = 'id') {
106
106
  if (!ids || ids.length === 0) return Promise.resolve();
107
107
 
108
108
  const placeholders = ids.map(() => '?').join(', ');
109
- const query = `DELETE FROM [${tableName}] WHERE id IN (${placeholders})`;
109
+ const query = `DELETE FROM [${tableName}] WHERE [${primaryKey}] IN (${placeholders})`;
110
110
  return Promise.resolve(this._runWithParams(query, ids));
111
111
  }
112
112
 
@@ -345,10 +345,15 @@ class SQLLiteEngine {
345
345
  var item = itemEntity[query.parentName][table];
346
346
  const expressions = [];
347
347
  for (let exp in item.expressions) {
348
- var field = tools.capitalizeFirstLetter(item.expressions[exp].field);
349
- if(mainQuery[field]){
350
- if(mainQuery[field].isNavigational){
351
- entity = $that.getEntity(field, query.entityMap);
348
+ // Use the field name verbatim for SQL emission; only
349
+ // use the capitalized form for the navigational
350
+ // relationship lookup (those are PascalCase keys).
351
+ const originalField = item.expressions[exp].field;
352
+ const capitalized = tools.capitalizeFirstLetter(originalField);
353
+ var field = originalField;
354
+ if(mainQuery[capitalized]){
355
+ if(mainQuery[capitalized].isNavigational){
356
+ entity = $that.getEntity(capitalized, query.entityMap);
352
357
  field = item.fields[1];
353
358
  }
354
359
  }
@@ -398,7 +403,12 @@ class SQLLiteEngine {
398
403
  var exprs = item.expressions || [];
399
404
 
400
405
  function exprToSql(expr){
401
- var field = expr.field.toLowerCase();
406
+ // Preserve case for column emission. SQLite identifier matching
407
+ // is case-insensitive so the old `.toLowerCase()` worked in
408
+ // practice, but it would have hidden a bug if SQLite were ever
409
+ // configured with strict case-sensitive identifiers, and it
410
+ // produced inconsistent SQL output across engines.
411
+ var field = expr.field;
402
412
  var ent = entityAlias;
403
413
  if(mainQuery[field]){
404
414
  if(mainQuery[field].isNavigational){
package/context.js CHANGED
@@ -240,6 +240,29 @@ class context {
240
240
  this._queryCache = context._sharedQueryCache;
241
241
  }
242
242
 
243
+ /**
244
+ * Parameter placeholder accessor for TypeScript / ESLint-clean queries.
245
+ *
246
+ * Bare `$$` in a lambda body is a free identifier that fails static
247
+ * analysis. Accessing `ctx.$$` (or `this.$$` from inside a context method)
248
+ * is a valid property reference, so editors and type checkers won't flag it.
249
+ *
250
+ * The getter just returns the string `'$$'`. The lambda is never evaluated
251
+ * at runtime — `.where()` / `.orderBy()` / `.and()` stringify it and treat
252
+ * any `<ident>.$$` token (or bare `$$`) as a parameter placeholder.
253
+ *
254
+ * @example
255
+ * // Bare $$ — works, but ESLint/TS flag it
256
+ * await ctx.User.where('u => u.id == $$', 42).single();
257
+ *
258
+ * @example
259
+ * // ctx.$$ — same behavior, ESLint/TS-clean
260
+ * await ctx.User.where(u => u.id == ctx.$$, 42).single();
261
+ */
262
+ get $$() {
263
+ return '$$';
264
+ }
265
+
243
266
  /**
244
267
  * Ensure the database engine is initialized and ready for queries.
245
268
  *
@@ -1792,24 +1815,28 @@ class context {
1792
1815
  const deleteObject = new deleteManager(this._SQLEngine, this.__entities);
1793
1816
  await deleteObject.init(entities[0]);
1794
1817
  } else {
1795
- // Batch delete - group by table for efficiency
1796
- const deletesByTable = new Map(); // Use Map instead of object for better performance
1818
+ // Batch delete - group by (table, primaryKey) for efficiency. The
1819
+ // primary-key column is part of the grouping key so a context with
1820
+ // entities that have different PK column names still produces one
1821
+ // bulkDelete call per (table, PK) pair.
1822
+ const deletesByTable = new Map(); // Map<`${table}::${pk}`, { tableName, primaryKey, ids: [] }>
1797
1823
 
1798
1824
  for (const entity of entities) {
1799
1825
  const tableName = entity.__entity.__name;
1800
1826
  const primaryKey = tools.getPrimaryKeyObject(entity.__entity);
1801
1827
  const id = entity[primaryKey];
1828
+ const groupKey = `${tableName}::${primaryKey}`;
1802
1829
 
1803
- if (!deletesByTable.has(tableName)) {
1804
- deletesByTable.set(tableName, []);
1830
+ if (!deletesByTable.has(groupKey)) {
1831
+ deletesByTable.set(groupKey, { tableName, primaryKey, ids: [] });
1805
1832
  }
1806
- deletesByTable.get(tableName).push(id);
1833
+ deletesByTable.get(groupKey).ids.push(id);
1807
1834
  }
1808
1835
 
1809
1836
  try {
1810
1837
  // Performance: Use for...of with Map entries
1811
- for (const [tableName, ids] of deletesByTable.entries()) {
1812
- await this._SQLEngine.bulkDelete(tableName, ids);
1838
+ for (const { tableName, primaryKey, ids } of deletesByTable.values()) {
1839
+ await this._SQLEngine.bulkDelete(tableName, ids, primaryKey);
1813
1840
  }
1814
1841
  } catch (error) {
1815
1842
  console.error('[Context] Bulk delete failed, falling back to individual deletes:', error.message);
package/mySQLEngine.js CHANGED
@@ -117,13 +117,18 @@ class MySQLEngine {
117
117
  }
118
118
 
119
119
  /**
120
- * Batch delete using WHERE IN
120
+ * Batch delete using WHERE IN.
121
+ * @param {string} tableName
122
+ * @param {Array} ids
123
+ * @param {string} [primaryKey='id'] - Primary-key column name. Defaults to
124
+ * 'id' for back-compat, but callers should pass the entity's actual PK
125
+ * to support custom primary-key names.
121
126
  */
122
- async bulkDelete(tableName, ids) {
127
+ async bulkDelete(tableName, ids, primaryKey = 'id') {
123
128
  if (!ids || ids.length === 0) return;
124
129
 
125
130
  const placeholders = ids.map(() => '?').join(', ');
126
- const query = `DELETE FROM \`${tableName}\` WHERE id IN (${placeholders})`;
131
+ const query = `DELETE FROM \`${tableName}\` WHERE \`${primaryKey}\` IN (${placeholders})`;
127
132
  return await this._runWithParams(query, ids);
128
133
  }
129
134
 
@@ -141,10 +146,6 @@ class MySQLEngine {
141
146
 
142
147
  if (queryString.query) {
143
148
  const params = query.parameters ? query.parameters.getParams() : [];
144
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
145
- console.debug("[SQL]", queryString.query);
146
- console.debug("[Params]", params);
147
- }
148
149
  const result = await this._runWithParams(queryString.query, params);
149
150
  return result[0] || null;
150
151
  }
@@ -177,10 +178,6 @@ class MySQLEngine {
177
178
 
178
179
  if (sql) {
179
180
  const params = query.parameters ? query.parameters.getParams() : [];
180
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
181
- console.debug("[SQL]", sql);
182
- console.debug("[Params]", params);
183
- }
184
181
  const result = await this._runWithParams(sql, params);
185
182
  return result[0] || null;
186
183
  }
@@ -219,10 +216,6 @@ class MySQLEngine {
219
216
 
220
217
  if (queryString.query) {
221
218
  const params = query.parameters ? query.parameters.getParams() : [];
222
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
223
- console.debug("[SQL]", queryString.query);
224
- console.debug("[Params]", params);
225
- }
226
219
  const result = await this._runWithParams(queryString.query, params);
227
220
  return result || [];
228
221
  }
@@ -359,9 +352,17 @@ class MySQLEngine {
359
352
  const item = itemEntity[query.parentName][table];
360
353
  const expressions = [];
361
354
  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);
355
+ // Use the field name verbatim for SQL emission. With
356
+ // backtick quoting, MySQL on case-sensitive filesystems
357
+ // (Linux defaults) wouldn't match a column named `stage`
358
+ // if we emit `\`Stage\``. Only use the capitalized form
359
+ // for the navigational-relationship lookup since those
360
+ // are stored as PascalCase keys on the entity.
361
+ const originalField = item.expressions[exp].field;
362
+ const capitalized = tools.capitalizeFirstLetter(originalField);
363
+ let field = originalField;
364
+ if (mainQuery[capitalized] && mainQuery[capitalized].isNavigational) {
365
+ entity = $that.getEntity(capitalized, query.entityMap);
365
366
  field = item.fields[1];
366
367
  }
367
368
 
@@ -476,7 +477,10 @@ class MySQLEngine {
476
477
  const exprs = item.expressions || [];
477
478
 
478
479
  function exprToSql(expr) {
479
- let field = expr.field.toLowerCase();
480
+ // Preserve case for column-name emission — `.toLowerCase()` used
481
+ // to turn `updatedAt` into `updatedat`, which doesn't match a
482
+ // case-sensitive backtick-quoted column on Linux MySQL.
483
+ let field = expr.field;
480
484
  let ent = entityAlias;
481
485
  if (mainQuery[field]) {
482
486
  if (mainQuery[field].isNavigational) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.0.005",
3
+ "version": "1.0.7",
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
@@ -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
 
@@ -170,10 +202,6 @@ class postgresEngine {
170
202
  }
171
203
 
172
204
  if (queryString.query) {
173
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
174
- console.debug("[SQL]", queryString.query);
175
- console.debug("[Params]", queryString.params || []);
176
- }
177
205
  const result = await this._runWithParams(queryString.query, queryString.params || []);
178
206
  return result.rows[0] || null;
179
207
  }
@@ -207,10 +235,6 @@ class postgresEngine {
207
235
  }
208
236
 
209
237
  if (queryString.query) {
210
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
211
- console.debug("[SQL]", queryString.query);
212
- console.debug("[Params]", queryString.params);
213
- }
214
238
  const result = await this._runWithParams(queryString.query, queryString.params);
215
239
  return result.rows[0] || null;
216
240
  }
@@ -234,10 +258,6 @@ class postgresEngine {
234
258
  }
235
259
 
236
260
  if (selectQuery.query) {
237
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
238
- console.debug("[SQL]", selectQuery.query);
239
- console.debug("[Params]", selectQuery.params || []);
240
- }
241
261
  const result = await this._runWithParams(selectQuery.query, selectQuery.params || []);
242
262
  return result.rows || [];
243
263
  }
@@ -296,21 +316,58 @@ class postgresEngine {
296
316
  buildSelectString(query, entity) {
297
317
  if (query.select && query.select.selectFields && query.select.selectFields.length > 0) {
298
318
  const alias = this.getEntity(query.parentName || entity.__name, query.entityMap);
299
- return query.select.selectFields.map(f => `${alias}.${f}`).join(', ');
319
+ // Alias is a generated short string (e.g. "a", "p") so does not need quoting,
320
+ // but the user-defined column names CAN be camelCase and MUST be quoted.
321
+ return query.select.selectFields.map(f => `${alias}.${this._q(f)}`).join(', ');
300
322
  }
301
- return `${tools.convertEntityToSelectParameterString(entity)}`;
323
+ // Fall back to a fully-qualified column list quoted per-identifier.
324
+ // tools.convertEntityToSelectParameterString returns "alias.col, alias.col"
325
+ // built off entity field names; rebuild it here with quoting since the
326
+ // helper itself is engine-agnostic and can't know our quoting rules.
327
+ const alias = this.getEntity(entity.__name, query.entityMap);
328
+ const cols = [];
329
+ for (const key in entity) {
330
+ if (key.startsWith('_')) continue;
331
+ const def = entity[key];
332
+ if (!def || typeof def !== 'object') continue;
333
+ if (def.type === 'hasMany' || def.type === 'hasOne' || def.type === 'hasManyThrough') continue;
334
+ if (def.lifecycle === true) continue;
335
+ // Use foreignKey for belongsTo, otherwise the column's declared name.
336
+ const colName = (def.relationshipType === 'belongsTo' && def.foreignKey)
337
+ ? def.foreignKey
338
+ : def.name;
339
+ if (!colName) continue;
340
+ cols.push(`${alias}.${this._q(colName)}`);
341
+ }
342
+ return cols.join(', ');
302
343
  }
303
344
 
304
345
  buildCount(query, entity) {
305
346
  const entityStr = this.getEntity(entity.__name, query.entityMap);
306
347
  if (query.count === "none") {
307
- return `COUNT(${entityStr}.*)`;
348
+ // `alias.*` is not standard Postgres syntax — use COUNT(*) instead.
349
+ return `COUNT(*)`;
350
+ }
351
+ // query.count is a cachedExpr with selectFields when set via `.count(p => p.field)`.
352
+ let field;
353
+ if (query.count && query.count.selectFields && query.count.selectFields[0]) {
354
+ field = query.count.selectFields[0];
355
+ } else if (typeof query.count === 'string') {
356
+ field = query.count;
308
357
  }
309
- return `COUNT(${entityStr}.${query.count})`;
358
+ if (!field) return `COUNT(*)`;
359
+ return `COUNT(${entityStr}.${this._q(field)})`;
310
360
  }
311
361
 
312
362
  buildFrom(query, entity) {
313
- return `FROM ${entity.__name}`;
363
+ // Quote the table name AND alias the table so downstream
364
+ // `alias.column` references in SELECT/WHERE/ORDER BY resolve against
365
+ // the alias rather than the bare CamelCase name.
366
+ const alias = this.getEntity(entity.__name, query.entityMap);
367
+ if (alias && alias !== entity.__name) {
368
+ return `FROM ${this._q(entity.__name)} AS ${alias}`;
369
+ }
370
+ return `FROM ${this._q(entity.__name)}`;
314
371
  }
315
372
 
316
373
  /**
@@ -330,11 +387,18 @@ class postgresEngine {
330
387
  const item = itemEntity[query.parentName][table];
331
388
  const expressions = [];
332
389
  for (let exp in item.expressions) {
333
- let field = tools.capitalizeFirstLetter(item.expressions[exp].field);
390
+ // Use the field name verbatim for SQL emission so it
391
+ // matches the actual column case. The capitalized form
392
+ // is only useful for the navigational-relationship
393
+ // lookup (relationships are stored with PascalCase keys
394
+ // like `User`, `Profile` on the entity).
395
+ const originalField = item.expressions[exp].field;
396
+ const capitalized = tools.capitalizeFirstLetter(originalField);
397
+ let field = originalField;
334
398
  let entityRef = entity;
335
399
 
336
- if (mainQuery[field] && mainQuery[field].isNavigational) {
337
- entityRef = $that.getEntity(field, query.entityMap);
400
+ if (mainQuery[capitalized] && mainQuery[capitalized].isNavigational) {
401
+ entityRef = $that.getEntity(capitalized, query.entityMap);
338
402
  field = item.fields[1];
339
403
  }
340
404
 
@@ -348,14 +412,14 @@ class postgresEngine {
348
412
  }
349
413
 
350
414
  if (arg === "null") {
351
- expressions.push(`${entityRef}.${field} ${func} ${arg}`);
415
+ expressions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
352
416
  } else {
353
417
  // Check if arg is a parameterized placeholder
354
418
  const isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg));
355
419
  if (isPlaceholder || func === "IN") {
356
- expressions.push(`${entityRef}.${field} ${func} ${arg}`);
420
+ expressions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
357
421
  } else {
358
- expressions.push(`${entityRef}.${field} ${func} '${arg}'`);
422
+ expressions.push(`${entityRef}.${$that._q(field)} ${func} '${arg}'`);
359
423
  }
360
424
  }
361
425
  }
@@ -386,11 +450,14 @@ class postgresEngine {
386
450
  const conditions = [];
387
451
 
388
452
  for (let exp in item.expressions) {
389
- let field = tools.capitalizeFirstLetter(item.expressions[exp].field);
453
+ // Use the field name verbatim for SQL emission. See buildAnd for full rationale.
454
+ const originalField = item.expressions[exp].field;
455
+ const capitalized = tools.capitalizeFirstLetter(originalField);
456
+ let field = originalField;
390
457
  let entityRef = entity;
391
458
 
392
- if (mainQuery[field] && mainQuery[field].isNavigational) {
393
- entityRef = $that.getEntity(field, query.entityMap);
459
+ if (mainQuery[capitalized] && mainQuery[capitalized].isNavigational) {
460
+ entityRef = $that.getEntity(capitalized, query.entityMap);
394
461
  field = item.fields[1];
395
462
  }
396
463
 
@@ -404,16 +471,16 @@ class postgresEngine {
404
471
  }
405
472
 
406
473
  if (arg === "null") {
407
- conditions.push(`${entityRef}.${field} ${func} ${arg}`);
474
+ conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
408
475
  } else if (func === "IN") {
409
- conditions.push(`${entityRef}.${field} ${func} ${arg}`);
476
+ conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
410
477
  } else {
411
478
  // Check if arg is a parameterized placeholder ($1, $2, etc.)
412
479
  const isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg));
413
480
  if (isPlaceholder) {
414
- conditions.push(`${entityRef}.${field} ${func} ${arg}`);
481
+ conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
415
482
  } else {
416
- conditions.push(`${entityRef}.${field} ${func} '${arg}'`);
483
+ conditions.push(`${entityRef}.${$that._q(field)} ${func} '${arg}'`);
417
484
  }
418
485
  }
419
486
  }
@@ -469,7 +536,7 @@ class postgresEngine {
469
536
  const entityStr = this.getEntity(query.parentName, query.entityMap);
470
537
  const fieldList = [];
471
538
  for (const item in orderByEntity.selectFields) {
472
- fieldList.push(`${entityStr}.${orderByEntity.selectFields[item]}`);
539
+ fieldList.push(`${entityStr}.${this._q(orderByEntity.selectFields[item])}`);
473
540
  }
474
541
  if (fieldList.length === 0) return "";
475
542
  return `ORDER BY ${fieldList.join(', ')} ${orderByType}`;
@@ -535,7 +602,7 @@ class postgresEngine {
535
602
  }
536
603
  fkValue = $that._convertValueForDatabase(fkValue, model.__entity[dirtyFields[column]].type);
537
604
  const fore = `_${dirtyFields[column]}`;
538
- sqlParts.push(`${foreignKey} = $${paramIndex++}`);
605
+ sqlParts.push(`${$that._q(foreignKey)} = $${paramIndex++}`);
539
606
  params.push(model[fore]);
540
607
  break;
541
608
 
@@ -553,7 +620,7 @@ class postgresEngine {
553
620
  throw new Error(`UPDATE failed: ${typeError.message}`);
554
621
  }
555
622
  intValue = $that._convertValueForDatabase(intValue, model.__entity[dirtyFields[column]].type);
556
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
623
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
557
624
  params.push(intValue);
558
625
  break;
559
626
 
@@ -571,7 +638,7 @@ class postgresEngine {
571
638
  throw new Error(`UPDATE failed: ${typeError.message}`);
572
639
  }
573
640
  strValue = $that._convertValueForDatabase(strValue, model.__entity[dirtyFields[column]].type);
574
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
641
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
575
642
  params.push(strValue);
576
643
  break;
577
644
 
@@ -589,7 +656,7 @@ class postgresEngine {
589
656
  throw new Error(`UPDATE failed: ${typeError.message}`);
590
657
  }
591
658
  boolValue = $that._convertValueForDatabase(boolValue, model.__entity[dirtyFields[column]].type);
592
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
659
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
593
660
  params.push(boolValue);
594
661
  break;
595
662
 
@@ -607,12 +674,12 @@ class postgresEngine {
607
674
  throw new Error(`UPDATE failed: ${typeError.message}`);
608
675
  }
609
676
  timeValue = $that._convertValueForDatabase(timeValue, model.__entity[dirtyFields[column]].type);
610
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
677
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
611
678
  params.push(timeValue);
612
679
  break;
613
680
 
614
681
  case "hasMany":
615
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
682
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
616
683
  params.push(model["_" + dirtyFields[column]]);
617
684
  break;
618
685
 
@@ -630,7 +697,7 @@ class postgresEngine {
630
697
  } catch (transformError) {
631
698
  throw new Error(`UPDATE failed: ${transformError.message}`);
632
699
  }
633
- sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
700
+ sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
634
701
  params.push(rawValue);
635
702
  }
636
703
  }
@@ -686,7 +753,16 @@ class postgresEngine {
686
753
 
687
754
  // Skip auto-increment primary keys
688
755
  if (modelEntity[column].auto !== true) {
689
- columnNames.push(column);
756
+ // For belongsTo relationships, the actual SQL column is
757
+ // the foreignKey (e.g. `user_id`), not the relationship
758
+ // property name (`User`). MySQL handles this; Postgres
759
+ // used to push the relationship name and emit invalid
760
+ // INSERT column lists.
761
+ const relationship = modelEntity[column].relationshipType;
762
+ const actualColumn = relationship === "belongsTo" && modelEntity[column].foreignKey
763
+ ? modelEntity[column].foreignKey
764
+ : column;
765
+ columnNames.push($that._q(actualColumn));
690
766
  params.push(fieldColumn);
691
767
  }
692
768
  }
@@ -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', () => {