masterrecord 1.32.1 → 1.32.3

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,35 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.32.3 — building a context is 7 times cheaper
4
+
5
+ **Fix: `dbset()` walked every registered entity each time it ran.** Registering an entity re-resolved
6
+ every foreign key and re-checked every many-to-many in the model, so building a context grew with the
7
+ square of its tables. CodeBook has 311 tables in one context and builds about 6 contexts a second while
8
+ idle: that was about 80% of its idle CPU, with nobody using it.
9
+
10
+ - `dbset()` now looks at the entity it was given, and foreign keys wait by parent name. A context with
11
+ 311 entities takes 6 ms to build, down from 43 ms. The model it ends up with is the same.
12
+ - A derived type (`dbset(Model, { extends })`) that declares `manyToMany()` now gets its join entity
13
+ straight away. Before, that only happened if another `dbset()` followed it.
14
+ - New `test/context-build-cost.test.js` checks the same FK types come out in any registration order,
15
+ and that the work grows linearly.
16
+
17
+ ## v1.32.2 — re-reads return current data again
18
+
19
+ **Fix: since 1.32.0 a tracked re-read could answer with an old row.** 1.32.0 returned the
20
+ instance the context already tracked and didn't refresh it, so `UPDATE ... WHERE` through
21
+ `executeUpdate` followed by a read of that row, or a write from another context or process
22
+ followed by a read, answered with the values from the first read. Applications written against
23
+ 1.31 rely on that read being current: CodeBook's run claims returned the lease as it was before
24
+ the update. **Don't use 1.32.0 or 1.32.1.**
25
+
26
+ - A tracked query returns the row as the database has it now, as a new object, as it did up to
27
+ 1.31. `a === b` for two reads of one row is no longer true.
28
+ - The memory fix from 1.32.0 stays: the read releases the clean copy of that row, so a long-lived
29
+ context holds one clean copy per row, not one per read.
30
+ - An object read earlier keeps its values and still works: editing it tracks it again. An instance
31
+ with pending changes stays tracked, and a re-read doesn't touch it.
32
+
3
33
  ## v1.32.1 — batched inserts keep add order on MySQL and Postgres
4
34
 
5
35
  **Fix: `saveChanges()` could assign ids out of add order on MySQL and Postgres.** A
@@ -194,8 +194,8 @@ class EntityTrackerModel {
194
194
 
195
195
  // Fetch fresh from database
196
196
  const EntityClass = this.__context[this.__name];
197
- // No tracking: a tracked findById would return THIS instance
198
- // (identity resolution), not the database values.
197
+ // No tracking: reading the values for THIS instance must not release it
198
+ // or track a second copy.
199
199
  const fresh = await EntityClass.asNoTracking().findById(...keyValues);
200
200
  if (!fresh) {
201
201
  throw new Error(
@@ -325,10 +325,10 @@ class queryMethods{
325
325
  }
326
326
 
327
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).
328
+ * Do this query's rows replace the context's clean copy of the row? Only when
329
+ * each row is a whole entity row: not raw() SQL, not a select() projection (a
330
+ * partial row must not replace the entity), and not a full-text search (each
331
+ * row carries a per-query __rank).
332
332
  */
333
333
  __identityResolvable(){
334
334
  const s = this.__queryObject.script;
@@ -347,13 +347,11 @@ class queryMethods{
347
347
  const derived = tph.derived.get(String(dataModel[tph.column]));
348
348
  if (derived) def = derived;
349
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
- }
350
+ // A query returns the row as the database has it now, as a new object.
351
+ // The clean copy this read replaces is released, so a context holds one
352
+ // clean copy per row however often it re-reads (memory follows the rows,
353
+ // not the reads). An instance with pending changes stays tracked.
354
+ if (resolvable) $that.__context.__releaseCleanCopy(def, dataModel);
357
355
  const ent = new entityTrackerModel();
358
356
  const mod = ent.build(dataModel, def, $that.__context);
359
357
  mod.__state = "track";
@@ -1424,8 +1422,8 @@ class queryMethods{
1424
1422
 
1425
1423
  // Fetch fresh from database
1426
1424
  const EntityClass = this.__context[this.__name];
1427
- // No tracking: a tracked findById would return THIS instance
1428
- // (identity resolution), not the database values.
1425
+ // No tracking: reading the values for THIS instance must not release it
1426
+ // or track a second copy.
1429
1427
  const fresh = await EntityClass.asNoTracking().findById(primaryKeyValue);
1430
1428
  if (!fresh) {
1431
1429
  throw new Error(
package/context.js CHANGED
@@ -138,13 +138,13 @@ function _poolKey(type, cfg) {
138
138
  }
139
139
 
140
140
  // ----------------------------------------------------------------------------
141
- // Identity resolution (EF Core's identity map keyed by primary key)
141
+ // One clean copy per row
142
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.
143
+ // A tracked query returns the row as the database has it now, as a new object,
144
+ // and releases the clean copy of that row this context already holds. Without
145
+ // this a long-lived context that re-reads the same rows kept a new tracked copy
146
+ // per read, so memory grew with the number of reads instead of the number of
147
+ // distinct rows. The key is "<table>\0<primary key>".
148
148
 
149
149
  // Entity definition -> its primary-key column names, or null when the type
150
150
  // cannot be keyed (no key, or a key column that is a navigation).
@@ -325,13 +325,15 @@ class context {
325
325
  // writes whenever the two disagreed (a stale/colliding id in one but not the
326
326
  // other). All mutations go through __track / __untrack / __clearTracked.
327
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.
328
+ // Identity index beside the map: "<table>\0<primary key>" -> the tracked
329
+ // instance of that row a query's read replaces, or which has pending changes.
330
+ // __identityCopies holds the row's clean copy while an instance with pending
331
+ // changes holds the key, so that copy is released by the next read as well.
330
332
  // __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).
333
+ // be removed even after its key value changed. All three are kept in step by
334
+ // __track / __untrack / __clearTracked.
334
335
  __identityIndex = new Map();
336
+ __identityCopies = new Map();
335
337
  __identityKeys = new WeakMap();
336
338
  // One-time "tracked set is large" warning (see __checkTrackedSize).
337
339
  __trackedWarnThreshold = undefined; // undefined = not resolved yet
@@ -1542,13 +1544,13 @@ class context {
1542
1544
  });
1543
1545
 
1544
1546
  // belongsTo() hardcodes type='integer' before the parent entity is known.
1545
- // Now that another entity is registered, re-resolve every belongsTo FK
1546
- // column's type from its parent's primary-key type. Idempotent.
1547
- this.#resolveBelongsToTypes();
1547
+ // Now that this entity is registered, resolve its FK columns and the ones
1548
+ // already waiting for it from the parent's primary-key type. Idempotent.
1549
+ this.#resolveBelongsToTypes(validModel);
1548
1550
 
1549
1551
  // EF 5+ skip navigations: materialize the implicit join entity for every
1550
- // manyToMany() declaration (idempotent; no-op while synthesizing).
1551
- this.#synthesizeJoinEntities();
1552
+ // manyToMany() this entity declares (idempotent; no-op while synthesizing).
1553
+ this.#synthesizeJoinEntities(validModel);
1552
1554
 
1553
1555
  // Return chainable object with seed() / queryFilter() methods
1554
1556
  const chain = {
@@ -1625,7 +1627,9 @@ class context {
1625
1627
  get: function() { return tools.createNewInstance(derivedDef, query, this); },
1626
1628
  configurable: true, enumerable: true,
1627
1629
  });
1628
- this.#resolveBelongsToTypes();
1630
+ // The derived type's columns live on the root now.
1631
+ this.#resolveBelongsToTypes(rootDef);
1632
+ this.#synthesizeJoinEntities(rootDef);
1629
1633
  const chain = {
1630
1634
  seed: (data) => this.#addSeedData(table, data),
1631
1635
  queryFilter: (...a) => { this.queryFilter(model.name, ...a); return chain; },
@@ -1636,42 +1640,39 @@ class context {
1636
1640
  // ---- Implicit many-to-many join entities (EF Core 5+ skip navigations) ---
1637
1641
 
1638
1642
  /**
1639
- * For each `manyToMany()` navigation whose join entity is not registered,
1643
+ * For each `manyToMany()` navigation of `entity` whose join entity is not registered,
1640
1644
  * synthesize it exactly as a user-written model would be: an auto PK,
1641
1645
  * `belongsTo()` to both sides (FK constraints, ON DELETE CASCADE) and a
1642
1646
  * unique composite index on the two FK columns. Registered through dbset()
1643
1647
  * so table prefix, validation, FK type resolution, migrations and query
1644
1648
  * builders all see it. Idempotent.
1645
1649
  */
1646
- #synthesizeJoinEntities() {
1650
+ #synthesizeJoinEntities(ent) {
1647
1651
  if (this.__synthesizingJoins) return;
1648
1652
  const prefix = (this.tablePrefix && typeof this.tablePrefix === 'string') ? this.tablePrefix : '';
1649
1653
  const registered = (name) => this.__entities.some(e => e && (e.__name === name || e.__name === prefix + name));
1650
- for (const ent of [...this.__entities]) {
1651
- if (!ent) continue;
1652
- for (const key of Object.keys(ent)) {
1653
- const def = ent[key];
1654
- if (key.startsWith('__') || !def || typeof def !== 'object' || !def.implicitJoin) continue;
1655
- const joinName = def.foreignTable;
1656
- if (!joinName || registered(joinName)) continue;
1657
- const ownerName = (prefix && ent.__name.startsWith(prefix)) ? ent.__name.slice(prefix.length) : ent.__name;
1658
- const targetName = def.targetTable;
1659
- const fkOwner = def.joinForeignKey;
1660
- const fkTarget = def.joinOtherKey;
1661
- const ownerField = fkOwner.replace(/_id$/i, '') || ownerName.toLowerCase();
1662
- const targetField = fkTarget.replace(/_id$/i, '') || targetName.toLowerCase();
1663
- if (ownerField === targetField) {
1664
- throw new Error(`masterrecord: manyToMany join '${joinName}' would have two identical fields '${ownerField}'; pass distinct { foreignKey, otherKey }.`);
1665
- }
1666
- const Join = { [joinName]: class { id(db) { db.integer().primary().auto(); } } }[joinName];
1667
- Object.defineProperty(Join.prototype, ownerField, { value: function(db) { db.belongsTo(ownerName, fkOwner); }, writable: true, configurable: true, enumerable: false });
1668
- Object.defineProperty(Join.prototype, targetField, { value: function(db) { db.belongsTo(targetName, fkTarget); }, writable: true, configurable: true, enumerable: false });
1669
- Join.compositeIndexes = [{ columns: [fkOwner, fkTarget], unique: true, name: `ux_${joinName.toLowerCase()}_${fkOwner}_${fkTarget}` }];
1670
- this.__synthesizingJoins = true;
1671
- try { this.dbset(Join); } finally { this.__synthesizingJoins = false; }
1672
- const joinDef = this.__entities.find(e => e && e.__name === prefix + joinName);
1673
- if (joinDef) Object.defineProperty(joinDef, '__implicitJoin', { value: true, enumerable: false, configurable: true });
1654
+ for (const key of Object.keys(ent)) {
1655
+ const def = ent[key];
1656
+ if (key.startsWith('__') || !def || typeof def !== 'object' || !def.implicitJoin) continue;
1657
+ const joinName = def.foreignTable;
1658
+ if (!joinName || registered(joinName)) continue;
1659
+ const ownerName = (prefix && ent.__name.startsWith(prefix)) ? ent.__name.slice(prefix.length) : ent.__name;
1660
+ const targetName = def.targetTable;
1661
+ const fkOwner = def.joinForeignKey;
1662
+ const fkTarget = def.joinOtherKey;
1663
+ const ownerField = fkOwner.replace(/_id$/i, '') || ownerName.toLowerCase();
1664
+ const targetField = fkTarget.replace(/_id$/i, '') || targetName.toLowerCase();
1665
+ if (ownerField === targetField) {
1666
+ throw new Error(`masterrecord: manyToMany join '${joinName}' would have two identical fields '${ownerField}'; pass distinct { foreignKey, otherKey }.`);
1674
1667
  }
1668
+ const Join = { [joinName]: class { id(db) { db.integer().primary().auto(); } } }[joinName];
1669
+ Object.defineProperty(Join.prototype, ownerField, { value: function(db) { db.belongsTo(ownerName, fkOwner); }, writable: true, configurable: true, enumerable: false });
1670
+ Object.defineProperty(Join.prototype, targetField, { value: function(db) { db.belongsTo(targetName, fkTarget); }, writable: true, configurable: true, enumerable: false });
1671
+ Join.compositeIndexes = [{ columns: [fkOwner, fkTarget], unique: true, name: `ux_${joinName.toLowerCase()}_${fkOwner}_${fkTarget}` }];
1672
+ this.__synthesizingJoins = true;
1673
+ try { this.dbset(Join); } finally { this.__synthesizingJoins = false; }
1674
+ const joinDef = this.__entities.find(e => e && e.__name === prefix + joinName);
1675
+ if (joinDef) Object.defineProperty(joinDef, '__implicitJoin', { value: true, enumerable: false, configurable: true });
1675
1676
  }
1676
1677
  }
1677
1678
 
@@ -2022,9 +2023,9 @@ class context {
2022
2023
  const loadedOut = [];
2023
2024
  const pending = [];
2024
2025
  // 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.
2026
+ // already loaded. A query can reach an instance whose navigation an
2027
+ // EARLIER query loaded (with other filters); an explicit include()
2028
+ // reloads it, so the result reflects this query.
2028
2029
  let loadedThisRun = null;
2029
2030
  if (opts.run instanceof Map) {
2030
2031
  const runKey = `${ownerDef.__name}.${nav}`;
@@ -2393,47 +2394,47 @@ class context {
2393
2394
  });
2394
2395
  }
2395
2396
 
2396
- // Walk every registered entity. For each column with relationshipType ===
2397
- // 'belongsTo', look up the parent entity by foreignTable name and copy the
2398
- // parent's primary-key type onto the FK column. Without this, FKs to a
2399
- // string/uuid/bigint PK end up declared INTEGER, which SQLite tolerates
2400
- // (dynamic typing) but Postgres and MySQL reject.
2401
- #resolveBelongsToTypes() {
2402
- const entities = this.__entities;
2403
- if (!entities || entities.length === 0) return;
2404
-
2405
- // Case-insensitive lookup table — users may write
2397
+ // For each column of `entity` with relationshipType === 'belongsTo', copy the
2398
+ // parent's primary-key type onto the FK column, now if the parent is registered
2399
+ // and otherwise when it is. Without this, FKs to a string/uuid/bigint PK end up
2400
+ // declared INTEGER, which SQLite tolerates (dynamic typing) but Postgres and
2401
+ // MySQL reject.
2402
+ //
2403
+ // Runs once per registered entity and touches only that entity's columns, so
2404
+ // building a context stays linear in its tables. It used to walk every entity
2405
+ // for every dbset(): 311 tables cost CodeBook 40 ms for each context it built.
2406
+ #resolveBelongsToTypes(entity) {
2407
+ // Case-insensitive lookups — users may write
2406
2408
  // db.belongsTo('run') while the class is `Run`.
2407
- const byName = {};
2408
- for (const e of entities) {
2409
- if (e && e.__name) {
2410
- byName[e.__name.toLowerCase()] = e;
2409
+ const parents = this.__fkParents || (this.__fkParents = new Map());
2410
+ const waiting = this.__fkWaiting || (this.__fkWaiting = new Map());
2411
+ const primaryKeyType = (parent) => {
2412
+ for (const pKey of Object.keys(parent)) {
2413
+ const pCol = parent[pKey];
2414
+ if (pCol && typeof pCol === 'object' && pCol.primary === true && pCol.type) return pCol.type;
2411
2415
  }
2412
- }
2416
+ return null;
2417
+ };
2418
+ const assign = (columns, type) => {
2419
+ if (!type) return;
2420
+ for (const col of columns) if (col.type !== type) col.type = type;
2421
+ };
2413
2422
 
2414
- for (const entity of entities) {
2415
- for (const key of Object.keys(entity)) {
2416
- const col = entity[key];
2417
- if (!col || typeof col !== 'object') continue;
2418
- if (col.relationshipType !== 'belongsTo') continue;
2419
- if (!col.foreignTable) continue;
2420
-
2421
- const parent = byName[String(col.foreignTable).toLowerCase()];
2422
- if (!parent) continue;
2423
-
2424
- // Find the parent's primary-key column.
2425
- for (const pKey of Object.keys(parent)) {
2426
- const pCol = parent[pKey];
2427
- if (!pCol || typeof pCol !== 'object') continue;
2428
- if (pCol.primary === true && pCol.type) {
2429
- if (col.type !== pCol.type) {
2430
- col.type = pCol.type;
2431
- }
2432
- break;
2433
- }
2434
- }
2435
- }
2423
+ if (entity.__name) parents.set(entity.__name.toLowerCase(), entity);
2424
+ for (const key of Object.keys(entity)) {
2425
+ const col = entity[key];
2426
+ if (!col || typeof col !== 'object') continue;
2427
+ if (col.relationshipType !== 'belongsTo') continue;
2428
+ if (!col.foreignTable) continue;
2429
+
2430
+ const parentName = String(col.foreignTable).toLowerCase();
2431
+ if (!waiting.has(parentName)) waiting.set(parentName, []);
2432
+ waiting.get(parentName).push(col);
2433
+ const parent = parents.get(parentName);
2434
+ if (parent) assign([col], primaryKeyType(parent));
2436
2435
  }
2436
+ // FK columns registered before this entity, and a self-reference.
2437
+ if (entity.__name && waiting.has(entity.__name.toLowerCase())) assign(waiting.get(entity.__name.toLowerCase()), primaryKeyType(entity));
2437
2438
  }
2438
2439
 
2439
2440
  /**
@@ -4372,23 +4373,22 @@ class context {
4372
4373
  this.__trackedEntitiesMap.clear(); // sole registry; the list view follows
4373
4374
  this.__dirtyEntities.clear();
4374
4375
  this.__identityIndex.clear();
4376
+ this.__identityCopies.clear();
4375
4377
  this.__identityKeys = new WeakMap();
4376
4378
  }
4377
4379
 
4378
- // ---- Identity resolution ------------------------------------------------
4380
+ // ---- One clean copy per row ----------------------------------------------
4379
4381
 
4380
4382
  /**
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.
4383
+ * Index a tracked entity under its type + primary key, so the next tracked
4384
+ * query that reads the same row can release it. Called from __track(). An
4385
+ * entity with no usable key yet (a pending insert with an auto key) is
4386
+ * skipped, and indexed once its key is assigned.
4385
4387
  *
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.
4388
+ * A context can track two instances of one row: an instance a read replaced
4389
+ * or a save detached re-tracks itself when it is edited. Then the instance
4390
+ * with pending changes holds the key and the clean copy moves to
4391
+ * __identityCopies. Neither is lost, and the next read releases the clean one.
4392
4392
  * @private
4393
4393
  */
4394
4394
  __indexIdentity(model) {
@@ -4402,9 +4402,16 @@ class context {
4402
4402
  const holder = this.__identityIndex.get(key);
4403
4403
  if (holder !== undefined && holder !== model && this.__isLiveIdentity(holder, key)) {
4404
4404
  const modelDirty = context._isEntityDirty(model);
4405
- if (!modelDirty || context._isEntityDirty(holder)) return;
4406
- this.__identityKeys.delete(holder); // the clean copy stays tracked, unindexed
4405
+ if (!modelDirty) {
4406
+ if (!context._isEntityDirty(holder)) return;
4407
+ this.__identityCopies.set(key, model); // a clean copy beside pending changes
4408
+ this.__identityKeys.set(model, key);
4409
+ return;
4410
+ }
4411
+ if (context._isEntityDirty(holder)) return;
4412
+ this.__identityCopies.set(key, holder); // the clean copy stays tracked
4407
4413
  }
4414
+ if (this.__identityCopies.get(key) === model) this.__identityCopies.delete(key);
4408
4415
  this.__identityIndex.set(key, model);
4409
4416
  this.__identityKeys.set(model, key);
4410
4417
  }
@@ -4414,8 +4421,16 @@ class context {
4414
4421
  if (!model || typeof model !== 'object') return;
4415
4422
  const key = this.__identityKeys.get(model);
4416
4423
  if (key === undefined) return;
4417
- if (this.__identityIndex.get(key) === model) this.__identityIndex.delete(key);
4418
4424
  this.__identityKeys.delete(model);
4425
+ if (this.__identityCopies.get(key) === model) this.__identityCopies.delete(key);
4426
+ if (this.__identityIndex.get(key) === model) {
4427
+ this.__identityIndex.delete(key);
4428
+ // The clean copy beside it went stale when this instance was saved or
4429
+ // detached; nothing would ever read it from here (a deleted row is
4430
+ // never read again), so it goes too.
4431
+ const copy = this.__identityCopies.get(key);
4432
+ if (copy !== undefined && !context._isEntityDirty(copy)) this.__untrack([copy]);
4433
+ }
4419
4434
  }
4420
4435
 
4421
4436
  /** Is `e` still tracked here and does its current key still equal `key`? @private */
@@ -4427,28 +4442,29 @@ class context {
4427
4442
  }
4428
4443
 
4429
4444
  /**
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).
4445
+ * A tracked query is about to build a new entity from `row` (a raw database row
4446
+ * of `def`): stop tracking the clean copies of that row. An older instance a
4447
+ * caller still holds keeps working: editing it tracks it again. An instance
4448
+ * with pending changes (modified, pending delete or insert) stays tracked and
4449
+ * is saved as usual.
4434
4450
  * @private
4435
4451
  */
4436
- __trackedForRow(def, row) {
4437
- if (this.__identityIndex.size === 0 || !row) return null;
4452
+ __releaseCleanCopy(def, row) {
4453
+ if (!row || (this.__identityIndex.size === 0 && this.__identityCopies.size === 0)) return;
4438
4454
  let key;
4439
4455
  try {
4440
4456
  key = _identityKey(def, (c) => FieldTransformer.fromDatabase(row[c], def[c], def.__name, c));
4441
4457
  } 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;
4458
+ return; // a failing transformer: let the normal build path report it
4459
+ }
4460
+ if (key === null) return;
4461
+ const holder = this.__identityIndex.get(key);
4462
+ const copy = this.__identityCopies.get(key);
4463
+ for (const e of [holder, copy]) {
4464
+ if (e === undefined) continue;
4465
+ if (!this.__isLiveIdentity(e, key)) this.__unindexIdentity(e); // detached elsewhere, or its key changed
4466
+ else if (!context._isEntityDirty(e)) this.__untrack([e]);
4467
+ }
4452
4468
  }
4453
4469
 
4454
4470
  /**
@@ -4502,8 +4518,8 @@ class context {
4502
4518
  *
4503
4519
  * A context is a unit of work and is safest scoped per request. If you must
4504
4520
  * reuse a long-lived (e.g. singleton) context, read-only queries still
4505
- * auto-track their results: one instance per distinct row (identity
4506
- * resolution), which still grows with every new row read — call this
4521
+ * auto-track their results: one clean copy per distinct row, which still
4522
+ * grows with every new row read — call this
4507
4523
  * after a read-only operation to release them and keep the tracked set
4508
4524
  * bounded. It drops PENDING changes too, so only call it when there is
4509
4525
  * nothing dirty you still intend to save.
@@ -19,24 +19,27 @@ user.blocked = 1; // dirty
19
19
  await db.saveChanges(); // one UPDATE
20
20
  ```
21
21
 
22
- ### Identity resolution (since 1.32.0)
22
+ ### Re-reads: current data, one clean copy per row (since 1.32.2)
23
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:
24
+ A tracked query returns the row **as the database has it now, as a new object**. It releases the clean copy of that row the context already holds (same entity type and primary key, composite keys included).
25
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.
26
+ - A read sees writes made any other way: `executeUpdate`, another context, another process.
27
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.
28
+ - An object you read earlier keeps the values it read. It still works: editing it tracks it again, and `saveChanges()` writes the change.
29
+ - An instance with pending changes (modified, or pending delete or insert) stays tracked, and a re-read does not touch it. The read answers with the database row until you save.
30
+ - `select()` projections, `raw()` SQL and full-text `search()` rows are tracked as before and do not replace the whole entity.
30
31
 
31
32
  ```javascript
32
33
  const a = await db.User.findById(1);
33
34
  a.name = 'pending';
34
35
  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
36
+ b === a; // false
37
+ b.name; // the database value: 'pending' is not saved yet
38
+ a.name; // 'pending'
39
+ await db.saveChanges(); // writes a's change
37
40
  ```
38
41
 
39
- ---
42
+ 1.32.0 and 1.32.1 returned the tracked instance without refreshing it. A read after `executeUpdate` or a write from another context answered with the old row. Don't use those two versions.
40
43
 
41
44
  ## Controlling what gets tracked (EF's `QueryTrackingBehavior`)
42
45
 
@@ -268,7 +271,7 @@ Transient errors (deadlocks, lock timeouts, busy SQLite, dropped connections) ar
268
271
  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):
269
272
 
270
273
  - **Lost writes** — one request's `saveChanges()` interacting with another's tracked entities.
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.
274
+ - **Unbounded memory** — read-only queries track results that are never released. One clean copy per row 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.
272
275
  - **Undefined behavior** under concurrent access (EF: "application crashes and data corruption").
273
276
 
274
277
  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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.32.1",
3
+ "version": "1.32.3",
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",
@@ -88,7 +88,7 @@
88
88
  "better-sqlite3": ">=12.6.2 <14",
89
89
  "commander": "^14.0.3",
90
90
  "deep-object-diff": "^1.1.9",
91
- "glob": "^13.0.6",
91
+ "glob": "^14.0.2",
92
92
  "mysql2": "^3.23.2",
93
93
  "pg": "^8.22.0"
94
94
  },