masterrecord 1.31.0 → 1.32.1

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/CHANGES.md CHANGED
@@ -1,5 +1,108 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.32.1 — batched inserts keep add order on MySQL and Postgres
4
+
5
+ **Fix: `saveChanges()` could assign ids out of add order on MySQL and Postgres.** A
6
+ multi-row INSERT can only serve rows with the same column list, and since 1.3.1 `bulkInsert`
7
+ pooled every row of a column list into one statement. A batch of `{name,bio}`, `{name}`,
8
+ `{name,bio}` therefore got the ids 1, 3, 2, and `ORDER BY id` returned the rows in a
9
+ different order than they were added. SQLite, the single-insert path and the per-row fallback
10
+ all assign ids in add order, so the result depended on the engine. Each entity still received
11
+ its own row's id, and stored values were correct.
12
+
13
+ - Only consecutive rows with the same columns now share a statement, so ids ascend in add
14
+ order. A batch whose rows all set the same columns is still one statement. One that
15
+ alternates column lists takes one statement per run, up to one per row, inside the same
16
+ transaction. Omitted columns still take their DB-level `DEFAULT`.
17
+ - New `test/bulk-insert-order.test.js` covers both engines without a server, because CI runs
18
+ SQLite only.
19
+
20
+ **Tests: the live MySQL and Postgres suite passes again.** 8 of the 20 tests in
21
+ `test/integration/cross-engine.test.js` failed, and only on a live server. Apart from the
22
+ ordering bug above, the rest were test faults. Since 1.23.0 a new entity's prototype is
23
+ `Object.prototype`, so the suite's `Object.getPrototypeOf(e)._role = …` wrote to every object
24
+ in the process. That emptied the row being tested (`No columns to insert`), and the
25
+ inherited key then surfaced as a column on MySQL (`Unknown column 'ran.operator'`) for any
26
+ later test in the file. The suite now sets the entity's own slot. Its check that a batch does
27
+ not fall back to per-row inserts looked for a log message that no longer exists, so it could
28
+ never fail; it now matches, and the `.set()` batch test makes the same check.
29
+
30
+ ## v1.32.0 — identity resolution: one tracked instance per row
31
+
32
+ **Memory fix for long-lived contexts.** A tracked query built a new entity for every row
33
+ and tracked it, even when the context already tracked that row. Nothing matched a row to
34
+ the instance already tracked, so a context kept alive for the whole process and re-reading
35
+ the same rows grew without limit: about 2 KB per row read. OpenBook's API ran out of heap
36
+ this way: a process-wide context polled a 200-row query every 30 s. Measured on one
37
+ context, 1,000 reads of 200 rows: 614 MB retained and 200,200 tracked entities before;
38
+ 0.5 MB and 200 tracked entities now.
39
+
40
+ Tracked queries now do EF Core's identity resolution. When a row's entity type and primary
41
+ key (every column of a composite key) match an entity this context already tracks, the
42
+ query returns that instance instead of a new one. A long-lived context's memory is bounded
43
+ by the number of distinct rows it has loaded, not by how many times it reads them.
44
+
45
+ **Behaviour changes you may notice:**
46
+
47
+ - **The same instance comes back.** `findById`, `find`, `single`, `toList` and lazy or
48
+ `include()` loading on one context return the same object for the same row
49
+ (`a === b`).
50
+ - **A re-read does not refresh a tracked entity.** As in EF, database values do not
51
+ overwrite the tracked instance: its pending changes are kept, and its unchanged columns
52
+ keep the values from when it was first loaded, even if the row changed since. Before,
53
+ each query returned a new copy with the current row. To see the current row, use
54
+ `asNoTracking()`, `entry(e).getDatabaseValues()`, `reload()`, or a fresh context.
55
+ - **A re-read returns a deleted-but-unsaved entity** in its `delete` state, instead of a
56
+ second clean copy.
57
+ - **`include()` reloads the navigation** on every row the query returns, including
58
+ instances an earlier query loaded (with other filters, for example). It used to skip any
59
+ navigation already loaded on the instance, which only mattered once instances were
60
+ shared.
61
+
62
+ Unchanged: `asNoTracking()` (new instances, database values, nothing tracked). `select()`
63
+ projections, `raw()` SQL and full-text `search()` rows are tracked as before but never
64
+ identity-resolved, so a partial row never stands in for the whole entity. Saved entities
65
+ are still detached after `saveChanges()`. If an edit re-tracks such an older instance while
66
+ a newer clean copy of the row is tracked, the instance with the pending change is the one
67
+ queries return, and after it is saved the next read loads the row again.
68
+
69
+ **New: one-time warning for large tracked sets.** When a context tracks 10,000 entities it
70
+ logs one warning (through `configureLogging`'s logger) that names `asNoTracking()`,
71
+ `setQueryTrackingBehavior('no-track')`, `clearChangeTracker()` and per-request contexts.
72
+ Change the threshold with `context.setTrackedEntityWarningThreshold(n)` or
73
+ `MASTERRECORD_TRACKED_WARN_THRESHOLD=<n>`; `0` turns it off.
74
+
75
+ Internals: an index keyed by table + primary key sits beside `__trackedEntitiesMap` and is
76
+ kept in step by `__track`, `__untrack`, `__clearTracked`, `attach()` re-homing and the insert
77
+ path (once an INSERT assigns the key). A lookup that finds a stale entry drops it. `reload()`
78
+ now reads with `asNoTracking()`, because a tracked `findById` would return the instance
79
+ being reloaded.
80
+
81
+ New test: `test/identity-resolution.test.js`. Full suite: 453 pass, 0 fail, 22 live-DB
82
+ tests skipped (MySQL/Postgres were not run locally).
83
+
84
+ ## v1.31.1 — better-sqlite3 range back to `>=12.6.2 <14`
85
+
86
+ **Fix for a build break introduced in 1.31.0.** 1.31.0 raised the floor to
87
+ `better-sqlite3@^13.0.3`. An app that pins `better-sqlite3@12` itself could then no longer
88
+ share its copy: npm installed a second, nested 13.x under `masterrecord/node_modules`. npm 10
89
+ (bundled with Node 20 and 22) runs `node-gyp rebuild` for that copy, which needs Python and
90
+ a compiler, so builds on slim images failed (`gyp ERR! find Python`). Three production apps
91
+ built with Nixpacks hit exactly this.
92
+
93
+ - The range is `>=12.6.2 <14` again, as in 1.30: npm shares an app-pinned 12.x, and a fresh
94
+ install still gets 13.x. 12.6.2+ ships prebuilt binaries for Node 22 and 24 (12.11.1 also
95
+ for Node 26), so no compiler is needed on either line.
96
+ - New test `test/better-sqlite3-range.test.js` keeps the range from being narrowed again.
97
+ The full suite also passes against `better-sqlite3@12.11.1` (SQLite 3.53.2).
98
+ - README install note corrected: 1.31.0 said npm 11.19+ blocks dependency install scripts.
99
+ Only npm 12 does; npm 11 runs them with a notice. The note now has a table for 12.x vs
100
+ 13.x on npm 10/11 vs 12 — `deny` is only right on 13.x, and a pinned 12.x must be
101
+ approved under npm 12.
102
+
103
+ Engines stay at `>=22.12.0`. If you are on 1.31.0 with a pinned `better-sqlite3@12`, upgrade
104
+ and re-lock: `npm install masterrecord@^1.31.1` leaves one copy in the lockfile.
105
+
3
106
  ## v1.31.0 — security maintenance: Node 22.12+, patched SQLite, clean audit
4
107
 
5
108
  Node 20 reached end-of-life on 2026-04-30 and no longer receives security releases,
@@ -194,7 +194,9 @@ class EntityTrackerModel {
194
194
 
195
195
  // Fetch fresh from database
196
196
  const EntityClass = this.__context[this.__name];
197
- const fresh = await EntityClass.findById(...keyValues);
197
+ // No tracking: a tracked findById would return THIS instance
198
+ // (identity resolution), not the database values.
199
+ const fresh = await EntityClass.asNoTracking().findById(...keyValues);
198
200
  if (!fresh) {
199
201
  throw new Error(
200
202
  `Cannot reload: ${this.__name} with ${keys.map((k, i) => `${k}=${keyValues[i]}`).join(', ')} not found`
@@ -225,12 +227,6 @@ class EntityTrackerModel {
225
227
  if (typeof this.__context._refreshOriginalValues === 'function') {
226
228
  this.__context._refreshOriginalValues(this);
227
229
  }
228
- // findById tracked a second instance of this row; drop it so the
229
- // identity map holds only this entity (EF never tracks two copies).
230
- if (typeof this.__context.__untrack === 'function') {
231
- this.__context.__untrack([fresh]);
232
- }
233
-
234
230
  return this;
235
231
  };
236
232
 
@@ -324,11 +324,21 @@ class queryMethods{
324
324
  }
325
325
  }
326
326
 
327
+ /**
328
+ * Can this query's rows be identity-resolved? Only when each row is a whole
329
+ * entity row: not raw() SQL, not a select() projection (a partial row must
330
+ * not stand in for the entity later), and not a full-text search (each row
331
+ * carries a per-query __rank).
332
+ */
333
+ __identityResolvable(){
334
+ const s = this.__queryObject.script;
335
+ return !this.__noTracking && !s.raw && !s.select && !s.search;
336
+ }
337
+
327
338
  // build a single entity
328
- __singleEntityBuilder(dataModel){
339
+ __singleEntityBuilder(dataModel, resolvable = this.__identityResolvable()){
329
340
  const $that = this;
330
341
  if(dataModel){
331
- const ent = new entityTrackerModel();
332
342
  // TPH: materialize the row as its DERIVED type when the discriminator
333
343
  // names one (EF returns Cat/Dog instances from the Animal set).
334
344
  let def = $that.__entity;
@@ -337,6 +347,14 @@ class queryMethods{
337
347
  const derived = tph.derived.get(String(dataModel[tph.column]));
338
348
  if (derived) def = derived;
339
349
  }
350
+ // Identity resolution (EF Core): if this context already tracks the
351
+ // row, return that instance. It is NOT refreshed from the row, so
352
+ // pending changes on it are kept.
353
+ if (resolvable) {
354
+ const tracked = $that.__context.__trackedForRow(def, dataModel);
355
+ if (tracked) return tracked;
356
+ }
357
+ const ent = new entityTrackerModel();
340
358
  const mod = ent.build(dataModel, def, $that.__context);
341
359
  mod.__state = "track";
342
360
  if ($that.__noTracking) {
@@ -344,6 +362,12 @@ class queryMethods{
344
362
  // (__markDirty ignores no-tracking entities) and never track it.
345
363
  mod.__noTracking = true;
346
364
  } else {
365
+ if (!resolvable) {
366
+ // Projection / raw / search row: tracked as before, but kept
367
+ // out of the identity index so it never stands in for the
368
+ // whole entity.
369
+ Object.defineProperty(mod, '__noIdentity', { value: true, enumerable: false, writable: true, configurable: true });
370
+ }
347
371
  $that.__context.__track(mod);
348
372
  }
349
373
  return mod;
@@ -357,8 +381,9 @@ class queryMethods{
357
381
  const $that = this;
358
382
  const listArray = [];
359
383
  if(entityValue){
384
+ const resolvable = $that.__identityResolvable();
360
385
  for(let i = 0; i < entityValue.length; i++){
361
- listArray.push($that.__singleEntityBuilder(entityValue[i]));
386
+ listArray.push($that.__singleEntityBuilder(entityValue[i], resolvable));
362
387
  }
363
388
  return listArray;
364
389
  }else{
@@ -625,10 +650,11 @@ class queryMethods{
625
650
  if (!paths || !paths.length) return;
626
651
  const roots = Array.isArray(result) ? result : (result ? [result] : []);
627
652
  if (!roots.length) return;
653
+ const run = new Map(); // navigations this query has loaded (see __batchLoadNavigation)
628
654
  for (const path of paths) {
629
655
  let level = roots;
630
656
  for (const nav of path) {
631
- level = await this.__context.__batchLoadNavigation(level, nav, { ignoredFilters: this.__ignoredFilters });
657
+ level = await this.__context.__batchLoadNavigation(level, nav, { ignoredFilters: this.__ignoredFilters, run });
632
658
  if (!level.length) break;
633
659
  }
634
660
  }
@@ -1398,7 +1424,9 @@ class queryMethods{
1398
1424
 
1399
1425
  // Fetch fresh from database
1400
1426
  const EntityClass = this.__context[this.__name];
1401
- const fresh = await EntityClass.findById(primaryKeyValue);
1427
+ // No tracking: a tracked findById would return THIS instance
1428
+ // (identity resolution), not the database values.
1429
+ const fresh = await EntityClass.asNoTracking().findById(primaryKeyValue);
1402
1430
  if (!fresh) {
1403
1431
  throw new Error(
1404
1432
  `Cannot reload: ${this.__name} with ${primaryKey}=${primaryKeyValue} not found`
@@ -1428,11 +1456,6 @@ class queryMethods{
1428
1456
  if (typeof this.__context._refreshOriginalValues === 'function') {
1429
1457
  this.__context._refreshOriginalValues(this);
1430
1458
  }
1431
- // Drop the duplicate instance findById tracked (one copy per row).
1432
- if (typeof this.__context.__untrack === 'function') {
1433
- this.__context.__untrack([fresh]);
1434
- }
1435
-
1436
1459
  return this;
1437
1460
  };
1438
1461
 
package/context.js CHANGED
@@ -23,6 +23,7 @@ import MySQLEngine from './mySQLEngine.js';
23
23
  import insertManager from './insertManager.js';
24
24
  import deleteManager from './deleteManager.js';
25
25
  import EntityTrackerModel from './Entity/entityTrackerModel.js';
26
+ import FieldTransformer from './Entity/fieldTransformer.js';
26
27
  import { ConcurrencyError } from './errors.js';
27
28
  import { withRetry } from './resilience.js';
28
29
  import { log } from './logging.js';
@@ -136,6 +137,73 @@ function _poolKey(type, cfg) {
136
137
  return key;
137
138
  }
138
139
 
140
+ // ----------------------------------------------------------------------------
141
+ // Identity resolution (EF Core's identity map keyed by primary key)
142
+ // ----------------------------------------------------------------------------
143
+ // A tracked query that reads a row this context already tracks returns the
144
+ // tracked instance instead of building a second copy. The key is
145
+ // "<table>\0<primary key>". Without it a long-lived context that re-reads the
146
+ // same rows kept a new tracked copy per read, so memory grew with the number of
147
+ // reads instead of the number of distinct rows.
148
+
149
+ // Entity definition -> its primary-key column names, or null when the type
150
+ // cannot be keyed (no key, or a key column that is a navigation).
151
+ const _identityColumnsCache = new WeakMap();
152
+
153
+ function _identityColumns(def) {
154
+ let cols = _identityColumnsCache.get(def);
155
+ if (cols !== undefined) return cols;
156
+ cols = tools.primaryKeys(def);
157
+ if (cols.length === 0 || cols.some(k => def[k].relationshipType === 'belongsTo')) cols = null;
158
+ _identityColumnsCache.set(def, cols);
159
+ return cols;
160
+ }
161
+
162
+ // One key column value as a string, or null when it cannot identify a row
163
+ // (unset, or a type with no reliable string form). Numbers and numeric strings
164
+ // map to the same text on purpose: Postgres returns BIGINT as "5" where the app
165
+ // assigned 5, and both name the same row. A column holds one type, so this
166
+ // cannot make two different rows equal.
167
+ function _identityPart(v) {
168
+ switch (typeof v) {
169
+ case 'string': return v === '' ? null : v;
170
+ case 'number': return Number.isFinite(v) ? String(v) : null;
171
+ case 'bigint': return String(v);
172
+ case 'boolean': return v ? 'true' : 'false';
173
+ case 'object':
174
+ if (v === null) return null;
175
+ if (v instanceof Date) { const t = v.getTime(); return Number.isNaN(t) ? null : `\u0001d${t}`; }
176
+ if (ArrayBuffer.isView(v)) return `\u0001x${Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString('hex')}`;
177
+ return null;
178
+ default: return null;
179
+ }
180
+ }
181
+
182
+ // Identity key for one row of `def`. `read(column)` returns that column's value
183
+ // in its in-memory form. null = this row cannot be identity-resolved.
184
+ function _identityKey(def, read) {
185
+ const cols = def ? _identityColumns(def) : null;
186
+ if (!cols) return null;
187
+ if (cols.length === 1) {
188
+ const p = _identityPart(read(cols[0]));
189
+ return p === null ? null : `${def.__name}\u0000${p}`;
190
+ }
191
+ const parts = new Array(cols.length);
192
+ for (let i = 0; i < cols.length; i++) {
193
+ const p = _identityPart(read(cols[i]));
194
+ if (p === null) return null;
195
+ parts[i] = p;
196
+ }
197
+ return `${def.__name}\u0000${JSON.stringify(parts)}`;
198
+ }
199
+
200
+ /**
201
+ * Default size of a context's tracked set at which a one-time warning is
202
+ * logged. Override per context with setTrackedEntityWarningThreshold(n), or
203
+ * process-wide with MASTERRECORD_TRACKED_WARN_THRESHOLD=<n>; 0 turns it off.
204
+ */
205
+ const DEFAULT_TRACKED_WARN_THRESHOLD = 10000;
206
+
139
207
  // ============================================================================
140
208
  // CONSTANTS - Extract all magic numbers for maintainability
141
209
  // ============================================================================
@@ -257,6 +325,17 @@ class context {
257
325
  // writes whenever the two disagreed (a stale/colliding id in one but not the
258
326
  // other). All mutations go through __track / __untrack / __clearTracked.
259
327
  __trackedEntitiesMap = new Map(); // __ID -> entity; the authority
328
+ // Identity index beside the map: "<table>\0<primary key>" -> the one tracked
329
+ // instance of that row, so a tracked query returns it instead of a new copy.
330
+ // __identityKeys remembers which key each entity was indexed under, so it can
331
+ // be removed even after its key value changed. Both are kept in step by
332
+ // __track / __untrack / __clearTracked; a stale entry is also dropped when a
333
+ // lookup finds it (see __trackedForRow).
334
+ __identityIndex = new Map();
335
+ __identityKeys = new WeakMap();
336
+ // One-time "tracked set is large" warning (see __checkTrackedSize).
337
+ __trackedWarnThreshold = undefined; // undefined = not resolved yet
338
+ __trackedWarned = false;
260
339
  // Default query tracking behavior, EF-style (QueryTrackingBehavior).
261
340
  // 'track' — queries track their results (edits persist); the default.
262
341
  // 'no-track' — queries do NOT track (read-only; nothing retained). Set once
@@ -1942,23 +2021,48 @@ class context {
1942
2021
  const uniq = (arr) => [...new Set(arr.filter(v => v !== undefined && v !== null && typeof v !== 'function'))];
1943
2022
  const loadedOut = [];
1944
2023
  const pending = [];
2024
+ // opts.run (one per query): the parents whose `nav` this query has
2025
+ // already loaded. With identity resolution a query can return an
2026
+ // instance whose navigation an EARLIER query loaded (with other filters);
2027
+ // an explicit include() reloads it, so the result reflects this query.
2028
+ let loadedThisRun = null;
2029
+ if (opts.run instanceof Map) {
2030
+ const runKey = `${ownerDef.__name}.${nav}`;
2031
+ loadedThisRun = opts.run.get(runKey);
2032
+ if (!loadedThisRun) { loadedThisRun = new WeakSet(); opts.run.set(runKey, loadedThisRun); }
2033
+ }
2034
+ const reloading = new Set(); // pending parents whose nav an earlier query loaded
1945
2035
  for (const p of list) {
1946
- if (this.isNavigationLoaded(p, nav)) {
2036
+ const loaded = this.isNavigationLoaded(p, nav);
2037
+ if (loaded && (!loadedThisRun || loadedThisRun.has(p))) {
1947
2038
  const v = slotOf(p)['_' + nav];
1948
2039
  if (Array.isArray(v)) loadedOut.push(...v); else if (v && typeof v === 'object') loadedOut.push(v);
1949
- } else pending.push(p);
2040
+ } else {
2041
+ pending.push(p);
2042
+ if (loaded) reloading.add(p);
2043
+ }
1950
2044
  }
2045
+ if (loadedThisRun) for (const p of pending) loadedThisRun.add(p);
1951
2046
  if (!pending.length) return loadedOut;
1952
2047
 
1953
2048
  if (isBt) {
1954
2049
  const parentSet = this._dbsetByName(def.foreignTable);
1955
2050
  if (!parentSet) throw new Error(`masterrecord: entity '${def.foreignTable}' (referenced by ${ownerDef.__name}.${nav}) is not registered on this context.`);
1956
2051
  const pk = tools.getPrimaryKeyObject(parentSet.__entity) || 'id';
1957
- const keys = uniq(pending.map(p => tools.foreignKeyValue(p, nav)));
2052
+ // On a reload the navigation slot holds the earlier result (null when
2053
+ // that query's filters hid the parent), so read the FK column itself.
2054
+ const fkOf = (p) => {
2055
+ if (reloading.has(p) && def.foreignKey) {
2056
+ const fk = tools.dataValue(p, def.foreignKey);
2057
+ if (fk === null || (fk !== undefined && typeof fk !== 'object' && typeof fk !== 'function')) return fk;
2058
+ }
2059
+ return tools.foreignKeyValue(p, nav);
2060
+ };
2061
+ const keys = uniq(pending.map(fkOf));
1958
2062
  const byKey = new Map();
1959
2063
  for (const c of chunks(keys)) for (const t of await withFilters(parentSet).where(`r => $$.includes(r.${pk})`, c).toList()) byKey.set(String(tools.dataValue(t, pk)), t);
1960
2064
  for (const p of pending) {
1961
- const k = tools.foreignKeyValue(p, nav);
2065
+ const k = fkOf(p);
1962
2066
  const t = (k === undefined || k === null) ? null : (byKey.get(String(k)) || null);
1963
2067
  setSlot(p, t);
1964
2068
  if (t) loadedOut.push(t);
@@ -2865,6 +2969,11 @@ class context {
2865
2969
  } catch (attachErr) {
2866
2970
  console.error(`[Context] Could not attach change-tracking to inserted ${entity.__name || 'entity'}: ${attachErr.message}`);
2867
2971
  }
2972
+ // The INSERT may have just assigned the key (auto-increment, read
2973
+ // back). Index the entity under it while it is still tracked.
2974
+ if (entity.__ID != null && this.__trackedEntitiesMap.get(entity.__ID) === entity) {
2975
+ this.__indexIdentity(entity);
2976
+ }
2868
2977
  }
2869
2978
  }
2870
2979
 
@@ -3566,6 +3675,7 @@ class context {
3566
3675
  if (!e) continue;
3567
3676
  if (e.__ID != null) this.__trackedEntitiesMap.delete(e.__ID);
3568
3677
  this.__dirtyEntities.delete(e); // keep the dirty index in lockstep
3678
+ this.__unindexIdentity(e); // and the identity index
3569
3679
  }
3570
3680
  }
3571
3681
 
@@ -4055,6 +4165,7 @@ class context {
4055
4165
  if (previous && previous !== this && entity.__ID &&
4056
4166
  previous.__trackedEntitiesMap && previous.__trackedEntitiesMap.has(entity.__ID)) {
4057
4167
  previous.__trackedEntitiesMap.delete(entity.__ID); // list view follows the map
4168
+ if (typeof previous.__unindexIdentity === 'function') previous.__unindexIdentity(entity);
4058
4169
  }
4059
4170
 
4060
4171
  // Mark entity as modified
@@ -4197,7 +4308,14 @@ class context {
4197
4308
  // the list view derives from it, so they cannot desynchronise.
4198
4309
  const wasTracked = this.__trackedEntitiesMap.has(model.__ID);
4199
4310
  this.__trackedEntitiesMap.set(model.__ID, model);
4200
- if (!wasTracked) this._emit('tracked', { context: this, entity: model });
4311
+ // Every path that tracks or re-tracks an entity (queries, setters,
4312
+ // add/remove, attach) comes through here, so this also picks up a key
4313
+ // that was assigned after the entity was first tracked.
4314
+ this.__indexIdentity(model);
4315
+ if (!wasTracked) {
4316
+ this._emit('tracked', { context: this, entity: model });
4317
+ this.__checkTrackedSize();
4318
+ }
4201
4319
  // Robustness: if the entity being tracked is ALREADY dirty, enqueue it in
4202
4320
  // the dirty index too. This guarantees the index is complete no matter
4203
4321
  // how an entity gets tracked (setter, add/remove, or a direct __track
@@ -4253,6 +4371,129 @@ class context {
4253
4371
  __clearTracked() {
4254
4372
  this.__trackedEntitiesMap.clear(); // sole registry; the list view follows
4255
4373
  this.__dirtyEntities.clear();
4374
+ this.__identityIndex.clear();
4375
+ this.__identityKeys = new WeakMap();
4376
+ }
4377
+
4378
+ // ---- Identity resolution ------------------------------------------------
4379
+
4380
+ /**
4381
+ * Index a tracked entity under its type + primary key, so a later tracked
4382
+ * query that reads the same row returns this instance. Called from
4383
+ * __track(). An entity with no usable key yet (a pending insert with an
4384
+ * auto key) is skipped, and indexed once its key is assigned.
4385
+ *
4386
+ * A context can still end up tracking two instances of one row: saved
4387
+ * entities are detached, and a later edit re-tracks the old instance while a
4388
+ * newer query copy is tracked. Then the instance with pending changes takes
4389
+ * the key from a clean holder, so once it is saved (and detached) the next
4390
+ * query reads the row afresh instead of returning the stale clean copy.
4391
+ * Otherwise the instance that already holds the key keeps it.
4392
+ * @private
4393
+ */
4394
+ __indexIdentity(model) {
4395
+ if (!model || !model.__entity) return;
4396
+ const key = (model.__noTracking || model.__noIdentity)
4397
+ ? null
4398
+ : _identityKey(model.__entity, (c) => tools.dataValue(model, c));
4399
+ const prev = this.__identityKeys.get(model);
4400
+ if (prev !== undefined && prev !== key) this.__unindexIdentity(model);
4401
+ if (key === null) return;
4402
+ const holder = this.__identityIndex.get(key);
4403
+ if (holder !== undefined && holder !== model && this.__isLiveIdentity(holder, key)) {
4404
+ const modelDirty = context._isEntityDirty(model);
4405
+ if (!modelDirty || context._isEntityDirty(holder)) return;
4406
+ this.__identityKeys.delete(holder); // the clean copy stays tracked, unindexed
4407
+ }
4408
+ this.__identityIndex.set(key, model);
4409
+ this.__identityKeys.set(model, key);
4410
+ }
4411
+
4412
+ /** Remove an entity from the identity index (it stays tracked). @private */
4413
+ __unindexIdentity(model) {
4414
+ if (!model || typeof model !== 'object') return;
4415
+ const key = this.__identityKeys.get(model);
4416
+ if (key === undefined) return;
4417
+ if (this.__identityIndex.get(key) === model) this.__identityIndex.delete(key);
4418
+ this.__identityKeys.delete(model);
4419
+ }
4420
+
4421
+ /** Is `e` still tracked here and does its current key still equal `key`? @private */
4422
+ __isLiveIdentity(e, key) {
4423
+ return e.__ID != null
4424
+ && this.__trackedEntitiesMap.get(e.__ID) === e
4425
+ && !e.__noTracking
4426
+ && _identityKey(e.__entity, (c) => tools.dataValue(e, c)) === key;
4427
+ }
4428
+
4429
+ /**
4430
+ * The tracked instance of the row `row` (a raw database row of `def`), or
4431
+ * null. Used by tracked queries before they build a new entity. The tracked
4432
+ * instance is returned as is: database values do not overwrite it, and a
4433
+ * modified instance keeps its pending changes (EF Core identity resolution).
4434
+ * @private
4435
+ */
4436
+ __trackedForRow(def, row) {
4437
+ if (this.__identityIndex.size === 0 || !row) return null;
4438
+ let key;
4439
+ try {
4440
+ key = _identityKey(def, (c) => FieldTransformer.fromDatabase(row[c], def[c], def.__name, c));
4441
+ } catch (_) {
4442
+ return null; // a failing transformer: let the normal build path report it
4443
+ }
4444
+ if (key === null) return null;
4445
+ const e = this.__identityIndex.get(key);
4446
+ if (e === undefined) return null;
4447
+ if (this.__isLiveIdentity(e, key)) return e;
4448
+ // Stale entry (detached elsewhere, or its key changed): drop it.
4449
+ this.__identityIndex.delete(key);
4450
+ this.__identityKeys.delete(e);
4451
+ return null;
4452
+ }
4453
+
4454
+ /**
4455
+ * Log a warning, once per context, when the tracked set reaches the
4456
+ * threshold. A context that keeps growing past this is usually a long-lived
4457
+ * context used for reads.
4458
+ * @private
4459
+ */
4460
+ __checkTrackedSize() {
4461
+ if (this.__trackedWarned) return;
4462
+ let threshold = this.__trackedWarnThreshold;
4463
+ if (threshold === undefined) {
4464
+ const env = process.env.MASTERRECORD_TRACKED_WARN_THRESHOLD;
4465
+ const n = env === undefined || env === '' ? NaN : Number(env);
4466
+ threshold = Number.isFinite(n) && n >= 0 ? n : DEFAULT_TRACKED_WARN_THRESHOLD;
4467
+ this.__trackedWarnThreshold = threshold;
4468
+ }
4469
+ if (!threshold || this.__trackedEntitiesMap.size < threshold) return;
4470
+ this.__trackedWarned = true;
4471
+ log('warn',
4472
+ `[masterrecord] WARNING: context '${this.__name}' is tracking ${this.__trackedEntitiesMap.size} entities ` +
4473
+ `(warning threshold ${threshold}). Every entity a tracked query returns stays in memory until it is ` +
4474
+ `saved, detached or the context is closed. If this context lives for the whole process, read with ` +
4475
+ `asNoTracking() (or setQueryTrackingBehavior('no-track') on the context), call clearChangeTracker() ` +
4476
+ `after read-only work, or create a context per request / unit of work (ContextPool). ` +
4477
+ `Change the threshold with setTrackedEntityWarningThreshold(n) or ` +
4478
+ `MASTERRECORD_TRACKED_WARN_THRESHOLD=<n>; 0 turns the warning off.`
4479
+ );
4480
+ }
4481
+
4482
+ /**
4483
+ * Set the tracked-set size at which this context logs its one-time
4484
+ * "tracking many entities" warning (default 10,000, or
4485
+ * MASTERRECORD_TRACKED_WARN_THRESHOLD). 0, null or false turns it off.
4486
+ * Setting it re-arms the warning.
4487
+ */
4488
+ setTrackedEntityWarningThreshold(n) {
4489
+ if (n === null || n === false) n = 0;
4490
+ if (typeof n !== 'number' || !Number.isFinite(n) || n < 0) {
4491
+ throw new TypeError(`masterrecord: setTrackedEntityWarningThreshold expects a non-negative number, got ${JSON.stringify(n)}`);
4492
+ }
4493
+ this.__trackedWarnThreshold = n;
4494
+ this.__trackedWarned = false;
4495
+ this.__checkTrackedSize();
4496
+ return this;
4256
4497
  }
4257
4498
 
4258
4499
  /**
@@ -4261,7 +4502,8 @@ class context {
4261
4502
  *
4262
4503
  * A context is a unit of work and is safest scoped per request. If you must
4263
4504
  * reuse a long-lived (e.g. singleton) context, read-only queries still
4264
- * auto-track their results, and those clean entities accumulate — call this
4505
+ * auto-track their results: one instance per distinct row (identity
4506
+ * resolution), which still grows with every new row read — call this
4265
4507
  * after a read-only operation to release them and keep the tracked set
4266
4508
  * bounded. It drops PENDING changes too, so only call it when there is
4267
4509
  * nothing dirty you still intend to save.
@@ -19,6 +19,23 @@ user.blocked = 1; // dirty
19
19
  await db.saveChanges(); // one UPDATE
20
20
  ```
21
21
 
22
+ ### Identity resolution (since 1.32.0)
23
+
24
+ A context tracks **one instance per row**. When a tracked query reads a row the context already tracks (same entity type and primary key, composite keys included), it returns the tracked instance instead of building a new one, as EF Core does:
25
+
26
+ - The tracked instance is **not** overwritten with the database values. Pending changes on it survive a re-read; unchanged columns keep the values they had when the row was first loaded. Use `asNoTracking()`, `entry(e).getDatabaseValues()` or `reload()` to see the current row.
27
+ - A long-lived context's memory is bounded by the number of **distinct** rows it has loaded, not by how many times it re-reads them.
28
+ - An explicit `include()` still loads the navigation for every row the query returns, including instances an earlier query loaded.
29
+ - `select()` projections, `raw()` SQL and full-text `search()` rows are tracked as before but never identity-resolved: a partial row never stands in for the whole entity.
30
+
31
+ ```javascript
32
+ const a = await db.User.findById(1);
33
+ a.name = 'pending';
34
+ const b = await db.User.where('u => u.id == $$', 1).single();
35
+ b === a; // true
36
+ b.name; // 'pending': the re-read did not overwrite it
37
+ ```
38
+
22
39
  ---
23
40
 
24
41
  ## Controlling what gets tracked (EF's `QueryTrackingBehavior`)
@@ -61,6 +78,8 @@ If you set a `no-track` default on a shared/long-lived context, remember every w
61
78
 
62
79
  `clearChangeTracker()` drops pending changes, so on a shared context it can destroy another in-flight request's writes — it is not a safe per-request mitigation. Use request-scoped contexts or `asNoTracking()` instead.
63
80
 
81
+ **Large tracked sets are reported once.** When a context's tracked set reaches 10,000 entities it logs one warning (through `configureLogging`'s logger) naming `asNoTracking()`, `clearChangeTracker()` and per-request contexts. Change the threshold per context with `context.setTrackedEntityWarningThreshold(n)` or process-wide with `MASTERRECORD_TRACKED_WARN_THRESHOLD=<n>`; `0` turns it off.
82
+
64
83
  ---
65
84
 
66
85
  ## Scoping a context (the memory bound)
@@ -249,7 +268,7 @@ Transient errors (deadlocks, lock timeouts, busy SQLite, dropped connections) ar
249
268
  A singleton context shared across concurrent requests is the root cause of an entire class of bugs (and is unsupported in EF for the same reasons):
250
269
 
251
270
  - **Lost writes** — one request's `saveChanges()` interacting with another's tracked entities.
252
- - **Unbounded memory** — read-only queries track results that are never released.
271
+ - **Unbounded memory** — read-only queries track results that are never released. Identity resolution bounds this by the number of distinct rows, but a singleton that reads a large or growing table still keeps every row it has seen.
253
272
  - **Undefined behavior** under concurrent access (EF: "application crashes and data corruption").
254
273
 
255
274
  MasterRecord hardens against the worst symptoms (each save commits only its own change set; identities are collision-free; the dirty index is complete), but the correct and supported model is a **per-request context** — pooled if you need to amortize setup.
@@ -88,6 +88,7 @@ context.User.where(u => $$.includes(u.id), [1, 2, 3]).toList();
88
88
  | `context.setRetryOnFailure(opts)` | `EnableRetryOnFailure` | Transient-error retry |
89
89
  | `await context.healthCheck()` / `await context.canConnect()` | `Database.CanConnect` / health check | `{ healthy, engine, latencyMs, version, … }`; never throws |
90
90
  | `context.setQueryTrackingBehavior('no-track')` / `clearChangeTracker()` / `reset()` / `close()` | `QueryTrackingBehavior` / `ChangeTracker.Clear` / `Dispose` | Tracker lifetime |
91
+ | `context.setTrackedEntityWarningThreshold(n)` | — | One-time warning when the tracked set reaches `n` (default 10,000; `0` = off; or `MASTERRECORD_TRACKED_WARN_THRESHOLD`) |
91
92
  | `db.rowVersion()` / `db.concurrencyToken()` (model builder) | `IsRowVersion` / `IsConcurrencyToken` | Optimistic concurrency (throws `ConcurrencyError`) |
92
93
  | `db.belongsTo(...).onDelete('cascade'\|'restrict'\|'setNull'\|'noAction')` / `.excludeForeignKeyFromMigrations()` | `OnDelete` / EF 11 | FK constraint behavior |
93
94
  | `db.defaultSql('CURRENT_TIMESTAMP')` | `HasDefaultValueSql` | Database-side default expression (read back after insert) |
package/mySQLEngine.js CHANGED
@@ -195,15 +195,23 @@ class MySQLEngine {
195
195
  // by table + exact column signature and emit one statement per group.
196
196
  // No NULL-padding to a column union — that would override DB-level
197
197
  // column defaults.
198
- const groups = new Map();
198
+ //
199
+ // Only CONSECUTIVE rows share a statement: pooling all rows of a
200
+ // signature would hand out auto-increment ids out of add order, unlike
201
+ // SQLite, the single-insert path and the per-row fallback.
202
+ const groups = [];
203
+ let lastKey;
199
204
  for (const row of rows) {
200
205
  const key = `${row.sql.tableName}\u0000${row.sql.columns}`;
201
- if (!groups.has(key)) groups.set(key, []);
202
- groups.get(key).push(row);
206
+ if (groups.length === 0 || key !== lastKey) {
207
+ groups.push([]);
208
+ lastKey = key;
209
+ }
210
+ groups[groups.length - 1].push(row);
203
211
  }
204
212
 
205
213
  const results = new Array(entities.length);
206
- for (const group of groups.values()) {
214
+ for (const group of groups) {
207
215
  const first = group[0].sql;
208
216
  const valueGroups = [];
209
217
  const allParams = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.31.0",
3
+ "version": "1.32.1",
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",
@@ -85,7 +85,7 @@
85
85
  "masterrecord"
86
86
  ],
87
87
  "dependencies": {
88
- "better-sqlite3": "^13.0.3",
88
+ "better-sqlite3": ">=12.6.2 <14",
89
89
  "commander": "^14.0.3",
90
90
  "deep-object-diff": "^1.1.9",
91
91
  "glob": "^13.0.6",
package/postgresEngine.js CHANGED
@@ -248,15 +248,23 @@ class postgresEngine {
248
248
  // by table + exact column signature and emit one statement per group.
249
249
  // No NULL-padding to a column union — that would override DB-level
250
250
  // column defaults.
251
- const groups = new Map();
251
+ //
252
+ // Only CONSECUTIVE rows share a statement: pooling all rows of a
253
+ // signature would hand out auto-increment ids out of add order, unlike
254
+ // SQLite, the single-insert path and the per-row fallback.
255
+ const groups = [];
256
+ let lastKey;
252
257
  for (const row of rows) {
253
258
  const key = `${row.sql.tableName} ${row.sql.columns}`;
254
- if (!groups.has(key)) groups.set(key, []);
255
- groups.get(key).push(row);
259
+ if (groups.length === 0 || key !== lastKey) {
260
+ groups.push([]);
261
+ lastKey = key;
262
+ }
263
+ groups[groups.length - 1].push(row);
256
264
  }
257
265
 
258
266
  const results = new Array(entities.length);
259
- for (const group of groups.values()) {
267
+ for (const group of groups) {
260
268
  const first = group[0].sql;
261
269
  const primaryKey = tools.getPrimaryKeyObject(group[0].entity.__entity);
262
270
 
package/readme.md CHANGED
@@ -207,27 +207,30 @@ npm install masterrecord better-sqlite3 # SQLite
207
207
  MasterRecord includes the following database drivers by default:
208
208
  - `pg@^8.22.0` - PostgreSQL (async)
209
209
  - `mysql2@^3.23.2` - MySQL (async with connection pooling)
210
- - `better-sqlite3@^13.0.3` - SQLite (async API wrapper for consistency)
210
+ - `better-sqlite3@>=12.6.2 <14` - SQLite (async API wrapper for consistency; an app-pinned 12.x is shared)
211
211
 
212
212
  ### npm install-script note (native SQLite build)
213
213
 
214
- npm 12 (and the npm 11.19+ bundled with Node 24.22) **blocks dependency install
215
- scripts by default** and lists them under `npm install-scripts ls`.
216
- `better-sqlite3@13` ships prebuilt N-API binaries for macOS, Linux (glibc and musl)
217
- and Windows on x64 and arm64, so SQLite loads without its install script running and
218
- there is nothing to approve on those platforms. npm still lists it, because the
219
- package carries a `binding.gyp`; record the decision once so the notice goes away:
214
+ How `better-sqlite3` gets its native binary depends on its major version and your npm:
215
+
216
+ | | npm 10 / 11 (Node 20–24) | npm 12 |
217
+ |---|---|---|
218
+ | **13.x** (what a fresh install gets) | runs `node-gyp rebuild` — needs `python3`, `make` and `g++` in the build image | script blocked by default; the bundled prebuilt binary is used — nothing to approve |
219
+ | **12.x** (if your app pins it) | runs its install script, which downloads a prebuilt binary — no compiler needed | script blocked by default — **approve it**, or SQLite fails with "Could not locate the bindings file" |
220
+
221
+ npm 11 runs dependency install scripts but lists them with a notice; npm 12 blocks
222
+ them unless your `package.json` `allowScripts` allows them. Record the decision once:
220
223
 
221
224
  ```bash
222
- npm install-scripts deny better-sqlite3 # prebuilt binary is enough
223
- # or, on a platform with no prebuilt binary (it will compile from source):
224
- npm install-scripts approve better-sqlite3
225
+ npm install-scripts deny better-sqlite3 # on 13.x: the bundled binary is enough
226
+ npm install-scripts approve better-sqlite3 # on 12.x, or on a platform with no prebuilt binary
225
227
  ```
226
228
 
227
- Either command writes `allowScripts` into your `package.json`; commit it. If SQLite
228
- fails to load with a "did not self-register" or missing-binding error, you are on a
229
- platform without a prebuilt binary — approve the script. If you only use MySQL or
230
- Postgres, you can drop `better-sqlite3` entirely and this doesn't apply.
229
+ Either command writes `allowScripts` into your `package.json`; commit it. On a slim
230
+ Docker or Nixpacks image with npm 10/11 and no Python, pin `better-sqlite3@^12.6.2`
231
+ in your app — masterrecord accepts `>=12.6.2 <14` and shares your copy, so nothing
232
+ compiles. If you only use MySQL or Postgres, you can drop `better-sqlite3` entirely and
233
+ this doesn't apply.
231
234
 
232
235
  ## Two Patterns: Entity Framework & Active Record
233
236