masterrecord 1.0.6 → 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.
- package/.claude/settings.local.json +4 -1
- package/QueryLanguage/queryMethods.js +8 -0
- package/QueryLanguage/queryScript.js +18 -8
- package/SQLLiteEngine.js +17 -7
- package/context.js +34 -7
- package/mySQLEngine.js +23 -7
- package/package.json +1 -1
- package/postgresEngine.js +123 -35
- package/test/count-no-from-audit.test.js +1 -1
- package/test/ctx-dollar-placeholder.test.js +142 -0
- package/test/postgres-camelcase-quoting.test.js +249 -0
- package/test/query-builder-parity.test.js +2 -2
- package/test/fixtures/broad-audit/config/environments/env.audit.json +0 -1
- package/test/fixtures/broad-audit/db/auditctx.sqlite +0 -0
- package/test/fixtures/count-chained-where/config/environments/env.countchained.json +0 -1
- package/test/fixtures/count-chained-where/db/countctx.sqlite +0 -0
- package/test/fixtures/count-no-from/config/environments/env.countfrom.json +0 -1
- package/test/fixtures/count-no-from/db/countfromctx.sqlite +0 -0
- package/test/fixtures/edge-cases-audit/config/environments/env.edgeaudit.json +0 -1
- package/test/fixtures/edge-cases-audit/db/edgectx.sqlite +0 -0
- package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
- package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
- package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
- package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -96
- package/test/fixtures/multi-migration-N4bUYy/app/models/multimigctx.js +0 -26
- package/test/fixtures/multi-migration-N4bUYy/config/environments/env.multimig.json +0 -1
- package/test/fixtures/multi-migration-N4bUYy/db/multimigctx.sqlite +0 -0
- package/test/fixtures/multi-migration-N4bUYy/package.json +0 -1
- package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
- package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
- package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
- package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -96
- package/test/fixtures/multi-migration-Qu42ZE/app/models/multimigctx.js +0 -26
- package/test/fixtures/multi-migration-Qu42ZE/config/environments/env.multimig.json +0 -1
- package/test/fixtures/multi-migration-Qu42ZE/db/multimigctx.sqlite +0 -0
- package/test/fixtures/multi-migration-Qu42ZE/package.json +0 -1
- package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
- package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
- package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
- package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -104
- package/test/fixtures/multi-migration-xDfXbJ/app/models/multimigctx.js +0 -26
- package/test/fixtures/multi-migration-xDfXbJ/config/environments/env.multimig.json +0 -1
- package/test/fixtures/multi-migration-xDfXbJ/db/multimigctx.sqlite +0 -0
- package/test/fixtures/multi-migration-xDfXbJ/package.json +0 -1
- package/test/fixtures/new-setter-large-string/config/environments/env.newsetter.json +0 -1
- package/test/fixtures/new-setter-large-string/db/newsettercontext.sqlite +0 -0
- package/test/fixtures/query-builder-parity/config/environments/env.parity.json +0 -1
- package/test/fixtures/query-builder-parity/db/parityctx.sqlite +0 -0
- package/test/fixtures/setter-and-update-drop/config/environments/env.setterdrop.json +0 -1
- package/test/fixtures/setter-and-update-drop/db/setdropctx.sqlite +0 -0
- package/test/fixtures/sqlite-lifecycle/config/environments/env.test.json +0 -1
- package/test/fixtures/sqlite-lifecycle/db/lifecyclecontext.sqlite +0 -0
- package/test/fixtures/text-types/config/environments/env.texttypes.json +0 -1
- 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
|
-
|
|
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[
|
|
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
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
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
|
|
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
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
1804
|
-
deletesByTable.set(tableName, []);
|
|
1830
|
+
if (!deletesByTable.has(groupKey)) {
|
|
1831
|
+
deletesByTable.set(groupKey, { tableName, primaryKey, ids: [] });
|
|
1805
1832
|
}
|
|
1806
|
-
deletesByTable.get(
|
|
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
|
|
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
|
|
131
|
+
const query = `DELETE FROM \`${tableName}\` WHERE \`${primaryKey}\` IN (${placeholders})`;
|
|
127
132
|
return await this._runWithParams(query, ids);
|
|
128
133
|
}
|
|
129
134
|
|
|
@@ -347,9 +352,17 @@ class MySQLEngine {
|
|
|
347
352
|
const item = itemEntity[query.parentName][table];
|
|
348
353
|
const expressions = [];
|
|
349
354
|
for (const exp in item.expressions) {
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
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);
|
|
353
366
|
field = item.fields[1];
|
|
354
367
|
}
|
|
355
368
|
|
|
@@ -464,7 +477,10 @@ class MySQLEngine {
|
|
|
464
477
|
const exprs = item.expressions || [];
|
|
465
478
|
|
|
466
479
|
function exprToSql(expr) {
|
|
467
|
-
|
|
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;
|
|
468
484
|
let ent = entityAlias;
|
|
469
485
|
if (mainQuery[field]) {
|
|
470
486
|
if (mainQuery[field].isNavigational) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.0.
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
|
@@ -284,21 +316,58 @@ class postgresEngine {
|
|
|
284
316
|
buildSelectString(query, entity) {
|
|
285
317
|
if (query.select && query.select.selectFields && query.select.selectFields.length > 0) {
|
|
286
318
|
const alias = this.getEntity(query.parentName || entity.__name, query.entityMap);
|
|
287
|
-
|
|
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(', ');
|
|
322
|
+
}
|
|
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)}`);
|
|
288
341
|
}
|
|
289
|
-
return
|
|
342
|
+
return cols.join(', ');
|
|
290
343
|
}
|
|
291
344
|
|
|
292
345
|
buildCount(query, entity) {
|
|
293
346
|
const entityStr = this.getEntity(entity.__name, query.entityMap);
|
|
294
347
|
if (query.count === "none") {
|
|
295
|
-
|
|
348
|
+
// `alias.*` is not standard Postgres syntax — use COUNT(*) instead.
|
|
349
|
+
return `COUNT(*)`;
|
|
296
350
|
}
|
|
297
|
-
|
|
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;
|
|
357
|
+
}
|
|
358
|
+
if (!field) return `COUNT(*)`;
|
|
359
|
+
return `COUNT(${entityStr}.${this._q(field)})`;
|
|
298
360
|
}
|
|
299
361
|
|
|
300
362
|
buildFrom(query, entity) {
|
|
301
|
-
|
|
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)}`;
|
|
302
371
|
}
|
|
303
372
|
|
|
304
373
|
/**
|
|
@@ -318,11 +387,18 @@ class postgresEngine {
|
|
|
318
387
|
const item = itemEntity[query.parentName][table];
|
|
319
388
|
const expressions = [];
|
|
320
389
|
for (let exp in item.expressions) {
|
|
321
|
-
|
|
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;
|
|
322
398
|
let entityRef = entity;
|
|
323
399
|
|
|
324
|
-
if (mainQuery[
|
|
325
|
-
entityRef = $that.getEntity(
|
|
400
|
+
if (mainQuery[capitalized] && mainQuery[capitalized].isNavigational) {
|
|
401
|
+
entityRef = $that.getEntity(capitalized, query.entityMap);
|
|
326
402
|
field = item.fields[1];
|
|
327
403
|
}
|
|
328
404
|
|
|
@@ -336,14 +412,14 @@ class postgresEngine {
|
|
|
336
412
|
}
|
|
337
413
|
|
|
338
414
|
if (arg === "null") {
|
|
339
|
-
expressions.push(`${entityRef}.${field} ${func} ${arg}`);
|
|
415
|
+
expressions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
|
|
340
416
|
} else {
|
|
341
417
|
// Check if arg is a parameterized placeholder
|
|
342
418
|
const isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg));
|
|
343
419
|
if (isPlaceholder || func === "IN") {
|
|
344
|
-
expressions.push(`${entityRef}.${field} ${func} ${arg}`);
|
|
420
|
+
expressions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
|
|
345
421
|
} else {
|
|
346
|
-
expressions.push(`${entityRef}.${field} ${func} '${arg}'`);
|
|
422
|
+
expressions.push(`${entityRef}.${$that._q(field)} ${func} '${arg}'`);
|
|
347
423
|
}
|
|
348
424
|
}
|
|
349
425
|
}
|
|
@@ -374,11 +450,14 @@ class postgresEngine {
|
|
|
374
450
|
const conditions = [];
|
|
375
451
|
|
|
376
452
|
for (let exp in item.expressions) {
|
|
377
|
-
|
|
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;
|
|
378
457
|
let entityRef = entity;
|
|
379
458
|
|
|
380
|
-
if (mainQuery[
|
|
381
|
-
entityRef = $that.getEntity(
|
|
459
|
+
if (mainQuery[capitalized] && mainQuery[capitalized].isNavigational) {
|
|
460
|
+
entityRef = $that.getEntity(capitalized, query.entityMap);
|
|
382
461
|
field = item.fields[1];
|
|
383
462
|
}
|
|
384
463
|
|
|
@@ -392,16 +471,16 @@ class postgresEngine {
|
|
|
392
471
|
}
|
|
393
472
|
|
|
394
473
|
if (arg === "null") {
|
|
395
|
-
conditions.push(`${entityRef}.${field} ${func} ${arg}`);
|
|
474
|
+
conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
|
|
396
475
|
} else if (func === "IN") {
|
|
397
|
-
conditions.push(`${entityRef}.${field} ${func} ${arg}`);
|
|
476
|
+
conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
|
|
398
477
|
} else {
|
|
399
478
|
// Check if arg is a parameterized placeholder ($1, $2, etc.)
|
|
400
479
|
const isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg));
|
|
401
480
|
if (isPlaceholder) {
|
|
402
|
-
conditions.push(`${entityRef}.${field} ${func} ${arg}`);
|
|
481
|
+
conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
|
|
403
482
|
} else {
|
|
404
|
-
conditions.push(`${entityRef}.${field} ${func} '${arg}'`);
|
|
483
|
+
conditions.push(`${entityRef}.${$that._q(field)} ${func} '${arg}'`);
|
|
405
484
|
}
|
|
406
485
|
}
|
|
407
486
|
}
|
|
@@ -457,7 +536,7 @@ class postgresEngine {
|
|
|
457
536
|
const entityStr = this.getEntity(query.parentName, query.entityMap);
|
|
458
537
|
const fieldList = [];
|
|
459
538
|
for (const item in orderByEntity.selectFields) {
|
|
460
|
-
fieldList.push(`${entityStr}.${orderByEntity.selectFields[item]}`);
|
|
539
|
+
fieldList.push(`${entityStr}.${this._q(orderByEntity.selectFields[item])}`);
|
|
461
540
|
}
|
|
462
541
|
if (fieldList.length === 0) return "";
|
|
463
542
|
return `ORDER BY ${fieldList.join(', ')} ${orderByType}`;
|
|
@@ -523,7 +602,7 @@ class postgresEngine {
|
|
|
523
602
|
}
|
|
524
603
|
fkValue = $that._convertValueForDatabase(fkValue, model.__entity[dirtyFields[column]].type);
|
|
525
604
|
const fore = `_${dirtyFields[column]}`;
|
|
526
|
-
sqlParts.push(`${foreignKey} = $${paramIndex++}`);
|
|
605
|
+
sqlParts.push(`${$that._q(foreignKey)} = $${paramIndex++}`);
|
|
527
606
|
params.push(model[fore]);
|
|
528
607
|
break;
|
|
529
608
|
|
|
@@ -541,7 +620,7 @@ class postgresEngine {
|
|
|
541
620
|
throw new Error(`UPDATE failed: ${typeError.message}`);
|
|
542
621
|
}
|
|
543
622
|
intValue = $that._convertValueForDatabase(intValue, model.__entity[dirtyFields[column]].type);
|
|
544
|
-
sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
|
|
623
|
+
sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
|
|
545
624
|
params.push(intValue);
|
|
546
625
|
break;
|
|
547
626
|
|
|
@@ -559,7 +638,7 @@ class postgresEngine {
|
|
|
559
638
|
throw new Error(`UPDATE failed: ${typeError.message}`);
|
|
560
639
|
}
|
|
561
640
|
strValue = $that._convertValueForDatabase(strValue, model.__entity[dirtyFields[column]].type);
|
|
562
|
-
sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
|
|
641
|
+
sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
|
|
563
642
|
params.push(strValue);
|
|
564
643
|
break;
|
|
565
644
|
|
|
@@ -577,7 +656,7 @@ class postgresEngine {
|
|
|
577
656
|
throw new Error(`UPDATE failed: ${typeError.message}`);
|
|
578
657
|
}
|
|
579
658
|
boolValue = $that._convertValueForDatabase(boolValue, model.__entity[dirtyFields[column]].type);
|
|
580
|
-
sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
|
|
659
|
+
sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
|
|
581
660
|
params.push(boolValue);
|
|
582
661
|
break;
|
|
583
662
|
|
|
@@ -595,12 +674,12 @@ class postgresEngine {
|
|
|
595
674
|
throw new Error(`UPDATE failed: ${typeError.message}`);
|
|
596
675
|
}
|
|
597
676
|
timeValue = $that._convertValueForDatabase(timeValue, model.__entity[dirtyFields[column]].type);
|
|
598
|
-
sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
|
|
677
|
+
sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
|
|
599
678
|
params.push(timeValue);
|
|
600
679
|
break;
|
|
601
680
|
|
|
602
681
|
case "hasMany":
|
|
603
|
-
sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
|
|
682
|
+
sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
|
|
604
683
|
params.push(model["_" + dirtyFields[column]]);
|
|
605
684
|
break;
|
|
606
685
|
|
|
@@ -618,7 +697,7 @@ class postgresEngine {
|
|
|
618
697
|
} catch (transformError) {
|
|
619
698
|
throw new Error(`UPDATE failed: ${transformError.message}`);
|
|
620
699
|
}
|
|
621
|
-
sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
|
|
700
|
+
sqlParts.push(`${$that._q(dirtyFields[column])} = $${paramIndex++}`);
|
|
622
701
|
params.push(rawValue);
|
|
623
702
|
}
|
|
624
703
|
}
|
|
@@ -674,7 +753,16 @@ class postgresEngine {
|
|
|
674
753
|
|
|
675
754
|
// Skip auto-increment primary keys
|
|
676
755
|
if (modelEntity[column].auto !== true) {
|
|
677
|
-
|
|
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));
|
|
678
766
|
params.push(fieldColumn);
|
|
679
767
|
}
|
|
680
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
|
|
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', () => {
|