masterrecord 1.3.3 → 1.5.5

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/Tools.js CHANGED
@@ -212,6 +212,82 @@ class Tools{
212
212
  num = num === 'true' ? true : (num === 'false' ? false : num);
213
213
  return num ? 1 : 0;
214
214
  }
215
+
216
+ // ---------------------------------------------------------------------
217
+ // Security helpers shared by every SQL engine (SQLite / MySQL / Postgres)
218
+ // ---------------------------------------------------------------------
219
+
220
+ // The complete set of comparison operators the query builders are allowed
221
+ // to emit into a WHERE/AND clause. `func` is derived from parsing the
222
+ // lambda source (queryScript's OPERATORS_REGEX already restricts it), but
223
+ // we re-assert the whitelist at the SQL boundary so a hand-built query
224
+ // string or a future parser change can never emit an arbitrary operator
225
+ // (which would allow SQL to be smuggled in after the column name).
226
+ static SAFE_SQL_OPERATORS = new Set([
227
+ '=', '!=', '<>', '<', '>', '<=', '>=',
228
+ 'is', 'is not', 'in', 'like', 'not like'
229
+ ]);
230
+
231
+ // Validate an operator against the whitelist. Returns the operator
232
+ // unchanged (case/whitespace-normalized) or throws. Comparison is
233
+ // case-insensitive so engines that upper-case (`IS`, `IN`) still pass.
234
+ static assertSafeOperator(func){
235
+ if(typeof func !== 'string'){
236
+ throw new Error(`Unsupported SQL operator: ${JSON.stringify(func)}`);
237
+ }
238
+ const normalized = func.trim().replace(/\s+/g, ' ').toLowerCase();
239
+ if(!Tools.SAFE_SQL_OPERATORS.has(normalized)){
240
+ throw new Error(`Unsupported SQL operator: '${func}'. Allowed: ${[...Tools.SAFE_SQL_OPERATORS].join(', ')}`);
241
+ }
242
+ return func;
243
+ }
244
+
245
+ // Detect a "table/relation does not exist" error across all three engines
246
+ // and extract the table name. Returns the name, or null if `err` is not a
247
+ // missing-table error. Signatures:
248
+ // - Postgres (42P01) : relation "x" does not exist
249
+ // - MySQL (ER_NO_SUCH_TABLE) : Table 'db.tbl' doesn't exist
250
+ // - SQLite (better-sqlite3) : no such table: tbl
251
+ static missingTableName(err){
252
+ if(!err) return null;
253
+ const msg = String(err.message || err);
254
+ let m = /relation "([^"]+)" does not exist/i.exec(msg);
255
+ if(m) return m[1];
256
+ m = /Table '(?:[^.']*\.)?([^']+)' doesn't exist/i.exec(msg);
257
+ if(m) return m[1];
258
+ m = /no such table:?\s*([A-Za-z0-9_]+)/i.exec(msg);
259
+ if(m) return m[1];
260
+ return null;
261
+ }
262
+
263
+ // Turn a missing-table driver error into a loud, actionable masterrecord
264
+ // error, or null if `err` isn't one. This is what stops schema drift from
265
+ // accumulating silently: a query against a not-yet-migrated table fails
266
+ // with a clear message on EVERY engine instead of quietly returning null
267
+ // (which made SQLite dev "just work" while MySQL/Postgres broke later).
268
+ static missingTableError(err){
269
+ const name = Tools.missingTableName(err);
270
+ if(!name) return null;
271
+ const friendly = new Error(
272
+ `masterrecord: table '${name}' does not exist. If this is a new entity, ` +
273
+ `generate and run a migration first ` +
274
+ `(npx masterrecord add-migration <name> <context> && npx masterrecord update-database <context>). ` +
275
+ `Original error: ${err.message || err}`
276
+ );
277
+ friendly.cause = err;
278
+ friendly.missingTable = name;
279
+ return friendly;
280
+ }
281
+
282
+ // Escape a value for safe interpolation inside a single-quoted SQL string
283
+ // literal. Doubling the single quote is the ANSI-standard escape and is
284
+ // correct on SQLite, MySQL, and Postgres (with standard_conforming_strings,
285
+ // the default). Runtime user values should still go through `$$`/`$`
286
+ // parameter binding; this protects the literal path (inline lambda
287
+ // constants, string-built queries) as defense-in-depth.
288
+ static escapeSqlLiteral(value){
289
+ return String(value).replace(/'/g, "''");
290
+ }
215
291
  }
216
292
 
217
293
  export default Tools;
package/context.js CHANGED
@@ -21,11 +21,11 @@ import SQLLiteEngine from './SQLLiteEngine.js';
21
21
  import MySQLEngine from './mySQLEngine.js';
22
22
  import insertManager from './insertManager.js';
23
23
  import deleteManager from './deleteManager.js';
24
+ import EntityTrackerModel from './Entity/entityTrackerModel.js';
24
25
  import { globSync } from 'glob';
25
26
  import fs from 'node:fs';
26
27
  import path from 'node:path';
27
28
  import { fileURLToPath } from 'node:url';
28
- import appRoot from 'app-root-path';
29
29
  import Database from 'better-sqlite3';
30
30
  import MySQLAsyncClient from './mySQLConnect.js';
31
31
  import PostgresClient from './postgresSyncConnect.js';
@@ -35,17 +35,70 @@ import DependencyGraph from './Migrations/dependencyGraph.js';
35
35
  const __filename = fileURLToPath(import.meta.url);
36
36
  const __dirname = path.dirname(__filename);
37
37
 
38
+ // Resolve the consuming application's root directory (replaces the former
39
+ // `app-root-path` dependency). If masterrecord is installed under node_modules,
40
+ // the app root is the directory containing that node_modules; otherwise walk up
41
+ // from the current working directory to the nearest package.json, falling back
42
+ // to cwd. Used to locate the app's config/environments/*.json files.
43
+ function findAppRoot(){
44
+ const marker = `${path.sep}node_modules${path.sep}`;
45
+ const idx = __dirname.lastIndexOf(marker);
46
+ if(idx !== -1){ return __dirname.slice(0, idx); }
47
+ let dir = process.cwd();
48
+ while(true){
49
+ if(fs.existsSync(path.join(dir, 'package.json'))){ return dir; }
50
+ const parent = path.dirname(dir);
51
+ if(parent === dir){ return process.cwd(); }
52
+ dir = parent;
53
+ }
54
+ }
55
+
38
56
  // ============================================================================
39
57
  // GLOBAL POOL REGISTRY - One pool per database, shared across all contexts
40
58
  // ============================================================================
41
59
 
42
60
  const _pools = global.__MR_POOLS__ || (global.__MR_POOLS__ = new Map());
43
61
 
62
+ // Registry of live context instances so saveChanges()/close() can detect entities
63
+ // with unsaved changes that are tracked by a DIFFERENT context instance — the
64
+ // classic "saveChanges() succeeded but nothing was written" bug: you mutate an
65
+ // entity loaded by context A, then call saveChanges() on context B (a different
66
+ // instance), and B silently writes nothing because A owns the change tracking.
67
+ //
68
+ // Leak-safe: the Set holds WeakRefs (never strong references to a context), and a
69
+ // FinalizationRegistry prunes a context's WeakRef once the context is GC'd. Live
70
+ // contexts are also removed explicitly on close().
71
+ const _liveContexts = global.__MR_LIVE_CONTEXTS__ || (global.__MR_LIVE_CONTEXTS__ = new Set());
72
+ const _liveContextFinalizer = global.__MR_LIVE_CTX_FIN__ || (global.__MR_LIVE_CTX_FIN__ =
73
+ new FinalizationRegistry((ref) => { _liveContexts.delete(ref); }));
74
+
44
75
  function _poolKey(type, cfg) {
45
76
  if (type === 'sqlite') return `sqlite:${cfg.completeConnection || cfg.connection}`;
46
77
  const host = cfg.host || 'localhost';
47
78
  const port = cfg.port || (type === 'mysql' ? 3306 : 5432);
48
- return `${type}:${cfg.user}@${host}:${port}/${cfg.database}`;
79
+ let key = `${type}:${cfg.user}@${host}:${port}/${cfg.database}`;
80
+ // Postgres: the schema / search_path is a PER-CONNECTION setting. Two contexts
81
+ // on the SAME database but DIFFERENT schemas must NOT share a pooled connection
82
+ // — otherwise the second context reuses the first's connection (whose
83
+ // search_path was already set) and its CREATE TABLE / queries land in the
84
+ // WRONG schema. This was the update-database-all cross-context bug that created
85
+ // tables in the wrong schemas. Fold the resolved search_path into the key so
86
+ // different-schema contexts get their own pool (same-schema contexts still
87
+ // share one). MySQL needs nothing here — its "database" IS the schema and is
88
+ // already in the key. (`schema` and an equivalent `searchPath` resolve to the
89
+ // same value, so they correctly share a pool.)
90
+ if (type === 'postgres' || type === 'postgresql') {
91
+ let searchPath = '';
92
+ try {
93
+ searchPath = (PostgresClient.resolveSearchPath(cfg).searchPath) || '';
94
+ } catch (_) {
95
+ // Invalid schema names are surfaced later by connect(); for keying,
96
+ // fall back to the raw values so distinct configs still don't collide.
97
+ searchPath = String(cfg.searchPath || cfg.schema || '');
98
+ }
99
+ if (searchPath) { key += `#${searchPath}`; }
100
+ }
101
+ return key;
49
102
  }
50
103
 
51
104
  // ============================================================================
@@ -213,6 +266,13 @@ class context {
213
266
  this._SQLEngine = null; // Will be set during database initialization
214
267
  this.__trackedEntitiesMap = new Map(); // Initialize Map for O(1) lookups
215
268
 
269
+ // Register this instance for cross-context change-tracking detection
270
+ // (see _liveContexts). Held only as a WeakRef so it never keeps the
271
+ // context alive; removed on close() and auto-pruned on GC.
272
+ this.__liveRef = new WeakRef(this);
273
+ _liveContexts.add(this.__liveRef);
274
+ _liveContextFinalizer.register(this, this.__liveRef, this.__liveRef);
275
+
216
276
  // Track if this is the first instance of this context class
217
277
  // Used to determine if duplicate warnings should be shown
218
278
  const globalRegistry = context._globalModelRegistry[this.__name];
@@ -773,7 +833,7 @@ class context {
773
833
  } else {
774
834
  // (2) Folder path — locate and read env.<NODE_ENV>.json.
775
835
  // Try multiple base roots for robustness
776
- const candidateRoots = [process.cwd(), appRoot.path, __dirname];
836
+ const candidateRoots = [process.cwd(), findAppRoot(), __dirname];
777
837
  let file = null;
778
838
  const searchErrors = [];
779
839
 
@@ -1174,7 +1234,7 @@ class context {
1174
1234
  );
1175
1235
  }
1176
1236
  const contextName = this.__name;
1177
- const root = appRoot.path;
1237
+ const root = findAppRoot();
1178
1238
  const file = this.__findSettings(root, rootFolderLocation, envType);
1179
1239
  const settings = JSON.parse(fs.readFileSync(file.file, 'utf8'));
1180
1240
  const options = settings[contextName];
@@ -1715,6 +1775,50 @@ class context {
1715
1775
  }
1716
1776
  }
1717
1777
 
1778
+ /**
1779
+ * Run a bulk write, falling back to a per-row path if the bulk attempt
1780
+ * fails. When saveChanges() has a transaction open, the attempt is
1781
+ * bracketed by a SAVEPOINT so a failure can be rolled back to a clean
1782
+ * point before the fallback runs. Without this, Postgres marks the whole
1783
+ * transaction "aborted" after the first error and refuses every subsequent
1784
+ * statement — so the old bare try/catch fallback would have turned one
1785
+ * failed bulk into a fully failed saveChanges. Outside a transaction this
1786
+ * degrades to the previous plain try/catch.
1787
+ *
1788
+ * If the fallback itself throws, it propagates to saveChanges()'s catch,
1789
+ * which rolls back the entire transaction (true atomicity).
1790
+ *
1791
+ * @private
1792
+ */
1793
+ async _bulkWithFallback(label, attemptFn, fallbackFn){
1794
+ const eng = this._SQLEngine;
1795
+ const useSavepoint = typeof eng.inTransaction === 'function'
1796
+ && eng.inTransaction()
1797
+ && typeof eng.savepoint === 'function';
1798
+
1799
+ if(!useSavepoint){
1800
+ try {
1801
+ return await attemptFn();
1802
+ } catch (error) {
1803
+ console.error(`[Context] ${label} failed, falling back to individual operations:`, error.message);
1804
+ return await fallbackFn();
1805
+ }
1806
+ }
1807
+
1808
+ this.__savepointSeq = (this.__savepointSeq || 0) + 1;
1809
+ const sp = `mr_sp_${this.__savepointSeq}`;
1810
+ await eng.savepoint(sp);
1811
+ try {
1812
+ const result = await attemptFn();
1813
+ await eng.releaseSavepoint(sp);
1814
+ return result;
1815
+ } catch (error) {
1816
+ console.error(`[Context] ${label} failed, rolling back to savepoint and falling back:`, error.message);
1817
+ await eng.rollbackToSavepoint(sp);
1818
+ return await fallbackFn();
1819
+ }
1820
+ }
1821
+
1718
1822
  /**
1719
1823
  * Detect whether a tracked entity carries child-relationship data
1720
1824
  * (hasMany / hasOne / hasManyThrough) that was explicitly assigned by the
@@ -1802,35 +1906,37 @@ class context {
1802
1906
 
1803
1907
  // Flat entities: normalize each, then one fast batched insert.
1804
1908
  if (flatEntities.length > 0) {
1805
- try {
1806
- const manager = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
1807
- const preparedModels = [];
1808
- for (const entity of flatEntities) {
1809
- preparedModels.push(await manager.prepareInsertModel(entity));
1810
- }
1909
+ await this._bulkWithFallback('Bulk insert',
1910
+ async () => {
1911
+ const manager = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
1912
+ const preparedModels = [];
1913
+ for (const entity of flatEntities) {
1914
+ preparedModels.push(await manager.prepareInsertModel(entity));
1915
+ }
1811
1916
 
1812
- const results = await this._SQLEngine.bulkInsert(preparedModels);
1917
+ const results = await this._SQLEngine.bulkInsert(preparedModels);
1813
1918
 
1814
- // Set auto-increment IDs back on the original tracked entities
1815
- for (let i = 0; i < flatEntities.length; i++) {
1816
- const entity = flatEntities[i];
1817
- const result = results[i];
1919
+ // Set auto-increment IDs back on the original tracked entities
1920
+ for (let i = 0; i < flatEntities.length; i++) {
1921
+ const entity = flatEntities[i];
1922
+ const result = results[i];
1818
1923
 
1819
- if (result && result.id) {
1820
- const primaryKey = tools.getPrimaryKeyObject(entity.__entity);
1821
- if (entity.__entity[primaryKey]?.auto === true) {
1822
- entity[primaryKey] = result.id;
1924
+ if (result && result.id) {
1925
+ const primaryKey = tools.getPrimaryKeyObject(entity.__entity);
1926
+ if (entity.__entity[primaryKey]?.auto === true) {
1927
+ entity[primaryKey] = result.id;
1928
+ }
1823
1929
  }
1824
1930
  }
1931
+ },
1932
+ async () => {
1933
+ // Fallback to individual inserts
1934
+ for (const entity of flatEntities) {
1935
+ const insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
1936
+ await insert.init(entity);
1937
+ }
1825
1938
  }
1826
- } catch (error) {
1827
- console.error('[Context] Bulk insert failed, falling back to individual inserts:', error.message);
1828
- // Fallback to individual inserts
1829
- for (const entity of flatEntities) {
1830
- const insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
1831
- await insert.init(entity);
1832
- }
1833
- }
1939
+ );
1834
1940
  }
1835
1941
  }
1836
1942
 
@@ -1842,10 +1948,24 @@ class context {
1842
1948
  }
1843
1949
 
1844
1950
  // Transition inserted entities to tracked state so subsequent
1845
- // property changes trigger UPDATE instead of a second INSERT
1951
+ // property changes trigger UPDATE instead of a second INSERT.
1952
+ //
1953
+ // A plain `new Model()` passed to add() has ordinary own-property
1954
+ // fields, NOT the change-tracking accessors a queried entity has — so
1955
+ // without this a later edit (`row.name = 'x'`) is a silent write that
1956
+ // never marks the entity modified, and the change is dropped on the next
1957
+ // saveChanges(). attachTrackingTo() installs those accessors in place so
1958
+ // the just-inserted entity is update-trackable, exactly like one loaded
1959
+ // from the database.
1960
+ const tracker = new EntityTrackerModel();
1846
1961
  for (const entity of entities) {
1847
1962
  entity.__state = 'track';
1848
1963
  entity.__dirtyFields = [];
1964
+ try {
1965
+ tracker.attachTrackingTo(entity);
1966
+ } catch (attachErr) {
1967
+ console.error(`[Context] Could not attach change-tracking to inserted ${entity.__name || 'entity'}: ${attachErr.message}`);
1968
+ }
1849
1969
  }
1850
1970
  }
1851
1971
 
@@ -1906,15 +2026,15 @@ class context {
1906
2026
  }
1907
2027
 
1908
2028
  if (updateQueries.length > 0) {
1909
- try {
1910
- await this._SQLEngine.bulkUpdate(updateQueries);
1911
- } catch (error) {
1912
- console.error('[Context] Bulk update failed, falling back to individual updates:', error.message);
1913
- // Fallback to individual updates
1914
- for (const query of updateQueries) {
1915
- await this._SQLEngine.update(query);
2029
+ await this._bulkWithFallback('Bulk update',
2030
+ async () => { await this._SQLEngine.bulkUpdate(updateQueries); },
2031
+ async () => {
2032
+ // Fallback to individual updates
2033
+ for (const query of updateQueries) {
2034
+ await this._SQLEngine.update(query);
2035
+ }
1916
2036
  }
1917
- }
2037
+ );
1918
2038
  }
1919
2039
  }
1920
2040
 
@@ -1975,19 +2095,21 @@ class context {
1975
2095
  deletesByTable.get(groupKey).ids.push(id);
1976
2096
  }
1977
2097
 
1978
- try {
1979
- // Performance: Use for...of with Map entries
1980
- for (const { tableName, primaryKey, ids } of deletesByTable.values()) {
1981
- await this._SQLEngine.bulkDelete(tableName, ids, primaryKey);
1982
- }
1983
- } catch (error) {
1984
- console.error('[Context] Bulk delete failed, falling back to individual deletes:', error.message);
1985
- // Fallback to individual deletes
1986
- for (const entity of entities) {
1987
- const deleteObject = new deleteManager(this._SQLEngine, this.__entities);
1988
- await deleteObject.init(entity);
2098
+ await this._bulkWithFallback('Bulk delete',
2099
+ async () => {
2100
+ // Performance: Use for...of with Map entries
2101
+ for (const { tableName, primaryKey, ids } of deletesByTable.values()) {
2102
+ await this._SQLEngine.bulkDelete(tableName, ids, primaryKey);
2103
+ }
2104
+ },
2105
+ async () => {
2106
+ // Fallback to individual deletes
2107
+ for (const entity of entities) {
2108
+ const deleteObject = new deleteManager(this._SQLEngine, this.__entities);
2109
+ await deleteObject.init(entity);
2110
+ }
1989
2111
  }
1990
- }
2112
+ );
1991
2113
  }
1992
2114
 
1993
2115
  // Execute afterDelete hooks
@@ -2013,9 +2135,57 @@ class context {
2013
2135
  * db.saveChanges();
2014
2136
  */
2015
2137
  async saveChanges() {
2138
+ // Concurrent saveChanges() calls on a shared context are serialized.
2139
+ // The engines hold ONE transaction client (`_txnClient`) and the
2140
+ // tracked-entity list is shared context state, so two overlapping
2141
+ // calls used to ride the same BEGIN..COMMIT: whichever finished first
2142
+ // committed (or rolled back) BOTH callers' writes, and the other
2143
+ // caller's remaining statements fell through to autocommit on random
2144
+ // pooled connections. Under load that shows up as "the row I saved
2145
+ // (and whose id my child rows reference) is gone" — an aborted
2146
+ // sibling transaction took it down. Queuing removes the interleaving
2147
+ // while keeping each batch atomic.
2148
+ // The queue must live on whatever object owns the transaction client,
2149
+ // NOT on the context instance. MySQL/Postgres context instances built
2150
+ // from the same pooled connection all reuse ONE engine object
2151
+ // (`this._SQLEngine = cached.engine`) with a single `_txnClient`, so a
2152
+ // per-instance queue lets two DIFFERENT instances still ride the same
2153
+ // BEGIN..COMMIT — the exact cross-instance data loss 1.5.4 only fixed
2154
+ // for a single instance. Chaining on the engine serializes every save
2155
+ // that shares a connection. (SQLite opens its own engine per instance,
2156
+ // so its per-engine queue is naturally per-instance — correct, since
2157
+ // those connections are independent.)
2158
+ //
2159
+ // The queue is chained SYNCHRONOUSLY (no await before this point): an
2160
+ // await here would defer the assignment to a microtask, so concurrent
2161
+ // callers would all read the queue before any of them wrote it and run
2162
+ // in parallel. `_saveChangesExclusive()` awaits `_ensureReady()` itself,
2163
+ // and by the time overlapping saves race the engine is already set, so
2164
+ // `this._SQLEngine` is the shared lock host; before init (the very first
2165
+ // save) it falls back to the instance, which is fine — there is nothing
2166
+ // concurrent to serialize against yet.
2167
+ const lockHost = this._SQLEngine || this;
2168
+ const run = () => this._saveChangesExclusive();
2169
+ const prev = lockHost.__saveQueue || Promise.resolve();
2170
+ const next = prev.then(run, run);
2171
+ // The queue itself must swallow rejections or one failed save would
2172
+ // poison every save after it; callers still see their own rejection
2173
+ // through `next`.
2174
+ lockHost.__saveQueue = next.catch(() => {});
2175
+ return next;
2176
+ }
2177
+
2178
+ async _saveChangesExclusive() {
2016
2179
  await this._ensureReady();
2180
+ // Snapshot the batch: entities add()ed while this save is in flight
2181
+ // belong to the NEXT queued save, and must not be cleared by this one.
2182
+ const tracked = this.__trackedEntities.slice();
2017
2183
  try {
2018
- const tracked = this.__trackedEntities;
2184
+ // Loud guard against silent data loss: if entities with unsaved
2185
+ // changes are tracked by a DIFFERENT context instance, THIS
2186
+ // saveChanges() will not write them. Warn loudly (this is the #1
2187
+ // cause of "saveChanges succeeded but nothing was written").
2188
+ this._warnForeignDirty('saveChanges()');
2019
2189
 
2020
2190
  if (tracked.length === 0) {
2021
2191
  console.log('[Context] No tracked entities to save');
@@ -2030,8 +2200,12 @@ class context {
2030
2200
  }
2031
2201
  }
2032
2202
 
2033
- // Handle transactions based on database type
2034
- if (this.isSQLite) {
2203
+ // Atomicity: wrap every write in a single transaction so a partial
2204
+ // failure rolls the whole batch back. All three engines now expose
2205
+ // startTransaction/endTransaction/errorTransaction (MySQL/Postgres
2206
+ // gained them in 1.4.0; previously their writes were autocommitted
2207
+ // per statement, leaving partial data on a mid-batch error).
2208
+ if (this.isSQLite || this.isMySQL || this.isPostgres) {
2035
2209
  await this._SQLEngine.startTransaction();
2036
2210
  try {
2037
2211
  await this._processTrackedEntities(tracked);
@@ -2041,14 +2215,6 @@ class context {
2041
2215
  await this._SQLEngine.errorTransaction();
2042
2216
  throw error;
2043
2217
  }
2044
- } else if (this.isMySQL) {
2045
- // MySQL: Async operations
2046
- await this._processTrackedEntities(tracked);
2047
- this.__clearErrorHandler();
2048
- } else if (this.isPostgres) {
2049
- // PostgreSQL: Async operations
2050
- await this._processTrackedEntities(tracked);
2051
- this.__clearErrorHandler();
2052
2218
  }
2053
2219
 
2054
2220
  // Invalidate query cache for affected tables
@@ -2056,19 +2222,29 @@ class context {
2056
2222
  this._queryCache.invalidateTable(tableName);
2057
2223
  }
2058
2224
 
2059
- // Clear tracked entities after successful save
2060
- this.__clearTracked();
2225
+ // Clear only THIS batch — entities tracked mid-save stay queued.
2226
+ this.__untrack(tracked);
2061
2227
  return true;
2062
2228
  } catch (error) {
2063
- // Clean up on error
2229
+ // Clean up on error (this batch only)
2064
2230
  this.__clearErrorHandler();
2065
- this.__clearTracked();
2231
+ this.__untrack(tracked);
2066
2232
 
2067
2233
  console.error('[Context] Failed to save changes:', error);
2068
2234
  throw error;
2069
2235
  }
2070
2236
  }
2071
2237
 
2238
+ /** Remove a specific batch of entities from change tracking. */
2239
+ __untrack(batch) {
2240
+ if (!batch || !batch.length) return;
2241
+ const drop = new Set(batch);
2242
+ this.__trackedEntities = this.__trackedEntities.filter(e => !drop.has(e));
2243
+ for (const e of batch) {
2244
+ if (e && e.__ID !== undefined) this.__trackedEntitiesMap.delete(e.__ID);
2245
+ }
2246
+ }
2247
+
2072
2248
 
2073
2249
  /**
2074
2250
  * Execute a raw SQL query, optionally with parameterized values
@@ -2381,6 +2557,21 @@ class context {
2381
2557
  * db.close(); // Close connections
2382
2558
  */
2383
2559
  async close() {
2560
+ // Deregister from the live-context registry so it stops appearing in
2561
+ // cross-context checks and doesn't linger until GC.
2562
+ //
2563
+ // Note: we intentionally do NOT warn about unsaved changes on close.
2564
+ // The framework can't distinguish "forgot to save" from "deliberately
2565
+ // abandoned these changes" (a legitimate pattern — load, mutate, decide
2566
+ // not to persist, dispose), so such a warning would false-positive. The
2567
+ // real bug — mutating an entity from one context and calling
2568
+ // saveChanges() on another — is caught precisely at saveChanges().
2569
+ if (this.__liveRef) {
2570
+ _liveContexts.delete(this.__liveRef);
2571
+ _liveContextFinalizer.unregister(this.__liveRef);
2572
+ this.__liveRef = null;
2573
+ }
2574
+
2384
2575
  // Find this instance's pool in the registry and decrement
2385
2576
  for (const [key, entry] of _pools) {
2386
2577
  // Skip pending entries -- they have no engine yet
@@ -2500,6 +2691,17 @@ class context {
2500
2691
  );
2501
2692
  }
2502
2693
 
2694
+ // An entity is tracked by exactly one context. If it's currently tracked
2695
+ // by a DIFFERENT context instance, detach it from that one first — this
2696
+ // is what makes re-homing correct (and stops the cross-context guard from
2697
+ // continuing to flag it once it's been legitimately moved here).
2698
+ const previous = entity.__context;
2699
+ if (previous && previous !== this && entity.__ID &&
2700
+ previous.__trackedEntitiesMap && previous.__trackedEntitiesMap.has(entity.__ID)) {
2701
+ previous.__trackedEntitiesMap.delete(entity.__ID);
2702
+ previous.__trackedEntities = previous.__trackedEntities.filter(e => e.__ID !== entity.__ID);
2703
+ }
2704
+
2503
2705
  // Mark entity as modified
2504
2706
  entity.__state = 'modified';
2505
2707
 
@@ -2657,6 +2859,86 @@ class context {
2657
2859
  this.__trackedEntities = [];
2658
2860
  this.__trackedEntitiesMap.clear(); // Clear Map for proper garbage collection
2659
2861
  }
2862
+
2863
+ // ------------------------------------------------------------------
2864
+ // Cross-context change-tracking guards (silent-data-loss prevention)
2865
+ // ------------------------------------------------------------------
2866
+
2867
+ /**
2868
+ * True when an entity has unsaved changes — a pending insert, an in-place
2869
+ * modification, or a pending delete. A freshly loaded (unmutated) entity is
2870
+ * in the clean 'track' state and is NOT dirty, so read-heavy multi-context
2871
+ * usage never trips the cross-context guard.
2872
+ * @private
2873
+ */
2874
+ static _isEntityDirty(entity) {
2875
+ return !!(entity && entity.__state && entity.__state !== 'track');
2876
+ }
2877
+
2878
+ /**
2879
+ * Short, human-readable identifier for an entity, used in warnings.
2880
+ * Prefers "Table#<primaryKeyValue>"; falls back to the internal tracking id.
2881
+ * @private
2882
+ */
2883
+ _describeEntity(entity) {
2884
+ const name = (entity && entity.__name) || 'Entity';
2885
+ let id = entity && entity.__ID;
2886
+ try {
2887
+ if (entity && entity.__entity) {
2888
+ const pk = tools.getPrimaryKeyObject(entity.__entity);
2889
+ if (pk && entity[pk] !== undefined && entity[pk] !== null) {
2890
+ id = entity[pk];
2891
+ }
2892
+ }
2893
+ } catch (_) { /* fall back to __ID */ }
2894
+ return `${name}#${id === undefined || id === null ? '?' : id}`;
2895
+ }
2896
+
2897
+ /**
2898
+ * Collect entities that have unsaved changes but are tracked by a DIFFERENT
2899
+ * live context instance than this one. Prunes GC'd contexts from the registry
2900
+ * as it walks it.
2901
+ * @private
2902
+ */
2903
+ _foreignDirtyEntities() {
2904
+ const foreign = [];
2905
+ for (const ref of _liveContexts) {
2906
+ const ctx = ref.deref();
2907
+ if (!ctx) { _liveContexts.delete(ref); continue; } // prune dead ref
2908
+ if (ctx === this) { continue; }
2909
+ const tracked = ctx.__trackedEntities || [];
2910
+ for (const e of tracked) {
2911
+ if (context._isEntityDirty(e)) { foreign.push(e); }
2912
+ }
2913
+ }
2914
+ return foreign;
2915
+ }
2916
+
2917
+ /**
2918
+ * Emit a loud warning if entities with unsaved changes are tracked by a
2919
+ * different context instance — they will NOT be persisted by `action` here.
2920
+ * This is the framework-level guard against the "saveChanges() succeeded but
2921
+ * nothing was written" class of bug. Suppressible with
2922
+ * MASTERRECORD_SILENCE_CROSS_CONTEXT=1 (e.g. for apps that intentionally run
2923
+ * multiple concurrent context instances with independent pending changes).
2924
+ * @private
2925
+ */
2926
+ _warnForeignDirty(action) {
2927
+ if (process.env.MASTERRECORD_SILENCE_CROSS_CONTEXT === '1') { return; }
2928
+ const foreign = this._foreignDirtyEntities();
2929
+ if (foreign.length === 0) { return; }
2930
+ const shown = foreign.slice(0, 10).map(e => this._describeEntity(e)).join(', ');
2931
+ const more = foreign.length > 10 ? `, +${foreign.length - 10} more` : '';
2932
+ const plural = foreign.length === 1 ? 'entity' : 'entities';
2933
+ const verb = foreign.length === 1 ? 'is' : 'are';
2934
+ console.warn(
2935
+ `[masterrecord] WARNING: ${action} on context '${this.__name}' will NOT persist ${foreign.length} ` +
2936
+ `${plural} with unsaved changes that ${verb} tracked by a DIFFERENT context instance: ${shown}${more}. ` +
2937
+ `Those changes are being silently dropped. Fix: call saveChanges() on the context that loaded them, ` +
2938
+ `use entity.save(), or re-track them here first with context.attach(entity). ` +
2939
+ `(Silence with MASTERRECORD_SILENCE_CROSS_CONTEXT=1.)`
2940
+ );
2941
+ }
2660
2942
  }
2661
2943
 
2662
2944
  // ============================================================================
package/mySQLEngine.js CHANGED
Binary file