masterrecord 1.5.16 → 1.22.0

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.
@@ -3,6 +3,7 @@
3
3
  import entityTrackerModel from '../Entity/entityTrackerModel.js';
4
4
  import tools from '../Tools.js';
5
5
  import queryScript from './queryScript.js';
6
+ import FieldTransformer from '../Entity/fieldTransformer.js';
6
7
 
7
8
  // Security: `.take()`/`.skip()` values are interpolated directly into
8
9
  // LIMIT/OFFSET (these clauses cannot be parameterized on SQLite/MySQL/Postgres).
@@ -31,6 +32,59 @@ class queryMethods{
31
32
  // Tracking follows the context's default (EF's QueryTrackingBehavior);
32
33
  // override per query with .asNoTracking() / .asTracking().
33
34
  this.__noTracking = (context && context.__queryTrackingBehavior === 'no-track');
35
+ // Global query filters: applied once per execution unless ignored.
36
+ this.__ignoredFilters = null; // null = apply all; true = ignore all; Set = ignore these names
37
+ this.__filtersApplied = false;
38
+ // EF split query: navigation paths loaded AFTER the main query, one
39
+ // batched (IN-list) query per level — used by thenInclude(),
40
+ // asSplitQuery() and include() of implicit many-to-many navigations.
41
+ this.__postIncludes = []; // [['tags', 'category'], ['author']]
42
+ this.__splitQuery = false;
43
+ this.__lastSqlIncludeNav = null;
44
+ }
45
+
46
+ /**
47
+ * Skip this entity's global query filters for this query (EF Core
48
+ * IgnoreQueryFilters). With no argument ALL filters are ignored; pass an
49
+ * array of names to ignore only those (EF 10 named filters).
50
+ * @example db.Blog.ignoreQueryFilters().toList(); // include soft-deleted rows
51
+ * @example db.Blog.ignoreQueryFilters(['softDelete']).toList(); // keep the tenant filter
52
+ */
53
+ ignoreQueryFilters(names){
54
+ if (names === undefined || names === null || names === true) { this.__ignoredFilters = true; return this; }
55
+ const list = Array.isArray(names) ? names : [names];
56
+ this.__ignoredFilters = new Set(list.map(String));
57
+ return this;
58
+ }
59
+
60
+ /** Append the entity's active global query filters to the WHERE (once). */
61
+ __applyQueryFilters(){
62
+ if (this.__filtersApplied) return;
63
+ this.__filtersApplied = true;
64
+ // TPH: a derived dbset always carries its discriminator predicate (EF:
65
+ // it is part of the type mapping, NOT a query filter — IgnoreQueryFilters
66
+ // never removes it).
67
+ const tph = this.__entity && this.__entity.__tph;
68
+ if (tph && tph.isDerived) {
69
+ const hasWhere = !!(this.__queryObject.script && this.__queryObject.script.where);
70
+ if (hasWhere) this.and(`r => r.${tph.column} == $$`, tph.value);
71
+ else this.where(`r => r.${tph.column} == $$`, tph.value);
72
+ }
73
+ if (this.__ignoredFilters === true) return;
74
+ const ctx = this.__context;
75
+ if (!ctx || typeof ctx._queryFiltersFor !== 'function') return;
76
+ // base-type filters apply to derived sets (EF); plus the derived type's own
77
+ const filters = ctx._queryFiltersFor(this.__entity.__name)
78
+ .concat(tph && tph.isDerived ? ctx._queryFiltersFor(tph.typeName) : []);
79
+ for (const f of filters) {
80
+ if (this.__ignoredFilters instanceof Set && this.__ignoredFilters.has(f.name)) continue;
81
+ // Function args are resolved at query time with the context
82
+ // (e.g. the current tenant id held on the context instance).
83
+ const args = (f.args || []).map(a => (typeof a === 'function' ? a(ctx) : a));
84
+ const hasWhere = !!(this.__queryObject.script && this.__queryObject.script.where);
85
+ if (hasWhere) this.and(f.expr, ...args);
86
+ else this.where(f.expr, ...args);
87
+ }
34
88
  }
35
89
 
36
90
  /**
@@ -58,12 +112,213 @@ class queryMethods{
58
112
  return this;
59
113
  }
60
114
 
115
+ // ---- EF Core query ergonomics: Find, Any, aggregates, ThenBy, Distinct ----
116
+
117
+ /**
118
+ * Find by primary key, checking the context's identity map FIRST (EF Core
119
+ * Find/FindAsync): a tracked instance is returned without a query; otherwise
120
+ * the row is loaded (and tracked). Returns null if not found.
121
+ */
122
+ async find(...ids){
123
+ const keys = tools.primaryKeys(this.__entity);
124
+ if (!keys.length) throw new Error(`masterrecord: find() — no primary key defined on entity '${this.__entity.__name}'`);
125
+ const values = this.__keyValuesFromArgs(keys, ids, 'find');
126
+ const ctx = this.__context;
127
+ const table = this.__entity.__name;
128
+ for (const e of ctx.__trackedEntitiesMap.values()) {
129
+ if (e && e.__entity && e.__entity.__name === table && e.__state !== 'delete'
130
+ && keys.every((k, i) => String(tools.dataValue(e, k)) === String(values[i]))) {
131
+ this.__reset();
132
+ return e;
133
+ }
134
+ }
135
+ return this.findById(...values);
136
+ }
137
+
138
+ /** Key values from find()/findById() args: (a, b) or ({ a, b }) for composite keys. */
139
+ __keyValuesFromArgs(keys, ids, method){
140
+ if (keys.length === 1) {
141
+ if (ids.length === 1 && ids[0] && typeof ids[0] === 'object' && !Array.isArray(ids[0]) && keys[0] in ids[0]) return [ids[0][keys[0]]];
142
+ return [ids[0]];
143
+ }
144
+ if (ids.length === 1 && ids[0] && typeof ids[0] === 'object' && !Array.isArray(ids[0])) {
145
+ const missing = keys.filter(k => !(k in ids[0]));
146
+ if (missing.length) throw new Error(`masterrecord: ${method}() on '${this.__entity.__name}' needs all key values { ${keys.join(', ')} }; missing: ${missing.join(', ')}.`);
147
+ return keys.map(k => ids[0][k]);
148
+ }
149
+ if (ids.length !== keys.length) throw new Error(`masterrecord: ${method}() on '${this.__entity.__name}' takes ${keys.length} key values (${keys.join(', ')}) — EF Find(a, b); received ${ids.length}.`);
150
+ return ids;
151
+ }
152
+
153
+ /**
154
+ * EF Any(): true if at least one row matches (optionally with a predicate).
155
+ * `any('u => u.email == $$', email)` ≡ `where(...).exists()`.
156
+ */
157
+ async any(predicate, ...args){
158
+ if (predicate !== undefined && predicate !== null) this.where(predicate, ...args);
159
+ return this.exists();
160
+ }
161
+
162
+ /** EF Sum(): 0 for no rows. */
163
+ async sum(field){ return this.__aggregate('SUM', field, 0); }
164
+ /** EF Average(): null for no rows. */
165
+ async avg(field){ return this.__aggregate('AVG', field, null); }
166
+ /** EF Min(): null for no rows. */
167
+ async min(field){ return this.__aggregate('MIN', field, null); }
168
+ /** EF Max(): null for no rows. */
169
+ async max(field){ return this.__aggregate('MAX', field, null); }
170
+
171
+ async __aggregate(fn, field, emptyValue){
172
+ if (!field || typeof field !== 'string') throw new TypeError(`masterrecord: ${fn.toLowerCase()}(field) requires a column name.`);
173
+ const def = this.__entity[field];
174
+ if (!def || typeof def !== 'object' || def.type === 'hasOne' || def.type === 'hasMany' || def.type === 'hasManyThrough') {
175
+ throw new Error(`masterrecord: ${fn.toLowerCase()}('${field}') — '${field}' is not a column of ${this.__entity.__name}.`);
176
+ }
177
+ const column = (def.relationshipType === 'belongsTo' && def.foreignKey) ? def.foreignKey : (def.name || field);
178
+ this.__applyQueryFilters();
179
+ if (this.__queryObject.script.entityMap.length === 0) this.__queryObject.skipClause(this.__entity.__name);
180
+ const ctx = this.__context;
181
+ await ctx._ensureReady();
182
+ try {
183
+ const v = await ctx._execWithRetry(() => ctx._SQLEngine.getAggregate(this.__queryObject, this.__entity, fn, column));
184
+ if (v === null || v === undefined) return emptyValue;
185
+ const n = Number(v);
186
+ return Number.isNaN(n) ? v : n;
187
+ } finally {
188
+ this.__reset();
189
+ }
190
+ }
191
+
192
+ /** EF Distinct(): SELECT DISTINCT over the projected columns. */
193
+ distinct(){
194
+ this.__queryObject.script.distinct = true;
195
+ return this;
196
+ }
197
+
198
+ /**
199
+ * EF ThenBy / ThenByDescending: secondary sort keys after orderBy().
200
+ * Accepts a lambda (`'u => u.name'`) or a bare column name.
201
+ */
202
+ thenBy(fieldOrLambda){ return this.__thenBy(fieldOrLambda, 'ASC'); }
203
+ thenByDescending(fieldOrLambda){ return this.__thenBy(fieldOrLambda, 'DESC'); }
204
+ __thenBy(fieldOrLambda, dir){
205
+ const text = String(typeof fieldOrLambda === 'function' ? fieldOrLambda.toString() : fieldOrLambda).trim();
206
+ const m = text.match(/=>\s*\w+\.(\w+)\s*;?\s*$/) || (/^\w+$/.test(text) ? [null, text] : null);
207
+ if (!m) throw new TypeError(`masterrecord: thenBy expects a column lambda like 'u => u.name' or a column name, got ${JSON.stringify(fieldOrLambda)}`);
208
+ const field = m[1];
209
+ if (!this.__entity[field] || typeof this.__entity[field] !== 'object') {
210
+ throw new Error(`masterrecord: thenBy — '${field}' is not a column of ${this.__entity.__name}.`);
211
+ }
212
+ const s = this.__queryObject.script;
213
+ (s.thenBy ||= []).push({ field, dir });
214
+ return this;
215
+ }
216
+
217
+ /**
218
+ * Materialize rows as plain objects (DTO-style projection). Results are
219
+ * not tracked. `options` are passed to entity.toObject().
220
+ */
221
+ async toObjectList(options){
222
+ const rows = await this.asNoTracking().toList();
223
+ return rows.map(r => (typeof r.toObject === 'function' ? r.toObject(options) : r));
224
+ }
225
+
226
+ // ---- Set-based writes (EF Core ExecuteUpdate / ExecuteDelete) ----------
227
+ // One SQL statement over the rows the query selects. They bypass the
228
+ // change tracker entirely (tracked instances are NOT refreshed — don't mix
229
+ // them with pending tracked edits to the same rows), execute immediately,
230
+ // and return the number of rows affected. Inside ctx.transaction() they
231
+ // join the open transaction; otherwise each is its own autocommit statement.
232
+
233
+ /**
234
+ * UPDATE every row the query selects.
235
+ * @param {Object} setters - { column: value } — values are parameterized
236
+ * (and run through the column's transformer); use `sql\`col + 1\`` (from
237
+ * `masterrecord.sql` / 'masterrecord/sql') to reference existing values
238
+ * (EF's SetProperty(b => b.X, b => b.X + 1)).
239
+ * @returns {Promise<number>} rows affected
240
+ * @example await db.Blog.where('b => b.rating < $$', 3).executeUpdate({ hidden: true, views: sql`views + 1` });
241
+ */
242
+ async executeUpdate(setters){
243
+ if (!setters || typeof setters !== 'object' || Array.isArray(setters) || Object.keys(setters).length === 0) {
244
+ throw new TypeError('masterrecord: executeUpdate(setters) expects a non-empty object of { column: value | sql`...` }.');
245
+ }
246
+ this.__guardExecuteQuery('executeUpdate');
247
+ const def = this.__entity;
248
+ const list = [];
249
+ for (const [col, val] of Object.entries(setters)) {
250
+ const f = def[col];
251
+ if (!f || typeof f !== 'object' || f.type === 'hasOne' || f.type === 'hasMany' || f.type === 'hasManyThrough') {
252
+ throw new Error(`masterrecord: executeUpdate — '${col}' is not a column of ${def.__name}.`);
253
+ }
254
+ if (f.primary) throw new Error(`masterrecord: executeUpdate — cannot update the primary key '${col}'.`);
255
+ const column = (f.relationshipType === 'belongsTo' && f.foreignKey) ? f.foreignKey : (f.name || col);
256
+ if (val && typeof val === 'object' && typeof val.__rawSql === 'string') {
257
+ list.push({ column, raw: val.__rawSql });
258
+ } else {
259
+ let v = val;
260
+ if (FieldTransformer.hasTransformer(f)) v = FieldTransformer.toDatabase(v, f, def.__name, col);
261
+ if (typeof v === 'boolean' && !this.__context.isPostgres) v = v ? 1 : 0;
262
+ list.push({ column, value: v });
263
+ }
264
+ }
265
+ return this.__runExecute(eng => eng.executeUpdate(this.__queryObject.script, this.__entity, list));
266
+ }
267
+
268
+ /**
269
+ * DELETE every row the query selects (one statement, no loading, no tracker).
270
+ * @returns {Promise<number>} rows affected
271
+ * @example await db.Session.where('s => s.expiresAt < $$', now).executeDelete();
272
+ */
273
+ async executeDelete(){
274
+ this.__guardExecuteQuery('executeDelete');
275
+ return this.__runExecute(eng => eng.executeDelete(this.__queryObject.script, this.__entity));
276
+ }
277
+
278
+ __guardExecuteQuery(name){
279
+ const s = this.__queryObject.script;
280
+ if (s.raw) throw new Error(`masterrecord: ${name}() cannot be combined with raw().`);
281
+ if (s.include && s.include.length) throw new Error(`masterrecord: ${name}() does not support include() — filter on the table's own columns.`);
282
+ // Global query filters apply to set-based writes too (EF applies them to
283
+ // ExecuteUpdate/ExecuteDelete): a soft-delete filter keeps deleted rows
284
+ // out of a bulk update; a tenant filter scopes a bulk delete.
285
+ this.__applyQueryFilters();
286
+ // Bootstrap the alias/entityMap when no clause was chained (same as count()).
287
+ if (s.entityMap.length === 0) this.__queryObject.skipClause(this.__entity.__name);
288
+ }
289
+
290
+ async __runExecute(fn){
291
+ const ctx = this.__context;
292
+ await ctx._ensureReady();
293
+ const run = async () => {
294
+ const affected = await fn(ctx._SQLEngine);
295
+ ctx._queryCache.invalidateTable(this.__entity.__name);
296
+ return affected;
297
+ };
298
+ try {
299
+ // Inside a user transaction this context already holds the engine
300
+ // lock; otherwise serialize with other units of work on the shared
301
+ // connection.
302
+ return (ctx.__engineLockDepth > 0) ? await run() : await ctx._withEngineLock(() => ctx._execWithRetry(run));
303
+ } finally {
304
+ this.__reset();
305
+ }
306
+ }
307
+
61
308
  // build a single entity
62
309
  __singleEntityBuilder(dataModel){
63
310
  const $that = this;
64
311
  if(dataModel){
65
312
  const ent = new entityTrackerModel();
66
- const mod = ent.build(dataModel, $that.__entity, $that.__context);
313
+ // TPH: materialize the row as its DERIVED type when the discriminator
314
+ // names one (EF returns Cat/Dog instances from the Animal set).
315
+ let def = $that.__entity;
316
+ const tph = def && def.__tph;
317
+ if (tph && tph.derived && dataModel[tph.column] !== undefined && dataModel[tph.column] !== null) {
318
+ const derived = tph.derived.get(String(dataModel[tph.column]));
319
+ if (derived) def = derived;
320
+ }
321
+ const mod = ent.build(dataModel, def, $that.__context);
67
322
  mod.__state = "track";
68
323
  if ($that.__noTracking) {
69
324
  // AsNoTracking: flag it so a later mutation won't enqueue a write
@@ -94,21 +349,110 @@ class queryMethods{
94
349
 
95
350
  __reset(){
96
351
  this.__queryObject.reset();
352
+ this.__filtersApplied = false;
353
+ this.__ignoredFilters = null;
354
+ this.__postIncludes = [];
355
+ this.__splitQuery = false;
356
+ this.__lastSqlIncludeNav = null;
357
+ this.__groupBy = null;
97
358
  }
98
359
 
99
360
 
100
361
  // do join on two tables = inner join
362
+ // These operators are not implemented yet. They used to be empty bodies
363
+ // returning undefined, so chaining off them threw a bare TypeError far
364
+ // from the call site. Fail loudly and explain the alternative instead.
101
365
  join(){
366
+ throw new Error('masterrecord: join() is not supported yet. Use include() for eager-loaded relationships, or ctx.query()/ctx.execute() for a hand-written JOIN.');
367
+ }
102
368
 
369
+ /**
370
+ * EF Core `GroupBy(x => x.status)` — group the filtered rows by one or more
371
+ * columns, then project aggregates with `.aggregate({...})`:
372
+ *
373
+ * await db.Order.where('o => o.year == $$', 2026)
374
+ * .groupBy('o => o.status')
375
+ * .aggregate({ n: 'count', total: ['sum', 'amount'], avg: ['avg', 'amount'] },
376
+ * { having: { n: ['>', 1] }, orderBy: [['total', 'desc']] });
377
+ * // -> [{ status: 'paid', n: 12, total: 980, avg: 81.6 }, ...]
378
+ *
379
+ * Translates to `SELECT <groups>, <aggregates> ... GROUP BY ... [HAVING] [ORDER BY]`
380
+ * on every engine (EF's GroupBy + Select(g => new { g.Key, g.Count(), g.Sum() })).
381
+ * Global query filters and where()/and() apply; take()/skip() page the groups.
382
+ */
383
+ groupBy(...fields){
384
+ const cols = fields.flat().map(f => this.__columnNameFrom(f, 'groupBy'));
385
+ if (!cols.length) throw new Error('masterrecord: groupBy() requires at least one column, e.g. groupBy("o => o.status").');
386
+ this.__groupBy = cols;
387
+ return this;
103
388
  }
104
389
 
105
- groupBy(){
106
-
390
+ /** Terminal for groupBy(): project aggregates per group (see groupBy()). */
391
+ async aggregate(spec, opts = {}){
392
+ if (!this.__groupBy || !this.__groupBy.length) throw new Error('masterrecord: aggregate() must follow groupBy().');
393
+ if (!spec || typeof spec !== 'object' || !Object.keys(spec).length) throw new Error('masterrecord: aggregate({ alias: "count" | [fn, column] }) requires at least one aggregate.');
394
+ const FN = { count: 'COUNT', sum: 'SUM', avg: 'AVG', min: 'MIN', max: 'MAX' };
395
+ const ident = /^[A-Za-z_][A-Za-z0-9_]*$/;
396
+ const aggs = [];
397
+ for (const [alias, def] of Object.entries(spec)) {
398
+ if (!ident.test(alias)) throw new Error(`masterrecord: aggregate alias '${alias}' must be an identifier.`);
399
+ if (this.__groupBy.some(g => g.column === alias)) throw new Error(`masterrecord: aggregate alias '${alias}' collides with a group column.`);
400
+ let fn, column = null;
401
+ if (typeof def === 'string') { fn = def; }
402
+ else if (Array.isArray(def)) { [fn, column] = def; }
403
+ else throw new Error(`masterrecord: aggregate '${alias}' must be 'count' or [fn, column].`);
404
+ fn = String(fn).toLowerCase();
405
+ if (!FN[fn]) throw new Error(`masterrecord: unknown aggregate '${fn}' for '${alias}' (count, sum, avg, min, max).`);
406
+ if (fn !== 'count' || column) column = this.__columnNameFrom(column, 'aggregate').column;
407
+ aggs.push({ alias, fn: FN[fn], column });
408
+ }
409
+ const having = [];
410
+ for (const [alias, cond] of Object.entries(opts.having || {})) {
411
+ const agg = aggs.find(a => a.alias === alias);
412
+ if (!agg) throw new Error(`masterrecord: having refers to unknown aggregate '${alias}'.`);
413
+ const [op, value] = Array.isArray(cond) ? cond : ['==', cond];
414
+ const ops = { '==': '=', '=': '=', '!=': '<>', '<>': '<>', '>': '>', '>=': '>=', '<': '<', '<=': '<=' };
415
+ if (!ops[op]) throw new Error(`masterrecord: having operator '${op}' not supported (==, !=, >, >=, <, <=).`);
416
+ having.push({ agg, op: ops[op], value });
417
+ }
418
+ const orderBy = (opts.orderBy || []).map(o => {
419
+ const [name, dir] = Array.isArray(o) ? o : [o, 'asc'];
420
+ const known = aggs.some(a => a.alias === name) || this.__groupBy.some(g => g.column === name);
421
+ if (!known) throw new Error(`masterrecord: orderBy '${name}' must be a group column or an aggregate alias.`);
422
+ return { name, desc: String(dir).toLowerCase() === 'desc' };
423
+ });
424
+ this.__applyQueryFilters();
425
+ if (this.__queryObject.script.entityMap.length === 0) this.__queryObject.skipClause(this.__entity.__name);
426
+ const ctx = this.__context;
427
+ await ctx._ensureReady();
428
+ try {
429
+ const groups = this.__groupBy;
430
+ const rows = await ctx._execWithRetry(() => ctx._SQLEngine.getGrouped(this.__queryObject, this.__entity, groups, aggs, having, orderBy));
431
+ return (rows || []).map(r => {
432
+ const o = {};
433
+ for (const g of groups) o[g.field] = r[g.column];
434
+ for (const a of aggs) { const v = r[a.alias]; const n = Number(v); o[a.alias] = (v === null || v === undefined) ? null : (Number.isNaN(n) ? v : n); }
435
+ return o;
436
+ });
437
+ } finally {
438
+ this.__reset();
439
+ }
107
440
  }
108
441
 
109
- // do join on two tables = inner join
110
- _____leftJoin(){
442
+ /** { field, column } for a lambda ('o => o.status') or bare column name; validates it is a scalar column. */
443
+ __columnNameFrom(query, method){
444
+ const field = this.__navNameFrom(query);
445
+ const def = field ? this.__entity[field] : null;
446
+ if (!def || typeof def !== 'object' || def.type === 'hasOne' || def.type === 'hasMany' || def.type === 'hasManyThrough') {
447
+ throw new Error(`masterrecord: ${method}('${field}') — '${field}' is not a column of ${this.__entity.__name}.`);
448
+ }
449
+ const column = (def.relationshipType === 'belongsTo' && def.foreignKey) ? def.foreignKey : (def.name || field);
450
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(column)) throw new Error(`masterrecord: ${method} — invalid column '${column}'.`);
451
+ return { field, column };
452
+ }
111
453
 
454
+ leftJoin(){
455
+ throw new Error('masterrecord: leftJoin() is not supported yet. Use include() (compiles to a LEFT JOIN) or ctx.query() for a hand-written JOIN.');
112
456
  }
113
457
 
114
458
  ______orderByCount(query, ...args){
@@ -187,12 +531,90 @@ class queryMethods{
187
531
  // when you dont want to use lazy loading and want it called at that moment
188
532
  //Eagerly loading
189
533
  include(query, ...args){
534
+ // Implicit many-to-many (manyToMany()) and split-query mode load the
535
+ // navigation AFTER the main query, batched per level (EF AsSplitQuery).
536
+ const nav = this.__navNameFrom(query);
537
+ const def = nav ? this.__entity[nav] : null;
538
+ // EF applies global query filters to included navigations too: when the
539
+ // target entity has active filters, load it through the split loader
540
+ // (the dbset query applies them; ignoreQueryFilters() propagates).
541
+ const targetOf = (d) => !d || typeof d !== 'object' ? null
542
+ : d.relationshipType === 'belongsTo' ? d.foreignTable
543
+ : d.type === 'hasManyThrough' ? (d.targetTable || null)
544
+ : (d.foreignTable || nav);
545
+ const targetHasFilters = (t) => !!(t && this.__context && typeof this.__context._queryFiltersFor === 'function' && this.__context._queryFiltersFor(t).length > 0);
546
+ if ((def && typeof def === 'object' && def.implicitJoin) || this.__splitQuery || targetHasFilters(targetOf(def))) {
547
+ if (args && args.length) throw new Error('masterrecord: include() parameters are not supported for split-query / many-to-many includes; filter with where() on the result or use a query filter.');
548
+ this.__postIncludes.push([nav]);
549
+ return this;
550
+ }
190
551
  let str = query.toString();
191
552
  str = this.__validateAndCollectParameters(str, args, 'include');
192
553
  this.__queryObject.include(str, this.__entity.__name);
554
+ this.__lastSqlIncludeNav = nav;
555
+ return this;
556
+ }
557
+
558
+ /**
559
+ * EF Core `ThenInclude`: load the next navigation level of the preceding
560
+ * include() — `db.Post.include('p => p.tags').thenInclude('t => t.category')`.
561
+ * Implemented as EF's split query: after the main query, ONE batched query
562
+ * (IN on the parent keys) per level, on every engine, so there is no
563
+ * cartesian explosion and no N+1. Works for belongsTo, hasOne, hasMany,
564
+ * hasManyThrough and manyToMany at any depth; chain thenInclude() again
565
+ * for deeper levels.
566
+ */
567
+ thenInclude(query){
568
+ const nav = this.__navNameFrom(query);
569
+ if (!nav) throw new Error('masterrecord: thenInclude() expects a navigation, e.g. thenInclude("t => t.category") or thenInclude("category").');
570
+ if (this.__postIncludes.length) {
571
+ this.__postIncludes[this.__postIncludes.length - 1].push(nav);
572
+ } else if (this.__lastSqlIncludeNav) {
573
+ // The root was an eager (SQL) include: continue from its hydrated
574
+ // values; levels that were not hydrated are batch-loaded.
575
+ this.__postIncludes.push([this.__lastSqlIncludeNav, nav]);
576
+ } else {
577
+ throw new Error('masterrecord: thenInclude() must follow include().');
578
+ }
579
+ return this;
580
+ }
581
+
582
+ /**
583
+ * EF Core `AsSplitQuery`: load every include() of this query with a
584
+ * separate batched query per navigation instead of one joined SQL
585
+ * statement. Call it BEFORE include().
586
+ */
587
+ asSplitQuery(){
588
+ if (this.__lastSqlIncludeNav) throw new Error('masterrecord: asSplitQuery() must be called before include().');
589
+ this.__splitQuery = true;
193
590
  return this;
194
591
  }
195
592
 
593
+ /** Navigation name from 'p => p.tags', 'p => p.tags.select(...)', or 'tags'. */
594
+ __navNameFrom(query){
595
+ if (query === undefined || query === null) return null;
596
+ const s = typeof query === 'function' ? query.toString() : String(query);
597
+ const m = s.match(/=>\s*\(?\s*[A-Za-z_$][\w$]*\s*\)?\s*\.\s*([A-Za-z_$][\w$]*)/);
598
+ if (m) return m[1];
599
+ const bare = s.trim().match(/^([A-Za-z_$][\w$]*)/);
600
+ return bare ? bare[1] : null;
601
+ }
602
+
603
+ /** Run the split-query include paths on the materialized result (list or single). */
604
+ async __runPostIncludes(result){
605
+ const paths = this.__postIncludes;
606
+ if (!paths || !paths.length) return;
607
+ const roots = Array.isArray(result) ? result : (result ? [result] : []);
608
+ if (!roots.length) return;
609
+ for (const path of paths) {
610
+ let level = roots;
611
+ for (const nav of path) {
612
+ level = await this.__context.__batchLoadNavigation(level, nav, { ignoredFilters: this.__ignoredFilters });
613
+ if (!level.length) break;
614
+ }
615
+ }
616
+ }
617
+
196
618
  // only takes a array of selected items
197
619
  select(query, ...args){
198
620
  let str = query.toString();
@@ -269,6 +691,9 @@ class queryMethods{
269
691
  this.__queryObject.count(str, this.__entity.__name);
270
692
  }
271
693
 
694
+ // Global query filters (soft delete / tenant) apply to counts too.
695
+ this.__applyQueryFilters();
696
+
272
697
  // Bootstrap the entityMap if no prior clause was chained. Without
273
698
  // this, a plain `.count()` produced empty FROM/alias on SQLite and
274
699
  // silently returned 1 (the row count of a no-FROM SELECT). `.single()`
@@ -281,21 +706,21 @@ class queryMethods{
281
706
 
282
707
  if(this.__context.isSQLite){
283
708
  // trying to match string select and relace with select Count(*);
284
- var entityValue = await this.__context._SQLEngine.getCount(this.__queryObject, this.__entity, this.__context);
709
+ var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.getCount(this.__queryObject, this.__entity, this.__context));
285
710
  var val = entityValue[Object.keys(entityValue)[0]];
286
711
  this.__reset();
287
712
  return val;
288
713
  }
289
714
  else if(this.__context.isMySQL){
290
715
  // trying to match string select and relace with select Count(*);
291
- var entityValue = await this.__context._SQLEngine.getCount(this.__queryObject, this.__entity, this.__context);
716
+ var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.getCount(this.__queryObject, this.__entity, this.__context));
292
717
  var val = entityValue[Object.keys(entityValue)[0]];
293
718
  this.__reset();
294
719
  return val;
295
720
  }
296
721
  else if(this.__context.isPostgres){
297
722
  // trying to match string select and relace with select Count(*);
298
- var entityValue = await this.__context._SQLEngine.getCount(this.__queryObject, this.__entity, this.__context);
723
+ var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.getCount(this.__queryObject, this.__entity, this.__context));
299
724
  var val = entityValue[Object.keys(entityValue)[0]];
300
725
  this.__reset();
301
726
  return val;
@@ -372,8 +797,10 @@ class queryMethods{
372
797
  throw new Error(`Field '${fieldName}' does not exist on ${this.__entity.__name}`);
373
798
  }
374
799
 
375
- const entities = await this.toList();
376
- return entities.map(entity => entity[fieldName]);
800
+ // SQL projection (SELECT <field> only) with no tracking — pluck is a
801
+ // read of one column, not a full-entity load.
802
+ const rows = await this.asNoTracking().select(`r => r.${fieldName}`).toList();
803
+ return rows.map(entity => entity[fieldName]);
377
804
  }
378
805
 
379
806
  /**
@@ -507,30 +934,22 @@ class queryMethods{
507
934
  }
508
935
 
509
936
  // Convenience method: Find record by primary key ID
510
- async findById(id){
511
- // Find the primary key field in the entity
512
- let primaryKeyField = null;
513
- for (const fieldName in this.__entity) {
514
- const field = this.__entity[fieldName];
515
- if (field && field.primary === true) {
516
- primaryKeyField = fieldName;
517
- break;
518
- }
519
- }
520
-
521
- if (!primaryKeyField) {
937
+ async findById(...ids){
938
+ const keys = tools.primaryKeys(this.__entity);
939
+ if (!keys.length) {
522
940
  throw new Error(`findById error: No primary key defined on entity '${this.__entity.__name}'`);
523
941
  }
524
-
525
- // Build where clause: entity.primaryKey == id
526
- const entityParam = 'r'; // Standard parameter name
527
- const whereClause = `${entityParam} => ${entityParam}.${primaryKeyField} == $$`;
528
-
529
- // Chain where() and single()
530
- return await this.where(whereClause, id).single();
942
+ // Composite keys (EF HasKey(a, b)): findById(a, b) or findById({ a, b })
943
+ const values = this.__keyValuesFromArgs(keys, ids, 'findById');
944
+ let q = this;
945
+ for (let i = 0; i < keys.length; i++) {
946
+ q = i === 0 ? q.where(`r => r.${keys[i]} == $$`, values[i]) : q.and(`r => r.${keys[i]} == $$`, values[i]);
947
+ }
948
+ return await q.single();
531
949
  }
532
950
 
533
951
  async single(){
952
+ this.__applyQueryFilters(); // global query filters (soft delete / tenant)
534
953
  // If no clauses were used before single(), seed defaults so SQL is valid
535
954
  if(this.__queryObject.script.entityMap.length === 0){
536
955
  this.__queryObject.skipClause(this.__entity.__name);
@@ -545,7 +964,10 @@ class queryMethods{
545
964
 
546
965
  // Check cache first (if enabled for this query)
547
966
  if (this.__useCache) {
548
- const cached = this.__context._queryCache.get(cacheKey);
967
+ // `await` so an async cache (RedisQueryCache) works: without it a
968
+ // Promise is always truthy and `.cache()` queries returned a
969
+ // Promise-of-entity instead of the entity.
970
+ const cached = await this.__context._queryCache.get(cacheKey);
549
971
  if (cached) {
550
972
  this.__reset();
551
973
  // Cached entities already have methods - return directly
@@ -557,15 +979,15 @@ class queryMethods{
557
979
  await this.__context._ensureReady();
558
980
  let result = null;
559
981
  if(this.__context.isSQLite){
560
- var entityValue = await this.__context._SQLEngine.get(this.__queryObject.script, this.__entity, this.__context);
982
+ var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.get(this.__queryObject.script, this.__entity, this.__context));
561
983
  result = this.__singleEntityBuilder(entityValue);
562
984
  }
563
985
  else if(this.__context.isMySQL){
564
- var entityValue = await this.__context._SQLEngine.get(this.__queryObject.script, this.__entity, this.__context);
986
+ var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.get(this.__queryObject.script, this.__entity, this.__context));
565
987
  result = this.__singleEntityBuilder(entityValue);
566
988
  }
567
989
  else if(this.__context.isPostgres){
568
- var entityValue = await this.__context._SQLEngine.get(this.__queryObject.script, this.__entity, this.__context);
990
+ var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.get(this.__queryObject.script, this.__entity, this.__context));
569
991
  result = this.__singleEntityBuilder(entityValue);
570
992
  }
571
993
  else {
@@ -573,6 +995,8 @@ class queryMethods{
573
995
  throw new Error('No database type configured. Ensure context.env() or context.useMySql()/useSqlite() has been called and awaited.');
574
996
  }
575
997
 
998
+ await this.__runPostIncludes(result); // thenInclude / split-query / many-to-many includes
999
+
576
1000
  // Store in cache — but never cache a "not found" (null) result. A
577
1001
  // negative result is poisoned the instant any concurrent writer inserts
578
1002
  // the matching row: a reader that filled the cache with the pre-commit
@@ -589,6 +1013,7 @@ class queryMethods{
589
1013
  }
590
1014
 
591
1015
  async toList(){
1016
+ this.__applyQueryFilters(); // global query filters (soft delete / tenant)
592
1017
  if(this.__queryObject.script.entityMap.length === 0){
593
1018
  this.__queryObject.skipClause( this.__entity.__name);
594
1019
  }
@@ -601,7 +1026,10 @@ class queryMethods{
601
1026
 
602
1027
  // Check cache first (if enabled for this query)
603
1028
  if (this.__useCache) {
604
- const cached = this.__context._queryCache.get(cacheKey);
1029
+ // `await` so an async cache (RedisQueryCache) works: without it a
1030
+ // Promise is always truthy and `.cache()` queries returned a
1031
+ // Promise-of-entity instead of the entity.
1032
+ const cached = await this.__context._queryCache.get(cacheKey);
605
1033
  if (cached) {
606
1034
  this.__reset();
607
1035
  // Cached entities already have methods - return array directly
@@ -613,15 +1041,15 @@ class queryMethods{
613
1041
  await this.__context._ensureReady();
614
1042
  let result = [];
615
1043
  if(this.__context.isSQLite){
616
- var entityValue = await this.__context._SQLEngine.all(this.__queryObject.script, this.__entity, this.__context);
1044
+ var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.all(this.__queryObject.script, this.__entity, this.__context));
617
1045
  result = this.__multipleEntityBuilder(entityValue);
618
1046
  }
619
1047
  else if(this.__context.isMySQL){
620
- var entityValue = await this.__context._SQLEngine.all(this.__queryObject.script, this.__entity, this.__context);
1048
+ var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.all(this.__queryObject.script, this.__entity, this.__context));
621
1049
  result = this.__multipleEntityBuilder(entityValue);
622
1050
  }
623
1051
  else if(this.__context.isPostgres){
624
- var entityValue = await this.__context._SQLEngine.all(this.__queryObject.script, this.__entity, this.__context);
1052
+ var entityValue = await this.__context._execWithRetry(() => this.__context._SQLEngine.all(this.__queryObject.script, this.__entity, this.__context));
625
1053
  result = this.__multipleEntityBuilder(entityValue);
626
1054
  }
627
1055
  else {
@@ -629,6 +1057,8 @@ class queryMethods{
629
1057
  throw new Error('No database type configured. Ensure context.env() or context.useMySql()/useSqlite() has been called and awaited.');
630
1058
  }
631
1059
 
1060
+ await this.__runPostIncludes(result); // thenInclude / split-query / many-to-many includes
1061
+
632
1062
  // Store in cache — but NOT an empty result set. An empty array is
633
1063
  // truthy, so the old `&& result` guard cached `[]`, which is negative
634
1064
  // caching: the moment a concurrent writer inserts a matching row the
@@ -651,7 +1081,7 @@ class queryMethods{
651
1081
  // Returns an object with property setters that track changes
652
1082
  new(){
653
1083
  const newEntity = {
654
- __ID : Math.floor((Math.random() * 100000) + 1),
1084
+ __ID : null, // assigned sequentially by context.__track (collision-free; a random id here could collide in the identity map)
655
1085
  __dirtyFields : [],
656
1086
  __state : "insert",
657
1087
  __entity : this.__entity,
@@ -811,6 +1241,12 @@ class queryMethods{
811
1241
  // by DB hydration in
812
1242
  // entityTrackerModel.build().
813
1243
  const navVal = this.__proto__["_" + navName];
1244
+ if (navVal && typeof navVal === 'object' && navVal.__entity) {
1245
+ // An assigned parent ENTITY: the FK column reads its key.
1246
+ const def = navVal.__entity;
1247
+ const pk = Object.keys(def).find(k => def[k] && typeof def[k] === 'object' && def[k].primary === true);
1248
+ return pk ? navVal[pk] : undefined;
1249
+ }
814
1250
  return navVal !== undefined
815
1251
  ? navVal
816
1252
  : this.__proto__["_" + fkName];
@@ -823,6 +1259,9 @@ class queryMethods{
823
1259
  }
824
1260
  }
825
1261
 
1262
+ // TPH: a new entity of a derived/base set carries its discriminator (EF)
1263
+ if (this.__entity.__tph) newEntity[this.__entity.__tph.column] = this.__entity.__tph.value;
1264
+
826
1265
  // Add Active Record-style .save() method
827
1266
  newEntity.save = async function() {
828
1267
  if (!this.__context) {
@@ -980,6 +1419,15 @@ class queryMethods{
980
1419
  // Reset dirty fields and state
981
1420
  this.__dirtyFields = [];
982
1421
  this.__state = 'track';
1422
+ // Reload resets ORIGINAL values to the database state (EF Reload())
1423
+ // so the next concurrency check compares against the current row.
1424
+ if (typeof this.__context._refreshOriginalValues === 'function') {
1425
+ this.__context._refreshOriginalValues(this);
1426
+ }
1427
+ // Drop the duplicate instance findById tracked (one copy per row).
1428
+ if (typeof this.__context.__untrack === 'function') {
1429
+ this.__context.__untrack([fresh]);
1430
+ }
983
1431
 
984
1432
  return this;
985
1433
  };
@@ -1055,6 +1503,8 @@ class queryMethods{
1055
1503
  entityValue.__entity = this.__entity;
1056
1504
  entityValue.__context = this.__context;
1057
1505
  entityValue.__name = this.__entity.__name;
1506
+ // TPH: stamp the discriminator with this set's type value (EF)
1507
+ if (this.__entity.__tph) entityValue[this.__entity.__tph.column] = this.__entity.__tph.value;
1058
1508
  // An UNSET declared field still resolves to its definition method on the
1059
1509
  // class prototype (e.g. `apiKey(db){...}`) — a truthy function — so
1060
1510
  // `!entity.apiKey` never fires. Blank those so an added entity reads