masterrecord 1.5.16 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/context.js CHANGED
@@ -22,6 +22,8 @@ import MySQLEngine from './mySQLEngine.js';
22
22
  import insertManager from './insertManager.js';
23
23
  import deleteManager from './deleteManager.js';
24
24
  import EntityTrackerModel from './Entity/entityTrackerModel.js';
25
+ import { ConcurrencyError } from './errors.js';
26
+ import { withRetry } from './resilience.js';
25
27
  import { globSync } from 'glob';
26
28
  import fs from 'node:fs';
27
29
  import path from 'node:path';
@@ -59,6 +61,37 @@ function findAppRoot(){
59
61
 
60
62
  const _pools = global.__MR_POOLS__ || (global.__MR_POOLS__ = new Map());
61
63
 
64
+ // ADO.NET-style connection pooling (what EF sits on top of): when a pooled
65
+ // connection's refCount reaches zero it is NOT physically closed — it is kept
66
+ // OPEN and IDLE so the next context that needs it reuses a warm connection
67
+ // (this is why EF does not reconnect on every scope/DbContext dispose). A
68
+ // background reaper physically closes connections that have been idle longer
69
+ // than the timeout, so idle connections are eventually reclaimed. Set
70
+ // MR_POOL_IDLE_MS=0 to disable retention (close immediately at refCount 0).
71
+ const _POOL_IDLE_MS = process.env.MR_POOL_IDLE_MS !== undefined && Number(process.env.MR_POOL_IDLE_MS) >= 0
72
+ ? Number(process.env.MR_POOL_IDLE_MS)
73
+ : 60_000;
74
+ let _poolReaper = global.__MR_POOL_REAPER__ || null;
75
+ function _ensurePoolReaper() {
76
+ if (_poolReaper || _POOL_IDLE_MS <= 0) return;
77
+ _poolReaper = setInterval(() => {
78
+ const now = Date.now();
79
+ for (const [key, entry] of _pools) {
80
+ if (entry && !entry.promise && entry.refCount <= 0
81
+ && entry.idleSince != null && (now - entry.idleSince) >= _POOL_IDLE_MS) {
82
+ _pools.delete(key);
83
+ try {
84
+ if (entry.engine && typeof entry.engine.close === 'function') {
85
+ Promise.resolve(entry.engine.close()).catch(() => {});
86
+ }
87
+ } catch (_) { /* best-effort */ }
88
+ }
89
+ }
90
+ }, Math.min(Math.max(_POOL_IDLE_MS, 1000), 30_000));
91
+ if (typeof _poolReaper.unref === 'function') _poolReaper.unref(); // never keep the process alive
92
+ global.__MR_POOL_REAPER__ = _poolReaper;
93
+ }
94
+
62
95
  // Registry of live context instances so saveChanges()/close() can detect entities
63
96
  // with unsaved changes that are tracked by a DIFFERENT context instance — the
64
97
  // classic "saveChanges() succeeded but nothing was written" bug: you mutate an
@@ -234,6 +267,14 @@ class context {
234
267
  // saveChanges() reads ONLY this set, so a flush is O(changes) — not O(total
235
268
  // tracked) — and an empty save is O(1), even with tens of thousands tracked.
236
269
  __dirtyEntities = new Set();
270
+ // Named global query filters (EF Core HasQueryFilter / named filters in
271
+ // EF 10): Map<tableName, Map<filterName, { expr, args }>>. Applied to every
272
+ // query on that entity unless the query calls ignoreQueryFilters().
273
+ __queryFilters = new Map();
274
+ // Context-level event listeners (EF SavingChanges/SavedChanges/
275
+ // SaveChangesFailed, ChangeTracker.Tracked/StateChanged, and a 'command'
276
+ // observer akin to IDbCommandInterceptor): Map<event, Set<fn>>.
277
+ __listeners = new Map();
237
278
  __relationshipModels = [];
238
279
  __contextSeedData = {}; // Store seed data by table name
239
280
  __contextSeedConfig = { // Seed data configuration
@@ -363,6 +404,8 @@ class context {
363
404
  );
364
405
  }
365
406
  this._ready = true;
407
+ // 'command' listeners registered before the engine was up attach now.
408
+ if (this._hasListeners('command')) this._attachCommandObserver();
366
409
  }
367
410
 
368
411
  /**
@@ -414,6 +457,12 @@ class context {
414
457
  // Create database connection with validated path
415
458
  const db = new Database(dbAddress, env);
416
459
  db.__name = sqlName;
460
+ // Enforce FOREIGN KEY constraints (off by default in SQLite, per
461
+ // connection). Without this, the FK clauses migrations now emit
462
+ // would be inert. Set MR_SQLITE_FOREIGN_KEYS=off to opt out.
463
+ if (process.env.MR_SQLITE_FOREIGN_KEYS !== 'off') {
464
+ try { db.pragma('foreign_keys = ON'); } catch (_) { /* older driver */ }
465
+ }
417
466
  this._SQLEngine = new SQLLiteEngine();
418
467
 
419
468
  return db;
@@ -835,6 +884,19 @@ class context {
835
884
  }
836
885
  const contextName = this.__name;
837
886
 
887
+ // CLI `--connection <json>` override (EF `dotnet ef ... --connection`):
888
+ // a JSON connection config (optionally keyed by context name) that
889
+ // replaces the env-file lookup for this process.
890
+ const override = process.env.MASTERRECORD_CONNECTION_OVERRIDE;
891
+ if (override) {
892
+ let o;
893
+ try { o = JSON.parse(override); }
894
+ catch (e) { throw new ConfigurationError(`--connection / MASTERRECORD_CONNECTION_OVERRIDE must be a JSON object: ${e.message}`); }
895
+ if (o && typeof o === 'object' && o[contextName] && typeof o[contextName] === 'object') o = o[contextName];
896
+ if (!o || typeof o !== 'object') throw new ConfigurationError('--connection must be a JSON object (e.g. {"type":"sqlite","connection":"./db/"}).');
897
+ rootFolderLocationOrConfig = o;
898
+ }
899
+
838
900
  // The config can be supplied two ways:
839
901
  // 1. An inline config object: this.env({ type: 'sqlite', connection: './db/' })
840
902
  // 2. A folder path to load env.<NODE_ENV>.json (keyed by context name):
@@ -1314,6 +1376,15 @@ class context {
1314
1376
  );
1315
1377
  }
1316
1378
 
1379
+ // dbset(Model, 'table') or dbset(Model, { table, extends, discriminator, value })
1380
+ // — `extends` maps the model as a DERIVED type of an already-registered
1381
+ // base (EF table-per-hierarchy).
1382
+ if (name && typeof name === 'object') {
1383
+ const opts = name;
1384
+ name = opts.table;
1385
+ if (opts.extends) return this.#dbsetDerived(model, opts);
1386
+ }
1387
+
1317
1388
  const validModel = modelBuilder.create(model);
1318
1389
  let tableName = name !== undefined ? name : model.name;
1319
1390
 
@@ -1394,12 +1465,820 @@ class context {
1394
1465
  // column's type from its parent's primary-key type. Idempotent.
1395
1466
  this.#resolveBelongsToTypes();
1396
1467
 
1397
- // Return chainable object with seed() method
1468
+ // EF 5+ skip navigations: materialize the implicit join entity for every
1469
+ // manyToMany() declaration (idempotent; no-op while synthesizing).
1470
+ this.#synthesizeJoinEntities();
1471
+
1472
+ // Return chainable object with seed() / queryFilter() methods
1473
+ const chain = {
1474
+ seed: (data) => this.#addSeedData(tableName, data),
1475
+ // EF: modelBuilder.Entity<T>().HasQueryFilter([name,] predicate)
1476
+ queryFilter: (...a) => { this.queryFilter(tableName, ...a); return chain; },
1477
+ };
1478
+ return chain;
1479
+ }
1480
+
1481
+ // ---- Table-per-hierarchy inheritance (EF Core default inheritance mapping) -
1482
+
1483
+ /**
1484
+ * `dbset(Cat, { extends: Animal })`: map a derived model onto its base's
1485
+ * table (EF TPH). The base table gains a discriminator column (default
1486
+ * name 'discriminator', values = model names, like EF) and the derived
1487
+ * model's own columns (nullable — rows of other types leave them NULL).
1488
+ * `ctx.Cat` queries the base table with the discriminator predicate
1489
+ * (always applied — it is not a query filter), inserts stamp the
1490
+ * discriminator, and rows read through `ctx.Animal` are materialized as
1491
+ * their derived type. Base-type query filters apply to derived sets.
1492
+ * Options: `discriminator` (column name), `value` (this type's value).
1493
+ */
1494
+ #dbsetDerived(model, opts) {
1495
+ const baseRef = opts.extends;
1496
+ const baseName = typeof baseRef === 'string' ? baseRef : baseRef && baseRef.name;
1497
+ const prefix = (this.tablePrefix && typeof this.tablePrefix === 'string') ? this.tablePrefix : '';
1498
+ const baseDef = this.__entities.find(e => e && (e.__name === baseName || e.__name === prefix + baseName))
1499
+ || (this.__derivedEntities || []).find(d => d.__tph && d.__tph.typeName === baseName);
1500
+ if (!baseDef) {
1501
+ throw new Error(`masterrecord: dbset(${model.name}, { extends: '${baseName}' }) — register the base entity with dbset() first (EF configures the base type before derived types).`);
1502
+ }
1503
+ const table = baseDef.__name;
1504
+ const rootDef = baseDef.__tph ? (this.__entities.find(e => e && e.__name === baseDef.__tph.base) || baseDef) : baseDef;
1505
+ const discCol = opts.discriminator || (rootDef.__tph ? rootDef.__tph.column : 'discriminator');
1506
+ if (!rootDef.__tph) {
1507
+ if (!rootDef[discCol]) {
1508
+ rootDef[discCol] = { name: discCol, type: 'string', nullable: false, unique: false, auto: false, default: rootDef.__name.startsWith(prefix) && prefix ? rootDef.__name.slice(prefix.length) : rootDef.__name,
1509
+ cascadeOnDelete: true, lazyLoading: true, isNavigational: false, skipGetFunction: false, valueConversion: true };
1510
+ }
1511
+ Object.defineProperty(rootDef, '__tph', {
1512
+ value: { column: discCol, value: baseName, typeName: baseName, base: table, isDerived: false, derived: new Map() },
1513
+ enumerable: false, configurable: true, writable: true,
1514
+ });
1515
+ } else if (opts.discriminator && opts.discriminator !== rootDef.__tph.column) {
1516
+ throw new Error(`masterrecord: hierarchy '${table}' already uses discriminator column '${rootDef.__tph.column}'.`);
1517
+ }
1518
+ const derivedRaw = modelBuilder.create(model);
1519
+ const derivedDef = {};
1520
+ for (const k of Object.keys(baseDef)) if (!k.startsWith('__')) derivedDef[k] = baseDef[k]; // inherited columns (shared objects)
1521
+ const isRel = (c) => c && typeof c === 'object' && (c.type === 'hasOne' || c.type === 'hasMany' || c.type === 'hasManyThrough' || c.relationshipType === 'belongsTo');
1522
+ for (const k of Object.keys(derivedRaw)) {
1523
+ if (k.startsWith('__')) continue;
1524
+ const col = derivedRaw[k];
1525
+ if (!col || typeof col !== 'object') continue;
1526
+ if (col.lifecycle) { derivedDef[k] = col; continue; }
1527
+ if (derivedDef[k]) continue; // inherited property: the base definition wins (EF)
1528
+ if (col.primary) throw new Error(`masterrecord: derived entity ${model.name} cannot declare its own primary key — it is inherited from ${baseName}.`);
1529
+ if (!isRel(col) && !col.virtual) col.nullable = true; // other types' rows leave it NULL
1530
+ derivedDef[k] = col;
1531
+ rootDef[k] = col; // the physical column lives in the hierarchy table (migrations)
1532
+ }
1533
+ derivedDef.__name = table;
1534
+ derivedDef.__compositeIndexes = rootDef.__compositeIndexes;
1535
+ const value = opts.value || model.name;
1536
+ Object.defineProperty(derivedDef, '__tph', {
1537
+ value: { column: rootDef.__tph.column, value, typeName: model.name, base: table, isDerived: true, derived: rootDef.__tph.derived },
1538
+ enumerable: false, configurable: true, writable: true,
1539
+ });
1540
+ rootDef.__tph.derived.set(String(value), derivedDef);
1541
+ this.__derivedEntities = this.__derivedEntities || [];
1542
+ this.__derivedEntities.push(derivedDef);
1543
+ Object.defineProperty(this, model.name, {
1544
+ get: function() { return tools.createNewInstance(derivedDef, query, this); },
1545
+ configurable: true, enumerable: true,
1546
+ });
1547
+ this.#resolveBelongsToTypes();
1548
+ const chain = {
1549
+ seed: (data) => this.#addSeedData(table, data),
1550
+ queryFilter: (...a) => { this.queryFilter(model.name, ...a); return chain; },
1551
+ };
1552
+ return chain;
1553
+ }
1554
+
1555
+ // ---- Implicit many-to-many join entities (EF Core 5+ skip navigations) ---
1556
+
1557
+ /**
1558
+ * For each `manyToMany()` navigation whose join entity is not registered,
1559
+ * synthesize it exactly as a user-written model would be: an auto PK,
1560
+ * `belongsTo()` to both sides (FK constraints, ON DELETE CASCADE) and a
1561
+ * unique composite index on the two FK columns. Registered through dbset()
1562
+ * so table prefix, validation, FK type resolution, migrations and query
1563
+ * builders all see it. Idempotent.
1564
+ */
1565
+ #synthesizeJoinEntities() {
1566
+ if (this.__synthesizingJoins) return;
1567
+ const prefix = (this.tablePrefix && typeof this.tablePrefix === 'string') ? this.tablePrefix : '';
1568
+ const registered = (name) => this.__entities.some(e => e && (e.__name === name || e.__name === prefix + name));
1569
+ for (const ent of [...this.__entities]) {
1570
+ if (!ent) continue;
1571
+ for (const key of Object.keys(ent)) {
1572
+ const def = ent[key];
1573
+ if (key.startsWith('__') || !def || typeof def !== 'object' || !def.implicitJoin) continue;
1574
+ const joinName = def.foreignTable;
1575
+ if (!joinName || registered(joinName)) continue;
1576
+ const ownerName = (prefix && ent.__name.startsWith(prefix)) ? ent.__name.slice(prefix.length) : ent.__name;
1577
+ const targetName = def.targetTable;
1578
+ const fkOwner = def.joinForeignKey;
1579
+ const fkTarget = def.joinOtherKey;
1580
+ const ownerField = fkOwner.replace(/_id$/i, '') || ownerName.toLowerCase();
1581
+ const targetField = fkTarget.replace(/_id$/i, '') || targetName.toLowerCase();
1582
+ if (ownerField === targetField) {
1583
+ throw new Error(`masterrecord: manyToMany join '${joinName}' would have two identical fields '${ownerField}'; pass distinct { foreignKey, otherKey }.`);
1584
+ }
1585
+ const Join = { [joinName]: class { id(db) { db.integer().primary().auto(); } } }[joinName];
1586
+ Object.defineProperty(Join.prototype, ownerField, { value: function(db) { db.belongsTo(ownerName, fkOwner); }, writable: true, configurable: true, enumerable: false });
1587
+ Object.defineProperty(Join.prototype, targetField, { value: function(db) { db.belongsTo(targetName, fkTarget); }, writable: true, configurable: true, enumerable: false });
1588
+ Join.compositeIndexes = [{ columns: [fkOwner, fkTarget], unique: true, name: `ux_${joinName.toLowerCase()}_${fkOwner}_${fkTarget}` }];
1589
+ this.__synthesizingJoins = true;
1590
+ try { this.dbset(Join); } finally { this.__synthesizingJoins = false; }
1591
+ const joinDef = this.__entities.find(e => e && e.__name === prefix + joinName);
1592
+ if (joinDef) Object.defineProperty(joinDef, '__implicitJoin', { value: true, enumerable: false, configurable: true });
1593
+ }
1594
+ }
1595
+ }
1596
+
1597
+ /**
1598
+ * Resolve the two sides of a hasManyThrough / manyToMany navigation:
1599
+ * the join dbset and the join entity's belongsTo fields pointing at this
1600
+ * entity and at the target.
1601
+ */
1602
+ _joinSides(ownerDef, def) {
1603
+ const joinSet = this._dbsetByName(def.foreignTable);
1604
+ if (!joinSet) throw new Error(`masterrecord: join entity '${def.foreignTable}' is not registered on this context.`);
1605
+ const joinDef = joinSet.__entity;
1606
+ const isBt = (c) => c && typeof c === 'object' && c.relationshipType === 'belongsTo';
1607
+ const entries = Object.keys(joinDef).filter(k => !k.startsWith('__') && isBt(joinDef[k])).map(k => [k, joinDef[k]]);
1608
+ const toThisEntry = def.joinForeignKey
1609
+ ? entries.find(([, c]) => c.foreignKey === def.joinForeignKey)
1610
+ : entries.find(([, c]) => c.foreignTable === ownerDef.__name);
1611
+ const toTargetEntry = def.joinOtherKey
1612
+ ? entries.find(([, c]) => c.foreignKey === def.joinOtherKey)
1613
+ : entries.find(([, c]) => c.foreignTable !== ownerDef.__name);
1614
+ if (!toThisEntry || !toTargetEntry) throw new Error(`masterrecord: join entity '${joinDef.__name}' must declare belongsTo() to both '${ownerDef.__name}' and the target entity.`);
1615
+ const targetSet = this._dbsetByName(toTargetEntry[1].foreignTable);
1616
+ if (!targetSet) throw new Error(`masterrecord: entity '${toTargetEntry[1].foreignTable}' is not registered on this context.`);
1617
+ return { joinSet, joinDef, toThisField: toThisEntry[0], toThis: toThisEntry[1], toTargetField: toTargetEntry[0], toTarget: toTargetEntry[1], targetSet };
1618
+ }
1619
+
1620
+ /**
1621
+ * EF `entry.Collection(nav).Add(item)` semantics — link `item` to `owner`
1622
+ * through a collection navigation so saveChanges() persists it:
1623
+ * - manyToMany / hasManyThrough: a join entity row is added to the tracker
1624
+ * (an untracked new target is added first, like EF's cascade insert);
1625
+ * - hasMany: the child's FK is set to the owner's key (the child is added
1626
+ * to the tracker if it is new).
1627
+ * Synchronous; nothing hits the database until saveChanges().
1628
+ */
1629
+ linkNavigation(owner, field, item) {
1630
+ if (!owner || !owner.__entity) throw new TypeError('masterrecord: linkNavigation(owner, field, item) expects a tracked owner entity.');
1631
+ const def = owner.__entity[field];
1632
+ if (!def || (def.type !== 'hasMany' && def.type !== 'hasManyThrough')) throw new Error(`masterrecord: '${field}' on ${owner.__entity.__name} is not a collection navigation.`);
1633
+ if (item === undefined || item === null) throw new TypeError('masterrecord: cannot add null/undefined to a collection navigation.');
1634
+ const ownerPkName = tools.getPrimaryKeyObject(owner.__entity) || 'id';
1635
+ const ownerKey = tools.dataValue(owner, ownerPkName);
1636
+ if (ownerKey === undefined || ownerKey === null || typeof ownerKey === 'function') {
1637
+ throw new Error(`masterrecord: ${owner.__entity.__name} has no primary key yet — save it first, or assign the collection (owner.${field} = [...]) before add().`);
1638
+ }
1639
+ if (def.type === 'hasManyThrough') {
1640
+ const { joinSet, toThisField, toTargetField, targetSet } = this._joinSides(owner.__entity, def);
1641
+ const targetPkName = tools.getPrimaryKeyObject(targetSet.__entity) || 'id';
1642
+ let targetRef = item;
1643
+ if (typeof item === 'object') {
1644
+ const pk = tools.dataValue(item, targetPkName);
1645
+ const tracked = item.__ID != null && this.__trackedEntitiesMap.has(item.__ID);
1646
+ if ((pk === undefined || pk === null || typeof pk === 'function') && !tracked) targetSet.add(item); // new target: insert first
1647
+ targetRef = item; // the join row references the entity; the engine persists its key
1648
+ }
1649
+ const row = {};
1650
+ row[toThisField] = owner;
1651
+ row[toTargetField] = targetRef;
1652
+ joinSet.add(row);
1653
+ return row;
1654
+ }
1655
+ // hasMany: set the child's FK to the owner's key; add the child if new
1656
+ const childSet = this._dbsetByName(def.foreignTable || field);
1657
+ if (!childSet) throw new Error(`masterrecord: entity '${def.foreignTable || field}' is not registered on this context.`);
1658
+ const childCol = tools.findForeignTable(owner.__entity.__name, childSet.__entity);
1659
+ const navField = childCol && childCol.name ? childCol.name : null;
1660
+ const fkCol = childCol && childCol.foreignKey ? childCol.foreignKey : `${owner.__entity.__name.toLowerCase()}_id`;
1661
+ if (typeof item !== 'object') throw new TypeError(`masterrecord: ${owner.__entity.__name}.${field}.add() expects a ${childSet.__entity.__name} entity.`);
1662
+ const tracked = item.__ID != null && this.__trackedEntitiesMap.has(item.__ID);
1663
+ if (tracked && Object.getOwnPropertyDescriptor(item, fkCol) && Object.getOwnPropertyDescriptor(item, fkCol).set) item[fkCol] = ownerKey;
1664
+ else if (navField) item[navField] = ownerKey;
1665
+ else item[fkCol] = ownerKey;
1666
+ if (!tracked) childSet.add(item);
1667
+ return item;
1668
+ }
1669
+
1670
+ /**
1671
+ * EF `entry.Collection(nav).Remove(item)`: unlink `item` from `owner`.
1672
+ * - manyToMany / hasManyThrough: the join row(s) are scheduled for DELETE;
1673
+ * - hasMany: the child's FK is set to NULL when nullable, otherwise the
1674
+ * child is scheduled for DELETE (EF deletes orphans of required relationships).
1675
+ * Resolves when the change is tracked; persisted by saveChanges().
1676
+ */
1677
+ async unlinkNavigation(owner, field, item) {
1678
+ if (!owner || !owner.__entity) throw new TypeError('masterrecord: unlinkNavigation(owner, field, item) expects a tracked owner entity.');
1679
+ const def = owner.__entity[field];
1680
+ if (!def || (def.type !== 'hasMany' && def.type !== 'hasManyThrough')) throw new Error(`masterrecord: '${field}' on ${owner.__entity.__name} is not a collection navigation.`);
1681
+ const ownerPkName = tools.getPrimaryKeyObject(owner.__entity) || 'id';
1682
+ const ownerKey = tools.dataValue(owner, ownerPkName);
1683
+ if (def.type === 'hasManyThrough') {
1684
+ const { joinSet, toThis, toTarget, targetSet } = this._joinSides(owner.__entity, def);
1685
+ const targetPkName = tools.getPrimaryKeyObject(targetSet.__entity) || 'id';
1686
+ const targetKey = (item && typeof item === 'object') ? tools.dataValue(item, targetPkName) : item;
1687
+ if (targetKey === undefined || targetKey === null) return 0;
1688
+ const rows = await joinSet.where(`r => r.${toThis.foreignKey} == $$`, ownerKey).and(`r => r.${toTarget.foreignKey} == $$`, targetKey).toList();
1689
+ for (const r of rows) joinSet.remove(r);
1690
+ return rows.length;
1691
+ }
1692
+ const childSet = this._dbsetByName(def.foreignTable || field);
1693
+ const childCol = tools.findForeignTable(owner.__entity.__name, childSet.__entity);
1694
+ const fkCol = childCol && childCol.foreignKey ? childCol.foreignKey : `${owner.__entity.__name.toLowerCase()}_id`;
1695
+ if (!item || typeof item !== 'object') return 0;
1696
+ if (childCol && childCol.nullable === true) {
1697
+ if (Object.getOwnPropertyDescriptor(item, fkCol) && Object.getOwnPropertyDescriptor(item, fkCol).set) item[fkCol] = null;
1698
+ else item[childCol.name] = null;
1699
+ } else {
1700
+ childSet.remove(item);
1701
+ }
1702
+ return 1;
1703
+ }
1704
+
1705
+ /** Give a loaded collection EF's `Add` / `Remove` (non-enumerable, JSON-safe). */
1706
+ _decorateCollection(owner, field, arr) {
1707
+ if (!Array.isArray(arr) || Object.prototype.hasOwnProperty.call(arr, 'add')) return arr;
1708
+ const ctx = this;
1709
+ Object.defineProperties(arr, {
1710
+ add: { value(item) { if (arr.includes(item)) return arr; ctx.linkNavigation(owner, field, item); if (item && typeof item === 'object') arr.push(item); return arr; }, enumerable: false, configurable: true, writable: true },
1711
+ remove: { value(item) { const i = arr.indexOf(item); if (i >= 0) arr.splice(i, 1); return ctx.unlinkNavigation(owner, field, item); }, enumerable: false, configurable: true, writable: true },
1712
+ });
1713
+ return arr;
1714
+ }
1715
+
1716
+ // ---- Global query filters (EF Core HasQueryFilter / named filters) ------
1717
+
1718
+ /**
1719
+ * Attach a global query filter to an entity. The predicate is a where-lambda
1720
+ * (same syntax as .where()) appended to EVERY query on that entity — toList,
1721
+ * single/first/last, count/exists, findById, executeUpdate/executeDelete —
1722
+ * unless the query opts out with .ignoreQueryFilters(). Typical uses: soft
1723
+ * delete and multi-tenancy.
1724
+ *
1725
+ * Filters are NAMED (EF 10): several can coexist on one entity and be
1726
+ * disabled selectively. Omit the name for a single unnamed filter.
1727
+ * Parameter args may be values OR functions; a function is called at query
1728
+ * time with the context, so e.g. a tenant id can come from the context
1729
+ * instance (EF filters referencing DbContext fields).
1730
+ *
1731
+ * @example
1732
+ * this.dbset(Blog)
1733
+ * .queryFilter('softDelete', 'b => b.deletedAt == null')
1734
+ * .queryFilter('tenant', 'b => b.tenantId == $$', (ctx) => ctx.tenantId);
1735
+ * // or: ctx.queryFilter('Blog', 'softDelete', 'b => b.deletedAt == null');
1736
+ */
1737
+ queryFilter(modelName, nameOrPredicate, predicateOrArg, ...rest) {
1738
+ let name, expr, args;
1739
+ if (typeof predicateOrArg === 'string' || typeof predicateOrArg === 'function' && typeof nameOrPredicate === 'string' && !/=>/.test(nameOrPredicate)) {
1740
+ name = String(nameOrPredicate); expr = predicateOrArg; args = rest;
1741
+ } else {
1742
+ name = '__default'; expr = nameOrPredicate; args = [predicateOrArg, ...rest].filter(a => a !== undefined);
1743
+ }
1744
+ if (typeof expr === 'function') expr = expr.toString();
1745
+ if (typeof expr !== 'string' || !/=>/.test(expr)) {
1746
+ throw new TypeError(`masterrecord: queryFilter expects a where-lambda (e.g. 'b => b.deletedAt == null'), got ${JSON.stringify(expr)}`);
1747
+ }
1748
+ if (!this.__queryFilters.has(modelName)) this.__queryFilters.set(modelName, new Map());
1749
+ this.__queryFilters.get(modelName).set(name, { expr, args });
1750
+ return this;
1751
+ }
1752
+
1753
+ /** Remove a named (or the unnamed) global query filter from an entity. */
1754
+ removeQueryFilter(modelName, name = '__default') {
1755
+ const m = this.__queryFilters.get(modelName);
1756
+ if (m) m.delete(name);
1757
+ return this;
1758
+ }
1759
+
1760
+ /** @private [{ name, expr, args }] for an entity (empty if none). */
1761
+ _queryFiltersFor(modelName) {
1762
+ const m = this.__queryFilters.get(modelName);
1763
+ if (!m || m.size === 0) return [];
1764
+ return Array.from(m, ([name, f]) => ({ name, expr: f.expr, args: f.args }));
1765
+ }
1766
+
1767
+ // ---- Events / interceptors (EF SavingChanges, SavedChanges, SaveChangesFailed,
1768
+ // ChangeTracker.Tracked / StateChanged, IDbCommandInterceptor) --------------
1769
+
1770
+ /**
1771
+ * Subscribe to a context event. Events:
1772
+ * 'savingChanges' { context, entries } — before the flush; handlers may
1773
+ * mutate entities / mark more dirty
1774
+ * (audit columns, soft-delete); async ok
1775
+ * 'savedChanges' { context, entries } — after a successful commit
1776
+ * 'saveChangesFailed' { context, entries, error } — before the error is rethrown
1777
+ * 'tracked' { context, entity } — an entity entered tracking
1778
+ * 'stateChanged' { context, entity, state } — an entity became dirty
1779
+ * 'command' { sql, params, durationMs, engine, error? } — every SQL command
1780
+ * Returns an unsubscribe function.
1781
+ */
1782
+ on(event, handler) {
1783
+ if (typeof handler !== 'function') throw new TypeError('masterrecord: on(event, handler) expects a function.');
1784
+ if (!this.__listeners.has(event)) this.__listeners.set(event, new Set());
1785
+ this.__listeners.get(event).add(handler);
1786
+ if (event === 'command') this._attachCommandObserver();
1787
+ return () => this.off(event, handler);
1788
+ }
1789
+
1790
+ /** Subscribe for a single invocation. */
1791
+ once(event, handler) {
1792
+ const off = this.on(event, (payload) => { off(); return handler(payload); });
1793
+ return off;
1794
+ }
1795
+
1796
+ /** Unsubscribe. */
1797
+ off(event, handler) {
1798
+ const set = this.__listeners.get(event);
1799
+ if (set) set.delete(handler);
1800
+ return this;
1801
+ }
1802
+
1803
+ _hasListeners(event) {
1804
+ const set = this.__listeners.get(event);
1805
+ return !!(set && set.size);
1806
+ }
1807
+
1808
+ /** Fire synchronously (tracked / stateChanged / command). Listener errors are isolated. */
1809
+ _emit(event, payload) {
1810
+ const set = this.__listeners.get(event);
1811
+ if (!set || set.size === 0) return;
1812
+ for (const fn of Array.from(set)) {
1813
+ try { fn(payload); } catch (e) { console.error(`[Context] '${event}' listener threw:`, e); }
1814
+ }
1815
+ }
1816
+
1817
+ /** Fire and await every listener in order (savingChanges / savedChanges / saveChangesFailed). */
1818
+ async _emitAsync(event, payload) {
1819
+ const set = this.__listeners.get(event);
1820
+ if (!set || set.size === 0) return;
1821
+ for (const fn of Array.from(set)) { await fn(payload); }
1822
+ }
1823
+
1824
+ /** Snapshot of a change set for event payloads: [{ entity, state }]. */
1825
+ _entriesOf(entities) {
1826
+ return entities.map(e => ({ entity: e, state: e.__state, entityName: e.__entity ? e.__entity.__name : undefined }));
1827
+ }
1828
+
1829
+ /** Forward engine command notifications to 'command' listeners. */
1830
+ _attachCommandObserver() {
1831
+ const eng = this._SQLEngine;
1832
+ if (!eng || typeof eng.addCommandObserver !== 'function') return;
1833
+ if (!this.__commandObserver) {
1834
+ this.__commandObserver = (info) => { if (this._hasListeners('command')) this._emit('command', info); };
1835
+ }
1836
+ eng.addCommandObserver(this.__commandObserver);
1837
+ }
1838
+
1839
+ // ---- Explicit / lazy loading of navigations (EF Entry(e).Reference(n).Load() /
1840
+ // Collection(n).Load()) — engine-agnostic and parameterized -------------
1841
+
1842
+ /** Resolve a dbset by model/table name, honoring tablePrefix. */
1843
+ _dbsetByName(name) {
1844
+ if (!name) return null;
1845
+ if (this[name] && this[name].__entity) return this[name];
1846
+ const prefixed = (this.tablePrefix || '') + name;
1847
+ if (prefixed !== name && this[prefixed] && this[prefixed].__entity) return this[prefixed];
1848
+ const cap = name.charAt(0).toUpperCase() + name.slice(1);
1849
+ if (cap !== name && this[cap] && this[cap].__entity) return this[cap];
1850
+ return null;
1851
+ }
1852
+
1853
+ /**
1854
+ * Load a navigation property of a tracked entity from the database and
1855
+ * cache it on the entity (EF explicit loading). Works for belongsTo,
1856
+ * hasOne, hasMany and hasManyThrough on every engine, using the normal
1857
+ * parameterized query builder. Returns the loaded value (entity, array,
1858
+ * or null).
1859
+ *
1860
+ * @example const author = await db.entry(post).load('author');
1861
+ * @example await db.loadNavigation(author, 'posts');
1862
+ */
1863
+ async loadNavigation(entity, field) {
1864
+ if (!entity || !entity.__entity) throw new TypeError('masterrecord: loadNavigation(entity, field) expects a tracked entity.');
1865
+ const def = entity.__entity[field];
1866
+ if (!def || typeof def !== 'object') throw new Error(`masterrecord: '${field}' is not a navigation of ${entity.__entity.__name}.`);
1867
+ const isRel = def.relationshipType === 'belongsTo' || def.type === 'hasOne' || def.type === 'hasMany' || def.type === 'hasManyThrough';
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];
1871
+ let value = null;
1872
+
1873
+ if (def.relationshipType === 'belongsTo') {
1874
+ const parentSet = this._dbsetByName(def.foreignTable);
1875
+ if (!parentSet) throw new Error(`masterrecord: entity '${def.foreignTable}' (referenced by ${entity.__entity.__name}.${field}) is not registered on this context.`);
1876
+ const fkVal = backing(def.foreignKey);
1877
+ if (fkVal === undefined || fkVal === null || typeof fkVal === 'function') value = null;
1878
+ else {
1879
+ const pk = tools.getPrimaryKeyObject(parentSet.__entity) || 'id';
1880
+ value = await parentSet.where(`r => r.${pk} == $$`, fkVal).single();
1881
+ }
1882
+ } else {
1883
+ const thisPk = tools.getPrimaryKeyObject(entity.__entity) || 'id';
1884
+ const pkVal = backing(thisPk);
1885
+ if (def.type === 'hasManyThrough') {
1886
+ // through (join) table -> target table, two parameterized queries
1887
+ const { joinSet, toThis, toTarget, targetSet } = this._joinSides(entity.__entity, { ...def, foreignTable: def.foreignTable || field });
1888
+ const links = (pkVal === undefined || pkVal === null) ? [] : await joinSet.asNoTracking().where(`r => r.${toThis.foreignKey} == $$`, pkVal).toList();
1889
+ const ids = links.map(l => l[toTarget.foreignKey]).filter(v => v !== undefined && v !== null);
1890
+ if (ids.length === 0) value = [];
1891
+ else {
1892
+ const targetPk = tools.getPrimaryKeyObject(targetSet.__entity) || 'id';
1893
+ value = await targetSet.where(`r => $$.includes(r.${targetPk})`, ids).toList();
1894
+ }
1895
+ this._decorateCollection(entity, field, value);
1896
+ } else {
1897
+ const childSet = this._dbsetByName(def.foreignTable || field);
1898
+ if (!childSet) throw new Error(`masterrecord: entity '${def.foreignTable || field}' (referenced by ${entity.__entity.__name}.${field}) is not registered on this context.`);
1899
+ const childCol = tools.findForeignTable(entity.__entity.__name, childSet.__entity);
1900
+ const fkCol = childCol && childCol.foreignKey ? childCol.foreignKey : (def.foreignKey || `${entity.__entity.__name.toLowerCase()}_id`);
1901
+ if (pkVal === undefined || pkVal === null) value = def.type === 'hasMany' ? [] : null;
1902
+ else {
1903
+ const q = childSet.where(`r => r.${fkCol} == $$`, pkVal);
1904
+ value = def.type === 'hasMany' ? await q.toList() : await q.single();
1905
+ }
1906
+ if (def.type === 'hasMany') this._decorateCollection(entity, field, value);
1907
+ }
1908
+ }
1909
+ if (proto) proto['_' + field] = value; else entity['_' + field] = value;
1910
+ return value;
1911
+ }
1912
+
1913
+ /**
1914
+ * EF split query: load ONE navigation for MANY parents with a single
1915
+ * batched query per table (IN on the parent keys, chunked), setting each
1916
+ * parent's navigation slot. Parents whose navigation is already loaded are
1917
+ * skipped. Returns the flat list of loaded children (the next level's parents).
1918
+ * @private
1919
+ */
1920
+ async __batchLoadNavigation(parents, nav, opts = {}) {
1921
+ // EF: IgnoreQueryFilters() on the root query applies to every included level.
1922
+ const withFilters = (set) => {
1923
+ const ig = opts.ignoredFilters;
1924
+ if (ig === true) return set.ignoreQueryFilters();
1925
+ if (ig instanceof Set) return set.ignoreQueryFilters([...ig]);
1926
+ return set;
1927
+ };
1928
+ const list = (parents || []).filter(p => p && p.__entity);
1929
+ if (!list.length) return [];
1930
+ const ownerDef = list[0].__entity;
1931
+ const def = ownerDef[nav];
1932
+ if (!def || typeof def !== 'object') throw new Error(`masterrecord: '${nav}' is not a navigation of ${ownerDef.__name}.`);
1933
+ const isBt = def.relationshipType === 'belongsTo';
1934
+ if (!isBt && def.type !== 'hasOne' && def.type !== 'hasMany' && def.type !== 'hasManyThrough') {
1935
+ throw new Error(`masterrecord: '${nav}' on ${ownerDef.__name} is a column, not a navigation.`);
1936
+ }
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; };
1939
+ const CHUNK = 500;
1940
+ const chunks = (arr) => { const out = []; for (let i = 0; i < arr.length; i += CHUNK) out.push(arr.slice(i, i + CHUNK)); return out; };
1941
+ const uniq = (arr) => [...new Set(arr.filter(v => v !== undefined && v !== null && typeof v !== 'function'))];
1942
+ const loadedOut = [];
1943
+ const pending = [];
1944
+ for (const p of list) {
1945
+ if (this.isNavigationLoaded(p, nav)) {
1946
+ const v = slotOf(p)['_' + nav];
1947
+ if (Array.isArray(v)) loadedOut.push(...v); else if (v && typeof v === 'object') loadedOut.push(v);
1948
+ } else pending.push(p);
1949
+ }
1950
+ if (!pending.length) return loadedOut;
1951
+
1952
+ if (isBt) {
1953
+ const parentSet = this._dbsetByName(def.foreignTable);
1954
+ if (!parentSet) throw new Error(`masterrecord: entity '${def.foreignTable}' (referenced by ${ownerDef.__name}.${nav}) is not registered on this context.`);
1955
+ const pk = tools.getPrimaryKeyObject(parentSet.__entity) || 'id';
1956
+ const keys = uniq(pending.map(p => tools.foreignKeyValue(p, nav)));
1957
+ const byKey = new Map();
1958
+ 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);
1959
+ for (const p of pending) {
1960
+ const k = tools.foreignKeyValue(p, nav);
1961
+ const t = (k === undefined || k === null) ? null : (byKey.get(String(k)) || null);
1962
+ setSlot(p, t);
1963
+ if (t) loadedOut.push(t);
1964
+ }
1965
+ return loadedOut;
1966
+ }
1967
+
1968
+ const thisPk = tools.getPrimaryKeyObject(ownerDef) || 'id';
1969
+ const parentKeys = uniq(pending.map(p => tools.dataValue(p, thisPk)));
1970
+ if (def.type === 'hasManyThrough') {
1971
+ const { joinSet, toThis, toTarget, targetSet } = this._joinSides(ownerDef, { ...def, foreignTable: def.foreignTable || nav });
1972
+ const links = [];
1973
+ for (const c of chunks(parentKeys)) links.push(...await withFilters(joinSet.asNoTracking()).where(`r => $$.includes(r.${toThis.foreignKey})`, c).toList());
1974
+ const targetPk = tools.getPrimaryKeyObject(targetSet.__entity) || 'id';
1975
+ const targetIds = uniq(links.map(l => l[toTarget.foreignKey]));
1976
+ const byId = new Map();
1977
+ for (const c of chunks(targetIds)) for (const t of await withFilters(targetSet).where(`r => $$.includes(r.${targetPk})`, c).toList()) byId.set(String(tools.dataValue(t, targetPk)), t);
1978
+ const grouped = new Map();
1979
+ for (const l of links) {
1980
+ const t = byId.get(String(l[toTarget.foreignKey]));
1981
+ if (!t) continue;
1982
+ const k = String(l[toThis.foreignKey]);
1983
+ if (!grouped.has(k)) grouped.set(k, []);
1984
+ grouped.get(k).push(t);
1985
+ }
1986
+ for (const p of pending) {
1987
+ const arr = grouped.get(String(tools.dataValue(p, thisPk))) || [];
1988
+ this._decorateCollection(p, nav, arr);
1989
+ setSlot(p, arr);
1990
+ loadedOut.push(...arr);
1991
+ }
1992
+ return loadedOut;
1993
+ }
1994
+
1995
+ // hasOne / hasMany
1996
+ const childSet = this._dbsetByName(def.foreignTable || nav);
1997
+ if (!childSet) throw new Error(`masterrecord: entity '${def.foreignTable || nav}' (referenced by ${ownerDef.__name}.${nav}) is not registered on this context.`);
1998
+ const childCol = tools.findForeignTable(ownerDef.__name, childSet.__entity);
1999
+ const fkCol = childCol && childCol.foreignKey ? childCol.foreignKey : (def.foreignKey || `${ownerDef.__name.toLowerCase()}_id`);
2000
+ const children = [];
2001
+ for (const c of chunks(parentKeys)) children.push(...await withFilters(childSet).where(`r => $$.includes(r.${fkCol})`, c).toList());
2002
+ const grouped = new Map();
2003
+ for (const ch of children) {
2004
+ const fk = tools.dataValue(ch, fkCol);
2005
+ const k = String(fk !== undefined ? fk : ch[fkCol]);
2006
+ if (!grouped.has(k)) grouped.set(k, []);
2007
+ grouped.get(k).push(ch);
2008
+ }
2009
+ for (const p of pending) {
2010
+ const arr = grouped.get(String(tools.dataValue(p, thisPk))) || [];
2011
+ if (def.type === 'hasMany') { this._decorateCollection(p, nav, arr); setSlot(p, arr); loadedOut.push(...arr); }
2012
+ else { const one = arr[0] || null; setSlot(p, one); if (one) loadedOut.push(one); }
2013
+ }
2014
+ return loadedOut;
2015
+ }
2016
+
2017
+ /** Has this navigation been loaded (by include() or loadNavigation())? */
2018
+ isNavigationLoaded(entity, field) {
2019
+ const proto = Object.getPrototypeOf(entity);
2020
+ const v = proto ? proto['_' + field] : undefined;
2021
+ // null counts as loaded (EF: the reference was loaded and there is no related row)
2022
+ return v !== undefined && !(v && typeof v.then === 'function');
2023
+ }
2024
+
2025
+ // ---- Health check (EF Database.CanConnect / ASP.NET DbContext health check) -
2026
+
2027
+ /**
2028
+ * Probe the database connection: `{ healthy, engine, latencyMs, ... }` on
2029
+ * success, `{ healthy: false, engine, error }` on failure — never throws.
2030
+ * Same shape on SQLite, MySQL and Postgres (engine-specific extras such as
2031
+ * pool counters / server version are added when available).
2032
+ */
2033
+ async healthCheck() {
2034
+ const engine = this.isSQLite ? 'sqlite' : this.isMySQL ? 'mysql' : this.isPostgres ? 'postgres' : 'unknown';
2035
+ const started = Date.now();
2036
+ try {
2037
+ await this._ensureReady();
2038
+ const eng = this._SQLEngine;
2039
+ if (!eng || typeof eng.healthCheck !== 'function') return { healthy: false, engine, error: 'engine not initialized' };
2040
+ const res = await eng.healthCheck();
2041
+ return { engine, latencyMs: Date.now() - started, ...res };
2042
+ } catch (err) {
2043
+ return { healthy: false, engine, latencyMs: Date.now() - started, error: err && err.message ? err.message : String(err) };
2044
+ }
2045
+ }
2046
+
2047
+ /** EF `Database.CanConnect()`: true when a round-trip to the database succeeds. */
2048
+ async canConnect() {
2049
+ const res = await this.healthCheck();
2050
+ return res.healthy === true;
2051
+ }
2052
+
2053
+ // ---- Context-level Add / Remove (EF DbContext.Add / Remove) ----------------
2054
+
2055
+ /** Resolve the dbset (query builder) that owns an entity instance. */
2056
+ _dbsetFor(entity) {
2057
+ if (!entity || typeof entity !== 'object') throw new TypeError('masterrecord: expected an entity instance.');
2058
+ let name = entity.__entity && entity.__entity.__name;
2059
+ if (!name && entity.constructor && entity.constructor.name) {
2060
+ const byCtor = this.__entities.find(e => e && (e.__name === entity.constructor.name || e.__name === this.tablePrefix + entity.constructor.name));
2061
+ if (byCtor) name = byCtor.__name;
2062
+ }
2063
+ if (!name || !this.__entities.some(e => e && e.__name === name)) {
2064
+ throw new Error(`masterrecord: cannot determine which registered entity this instance belongs to (${entity.constructor && entity.constructor.name}). Register it with dbset() first.`);
2065
+ }
2066
+ return this[name];
2067
+ }
2068
+
2069
+ /** EF `context.Add(entity)`: schedule an INSERT (same as ctx.<Model>.add(entity)). */
2070
+ add(entity) { this._dbsetFor(entity).add(entity); return entity; }
2071
+
2072
+ /** EF `context.Remove(entity)`: schedule a DELETE (same as ctx.<Model>.remove(entity)). */
2073
+ remove(entity) { this._dbsetFor(entity).remove(entity); return entity; }
2074
+
2075
+ /** EF `context.AddRange(...)` / `RemoveRange(...)`. */
2076
+ addRange(entities) { for (const e of entities || []) this.add(e); return entities; }
2077
+ removeRange(entities) { for (const e of entities || []) this.remove(e); return entities; }
2078
+
2079
+ // ---- Entity entries / change-tracker introspection (EF DbContext.Entry,
2080
+ // ChangeTracker.Entries, ChangeTracker.HasChanges) --------------------
2081
+
2082
+ /** Scalar (non-navigation) column names of an entity, as stored in the DB. */
2083
+ _scalarColumns(entity) {
2084
+ const def = entity && entity.__entity;
2085
+ const out = [];
2086
+ if (!def) return out;
2087
+ for (const key of Object.keys(def)) {
2088
+ const f = def[key];
2089
+ // skip entity metadata (__name, __compositeIndexes, __foreignKeys, …) and navigations
2090
+ if (key.startsWith('__') || !f || typeof f !== 'object' || Array.isArray(f)) continue;
2091
+ if (f.type === 'hasOne' || f.type === 'hasMany' || f.type === 'hasManyThrough') continue;
2092
+ out.push((f.relationshipType === 'belongsTo' && f.foreignKey) ? f.foreignKey : (f.name || key));
2093
+ }
2094
+ return out;
2095
+ }
2096
+
2097
+ /**
2098
+ * Entity FIELD keys the ORM may write (what `__dirtyFields` holds): excludes
2099
+ * metadata, navigations, virtual and computed (DB-generated) columns and,
2100
+ * with `{ includePrimary: false }`, the primary key. belongsTo fields are
2101
+ * returned by their field key (the engines map it to the FK column).
2102
+ */
2103
+ _scalarFields(entity, { includePrimary = false } = {}) {
2104
+ const def = entity && entity.__entity;
2105
+ const out = [];
2106
+ if (!def) return out;
2107
+ for (const key of Object.keys(def)) {
2108
+ const f = def[key];
2109
+ if (key.startsWith('__') || !f || typeof f !== 'object' || Array.isArray(f)) continue;
2110
+ if (f.type === 'hasOne' || f.type === 'hasMany' || f.type === 'hasManyThrough') continue;
2111
+ if (f.virtual === true || f.computedSql) continue;
2112
+ if (!includePrimary && f.primary === true) continue;
2113
+ out.push(key);
2114
+ }
2115
+ return out;
2116
+ }
2117
+
2118
+ /**
2119
+ * EF Core's `context.Entry(entity)`: inspect and control one entity's
2120
+ * tracking state.
2121
+ * entry.state 'track' (unchanged) | 'modified' | 'insert' | 'delete' | 'detached'; settable
2122
+ * entry.originalValues values as loaded / last saved (used by concurrency checks)
2123
+ * entry.currentValues current stored values
2124
+ * entry.isModified(field?) whether a field (or the entity) has pending changes
2125
+ * entry.reload() overwrite with database values (resets originals)
2126
+ * entry.getDatabaseValues() fetch the row's current DB values without touching the entity (null if gone)
2127
+ * entry.detach() stop tracking
2128
+ */
2129
+ entry(entity) {
2130
+ if (!entity || !entity.__entity) throw new TypeError('masterrecord: entry(entity) expects an entity created by this ORM.');
2131
+ const ctx = this;
2132
+ const allowed = ['track', 'modified', 'insert', 'delete', 'detached'];
2133
+ return {
2134
+ entity,
2135
+ get entityName() { return entity.__entity.__name; },
2136
+ get state() {
2137
+ return ctx.__trackedEntitiesMap.has(entity.__ID) ? (entity.__state || 'track') : 'detached';
2138
+ },
2139
+ set state(s) {
2140
+ if (!allowed.includes(s)) throw new Error(`masterrecord: entry.state must be one of ${allowed.join(', ')}`);
2141
+ if (s === 'detached') { ctx.__untrack([entity]); return; }
2142
+ entity.__context = ctx;
2143
+ entity.__state = s;
2144
+ if (s === 'track') {
2145
+ entity.__dirtyFields = [];
2146
+ ctx.__dirtyEntities.delete(entity);
2147
+ ctx.__track(entity);
2148
+ } else {
2149
+ if (s === 'modified' && (!entity.__dirtyFields || entity.__dirtyFields.length === 0)) {
2150
+ // Like EF's Update(): mark every writable column modified
2151
+ // (not the PK, navigations, virtual or computed columns).
2152
+ entity.__dirtyFields = ctx._scalarFields(entity);
2153
+ }
2154
+ ctx.__markDirty(entity);
2155
+ }
2156
+ },
2157
+ get originalValues() { return { ...(entity.__originalValues || {}) }; },
2158
+ get currentValues() {
2159
+ const o = {};
2160
+ for (const c of ctx._scalarColumns(entity)) o[c] = ctx._backingValue(entity, c);
2161
+ return o;
2162
+ },
2163
+ isModified(field) {
2164
+ if (field === undefined) return !!(entity.__state && entity.__state !== 'track');
2165
+ return !!(entity.__dirtyFields && entity.__dirtyFields.includes(field));
2166
+ },
2167
+ reload() {
2168
+ if (typeof entity.reload !== 'function') return Promise.reject(new Error('masterrecord: this entity cannot be reloaded (no primary key / not query-built).'));
2169
+ return entity.reload();
2170
+ },
2171
+ async getDatabaseValues() {
2172
+ const keys = tools.primaryKeys(entity.__entity);
2173
+ if (!keys.length) return null;
2174
+ let q = ctx[entity.__entity.__name].asNoTracking().ignoreQueryFilters();
2175
+ for (let i = 0; i < keys.length; i++) {
2176
+ const v = tools.dataValue(entity, keys[i]);
2177
+ if (v === undefined || v === null) return null;
2178
+ q = i === 0 ? q.where(`r => r.${keys[i]} == $$`, v) : q.and(`r => r.${keys[i]} == $$`, v);
2179
+ }
2180
+ const fresh = await q.single();
2181
+ if (!fresh) return null;
2182
+ const o = {};
2183
+ for (const c of ctx._scalarColumns(entity)) o[c] = ctx._backingValue(fresh, c);
2184
+ return o;
2185
+ },
2186
+ detach() { ctx.__untrack([entity]); },
2187
+ /** EF Reference(nav).Load() / Collection(nav).Load(): explicit loading. */
2188
+ load(nav) { return ctx.loadNavigation(entity, nav); },
2189
+ isLoaded(nav) { return ctx.isNavigationLoaded(entity, nav); },
2190
+ /** EF `Entry(e).Collection(nav)`: Load / IsLoaded / Add / Remove. */
2191
+ collection(nav) {
2192
+ return {
2193
+ load: () => ctx.loadNavigation(entity, nav),
2194
+ get isLoaded() { return ctx.isNavigationLoaded(entity, nav); },
2195
+ add: (item) => ctx.linkNavigation(entity, nav, item),
2196
+ remove: (item) => ctx.unlinkNavigation(entity, nav, item),
2197
+ };
2198
+ },
2199
+ /** EF `Entry(e).Reference(nav)`: Load / IsLoaded. */
2200
+ reference(nav) {
2201
+ return {
2202
+ load: () => ctx.loadNavigation(entity, nav),
2203
+ get isLoaded() { return ctx.isNavigationLoaded(entity, nav); },
2204
+ };
2205
+ },
2206
+ };
2207
+ }
2208
+
2209
+ /** EF `ChangeTracker.HasChanges()`: are there pending inserts/updates/deletes? */
2210
+ hasChanges() {
2211
+ for (const e of this.__dirtyEntities) {
2212
+ if (e && e.__state && e.__state !== 'track') return true;
2213
+ }
2214
+ return false;
2215
+ }
2216
+
2217
+ /** EF `ChangeTracker.Entries([T])`: entries for all tracked entities (optionally one entity type). */
2218
+ entries(modelName) {
2219
+ const out = [];
2220
+ for (const e of this.__trackedEntitiesMap.values()) {
2221
+ if (!e || !e.__entity) continue;
2222
+ if (modelName && e.__entity.__name !== modelName) continue;
2223
+ out.push(this.entry(e));
2224
+ }
2225
+ return out;
2226
+ }
2227
+
2228
+ // ---- Connection resiliency (EF EnableRetryOnFailure / execution strategy) ----
2229
+
2230
+ /** Process-wide default retry policy (see setRetryOnFailure). `false` disables. */
2231
+ static configureRetry(options) {
2232
+ context._defaultRetry = context._normalizeRetry(options);
2233
+ return context._defaultRetry;
2234
+ }
2235
+
2236
+ static _normalizeRetry(options) {
2237
+ if (options === false || options === null || options === undefined) return null;
2238
+ const o = (options === true) ? {} : options;
1398
2239
  return {
1399
- seed: (data) => this.#addSeedData(tableName, data)
2240
+ maxRetries: Number.isInteger(o.maxRetries) && o.maxRetries >= 0 ? o.maxRetries : 3,
2241
+ maxDelayMs: Number(o.maxDelayMs) > 0 ? Number(o.maxDelayMs) : 2000,
2242
+ baseDelayMs: Number(o.baseDelayMs) > 0 ? Number(o.baseDelayMs) : 50,
2243
+ onRetry: typeof o.onRetry === 'function' ? o.onRetry : null,
1400
2244
  };
1401
2245
  }
1402
2246
 
2247
+ /**
2248
+ * Retry this context's operations on TRANSIENT database errors (deadlock,
2249
+ * lock timeout, dropped connection, busy SQLite) with capped exponential
2250
+ * backoff — EF Core's EnableRetryOnFailure. Applies to queries,
2251
+ * saveChanges() and executeUpdate/executeDelete. Like EF, nothing is
2252
+ * retried inside an explicit transaction (re-run the whole transaction).
2253
+ * Non-transient errors (constraints, syntax, ConcurrencyError) are never
2254
+ * retried. A 'retry' event { attempt, maxRetries, delayMs, error } fires
2255
+ * before each wait. Pass `false` to disable (also overrides a global default).
2256
+ *
2257
+ * @example db.setRetryOnFailure({ maxRetries: 5, maxDelayMs: 3000 });
2258
+ */
2259
+ setRetryOnFailure(options = {}) {
2260
+ this.__retry = context._normalizeRetry(options);
2261
+ return this;
2262
+ }
2263
+
2264
+ _engineName() {
2265
+ return this.isSQLite ? 'sqlite' : this.isMySQL ? 'mysql' : this.isPostgres ? 'postgres' : undefined;
2266
+ }
2267
+
2268
+ /** Run `fn` under the active retry policy (none -> once; in a user transaction -> once). */
2269
+ _execWithRetry(fn) {
2270
+ const cfg = (this.__retry !== undefined) ? this.__retry : context._defaultRetry;
2271
+ if (!cfg || this.__userTx) return fn();
2272
+ return withRetry(fn, {
2273
+ ...cfg,
2274
+ engine: this._engineName(),
2275
+ onRetry: (info) => {
2276
+ this._emit('retry', { context: this, ...info });
2277
+ if (cfg.onRetry) cfg.onRetry(info);
2278
+ },
2279
+ });
2280
+ }
2281
+
1403
2282
  // Walk every registered entity. For each column with relationshipType ===
1404
2283
  // 'belongsTo', look up the parent entity by foreignTable name and copy the
1405
2284
  // parent's primary-key type onto the FK column. Without this, FKs to a
@@ -1993,58 +2872,53 @@ class context {
1993
2872
  }
1994
2873
  }
1995
2874
 
1996
- if (entities.length === 1) {
1997
- // Single update - use existing logic.
1998
- // NOTE: the second argument must be `__entity` (double underscore).
1999
- // The previous code used `_entity` which is undefined, so
2000
- // `removePrimarykeyandVirtual` received `undefined` and stripped
2001
- // nothing — a latent bug that left primary-key/virtual fields in
2002
- // the UPDATE SET clause if they ever landed in __dirtyFields.
2003
- const currentModel = entities[0];
2875
+ // Each entity gets its own UPDATE (the engines' "bulk" update was a
2876
+ // per-row loop anyway) so that every statement can carry that row's
2877
+ // concurrency tokens and be checked for rows-affected individually —
2878
+ // EF's unit-of-work semantics: a concurrently modified/deleted row
2879
+ // affects 0 rows and raises ConcurrencyError, rolling the batch back.
2880
+ //
2881
+ // NOTE: the second argument to removePrimarykeyandVirtual must be
2882
+ // `__entity` (double underscore); `_entity` is undefined and would
2883
+ // strip nothing, leaving PK/virtual fields in the SET clause.
2884
+ for (const currentModel of entities) {
2885
+ const rowVersionColumn = this._rowVersionColumn(currentModel);
2886
+ // The ORM owns the rowVersion column (bumped atomically below). If the
2887
+ // app wrote to it, drop it from the SET so it is never assigned twice.
2888
+ if (rowVersionColumn && Array.isArray(currentModel.__dirtyFields)) {
2889
+ currentModel.__dirtyFields = currentModel.__dirtyFields.filter(f => f !== rowVersionColumn);
2890
+ }
2004
2891
  const cleanCurrentModel = tools.removePrimarykeyandVirtual(currentModel, currentModel.__entity);
2005
2892
  const argu = this._SQLEngine._buildSQLEqualToParameterized(cleanCurrentModel);
2006
2893
 
2007
- if (argu !== -1) {
2008
- const primaryKey = tools.getPrimaryKeyObject(cleanCurrentModel.__entity);
2009
- const sqlUpdate = {
2010
- tableName: cleanCurrentModel.__entity.__name,
2011
- arg: argu,
2012
- primaryKey: primaryKey,
2013
- primaryKeyValue: cleanCurrentModel[primaryKey]
2014
- };
2015
- await this._SQLEngine.update(sqlUpdate);
2016
- } else {
2894
+ if (argu === -1) {
2017
2895
  console.warn('[Context] Entity marked for update but no changes detected');
2018
- }
2019
- } else {
2020
- // Batch update - build all queries first
2021
- const updateQueries = [];
2022
-
2023
- for (const currentModel of entities) {
2024
- const cleanCurrentModel = tools.removePrimarykeyandVirtual(currentModel, currentModel.__entity);
2025
- const argu = this._SQLEngine._buildSQLEqualToParameterized(cleanCurrentModel);
2026
-
2027
- if (argu !== -1) {
2028
- const primaryKey = tools.getPrimaryKeyObject(cleanCurrentModel.__entity);
2029
- updateQueries.push({
2030
- tableName: cleanCurrentModel.__entity.__name,
2031
- arg: argu,
2032
- primaryKey: primaryKey,
2033
- primaryKeyValue: cleanCurrentModel[primaryKey]
2034
- });
2035
- }
2896
+ continue;
2036
2897
  }
2037
2898
 
2038
- if (updateQueries.length > 0) {
2039
- await this._bulkWithFallback('Bulk update',
2040
- async () => { await this._SQLEngine.bulkUpdate(updateQueries); },
2041
- async () => {
2042
- // Fallback to individual updates
2043
- for (const query of updateQueries) {
2044
- await this._SQLEngine.update(query);
2045
- }
2046
- }
2047
- );
2899
+ const primaryKey = tools.getPrimaryKeyObject(cleanCurrentModel.__entity);
2900
+ const sqlUpdate = {
2901
+ tableName: cleanCurrentModel.__entity.__name,
2902
+ arg: argu,
2903
+ primaryKey: primaryKey,
2904
+ primaryKeyValue: cleanCurrentModel[primaryKey],
2905
+ // Optimistic concurrency: ORIGINAL token values into the WHERE,
2906
+ // and the rowVersion column bumped atomically in the SET.
2907
+ // (+ the remaining columns of a composite key — EF HasKey(a, b))
2908
+ concurrency: [...this._concurrencyClause(currentModel), ...this._compositeKeyClause(currentModel)],
2909
+ rowVersionColumn,
2910
+ };
2911
+ const result = await this._SQLEngine.update(sqlUpdate);
2912
+ this._assertAffected(result, currentModel, 'update');
2913
+
2914
+ // Mirror the atomic `version = version + 1` onto the in-memory
2915
+ // entity so its value matches the row and the next save's WHERE
2916
+ // uses the new version.
2917
+ if (rowVersionColumn) {
2918
+ const proto = Object.getPrototypeOf(currentModel);
2919
+ const cur = Number(this._backingValue(currentModel, rowVersionColumn) || 0);
2920
+ if (proto && ('_' + rowVersionColumn) in proto) proto['_' + rowVersionColumn] = cur + 1;
2921
+ else currentModel[rowVersionColumn] = cur + 1;
2048
2922
  }
2049
2923
  }
2050
2924
 
@@ -2099,16 +2973,45 @@ class context {
2099
2973
  deletesByTable.get(groupKey).ids.push(id);
2100
2974
  }
2101
2975
 
2976
+ // Entities with concurrency tokens need a per-row DELETE so each
2977
+ // can carry its own token WHERE + rows-affected check; the rest go
2978
+ // through the set-based WHERE IN with a total-rows-affected check.
2979
+ // (composite-key entities too: a WHERE IN on one column cannot address them)
2980
+ const tokenEntities = entities.filter(e => this._concurrencyTokenColumns(e).length > 0 || tools.isCompositeKey(e.__entity));
2981
+ const tokenSet = new Set(tokenEntities);
2982
+ for (const entity of tokenEntities) {
2983
+ const deleteObject = new deleteManager(this._SQLEngine, this.__entities);
2984
+ await deleteObject.init(entity); // deleteManager asserts rows-affected
2985
+ }
2986
+ for (const [key, group] of deletesByTable) {
2987
+ group.ids = entities
2988
+ .filter(e => !tokenSet.has(e) && `${e.__entity.__name}::${tools.getPrimaryKeyObject(e.__entity)}` === key)
2989
+ .map(e => e[tools.getPrimaryKeyObject(e.__entity)]);
2990
+ if (group.ids.length === 0) deletesByTable.delete(key);
2991
+ }
2992
+
2102
2993
  await this._bulkWithFallback('Bulk delete',
2103
2994
  async () => {
2104
- // Performance: Use for...of with Map entries
2105
2995
  for (const { tableName, primaryKey, ids } of deletesByTable.values()) {
2106
- await this._SQLEngine.bulkDelete(tableName, ids, primaryKey);
2996
+ const result = await this._SQLEngine.bulkDelete(tableName, ids, primaryKey);
2997
+ const eng = this._SQLEngine;
2998
+ const affected = (eng && typeof eng.affectedRows === 'function') ? eng.affectedRows(result) : ids.length;
2999
+ if (affected !== ids.length) {
3000
+ // Some rows were already gone: EF treats this as a
3001
+ // concurrency conflict (expected N, affected M).
3002
+ const missing = entities.filter(e => !tokenSet.has(e) && e.__entity.__name === tableName);
3003
+ throw new ConcurrencyError(
3004
+ `Bulk delete of ${tableName} expected to affect ${ids.length} row(s) but affected ${affected}. ` +
3005
+ `One or more rows were modified or deleted by another operation since they were loaded.`,
3006
+ missing, { entity: tableName, expected: ids.length, affected, verb: 'delete' }
3007
+ );
3008
+ }
2107
3009
  }
2108
3010
  },
2109
3011
  async () => {
2110
- // Fallback to individual deletes
3012
+ // Fallback to individual deletes (each asserts rows-affected)
2111
3013
  for (const entity of entities) {
3014
+ if (tokenSet.has(entity)) continue;
2112
3015
  const deleteObject = new deleteManager(this._SQLEngine, this.__entities);
2113
3016
  await deleteObject.init(entity);
2114
3017
  }
@@ -2168,15 +3071,172 @@ class context {
2168
3071
  // `this._SQLEngine` is the shared lock host; before init (the very first
2169
3072
  // save) it falls back to the instance, which is fine — there is nothing
2170
3073
  // concurrent to serialize against yet.
3074
+ // If THIS context currently holds the engine lock (we're inside
3075
+ // ctx.transaction(fn) or between beginTransaction()/commit()), run the
3076
+ // flush directly — re-entering the mutex would deadlock. The flush uses
3077
+ // a SAVEPOINT in that case (see _saveChangesExclusive).
3078
+ if (this.__engineLockDepth > 0) {
3079
+ return this._saveChangesExclusive();
3080
+ }
3081
+ // Retry policy (EF EnableRetryOnFailure) wraps the whole unit of work:
3082
+ // a failed attempt rolled back and left entities dirty, so re-running
3083
+ // the flush is safe.
3084
+ return this._withEngineLock(() => this._execWithRetry(() => this._saveChangesExclusive()));
3085
+ }
3086
+
3087
+ /**
3088
+ * Async mutex on the engine (the object that owns the transaction client):
3089
+ * serializes units of work that share a connection. Replaces the old
3090
+ * promise-chain queue with an explicit acquire/release so a user
3091
+ * transaction can HOLD the lock across multiple awaits (begin ... commit).
3092
+ */
3093
+ _withEngineLock(fn) {
2171
3094
  const lockHost = this._SQLEngine || this;
2172
- const run = () => this._saveChangesExclusive();
2173
3095
  const prev = lockHost.__saveQueue || Promise.resolve();
2174
- const next = prev.then(run, run);
2175
- // The queue itself must swallow rejections or one failed save would
2176
- // poison every save after it; callers still see their own rejection
2177
- // through `next`.
2178
- lockHost.__saveQueue = next.catch(() => {});
2179
- return next;
3096
+ let release;
3097
+ const held = new Promise(resolve => { release = resolve; });
3098
+ // The queue never rejects: one failed unit of work must not poison the
3099
+ // ones after it. Callers still see their own rejection via `run`.
3100
+ lockHost.__saveQueue = prev.then(() => held, () => held);
3101
+ const run = prev.then(
3102
+ async () => { try { return await fn(); } finally { release(); } },
3103
+ async () => { try { return await fn(); } finally { release(); } }
3104
+ );
3105
+ return run;
3106
+ }
3107
+
3108
+ // ---- Explicit transactions (EF Core: Database.BeginTransaction / savepoints) ----
3109
+
3110
+ /**
3111
+ * Begin a user-controlled transaction spanning multiple saveChanges() and
3112
+ * raw queries. Holds the engine lock until commit()/rollback() so no other
3113
+ * unit of work on the shared connection can interleave. saveChanges()
3114
+ * calls made while the transaction is open run inside it (each protected
3115
+ * by a SAVEPOINT, like EF) and do NOT commit by themselves.
3116
+ *
3117
+ * @example
3118
+ * await db.beginTransaction();
3119
+ * try {
3120
+ * db.User.add(u); await db.saveChanges();
3121
+ * db.Audit.add(a); await db.saveChanges();
3122
+ * await db.commit();
3123
+ * } catch (e) { await db.rollback(); throw e; }
3124
+ */
3125
+ async beginTransaction() {
3126
+ if (this.__userTx) {
3127
+ throw new Error('masterrecord: a transaction is already open on this context (nested transactions are not supported — use createSavepoint()).');
3128
+ }
3129
+ // Only await readiness if the engine isn't up yet; otherwise acquire the
3130
+ // lock SYNCHRONOUSLY below so a save issued right after this call (but
3131
+ // before the transaction began) cannot slip in ahead of it.
3132
+ if (!this._SQLEngine) await this._ensureReady();
3133
+ // Acquire the engine lock and keep it until commit/rollback.
3134
+ let acquired;
3135
+ const gate = new Promise(resolve => { acquired = resolve; });
3136
+ let releaseLock;
3137
+ const holding = new Promise(resolve => { releaseLock = resolve; });
3138
+ this._withEngineLock(() => { acquired(); return holding; }).catch(() => {});
3139
+ await gate;
3140
+ this.__engineLockDepth = (this.__engineLockDepth || 0) + 1;
3141
+ try {
3142
+ await this._SQLEngine.startTransaction();
3143
+ } catch (e) {
3144
+ this.__engineLockDepth--;
3145
+ releaseLock();
3146
+ throw e;
3147
+ }
3148
+ this.__userTx = { releaseLock, savepoints: 0 };
3149
+ return this;
3150
+ }
3151
+
3152
+ /** Commit the transaction opened by beginTransaction(). */
3153
+ async commit() {
3154
+ if (!this.__userTx) throw new Error('masterrecord: commit() called with no open transaction.');
3155
+ const tx = this.__userTx;
3156
+ try {
3157
+ await this._SQLEngine.endTransaction();
3158
+ } finally {
3159
+ this.__userTx = null;
3160
+ this.__engineLockDepth--;
3161
+ tx.releaseLock();
3162
+ }
3163
+ return this;
3164
+ }
3165
+
3166
+ /** Roll back the transaction opened by beginTransaction(). */
3167
+ async rollback() {
3168
+ if (!this.__userTx) throw new Error('masterrecord: rollback() called with no open transaction.');
3169
+ const tx = this.__userTx;
3170
+ try {
3171
+ await this._SQLEngine.errorTransaction();
3172
+ } finally {
3173
+ this.__userTx = null;
3174
+ this.__engineLockDepth--;
3175
+ tx.releaseLock();
3176
+ }
3177
+ return this;
3178
+ }
3179
+
3180
+ /** Aliases matching common ORM naming. */
3181
+ commitTransaction() { return this.commit(); }
3182
+ rollbackTransaction() { return this.rollback(); }
3183
+
3184
+ /** True while a user transaction (beginTransaction/transaction(fn)) is open. */
3185
+ get inTransaction() { return !!this.__userTx; }
3186
+
3187
+ /**
3188
+ * Run `fn(ctx)` inside a transaction: begin, run, commit — or roll back if
3189
+ * `fn` throws (the error is rethrown). The recommended form.
3190
+ *
3191
+ * @example
3192
+ * await db.transaction(async (tx) => {
3193
+ * tx.Account.add(a); await tx.saveChanges();
3194
+ * await tx.execute('UPDATE ...');
3195
+ * });
3196
+ */
3197
+ async transaction(fn) {
3198
+ if (typeof fn !== 'function') throw new TypeError('masterrecord: transaction(fn) expects a function.');
3199
+ await this.beginTransaction();
3200
+ try {
3201
+ const result = await fn(this);
3202
+ await this.commit();
3203
+ return result;
3204
+ } catch (error) {
3205
+ if (this.__userTx) { try { await this.rollback(); } catch (_) { /* keep original error */ } }
3206
+ throw error;
3207
+ }
3208
+ }
3209
+
3210
+ /** Create a named savepoint inside the open transaction (EF CreateSavepoint). */
3211
+ async createSavepoint(name) {
3212
+ const sp = this._savepointName(name); // validate first (fail fast)
3213
+ if (!this.__userTx) throw new Error('masterrecord: createSavepoint() requires an open transaction.');
3214
+ await this._SQLEngine.savepoint(sp);
3215
+ return this;
3216
+ }
3217
+
3218
+ /** Roll back to a named savepoint, keeping the transaction open (EF RollbackToSavepoint). */
3219
+ async rollbackToSavepoint(name) {
3220
+ const sp = this._savepointName(name);
3221
+ if (!this.__userTx) throw new Error('masterrecord: rollbackToSavepoint() requires an open transaction.');
3222
+ await this._SQLEngine.rollbackToSavepoint(sp);
3223
+ return this;
3224
+ }
3225
+
3226
+ /** Release a named savepoint (EF ReleaseSavepoint). */
3227
+ async releaseSavepoint(name) {
3228
+ const sp = this._savepointName(name);
3229
+ if (!this.__userTx) throw new Error('masterrecord: releaseSavepoint() requires an open transaction.');
3230
+ await this._SQLEngine.releaseSavepoint(sp);
3231
+ return this;
3232
+ }
3233
+
3234
+ /** Savepoint names are identifiers, never user input in SQL: validate strictly. */
3235
+ _savepointName(name) {
3236
+ if (typeof name !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(name)) {
3237
+ throw new Error(`masterrecord: invalid savepoint name ${JSON.stringify(name)} (letters, digits, underscore; must not start with a digit).`);
3238
+ }
3239
+ return `mr_usp_${name}`;
2180
3240
  }
2181
3241
 
2182
3242
  async _saveChangesExclusive() {
@@ -2205,17 +3265,35 @@ class context {
2205
3265
  // O(total tracked). A read-heavy context can track tens of thousands of
2206
3266
  // clean rows; none of them are scanned here. (Self-heals if a clean
2207
3267
  // entity ever lingers in the index.)
2208
- const changeSet = [];
2209
- for (const e of this.__dirtyEntities) {
2210
- if (e && e.__state && e.__state !== 'track') changeSet.push(e);
2211
- else this.__dirtyEntities.delete(e);
2212
- }
3268
+ // EF DetectChanges for owned/complex (JSON) properties: nested mutations
3269
+ // don't go through a column setter, so compare serialized values first.
3270
+ this._detectOwnedChanges();
3271
+
3272
+ const collectChangeSet = () => {
3273
+ const cs = [];
3274
+ for (const e of this.__dirtyEntities) {
3275
+ if (e && e.__state && e.__state !== 'track') cs.push(e);
3276
+ else this.__dirtyEntities.delete(e);
3277
+ }
3278
+ return cs;
3279
+ };
3280
+ let changeSet = collectChangeSet();
2213
3281
 
2214
3282
  if (changeSet.length === 0) {
2215
3283
  // Nothing dirty — O(1) no-op; do NOT touch the tracked set.
2216
3284
  return true;
2217
3285
  }
2218
3286
 
3287
+ // EF SavingChanges: handlers run BEFORE the flush and may mutate entities
3288
+ // (audit columns), mark more entities dirty, or convert a delete into a
3289
+ // soft-delete update. Re-collect the change set afterwards so those
3290
+ // changes are included in this save.
3291
+ if (this._hasListeners('savingChanges')) {
3292
+ await this._emitAsync('savingChanges', { context: this, entries: this._entriesOf(changeSet) });
3293
+ changeSet = collectChangeSet();
3294
+ if (changeSet.length === 0) return true;
3295
+ }
3296
+
2219
3297
  // Snapshot the committed unit of work: for each entity in the change set,
2220
3298
  // capture the exact pending change we are about to flush — its mutation
2221
3299
  // GENERATION (version) and whether it was a delete. All post-commit
@@ -2236,14 +3314,31 @@ class context {
2236
3314
  // Atomicity: wrap the change set in a single transaction so a partial
2237
3315
  // failure rolls it back.
2238
3316
  if (this.isSQLite || this.isMySQL || this.isPostgres) {
2239
- await this._SQLEngine.startTransaction();
2240
- try {
2241
- await this._processTrackedEntities(changeSet);
2242
- this.__clearErrorHandler();
2243
- await this._SQLEngine.endTransaction();
2244
- } catch (error) {
2245
- await this._SQLEngine.errorTransaction();
2246
- throw error;
3317
+ if (this.__userTx) {
3318
+ // Inside a user transaction (beginTransaction/transaction(fn)):
3319
+ // do NOT begin/commit our own. Protect this flush with a
3320
+ // SAVEPOINT so a failure rolls back only this save and
3321
+ // leaves the outer transaction usable (EF semantics).
3322
+ const sp = `mr_save_${++this.__userTx.savepoints}`;
3323
+ await this._SQLEngine.savepoint(sp);
3324
+ try {
3325
+ await this._processTrackedEntities(changeSet);
3326
+ this.__clearErrorHandler();
3327
+ await this._SQLEngine.releaseSavepoint(sp);
3328
+ } catch (error) {
3329
+ try { await this._SQLEngine.rollbackToSavepoint(sp); } catch (_) { /* outer tx may be aborted */ }
3330
+ throw error;
3331
+ }
3332
+ } else {
3333
+ await this._SQLEngine.startTransaction();
3334
+ try {
3335
+ await this._processTrackedEntities(changeSet);
3336
+ this.__clearErrorHandler();
3337
+ await this._SQLEngine.endTransaction();
3338
+ } catch (error) {
3339
+ await this._SQLEngine.errorTransaction();
3340
+ throw error;
3341
+ }
2247
3342
  }
2248
3343
  }
2249
3344
 
@@ -2252,6 +3347,9 @@ class context {
2252
3347
  }
2253
3348
 
2254
3349
  this._reconcileFlushed(captured);
3350
+ if (this._hasListeners('savedChanges')) {
3351
+ await this._emitAsync('savedChanges', { context: this, entries: this._entriesOf(changeSet) });
3352
+ }
2255
3353
  return true;
2256
3354
  } catch (error) {
2257
3355
  this.__clearErrorHandler();
@@ -2259,6 +3357,10 @@ class context {
2259
3357
  // change set tracked and dirty so a retry can persist it — never
2260
3358
  // silently drop a pending write (the caller sees the rejection).
2261
3359
  console.error('[Context] Failed to save changes:', error);
3360
+ if (this._hasListeners('saveChangesFailed')) {
3361
+ try { await this._emitAsync('saveChangesFailed', { context: this, entries: this._entriesOf(changeSet), error }); }
3362
+ catch (e) { console.error("[Context] 'saveChangesFailed' listener threw:", e); }
3363
+ }
2262
3364
  throw error;
2263
3365
  }
2264
3366
  }
@@ -2292,12 +3394,152 @@ class context {
2292
3394
  if (!wasDelete) {
2293
3395
  entity.__state = 'track';
2294
3396
  entity.__dirtyFields = [];
3397
+ // What was just written IS the database state now: refresh the
3398
+ // original-value snapshot (EF does the same after SaveChanges),
3399
+ // so the next concurrency check compares against these values.
3400
+ this._refreshOriginalValues(entity);
2295
3401
  }
2296
3402
  detach.push(entity);
2297
3403
  }
2298
3404
  this.__untrack(detach);
2299
3405
  }
2300
3406
 
3407
+ // ---- Optimistic concurrency helpers (EF Core concurrency tokens) ---------
3408
+
3409
+ /** Column names on `entity` flagged as concurrency tokens (incl. rowVersion). */
3410
+ _concurrencyTokenColumns(entity) {
3411
+ const def = entity && entity.__entity;
3412
+ if (!def) return [];
3413
+ const cols = [];
3414
+ for (const key of Object.keys(def)) {
3415
+ const f = def[key];
3416
+ if (f && typeof f === 'object' && f.concurrencyToken === true && !f.__relationship) {
3417
+ cols.push(f.relationshipType === 'belongsTo' && f.foreignKey ? f.foreignKey : (f.name || key));
3418
+ }
3419
+ }
3420
+ return cols;
3421
+ }
3422
+
3423
+ /** The single ORM-managed rowVersion column on `entity`, or null. */
3424
+ _rowVersionColumn(entity) {
3425
+ const def = entity && entity.__entity;
3426
+ if (!def) return null;
3427
+ for (const key of Object.keys(def)) {
3428
+ const f = def[key];
3429
+ if (f && typeof f === 'object' && f.rowVersion === true) return f.name || key;
3430
+ }
3431
+ return null;
3432
+ }
3433
+
3434
+ /**
3435
+ * The concurrency WHERE additions for `entity`: each token column paired
3436
+ * with its ORIGINAL (as-loaded / as-last-saved) value. For a concurrency
3437
+ * token the application changed, the ORIGINAL still goes in the WHERE and
3438
+ * the new value in the SET — exactly EF's semantics.
3439
+ */
3440
+ _concurrencyClause(entity) {
3441
+ const cols = this._concurrencyTokenColumns(entity);
3442
+ if (cols.length === 0) return [];
3443
+ const originals = entity.__originalValues || {};
3444
+ return cols.map(column => ({
3445
+ column,
3446
+ value: Object.prototype.hasOwnProperty.call(originals, column)
3447
+ ? originals[column]
3448
+ : this._backingValue(entity, column),
3449
+ }));
3450
+ }
3451
+
3452
+ /** Raw stored (DB-side) value of a column on a tracked entity. */
3453
+ /**
3454
+ * EF DetectChanges for owned / complex properties (`db.owned(Class)`, JSON
3455
+ * columns): a nested mutation (`user.address.city = 'Paris'`) never touches
3456
+ * the column accessor, so before each save the serialized current value is
3457
+ * compared with the loaded one and the field is marked modified when it
3458
+ * differs. Pending inserts write everything anyway and are skipped.
3459
+ */
3460
+ _detectOwnedChanges() {
3461
+ const asJson = (v) => (v === undefined || v === null) ? null : (typeof v === 'string' ? v : JSON.stringify(v));
3462
+ for (const e of this.__trackedEntitiesMap.values()) {
3463
+ if (!e || !e.__entity || e.__noTracking || e.__state === 'insert' || e.__state === 'delete') continue;
3464
+ const def = e.__entity;
3465
+ for (const k of Object.keys(def)) {
3466
+ const f = def[k];
3467
+ if (k.startsWith('__') || !f || typeof f !== 'object' || !f.owned) continue;
3468
+ if (Array.isArray(e.__dirtyFields) && e.__dirtyFields.includes(k)) continue;
3469
+ const originals = e.__originalValues;
3470
+ if (!originals || !(k in originals)) continue;
3471
+ const cur = tools.dataValue(e, k);
3472
+ if (asJson(cur) !== asJson(originals[k])) e[k] = cur; // tracked setter → dirty + enqueued
3473
+ }
3474
+ }
3475
+ }
3476
+
3477
+ /**
3478
+ * Composite keys (EF HasKey(a, b)): the first key column is addressed as the
3479
+ * primary key; the remaining key columns are added to the UPDATE/DELETE
3480
+ * WHERE exactly like concurrency tokens ({ column, value }).
3481
+ */
3482
+ _compositeKeyClause(entity) {
3483
+ const def = entity && entity.__entity;
3484
+ const keys = tools.primaryKeys(def);
3485
+ if (keys.length < 2) return [];
3486
+ return keys.slice(1).map(k => {
3487
+ const f = def[k];
3488
+ const column = (f.relationshipType === 'belongsTo' && f.foreignKey) ? f.foreignKey : (f.name || k);
3489
+ return { column, value: tools.dataValue(entity, k) };
3490
+ });
3491
+ }
3492
+
3493
+ _backingValue(entity, column) {
3494
+ const proto = Object.getPrototypeOf(entity);
3495
+ if (proto && ('_' + column) in proto) return proto['_' + column];
3496
+ const v = entity[column];
3497
+ return typeof v === 'function' ? undefined : v;
3498
+ }
3499
+
3500
+ /** Re-snapshot original values from the entity's current stored values. */
3501
+ _refreshOriginalValues(entity) {
3502
+ const def = entity && entity.__entity;
3503
+ if (!def) return;
3504
+ const originals = {};
3505
+ for (const key of Object.keys(def)) {
3506
+ const f = def[key];
3507
+ if (!f || typeof f !== 'object') continue;
3508
+ if (f.type === 'hasOne' || f.type === 'hasMany' || f.type === 'hasManyThrough') continue;
3509
+ const column = (f.relationshipType === 'belongsTo' && f.foreignKey) ? f.foreignKey : (f.name || key);
3510
+ originals[column] = this._backingValue(entity, column);
3511
+ }
3512
+ Object.defineProperty(entity, '__originalValues', {
3513
+ value: originals, enumerable: false, writable: true, configurable: true,
3514
+ });
3515
+ }
3516
+
3517
+ /**
3518
+ * Rows-affected guard shared by UPDATE and DELETE: EF throws
3519
+ * DbUpdateConcurrencyException whenever a statement expected to affect one
3520
+ * row affected zero — the row was concurrently modified (token mismatch) or
3521
+ * deleted. The enclosing transaction is rolled back by saveChanges().
3522
+ */
3523
+ _assertAffected(result, entity, verb) {
3524
+ const eng = this._SQLEngine;
3525
+ const affected = (eng && typeof eng.affectedRows === 'function') ? eng.affectedRows(result) : 1;
3526
+ if (affected === 0) {
3527
+ const name = entity && entity.__entity ? entity.__entity.__name : 'entity';
3528
+ const pk = entity && entity.__entity ? tools.getPrimaryKeyObject(entity.__entity) : null;
3529
+ const id = pk ? entity[pk] : undefined;
3530
+ const tokens = this._concurrencyTokenColumns(entity);
3531
+ throw new ConcurrencyError(
3532
+ `The ${verb} of ${name}${id !== undefined ? '#' + id : ''} was expected to affect 1 row but affected 0. ` +
3533
+ `The row was modified or deleted by another operation since it was loaded` +
3534
+ (tokens.length ? ` (concurrency token${tokens.length > 1 ? 's' : ''}: ${tokens.join(', ')})` : '') +
3535
+ `. Reload the entity and retry, or resolve the conflict.`,
3536
+ [entity],
3537
+ { entity: name, primaryKey: pk, id, verb, tokens }
3538
+ );
3539
+ }
3540
+ return affected;
3541
+ }
3542
+
2301
3543
  /**
2302
3544
  * Remove an exact set of entities from change tracking (identity map +
2303
3545
  * tracked list). The caller curates the set — saveChanges passes only the
@@ -2519,28 +3761,27 @@ class context {
2519
3761
  throw new Error(`Entity ${entityName} not found in context`);
2520
3762
  }
2521
3763
 
2522
- // Fetch all entities by ID
2523
3764
  const ids = updates.map(u => u.id).filter(id => id !== undefined);
2524
3765
  if (ids.length !== updates.length) {
2525
3766
  throw new Error('All update objects must have an id property');
2526
3767
  }
2527
3768
 
2528
- // Load entities and apply updates
2529
- for (const update of updates) {
2530
- const entity = await EntityClass.findById(update.id);
2531
- if (!entity) {
2532
- throw new Error(`${entityName} with id ${update.id} not found`);
2533
- }
2534
-
2535
- // Apply updates to entity
2536
- for (const key in update) {
2537
- if (Object.prototype.hasOwnProperty.call(update, key) && key !== 'id') {
2538
- entity[key] = update[key];
3769
+ // Set-based: one UPDATE per item by primary key, all in one transaction,
3770
+ // with NO per-row SELECT and no change-tracker round trip (this used to
3771
+ // findById each row then saveChanges — N SELECTs + tracking). Each
3772
+ // UPDATE's rows-affected is checked so a missing id still fails loudly.
3773
+ const pk = tools.getPrimaryKeyObject(EntityClass.__entity) || 'id';
3774
+ await this.transaction(async () => {
3775
+ for (const update of updates) {
3776
+ const changes = {};
3777
+ for (const key in update) {
3778
+ if (Object.prototype.hasOwnProperty.call(update, key) && key !== 'id') changes[key] = update[key];
2539
3779
  }
3780
+ if (Object.keys(changes).length === 0) continue;
3781
+ const affected = await this[entityName].where(`r => r.${pk} == $$`, update.id).executeUpdate(changes);
3782
+ if (affected === 0) throw new Error(`${entityName} with id ${update.id} not found`);
2540
3783
  }
2541
- }
2542
-
2543
- await this.saveChanges();
3784
+ });
2544
3785
  return true;
2545
3786
  }
2546
3787
 
@@ -2567,15 +3808,19 @@ class context {
2567
3808
  throw new Error(`Entity ${entityName} not found in context`);
2568
3809
  }
2569
3810
 
2570
- // Load entities and mark for deletion
2571
- for (const id of ids) {
2572
- const entity = await EntityClass.findById(id);
2573
- if (entity) {
2574
- await entity.delete();
2575
- }
2576
- }
2577
-
2578
- return true;
3811
+ // Set-based: ONE `DELETE ... WHERE pk IN (...)` (this used to findById
3812
+ // + entity.delete() per id — N SELECTs and N transactions, despite the
3813
+ // docstring). Bypasses the change tracker like EF's ExecuteDelete.
3814
+ await this._ensureReady();
3815
+ const tableName = EntityClass.__entity.__name;
3816
+ const pk = tools.getPrimaryKeyObject(EntityClass.__entity) || 'id';
3817
+ const run = async () => {
3818
+ const result = await this._SQLEngine.bulkDelete(tableName, ids, pk);
3819
+ this._queryCache.invalidateTable(tableName);
3820
+ return (typeof this._SQLEngine.affectedRows === 'function') ? this._SQLEngine.affectedRows(result) : ids.length;
3821
+ };
3822
+ const affected = (this.__engineLockDepth > 0) ? await run() : await this._withEngineLock(run);
3823
+ return affected;
2579
3824
  }
2580
3825
 
2581
3826
  /**
@@ -2660,11 +3905,27 @@ class context {
2660
3905
  if (entry.engine === this._SQLEngine) {
2661
3906
  entry.refCount--;
2662
3907
  if (entry.refCount <= 0) {
2663
- _pools.delete(key);
2664
- if (this._SQLEngine && typeof this._SQLEngine.close === 'function') {
2665
- await this._SQLEngine.close();
3908
+ // ADO.NET-style: do NOT close the physical connection now.
3909
+ // Keep it OPEN and idle so the next context reuses a warm
3910
+ // connection (as EF does — a scoped DbContext dispose returns
3911
+ // its connection to the pool, it is not disconnected). The
3912
+ // reaper closes it only after it has been idle past the
3913
+ // timeout. (MR_POOL_IDLE_MS=0 disables retention -> close now.)
3914
+ entry.refCount = 0;
3915
+ if (_POOL_IDLE_MS <= 0) {
3916
+ _pools.delete(key);
3917
+ if (this._SQLEngine && typeof this._SQLEngine.close === 'function') {
3918
+ await this._SQLEngine.close();
3919
+ }
3920
+ } else {
3921
+ entry.idleSince = Date.now();
3922
+ _ensurePoolReaper();
2666
3923
  }
2667
3924
  }
3925
+ // Stop forwarding this (shared) engine's commands to a closed context.
3926
+ if (this.__commandObserver && typeof this._SQLEngine.removeCommandObserver === 'function') {
3927
+ this._SQLEngine.removeCommandObserver(this.__commandObserver);
3928
+ }
2668
3929
  this._SQLEngine = null;
2669
3930
  this.db = null;
2670
3931
  return;
@@ -2713,6 +3974,12 @@ class context {
2713
3974
  }
2714
3975
  }
2715
3976
  _pools.clear();
3977
+ // Stop the idle-connection reaper (nothing left to reap).
3978
+ if (_poolReaper) {
3979
+ clearInterval(_poolReaper);
3980
+ _poolReaper = null;
3981
+ global.__MR_POOL_REAPER__ = null;
3982
+ }
2716
3983
  }
2717
3984
 
2718
3985
  /**
@@ -2920,7 +4187,9 @@ class context {
2920
4187
  // Idempotent: keyed by the unique __ID, so re-tracking the same object is
2921
4188
  // a no-op and distinct objects never collide. Map is the sole registry;
2922
4189
  // the list view derives from it, so they cannot desynchronise.
4190
+ const wasTracked = this.__trackedEntitiesMap.has(model.__ID);
2923
4191
  this.__trackedEntitiesMap.set(model.__ID, model);
4192
+ if (!wasTracked) this._emit('tracked', { context: this, entity: model });
2924
4193
  // Robustness: if the entity being tracked is ALREADY dirty, enqueue it in
2925
4194
  // the dirty index too. This guarantees the index is complete no matter
2926
4195
  // how an entity gets tracked (setter, add/remove, or a direct __track
@@ -2944,8 +4213,12 @@ class context {
2944
4213
  */
2945
4214
  __markDirty(model) {
2946
4215
  if (!model || model.__noTracking) return model;
4216
+ // Capture BEFORE __track(): __track itself enqueues an already-dirty
4217
+ // entity into the dirty index, which would mask the transition here.
4218
+ const wasDirty = this.__dirtyEntities.has(model);
2947
4219
  this.__track(model);
2948
4220
  this.__dirtyEntities.add(model);
4221
+ if (!wasDirty) this._emit('stateChanged', { context: this, entity: model, state: model.__state });
2949
4222
  return model;
2950
4223
  }
2951
4224
 
@@ -3128,6 +4401,7 @@ export {
3128
4401
  ConfigurationError,
3129
4402
  DatabaseConnectionError,
3130
4403
  EntityValidationError,
4404
+ ConcurrencyError,
3131
4405
  _poolKey
3132
4406
  };
3133
4407
  export default context;