masterrecord 1.32.2 → 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.
Files changed (3) hide show
  1. package/CHANGES.md +14 -0
  2. package/context.js +68 -69
  3. package/package.json +2 -2
package/CHANGES.md CHANGED
@@ -1,5 +1,19 @@
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
+
3
17
  ## v1.32.2 — re-reads return current data again
4
18
 
5
19
  **Fix: since 1.32.0 a tracked re-read could answer with an old row.** 1.32.0 returned the
package/context.js CHANGED
@@ -1544,13 +1544,13 @@ class context {
1544
1544
  });
1545
1545
 
1546
1546
  // belongsTo() hardcodes type='integer' before the parent entity is known.
1547
- // Now that another entity is registered, re-resolve every belongsTo FK
1548
- // column's type from its parent's primary-key type. Idempotent.
1549
- 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);
1550
1550
 
1551
1551
  // EF 5+ skip navigations: materialize the implicit join entity for every
1552
- // manyToMany() declaration (idempotent; no-op while synthesizing).
1553
- this.#synthesizeJoinEntities();
1552
+ // manyToMany() this entity declares (idempotent; no-op while synthesizing).
1553
+ this.#synthesizeJoinEntities(validModel);
1554
1554
 
1555
1555
  // Return chainable object with seed() / queryFilter() methods
1556
1556
  const chain = {
@@ -1627,7 +1627,9 @@ class context {
1627
1627
  get: function() { return tools.createNewInstance(derivedDef, query, this); },
1628
1628
  configurable: true, enumerable: true,
1629
1629
  });
1630
- this.#resolveBelongsToTypes();
1630
+ // The derived type's columns live on the root now.
1631
+ this.#resolveBelongsToTypes(rootDef);
1632
+ this.#synthesizeJoinEntities(rootDef);
1631
1633
  const chain = {
1632
1634
  seed: (data) => this.#addSeedData(table, data),
1633
1635
  queryFilter: (...a) => { this.queryFilter(model.name, ...a); return chain; },
@@ -1638,42 +1640,39 @@ class context {
1638
1640
  // ---- Implicit many-to-many join entities (EF Core 5+ skip navigations) ---
1639
1641
 
1640
1642
  /**
1641
- * For each `manyToMany()` navigation whose join entity is not registered,
1643
+ * For each `manyToMany()` navigation of `entity` whose join entity is not registered,
1642
1644
  * synthesize it exactly as a user-written model would be: an auto PK,
1643
1645
  * `belongsTo()` to both sides (FK constraints, ON DELETE CASCADE) and a
1644
1646
  * unique composite index on the two FK columns. Registered through dbset()
1645
1647
  * so table prefix, validation, FK type resolution, migrations and query
1646
1648
  * builders all see it. Idempotent.
1647
1649
  */
1648
- #synthesizeJoinEntities() {
1650
+ #synthesizeJoinEntities(ent) {
1649
1651
  if (this.__synthesizingJoins) return;
1650
1652
  const prefix = (this.tablePrefix && typeof this.tablePrefix === 'string') ? this.tablePrefix : '';
1651
1653
  const registered = (name) => this.__entities.some(e => e && (e.__name === name || e.__name === prefix + name));
1652
- for (const ent of [...this.__entities]) {
1653
- if (!ent) continue;
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 }.`);
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 });
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 }.`);
1676
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 });
1677
1676
  }
1678
1677
  }
1679
1678
 
@@ -2395,47 +2394,47 @@ class context {
2395
2394
  });
2396
2395
  }
2397
2396
 
2398
- // Walk every registered entity. For each column with relationshipType ===
2399
- // 'belongsTo', look up the parent entity by foreignTable name and copy the
2400
- // parent's primary-key type onto the FK column. Without this, FKs to a
2401
- // string/uuid/bigint PK end up declared INTEGER, which SQLite tolerates
2402
- // (dynamic typing) but Postgres and MySQL reject.
2403
- #resolveBelongsToTypes() {
2404
- const entities = this.__entities;
2405
- if (!entities || entities.length === 0) return;
2406
-
2407
- // 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
2408
2408
  // db.belongsTo('run') while the class is `Run`.
2409
- const byName = {};
2410
- for (const e of entities) {
2411
- if (e && e.__name) {
2412
- 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;
2413
2415
  }
2414
- }
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
+ };
2415
2422
 
2416
- for (const entity of entities) {
2417
- for (const key of Object.keys(entity)) {
2418
- const col = entity[key];
2419
- if (!col || typeof col !== 'object') continue;
2420
- if (col.relationshipType !== 'belongsTo') continue;
2421
- if (!col.foreignTable) continue;
2422
-
2423
- const parent = byName[String(col.foreignTable).toLowerCase()];
2424
- if (!parent) continue;
2425
-
2426
- // Find the parent's primary-key column.
2427
- for (const pKey of Object.keys(parent)) {
2428
- const pCol = parent[pKey];
2429
- if (!pCol || typeof pCol !== 'object') continue;
2430
- if (pCol.primary === true && pCol.type) {
2431
- if (col.type !== pCol.type) {
2432
- col.type = pCol.type;
2433
- }
2434
- break;
2435
- }
2436
- }
2437
- }
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));
2438
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));
2439
2438
  }
2440
2439
 
2441
2440
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.32.2",
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
  },