masterrecord 1.22.1 → 1.23.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.
package/CHANGES.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.23.0 — entity property reads ~16x faster (shared prototype per entity type)
4
+
5
+ - **Perf:** every entity of a type now shares **one prototype** and keeps its backing slots (`_<col>`, `_<nav>`, `__loading_<nav>`) as **non-enumerable own properties**. Before, each row got a fresh `{}` prototype holding its slots, so every entity had its own V8 hidden class and `entity.col` was a megamorphic accessor read: **~326 ns/read** (both tracked and `asNoTracking()`), i.e. an O(n²) loop over two 2 000-row tables took seconds and over larger tables minutes. Now **~20 ns/read**; the 2 000×2 000 nested loop went from 2.07 s to 0.19 s. EF Core entities are POCOs — a property read should cost about what a plain object read costs.
6
+ - Public shape is unchanged: `Object.keys(entity)` / `JSON.stringify` / `{ ...entity }` still expose only columns; navigation getters, `asNoTracking()`, change tracking, `Object.create(entity)` clean models (engine idiom: reads walk the chain, writes reach the owner through the entity's `__self`) all behave as before. Internal slot access is centralized in `tools.slotOwner/getSlot/setSlot/hasSlot/deleteSlot` (code that poked `Object.getPrototypeOf(entity)['_col']` must use these).
7
+ - Guidance still holds for hot loops: prefer `asNoTracking()` for read-only queries (no tracking bookkeeping per row) and build one-pass `Map`s instead of nested loops.
8
+
9
+ New test: `test/entity-layout-read-performance.test.js`.
10
+
3
11
  ## v1.22.1 — boolean columns materialize as booleans on read (fix)
4
12
 
5
13
  - **Fix:** `db.boolean()` columns are now materialized as real `true`/`false` when rows are read (`toList()/find()/single()/first()`, tracked or `asNoTracking()`), matching EF Core value conversion. SQLite stores booleans as INTEGER `0/1` and MySQL as `TINYINT(1)`/`BIT(1)`, so an entity read back exposed `1`/`0` (an API echoed `{ published: true }` after the insert but `{ published: 1 }` after a later read/update). `null` is preserved; other types are untouched; a custom `transform()` still wins. Implemented as `FieldTransformer.materialize(value, fieldDef)`, applied on the single row→entity path.
@@ -12,7 +12,10 @@ class EntityTrackerModel {
12
12
  build(dataModel, currentEntity, context){
13
13
  const $that = this;
14
14
  const modelClass = this.buildObject(); // build entity with models
15
- modelClass.__proto__ = {};
15
+ // The entity's prototype stays the ordinary shared Object.prototype and its
16
+ // backing slots are non-enumerable OWN properties (see tools.slotOwner):
17
+ // every row of a type shares one hidden class, so reads stay monomorphic.
18
+ Object.defineProperty(modelClass, '__self', { value: modelClass, enumerable: false, writable: false, configurable: true });
16
19
  const modelFields = Object.entries(dataModel); /// return array of objects
17
20
 
18
21
  modelClass.__entity = currentEntity;
@@ -212,7 +215,7 @@ class EntityTrackerModel {
212
215
 
213
216
  // Only reload scalar fields
214
217
  if (!isRelationship) {
215
- this.__proto__["_" + fieldName] = fresh.__proto__["_" + fieldName];
218
+ tools.setSlot(this, "_" + fieldName, tools.getSlot(fresh, "_" + fieldName));
216
219
  }
217
220
  }
218
221
 
@@ -328,7 +331,10 @@ class EntityTrackerModel {
328
331
  }
329
332
  }
330
333
 
331
- target["__proto__"]["_" + modelField] = transformedValue;
334
+ const slot = "_" + modelField; // backing slot (non-enumerable own property)
335
+ const fieldDef = currentEntity[modelField] || null; // static column definition
336
+ const customGet = (fieldDef && typeof fieldDef.get === "function") ? fieldDef.get : null;
337
+ tools.setSlot(target, slot, transformedValue);
332
338
 
333
339
  Object.defineProperty(target, modelField, {
334
340
  enumerable: true,
@@ -431,33 +437,26 @@ class EntityTrackerModel {
431
437
  } else {
432
438
  storedValue = value;
433
439
  }
434
- this["__proto__"]["_" + modelField] = storedValue;
440
+ tools.setSlot(this, slot, storedValue);
435
441
  if (navNameForFk) {
436
442
  // FK -> navigation fix-up (EF): changing the FK column invalidates
437
443
  // a previously loaded/assigned navigation so the next read
438
444
  // re-resolves it (lazy) instead of returning a stale parent.
439
445
  // The engines persist the FK via tools.foreignKeyValue(), which
440
446
  // falls back to this column when the navigation slot is unset.
441
- const proto = this["__proto__"];
442
- const nav = proto["_" + navNameForFk];
443
- if (nav !== undefined && nav !== storedValue) delete proto["_" + navNameForFk];
444
- delete proto["__loading_" + navNameForFk];
447
+ const nav = tools.getSlot(this, "_" + navNameForFk);
448
+ if (nav !== undefined && nav !== storedValue) tools.deleteSlot(this, "_" + navNameForFk);
449
+ tools.deleteSlot(this, "__loading_" + navNameForFk);
445
450
  }
446
451
  },
452
+ // Hot path: a property read on an entity must cost about what a plain
453
+ // object read costs (EF Core entities are POCOs). The slot key, field
454
+ // definition and custom getter are resolved ONCE per accessor (closure),
455
+ // not per read — previously every read re-concatenated "_" + field and
456
+ // re-walked the definition (~300 ns/read, ~200x a plain property).
447
457
  get: function() {
448
- if (currentEntity[modelField]) {
449
- if (!currentEntity[modelField].skipGetFunction) {
450
- if (typeof currentEntity[modelField].get === "function") {
451
- return currentEntity[modelField].get(this["__proto__"]["_" + modelField]);
452
- } else {
453
- return this["__proto__"]["_" + modelField];
454
- }
455
- } else {
456
- return this["__proto__"]["_" + modelField];
457
- }
458
- } else {
459
- return this["__proto__"]["_" + modelField];
460
- }
458
+ const value = this[slot]; // own slot on the entity; a derived clean model reads it through the chain
459
+ return (customGet !== null && !fieldDef.skipGetFunction) ? customGet(value) : value;
461
460
  }
462
461
  });
463
462
  }
@@ -471,10 +470,9 @@ class EntityTrackerModel {
471
470
  * After this, the inserted entity behaves like a queried one: edits mark it
472
471
  * modified and produce an UPDATE.
473
472
  *
474
- * A per-entity backing layer is spliced into the prototype chain
475
- * (`Object.create(originalProto)`) so `_<field>` backings stay per-instance
476
- * while the class prototype — and any lifecycle-hook methods on it — remain
477
- * reachable.
473
+ * Backing slots (`_<field>`) are non-enumerable own properties of the object
474
+ * itself (see tools.slotOwner), so the class prototype — and any lifecycle-hook
475
+ * methods on it — is never touched.
478
476
  */
479
477
  attachTrackingTo(target) {
480
478
  const currentEntity = target && target.__entity;
@@ -508,12 +506,14 @@ class EntityTrackerModel {
508
506
  scalarFields.push(modelField);
509
507
  }
510
508
 
511
- // Splice a fresh backing layer in front of the original prototype so the
512
- // class prototype (and its lifecycle hooks) stays reachable.
513
- Object.setPrototypeOf(target, Object.create(Object.getPrototypeOf(target)));
509
+ // Backing slots become non-enumerable OWN properties of the user's object;
510
+ // its class prototype (and any lifecycle-hook methods on it) is untouched.
514
511
  Object.defineProperty(target, '__trackingAttached', {
515
512
  value: true, enumerable: false, writable: true, configurable: true,
516
513
  });
514
+ if (!Object.prototype.hasOwnProperty.call(target, '__self')) {
515
+ Object.defineProperty(target, '__self', { value: target, enumerable: false, writable: false, configurable: true });
516
+ }
517
517
 
518
518
  for (const modelField of scalarFields) {
519
519
  // applyFromDb=false: the captured value is already the domain value
@@ -584,7 +584,7 @@ class EntityTrackerModel {
584
584
  // belongsTo navigation also sets the foreign-key column, so
585
585
  // `post.author = someAuthor` persists author_id on save.
586
586
  const def = currentEntity[entityField];
587
- const proto = Object.getPrototypeOf(modelClass); // accessor owner's slot, never `this`
587
+ const proto = modelClass; // slots live on the accessor OWNER (own non-enumerable props), never on `this`
588
588
  if (value && typeof value === 'object' && value.__entity && def && def.relationshipType === 'belongsTo' && def.foreignKey) {
589
589
  const parentPk = tools.getPrimaryKeyObject(value.__entity);
590
590
  const fkVal = parentPk ? value[parentPk] : undefined;
@@ -594,10 +594,10 @@ class EntityTrackerModel {
594
594
  modelClass[def.foreignKey] = fkVal;
595
595
  }
596
596
  } else if ((value === null || typeof value !== 'object') && def && def.relationshipType === 'belongsTo' && def.foreignKey && ('_' + def.foreignKey) in proto) {
597
- proto['_' + def.foreignKey] = value; // legacy idiom `post.author = authorId`
597
+ tools.setSlot(proto, '_' + def.foreignKey, value); // legacy idiom `post.author = authorId`
598
598
  }
599
- delete proto['__loading_' + entityField];
600
- proto["_" + entityField] = value;
599
+ tools.deleteSlot(proto, '__loading_' + entityField);
600
+ tools.setSlot(proto, "_" + entityField, value);
601
601
  },
602
602
  get : function(){
603
603
  // Navigation getter (EF semantics, adapted to async JS drivers):
@@ -610,7 +610,7 @@ class EntityTrackerModel {
610
610
  // Resolve the backing slot from the accessor OWNER, never from
611
611
  // `this`: a derived object (Object.create(entity), used by the
612
612
  // engines) must not end up with its own shadowing `_<nav>`.
613
- const proto = Object.getPrototypeOf(modelClass);
613
+ const proto = modelClass;
614
614
  const loaded = proto['_' + entityField];
615
615
  // undefined = not loaded; null = loaded, no related row (EF); a thenable = in flight
616
616
  if (loaded !== undefined && !(loaded && typeof loaded.then === 'function')) return loaded;
@@ -621,10 +621,10 @@ class EntityTrackerModel {
621
621
  const inflightKey = '__loading_' + entityField;
622
622
  if (proto[inflightKey] && typeof proto[inflightKey].then === 'function') return proto[inflightKey];
623
623
  const p = ctx.loadNavigation(modelClass, entityField).then(
624
- (v) => { proto['_' + entityField] = v; delete proto[inflightKey]; return v; },
625
- (err) => { delete proto[inflightKey]; throw err; }
624
+ (v) => { tools.setSlot(proto, '_' + entityField, v); tools.deleteSlot(proto, inflightKey); return v; },
625
+ (err) => { tools.deleteSlot(proto, inflightKey); throw err; }
626
626
  );
627
- proto[inflightKey] = p;
627
+ tools.setSlot(proto, inflightKey, p);
628
628
  p.catch(() => {}); // awaiters still see the rejection; avoids an unhandled-rejection crash when un-awaited
629
629
  return p;
630
630
  }
@@ -1087,8 +1087,10 @@ class queryMethods{
1087
1087
  __entity : this.__entity,
1088
1088
  __context : this.__context,
1089
1089
  __name : this.__entity.__name,
1090
- __proto__ : {}
1091
1090
  };
1091
+ // Backing slots are non-enumerable own properties (see tools.slotOwner); the
1092
+ // prototype stays the shared Object.prototype so reads stay monomorphic.
1093
+ Object.defineProperty(newEntity, '__self', { value: newEntity, enumerable: false, writable: false, configurable: true });
1092
1094
 
1093
1095
  // Set up property setters for all entity fields
1094
1096
  for (const fieldName in this.__entity) {
@@ -1165,11 +1167,7 @@ class queryMethods{
1165
1167
  // tracker-entity setter (entityTrackerModel.build) already does
1166
1168
  // this on UPDATE; we need the same behavior on INSERT so values
1167
1169
  // normalize consistently regardless of which path created them.
1168
- if (fieldDef && typeof fieldDef.set === 'function') {
1169
- this.__proto__["_" + fname] = fieldDef.set(value);
1170
- } else {
1171
- this.__proto__["_" + fname] = value;
1172
- }
1170
+ tools.setSlot(this, "_" + fname, (fieldDef && typeof fieldDef.set === 'function') ? fieldDef.set(value) : value);
1173
1171
  if(!this.__dirtyFields.includes(fname)){
1174
1172
  this.__dirtyFields.push(fname);
1175
1173
  }
@@ -1187,9 +1185,9 @@ class queryMethods{
1187
1185
  get: function(){
1188
1186
  // Apply get function if defined
1189
1187
  if(fieldDef && typeof fieldDef.get === "function"){
1190
- return fieldDef.get(this.__proto__["_" + fname]);
1188
+ return fieldDef.get(this["_" + fname]);
1191
1189
  }
1192
- return this.__proto__["_" + fname];
1190
+ return this["_" + fname];
1193
1191
  }
1194
1192
  });
1195
1193
 
@@ -1221,7 +1219,7 @@ class queryMethods{
1221
1219
  enumerable: true,
1222
1220
  configurable: true,
1223
1221
  set: function(value) {
1224
- this.__proto__["_" + navName] = value;
1222
+ tools.setSlot(this, "_" + navName, value);
1225
1223
  if (!this.__dirtyFields.includes(navName)) {
1226
1224
  this.__dirtyFields.push(navName);
1227
1225
  }
@@ -1240,7 +1238,7 @@ class queryMethods{
1240
1238
  // to the FK-column backing populated
1241
1239
  // by DB hydration in
1242
1240
  // entityTrackerModel.build().
1243
- const navVal = this.__proto__["_" + navName];
1241
+ const navVal = this["_" + navName];
1244
1242
  if (navVal && typeof navVal === 'object' && navVal.__entity) {
1245
1243
  // An assigned parent ENTITY: the FK column reads its key.
1246
1244
  const def = navVal.__entity;
@@ -1249,7 +1247,7 @@ class queryMethods{
1249
1247
  }
1250
1248
  return navVal !== undefined
1251
1249
  ? navVal
1252
- : this.__proto__["_" + fkName];
1250
+ : this["_" + fkName];
1253
1251
  }
1254
1252
  });
1255
1253
  }
@@ -1412,7 +1410,7 @@ class queryMethods{
1412
1410
 
1413
1411
  // Only reload scalar fields
1414
1412
  if (!isRelationship) {
1415
- this.__proto__["_" + fieldName] = fresh.__proto__["_" + fieldName];
1413
+ tools.setSlot(this, "_" + fieldName, tools.getSlot(fresh, "_" + fieldName));
1416
1414
  }
1417
1415
  }
1418
1416
 
package/Tools.js CHANGED
@@ -150,17 +150,50 @@ class Tools{
150
150
 
151
151
  }
152
152
 
153
+ /**
154
+ * Backing-slot storage (1.23.0). A tracked entity keeps its column values,
155
+ * navigation values and in-flight markers in NON-ENUMERABLE OWN properties
156
+ * (`_<col>`, `_<nav>`, `__loading_<nav>`) and its prototype is the ordinary
157
+ * shared one — so every entity of a type has the same V8 hidden class and a
158
+ * property read costs what a plain object read costs (it used to be a fresh
159
+ * per-row prototype object holding the slots: ~300 ns/read, megamorphic).
160
+ * A derived clean model (`Object.create(entity)`, used by the engines) finds
161
+ * its owner through the entity's `__self`; reads walk the chain naturally.
162
+ */
163
+ static slotOwner(obj) {
164
+ if (!obj || typeof obj !== 'object') return obj;
165
+ const self = obj.__self;
166
+ return (self && typeof self === 'object') ? self : obj;
167
+ }
168
+ static hasSlot(obj, key) {
169
+ const o = Tools.slotOwner(obj);
170
+ return !!o && typeof o === 'object' && (key in o);
171
+ }
172
+ static getSlot(obj, key) {
173
+ const o = Tools.slotOwner(obj);
174
+ return (o && typeof o === 'object') ? o[key] : undefined;
175
+ }
176
+ static setSlot(obj, key, value) {
177
+ const o = Tools.slotOwner(obj);
178
+ if (!o || typeof o !== 'object') return;
179
+ if (Object.prototype.hasOwnProperty.call(o, key)) o[key] = value;
180
+ else Object.defineProperty(o, key, { value, writable: true, enumerable: false, configurable: true });
181
+ }
182
+ static deleteSlot(obj, key) {
183
+ const o = Tools.slotOwner(obj);
184
+ if (o && typeof o === 'object' && Object.prototype.hasOwnProperty.call(o, key)) delete o[key];
185
+ }
186
+
153
187
  /**
154
188
  * Read a field's stored value WITHOUT invoking a navigation getter:
155
189
  * a plain data property (new Model() before tracking accessors exist),
156
- * else the tracked backing slot `_<key>` on the prototype.
190
+ * else the tracked backing slot `_<key>`.
157
191
  */
158
192
  static dataValue(obj, key) {
159
193
  if (!obj || typeof obj !== 'object') return undefined;
160
194
  const d = Object.getOwnPropertyDescriptor(obj, key);
161
195
  if (d && 'value' in d) return d.value;
162
- const proto = Object.getPrototypeOf(obj);
163
- if (proto && ('_' + key) in proto) return proto['_' + key];
196
+ if (Tools.hasSlot(obj, '_' + key)) return Tools.getSlot(obj, '_' + key);
164
197
  return undefined;
165
198
  }
166
199
 
package/context.js CHANGED
@@ -1866,8 +1866,7 @@ class context {
1866
1866
  if (!def || typeof def !== 'object') throw new Error(`masterrecord: '${field}' is not a navigation of ${entity.__entity.__name}.`);
1867
1867
  const isRel = def.relationshipType === 'belongsTo' || def.type === 'hasOne' || def.type === 'hasMany' || def.type === 'hasManyThrough';
1868
1868
  if (!isRel) throw new Error(`masterrecord: '${field}' on ${entity.__entity.__name} is a column, not a navigation.`);
1869
- const proto = Object.getPrototypeOf(entity);
1870
- const backing = (col) => (proto && ('_' + col) in proto) ? proto['_' + col] : entity[col];
1869
+ const backing = (col) => tools.hasSlot(entity, '_' + col) ? tools.getSlot(entity, '_' + col) : entity[col];
1871
1870
  let value = null;
1872
1871
 
1873
1872
  if (def.relationshipType === 'belongsTo') {
@@ -1906,7 +1905,7 @@ class context {
1906
1905
  if (def.type === 'hasMany') this._decorateCollection(entity, field, value);
1907
1906
  }
1908
1907
  }
1909
- if (proto) proto['_' + field] = value; else entity['_' + field] = value;
1908
+ tools.setSlot(entity, '_' + field, value);
1910
1909
  return value;
1911
1910
  }
1912
1911
 
@@ -1934,8 +1933,8 @@ class context {
1934
1933
  if (!isBt && def.type !== 'hasOne' && def.type !== 'hasMany' && def.type !== 'hasManyThrough') {
1935
1934
  throw new Error(`masterrecord: '${nav}' on ${ownerDef.__name} is a column, not a navigation.`);
1936
1935
  }
1937
- const slotOf = (e) => Object.getPrototypeOf(e);
1938
- const setSlot = (e, v) => { const p = slotOf(e); if (p) p['_' + nav] = v; else e['_' + nav] = v; };
1936
+ const slotOf = (e) => tools.slotOwner(e);
1937
+ const setSlot = (e, v) => tools.setSlot(e, '_' + nav, v);
1939
1938
  const CHUNK = 500;
1940
1939
  const chunks = (arr) => { const out = []; for (let i = 0; i < arr.length; i += CHUNK) out.push(arr.slice(i, i + CHUNK)); return out; };
1941
1940
  const uniq = (arr) => [...new Set(arr.filter(v => v !== undefined && v !== null && typeof v !== 'function'))];
@@ -2016,8 +2015,7 @@ class context {
2016
2015
 
2017
2016
  /** Has this navigation been loaded (by include() or loadNavigation())? */
2018
2017
  isNavigationLoaded(entity, field) {
2019
- const proto = Object.getPrototypeOf(entity);
2020
- const v = proto ? proto['_' + field] : undefined;
2018
+ const v = tools.getSlot(entity, '_' + field);
2021
2019
  // null counts as loaded (EF: the reference was loaded and there is no related row)
2022
2020
  return v !== undefined && !(v && typeof v.then === 'function');
2023
2021
  }
@@ -2915,9 +2913,8 @@ class context {
2915
2913
  // entity so its value matches the row and the next save's WHERE
2916
2914
  // uses the new version.
2917
2915
  if (rowVersionColumn) {
2918
- const proto = Object.getPrototypeOf(currentModel);
2919
2916
  const cur = Number(this._backingValue(currentModel, rowVersionColumn) || 0);
2920
- if (proto && ('_' + rowVersionColumn) in proto) proto['_' + rowVersionColumn] = cur + 1;
2917
+ if (tools.hasSlot(currentModel, '_' + rowVersionColumn)) tools.setSlot(currentModel, '_' + rowVersionColumn, cur + 1);
2921
2918
  else currentModel[rowVersionColumn] = cur + 1;
2922
2919
  }
2923
2920
  }
@@ -3491,8 +3488,7 @@ class context {
3491
3488
  }
3492
3489
 
3493
3490
  _backingValue(entity, column) {
3494
- const proto = Object.getPrototypeOf(entity);
3495
- if (proto && ('_' + column) in proto) return proto['_' + column];
3491
+ if (tools.hasSlot(entity, '_' + column)) return tools.getSlot(entity, '_' + column);
3496
3492
  const v = entity[column];
3497
3493
  return typeof v === 'function' ? undefined : v;
3498
3494
  }
package/deleteManager.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // version 1.0.0 - FAANG-Level Refactored
2
+ import tools from './Tools.js';
2
3
 
3
4
  // Constants for relationship types
4
5
  const RELATIONSHIP_TYPES = {
@@ -81,9 +82,7 @@ class DeleteManager {
81
82
  if (this._isRelationshipType(propertyConfig.type)) {
82
83
  // Read the backing field directly to avoid triggering lazy-loading
83
84
  // getters, which can return Promises or error strings
84
- const relatedModel = entity.__proto__
85
- ? entity.__proto__["_" + property]
86
- : entity["_" + property];
85
+ const relatedModel = tools.getSlot(entity, "_" + property);
87
86
 
88
87
  if (relatedModel === null || relatedModel === undefined) {
89
88
  // Unloaded relationships are safe to skip — the database
@@ -159,9 +158,7 @@ class DeleteManager {
159
158
 
160
159
  if (this._isRelationshipType(propertyConfig.type)) {
161
160
  // Read backing field directly to avoid triggering lazy-loading getters
162
- const relatedModel = entity.__proto__
163
- ? entity.__proto__["_" + property]
164
- : entity["_" + property];
161
+ const relatedModel = tools.getSlot(entity, "_" + property);
165
162
 
166
163
  if (relatedModel === null || relatedModel === undefined) {
167
164
  continue;
package/insertManager.js CHANGED
@@ -564,8 +564,8 @@ class InsertManager {
564
564
  }
565
565
 
566
566
  // Fallback: check backing field on tracked model if both reads were undefined/null
567
- if (!hasValue && currentRealModel && currentRealModel.__proto__) {
568
- const backing = currentRealModel.__proto__['_' + entity];
567
+ if (!hasValue && currentRealModel) {
568
+ const backing = tools.getSlot(currentRealModel, '_' + entity);
569
569
  hasValue = (backing !== undefined && backing !== null);
570
570
  if (hasValue) {
571
571
  // normalize into both models so downstream sees it
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.22.1",
3
+ "version": "1.23.0",
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",