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/deleteManager.js CHANGED
@@ -34,7 +34,10 @@ class DeleteManager {
34
34
  try {
35
35
  await this.cascadeDelete(currentModel);
36
36
  } catch (error) {
37
- // Add context to error
37
+ // A concurrency conflict is a first-class, catchable outcome —
38
+ // surface it unwrapped so callers can `instanceof ConcurrencyError`.
39
+ if (error && error.name === 'ConcurrencyError') throw error;
40
+ // Add context to other errors
38
41
  const entityName = currentModel.__entity?.__name || 'unknown';
39
42
  throw new Error(`Failed to delete ${entityName}: ${error.message}`, { cause: error });
40
43
  }
@@ -101,8 +104,28 @@ class DeleteManager {
101
104
  }
102
105
  }
103
106
 
104
- // Delete the entity itself after cascading
105
- await this._SQLEngine.delete(entity);
107
+ // Delete the entity itself after cascading. Carry the entity's
108
+ // concurrency tokens (original values) into the DELETE's WHERE and
109
+ // assert one row was affected — a concurrently modified/deleted row
110
+ // matches 0 rows and must surface as ConcurrencyError, not silent
111
+ // success (EF throws DbUpdateConcurrencyException on delete too).
112
+ const ctx = entity.__context;
113
+ if (ctx && typeof ctx._concurrencyClause === 'function') {
114
+ // (+ the remaining columns of a composite key — EF HasKey(a, b))
115
+ const clause = [
116
+ ...ctx._concurrencyClause(entity),
117
+ ...(typeof ctx._compositeKeyClause === 'function' ? ctx._compositeKeyClause(entity) : []),
118
+ ];
119
+ if (clause.length) {
120
+ Object.defineProperty(entity, '__concurrency', {
121
+ value: clause, enumerable: false, writable: true, configurable: true,
122
+ });
123
+ }
124
+ }
125
+ const result = await this._SQLEngine.delete(entity);
126
+ if (ctx && typeof ctx._assertAffected === 'function') {
127
+ ctx._assertAffected(result, entity, 'delete');
128
+ }
106
129
  }
107
130
 
108
131
  /**
@@ -50,6 +50,14 @@ If you set a `no-track` default on a shared/long-lived context, remember every w
50
50
  | `context.clearChangeTracker()` | `ChangeTracker.Clear()` | Detach all entities and drop all pending changes. |
51
51
  | `context.reset()` | (pool release reset) | Detach all + clear the query cache, but **keep the connection open** — the "reuse this instance" primitive. |
52
52
  | `await context.close()` | `Dispose()` | Release the change tracker **and** the connection (decrements the connection-pool ref). |
53
+ | `context.entry(entity)` | `Entry(entity)` | `state` (get/set), `originalValues`, `currentValues`, `isModified(field)`, `reload()`, `getDatabaseValues()`, `detach()`. |
54
+ | `context.hasChanges()` / `context.entries([model])` | `ChangeTracker.HasChanges()` / `Entries()` | Pending changes? / all tracked entries. |
55
+ | `context.add(e)` / `context.remove(e)` | `Add` / `Remove` | Context-level add/remove (resolves the owning dbset). |
56
+ | `ctx.Model.find(pk)` | `Find` | Identity map first — no query if the row is already tracked. |
57
+ | `await ctx.entry(e).load('nav')` / `ctx.loadNavigation(e, 'nav')` | `Entry(e).Reference(n).Load()` / `Collection(n).Load()` | Explicit loading of a navigation on any engine (parameterized). `entry(e).isLoaded('nav')`. |
58
+ | `await post.author` (lazy) | lazy-loading proxies | An unloaded navigation returns a Promise that loads it once and caches it; loaded navigations read synchronously. `lazyLoadingOff()` → `null` until loaded explicitly. |
59
+ | `post.author = anAuthor` / `post.author_id = id` | relationship fix-up | Assigning a parent sets the FK and marks dirty; changing the FK invalidates a loaded parent. Engines persist the **key**, never the navigation object. |
60
+ | `(await post.tags).add(tag)` / `.remove(tag)`, `ctx.entry(post).collection('tags')` | `Collection(n).Add/Remove` | `db.manyToMany('Tag')` synthesizes the join entity (EF skip navigation); add tracks a join row (new targets inserted first), remove schedules its DELETE; hasMany add sets the child FK. Persisted by `saveChanges()`. |
53
61
 
54
62
  `clearChangeTracker()` drops pending changes, so on a shared context it can destroy another in-flight request's writes — it is not a safe per-request mitigation. Use request-scoped contexts or `asNoTracking()` instead.
55
63
 
@@ -61,7 +69,9 @@ MasterRecord holds tracked entities with **strong references** for the life of t
61
69
 
62
70
  ### 1. Request-scoped context (recommended)
63
71
 
64
- Create a context per request and `close()` it when the request ends. Connections are pooled underneath, and `close()` releases the whole change tracker. Every `load → mutate → saveChanges` handler works unchanged, with no tracking-behavior tweaks and no way to introduce a lost write.
72
+ Create a context per request and `close()` it when the request ends. Every `load → mutate → saveChanges` handler works unchanged, with no tracking-behavior tweaks and no way to introduce a lost write.
73
+
74
+ `new AppContext()` is cheap — it does **not** open a new connection. Connections are pooled per database (like ADO.NET under EF): `close()` releases the change tracker and returns the connection to the pool **kept open and idle**, so the next context reuses a warm connection with no reconnect. Idle connections are reclaimed by a background reaper after `MR_POOL_IDLE_MS` (default 60000ms; set `0` to close immediately at refcount zero). So per-request contexts — and background jobs that build a scope per run — do not churn connections.
65
75
 
66
76
  ```javascript
67
77
  async function handler(req, res) {
@@ -99,6 +109,141 @@ await pool.drain();
99
109
 
100
110
  ---
101
111
 
112
+ ## Optimistic concurrency (EF's concurrency tokens)
113
+
114
+ Without a token, two writers that load the same row and save different changes silently overwrite each other — last write wins. MasterRecord implements EF Core's optimistic concurrency:
115
+
116
+ ```javascript
117
+ class Doc {
118
+ id(db) { db.integer().primary().auto(); }
119
+ title(db) { db.string(); }
120
+ version(db) { db.rowVersion(); } // ORM-managed: bumped on every UPDATE
121
+ }
122
+ class Tagged {
123
+ id(db) { db.integer().primary().auto(); }
124
+ etag(db) { db.string().concurrencyToken(); } // app-managed: you set a new value when you change the row
125
+ }
126
+ ```
127
+
128
+ - **`rowVersion()`** — an integer token the ORM owns. Every UPDATE runs `SET ..., version = version + 1 WHERE id = ? AND version = <original>`. Works identically on SQLite, MySQL and PostgreSQL (EF's `IsRowVersion`, but application-managed so it is portable).
129
+ - **`concurrencyToken()`** — any column whose **original** (as-loaded) value is added to the UPDATE/DELETE `WHERE`. You rotate its value yourself (e.g. a GUID/etag) when you change the row (EF's `IsConcurrencyToken`).
130
+ - **Rows-affected is always checked**, token or not: updating or deleting a row that was concurrently deleted affects 0 rows and throws.
131
+
132
+ When a conflict is detected, `saveChanges()` rolls the whole batch back and throws **`ConcurrencyError`** (EF's `DbUpdateConcurrencyException`). `err.entries` holds the conflicting entities; they stay tracked and dirty so you can resolve and retry:
133
+
134
+ ```javascript
135
+ import { ConcurrencyError } from 'masterrecord/errors'; // also re-exported from 'masterrecord/context'
136
+
137
+ for (let attempt = 0; attempt < 3; attempt++) {
138
+ try { await db.saveChanges(); break; }
139
+ catch (e) {
140
+ if (!(e instanceof ConcurrencyError)) throw e;
141
+ for (const entity of e.entries) {
142
+ await entity.reload(); // database wins: refresh values + original values
143
+ entity.title = myNewTitle; // re-apply what you still want
144
+ }
145
+ }
146
+ }
147
+ ```
148
+
149
+ Resolution strategies mirror EF: **database wins** (`reload()` then re-apply), **client wins** (`reload()`, then set your values on the now-fresh originals and save), or merge per field using `entity.__originalValues` vs the reloaded values.
150
+
151
+ ## Transactions (EF's `Database.BeginTransaction`)
152
+
153
+ `saveChanges()` is always atomic on its own. To span several saves (or raw SQL) in one unit:
154
+
155
+ ```javascript
156
+ await db.transaction(async (tx) => { // begin → run → commit; rollback + rethrow on error
157
+ tx.Account.add(a); await tx.saveChanges();
158
+ await tx.execute('UPDATE Ledger SET ...');
159
+ tx.Audit.add(log); await tx.saveChanges();
160
+ });
161
+
162
+ // manual control
163
+ await db.beginTransaction();
164
+ try { ...; await db.commit(); } catch (e) { await db.rollback(); throw e; }
165
+
166
+ // savepoints inside an open transaction
167
+ await db.createSavepoint('beforeBulk');
168
+ ...
169
+ await db.rollbackToSavepoint('beforeBulk'); // or releaseSavepoint('beforeBulk')
170
+ ```
171
+
172
+ Inside a user transaction each `saveChanges()` is protected by a savepoint and does **not** commit by itself — a failed save leaves the outer transaction usable, exactly as in EF. The transaction holds the context's engine lock, so another unit of work on the same pooled connection waits rather than interleaving. Nested `beginTransaction()` is rejected; use savepoints.
173
+
174
+ ## Set-based writes (EF's `ExecuteUpdate` / `ExecuteDelete`)
175
+
176
+ One SQL statement over the rows a query selects — no loading, no change tracker, returns rows affected:
177
+
178
+ ```javascript
179
+ import { sql } from 'masterrecord/sql';
180
+ await db.Blog.where('b => b.rating < $$', 3).executeUpdate({ hidden: true, views: sql`views + 1` });
181
+ await db.Session.where('s => s.expiresAt < $$', Date.now()).executeDelete();
182
+ ```
183
+
184
+ Setter values are parameterized; `sql\`…\`` inlines a trusted fragment (it refuses interpolations). Like EF, these don't refresh tracked instances — avoid mixing them with pending tracked edits to the same rows. Inside `transaction()` they join the transaction.
185
+
186
+ ## Global query filters (EF's `HasQueryFilter`)
187
+
188
+ A filter is a where-lambda appended to every query on an entity — soft delete and multi-tenancy without repeating the predicate:
189
+
190
+ ```javascript
191
+ this.dbset(Blog)
192
+ .queryFilter('softDelete', 'b => b.deletedAt == null')
193
+ .queryFilter('tenant', 'b => b.tenantId == $$', ctx => ctx.tenantId); // evaluated per query
194
+
195
+ await db.Blog.toList(); // filtered
196
+ await db.Blog.ignoreQueryFilters().toList(); // all rows
197
+ await db.Blog.ignoreQueryFilters(['softDelete']).toList(); // EF 10: ignore by name
198
+ ```
199
+
200
+ Filters apply to `toList`/`single`/`first`/`findById`/`count`/`exists` and to `executeUpdate`/`executeDelete`. They currently apply to the root entity of a query (not inside `include()`d navigations).
201
+
202
+ ## Events & interceptors (EF's `SavingChanges` / interceptors)
203
+
204
+ ```javascript
205
+ db.on('savingChanges', ({ entries }) => {
206
+ for (const { entity, state } of entries) {
207
+ if (state === 'modified') entity.updatedAt = Date.now(); // audit column
208
+ if (state === 'delete') { entity.__state = 'modified'; entity.deletedAt = Date.now(); } // soft delete
209
+ }
210
+ });
211
+ db.on('savedChanges', ({ entries }) => { /* after commit */ });
212
+ db.on('saveChangesFailed', ({ error }) => { /* before rethrow */ });
213
+ db.on('command', ({ sql, params, durationMs, engine, error }) => { /* every SQL statement */ });
214
+ db.on('tracked', …); db.on('stateChanged', …);
215
+ ```
216
+
217
+ `on()` returns an unsubscribe function; `once()` fires a single time. `savingChanges` runs before the flush and the change set is re-collected afterwards, so edits made by handlers ship in the same save.
218
+
219
+ ## Logging & diagnostics (EF's `LogTo` / `EnableSensitiveDataLogging`)
220
+
221
+ Nothing is logged by default, and parameter values are **redacted** unless you opt in — exactly EF's defaults:
222
+
223
+ ```javascript
224
+ import masterrecord from 'masterrecord';
225
+ masterrecord.configureLogging({
226
+ logger: myLogger, // { debug, info, warn, error } — default console
227
+ level: 'debug', // min level
228
+ logSql: true, // log every command (or LOG_SQL=true)
229
+ sensitiveData: false, // show parameter values? (or MR_SENSITIVE_LOGGING=true)
230
+ slowQueryMs: 250, // warn on slow commands even when logSql is off (or MR_SLOW_QUERY_MS)
231
+ migrations: true, // log migration DDL at info (MR_SILENT_MIGRATIONS=true to silence)
232
+ });
233
+ ```
234
+
235
+ Every command on every engine flows through one timed path → the logger and the `command` event (`{ sql, params, durationMs, engine, error? }`).
236
+
237
+ ## Connection resiliency (EF's `EnableRetryOnFailure`)
238
+
239
+ ```javascript
240
+ db.setRetryOnFailure({ maxRetries: 3, maxDelayMs: 2000 }); // per context (false to disable)
241
+ masterrecord.configureRetry({ maxRetries: 3 }); // process-wide default
242
+ db.on('retry', ({ attempt, delayMs, error }) => …);
243
+ ```
244
+
245
+ Transient errors (deadlocks, lock timeouts, busy SQLite, dropped connections) are retried with capped exponential backoff; constraint/syntax errors and `ConcurrencyError` are not. Queries, `saveChanges()` and `executeUpdate`/`executeDelete` are covered; nothing is retried inside an explicit transaction — re-run the whole transaction (EF semantics). Off by default.
246
+
102
247
  ## Why not a singleton context?
103
248
 
104
249
  A singleton context shared across concurrent requests is the root cause of an entire class of bugs (and is unsupported in EF for the same reasons):
@@ -0,0 +1,132 @@
1
+ # MasterRecord vs. Entity Framework Core — Gap Analysis
2
+
3
+ _Compared against EF Core 10 (current stable, LTS, Nov 2025) and EF Core 11 (preview, due Nov 2026). Every MasterRecord claim below was verified against the source with a file:line citation._
4
+
5
+ MasterRecord has deliberately adopted EF Core's architecture for change tracking and context lifetime (1.5.9–1.5.17: unit-of-work `saveChanges`, identity map, dirty index, `asNoTracking`/`asTracking`/`setQueryTrackingBehavior`, `clearChangeTracker`, `close()`=Dispose, `ContextPool`=`AddDbContextPool`, ADO.NET-style warm connection pooling, scoped DI + `createScope()`). This document lists what EF Core has that MasterRecord still **doesn't**, ranked by how much it matters for a production ORM, plus what's deliberately out of scope.
6
+
7
+ ---
8
+
9
+ > **Status (Aug 2026):** Tier 1 #1 (optimistic concurrency + rows-affected check) and #2 (explicit transactions) shipped in **1.6.0**; FK constraint DDL + honored cascade behaviors + rename advisories shipped in **1.7.0**; #3 `executeUpdate`/`executeDelete` + set-based `bulkUpdate`/`bulkDelete` shipped in **1.8.0**; #4 named global query filters and #10 context events/interceptors (+ `command` observer) shipped in **1.9.0**; #5 retry/resiliency and #6 pluggable logging with parameter redaction shipped in **1.10.0**; #7 migrations tooling (atomic apply, `script`, `migrations-status`, `--connection`, latest-migration id) shipped in **1.11.0**; #8 `find`, #9 `entry()`/`hasChanges()`/`entries()` and most of #11 (`sum/avg/min/max`, `thenBy`, `distinct`, `any`, DTO list, projected `pluck`, loud `join`/`groupBy`) plus `ctx.add/remove` shipped in **1.12.0**; the three addendum bugs (lazy navigation via un-awaited SQLite-shaped SQL → engine-agnostic explicit/lazy loading with fix-up, async `RedisQueryCache` not awaited, readme `.any()`/`context.remove()` mismatches) shipped in **1.13.0**; Tier-3 DDL modeling (`defaultSql` = HasDefaultValueSql, `computed` = HasComputedColumnSql, `check` = HasCheckConstraint, generated values read back after insert) shipped in **1.14.0**; health checks on every engine (`healthCheck`/`canConnect`) and `remove-migration` (EF `migrations remove`, `--force` reverts first) shipped in **1.15.0**; many-to-many skip navigations (`manyToMany()` with a synthesized join entity, collection `add`/`remove`, `entry().collection()/reference()`) shipped in **1.16.0**; `thenInclude()` / `asSplitQuery()` as EF split queries shipped in **1.17.0**; query filters applied inside `include()` with `ignoreQueryFilters()` propagating to every level shipped in **1.18.0**; TPH inheritance (`dbset(Cat, { extends: Animal })`, discriminator, derived sets, materialization as derived types) shipped in **1.19.0**; composite primary keys (`HasKey(a, b)`: DDL, keyed UPDATE/DELETE, `find(a, b)`) shipped in **1.20.0**; `groupBy().aggregate()` (GROUP BY / HAVING translation) shipped in **1.21.0**; owned/complex JSON types (`db.owned(Class)`, DetectChanges on nested mutations) shipped in **1.22.0**. Still open (by design): `join()`/`leftJoin()` LINQ-style joins — use `include()`/`thenInclude()` or `ctx.query()`; FKs to composite-key entities; `manyToMany()` on composite-key owners. Previously listed as open: `thenInclude`, `groupBy`/`join` translation, and Tier 3 modeling. Remaining items are tracked below in their original ranking.
10
+
11
+ ## Tier 1 — Production correctness / safety (do first)
12
+
13
+ These are the gaps where EF provides a guarantee MasterRecord currently lacks, and where the absence can cause **silent data loss or corruption**.
14
+
15
+ ### 1. Optimistic concurrency (concurrency tokens / rowversion) — MISSING
16
+ - **EF:** a property marked `IsConcurrencyToken()` / `[Timestamp]` (`IsRowVersion()`) is added to the UPDATE/DELETE `WHERE` clause: `UPDATE ... WHERE Id = @p0 AND Version = @p1`. If 0 rows are affected, `SaveChanges` throws `DbUpdateConcurrencyException`, and the app resolves it (client-wins / database-wins / merge via `OriginalValues`/`GetDatabaseValues`). Application-managed tokens (GUID/version counter) work on every DB incl. SQLite.
17
+ - **MasterRecord:** UPDATE is primary-key-only on all three engines — `mySQLEngine.js:44`, `postgresEngine.js:82`, `SQLLiteEngine.js:16-19` — and `_saveChangesExclusive` (`context.js:2266-2286`) returns `true` **without inspecting rows-affected**. Two concurrent writers silently clobber each other, and an UPDATE of a row that was concurrently deleted is reported as success.
18
+ - **Do:** add `db.field().concurrencyToken()` (and an auto-incrementing `.version()` sugar); include tokens in the UPDATE/DELETE `WHERE`; **check rows-affected === 1 and throw `ConcurrencyError`** (with the affected entity) otherwise. This is the single most important missing guarantee.
19
+
20
+ ### 2. Explicit transaction API — MISSING (public)
21
+ - **EF:** `context.Database.BeginTransaction()` / `Commit` / `Rollback`, savepoints (`CreateSavepoint`/`RollbackToSavepoint`), `SaveChanges` auto-creates a savepoint when already inside a transaction, isolation levels, cross-context `UseTransaction`.
22
+ - **MasterRecord:** engines already implement `startTransaction`/`endTransaction`/`errorTransaction`/`savepoint`/`rollbackToSavepoint` (`SQLLiteEngine.js:753-777`, `postgresEngine.js:1093-1135`), but the context exposes **no** `beginTransaction`/`commit`/`rollback`/`transaction(fn)` — they're used only internally by `saveChanges` (`context.js:2270-2277`) and `_bulkWithFallback` (`context.js:1840-1866`). A user cannot span two `saveChanges()` calls (or a save + raw SQL) in one atomic unit.
23
+ - **Do:** `await ctx.beginTransaction()` / `ctx.commit()` / `ctx.rollback()` + `await ctx.transaction(async (tx) => {...})` (auto-commit/rollback), savepoint helpers, and make `saveChanges()` create a savepoint when a user transaction is open (EF semantics). The engine plumbing already exists — this is mostly wiring.
24
+
25
+ ### 3. Set-based bulk update/delete (`ExecuteUpdate` / `ExecuteDelete`) — MISSING
26
+ - **EF:** `ctx.Blogs.Where(b => b.Rating < 3).ExecuteDeleteAsync()` / `.ExecuteUpdateAsync(s => s.SetProperty(...))` — one SQL statement, bypasses the change tracker, returns rows-affected (EF10: setter lambda can be a plain non-expression lambda).
27
+ - **MasterRecord:** no `.where(...).update({...})` / `.where(...).delete()` on the query builder. The existing `bulkUpdate` (`context.js:2543`) and `bulkDelete` (`context.js:2591`) are **N+1**: per id they `findById` (a SELECT) and `bulkDelete` calls `entity.delete()` which runs a full `saveChanges()` each — so 100 ids = 100 SELECTs + 100 transactions, despite the docstring "Much faster than deleting individually."
28
+ - **Do:** `ctx.Model.where(...).executeUpdate({col: value | fn})` and `.executeDelete()` that emit a single UPDATE/DELETE with the query's WHERE, return affected count, don't touch the tracker (document the EF caveat that tracked entities are not refreshed). Reimplement `bulkUpdate`/`bulkDelete` on top of it.
29
+
30
+ ### 4. Global query filters (soft delete, multi-tenancy) — MISSING
31
+ - **EF:** `HasQueryFilter(b => !b.IsDeleted)` is appended to every query on that entity (incl. navigations); `IgnoreQueryFilters()` per query; **EF10: named filters** (`HasQueryFilter("SoftDeletion", ...)` + `HasQueryFilter("Tenant", ...)`, disable selectively with `IgnoreQueryFilters(["SoftDeletion"])`).
32
+ - **MasterRecord:** zero hits for any filter mechanism. Soft-delete/tenant scoping must be hand-written in every query — the class of bug filters exist to eliminate.
33
+ - **Do:** `ctx.Model.queryFilter('softDelete', e => e.deletedAt == null)` at model/context setup, applied in `where`-building for `toList/first/single/count/…` and `include`d navigations; `.ignoreQueryFilters()` / `.ignoreQueryFilters(['softDelete'])`. Ship named filters from day one (EF10 shape).
34
+
35
+ ### 5. Connection resiliency (retry on transient failure) — MISSING
36
+ - **EF:** `EnableRetryOnFailure()` / execution strategy with exponential backoff on transient errors (timeouts, connection reset, deadlock), incl. retrying whole transactions.
37
+ - **MasterRecord:** no retry/backoff anywhere in `mySQLEngine.js`/`postgresEngine.js`/`context.js`; no `ETIMEDOUT`/`ECONNRESET`/deadlock handling. A transient blip is a hard failure. (The only "retry" is one-shot re-init after DB creation in migrations, `Migrations/schema.js:92,169`.)
38
+ - **Do:** an execution strategy around query/save with a transient-error classifier per engine (MySQL `ER_LOCK_DEADLOCK`/`ECONNRESET`, PG `40001`/`40P01`/`57P01`, SQLite `SQLITE_BUSY`) and capped exponential backoff; opt-in `retryOnFailure({ maxRetries, maxDelayMs })`.
39
+
40
+ ### 6. Pluggable logging + sensitive-data redaction — MISSING
41
+ - **EF:** `LogTo(...)`/ILogger integration, command/transaction/connection events, **parameter values redacted by default** (`EnableSensitiveDataLogging` to opt in); EF10 also redacts inlined constants.
42
+ - **MasterRecord:** logging is hardcoded `console.*` gated on env vars (`SQLLiteEngine.js:1409`, `postgresEngine.js:1062-1066`), **on by default whenever `NODE_ENV !== 'production'`**, and **logs parameter values verbatim** (`postgresEngine.js:1065`, `SQLLiteEngine.js:1418`) — PII/secrets leak into dev logs. No slow-query timing.
43
+ - **Do:** `ctx.setLogger(fn)` / `masterrecord.configureLogging({ level, sensitiveData: false })`; redact params unless `sensitiveData: true`; emit `{ sql, durationMs, rows }` with a `slowQueryMs` threshold.
44
+
45
+ ### 7. Migrations: transactional apply, script/dry-run, pending list — PARTIAL
46
+ - **EF:** each migration applies in a transaction (EF10 reverted to *per-migration*, not one giant one); `migrations script` (incl. `--idempotent`) for DBA review; `migrations list` shows applied vs pending; `--connection` override; EF11 adds `database update --add`, wildcard `--context "*"`, and records the latest migration id in the snapshot to surface divergent-branch merges.
47
+ - **MasterRecord:** CLI (`Migrations/cli.js`) has enable/add/update/down/restart/target/get-migrations + `*-all` variants, but: **no transaction around a migration** (DDL autocommits statement-by-statement; a mid-migration failure leaves a half-applied schema — acknowledged at `cli.js:607`), **no script/dry-run**, `get-migrations` (`cli.js:872`) lists files only (applied/pending is computed internally at `cli.js:582-591` but never exposed), **no `--connection`**.
48
+ - **Do:** wrap each migration's `up()` in a transaction where the engine supports transactional DDL (Postgres, SQLite; MySQL implicit-commits DDL — document that), add `script [--idempotent]` and `migrations-status` (applied/pending), `--connection`, and record the latest migration id in the snapshot (EF11's team-merge safety).
49
+
50
+ ---
51
+
52
+ ## Tier 2 — API completeness (developer ergonomics)
53
+
54
+ ### 8. `find(pk)` that checks the identity map first — MISSING
55
+ - **EF:** `Find`/`FindAsync` returns the tracked instance without a query if present; composite keys supported.
56
+ - **MasterRecord:** `findById` (`queryMethods.js:510`) always hits the DB; `__findTracked` (`context.js:3008`) exists but is internal. **Do:** `ctx.Model.find(id)` = identity-map lookup by table+pk, then DB fallback (and track).
57
+
58
+ ### 9. Entity-entry / change-tracker introspection — MISSING
59
+ - **EF:** `ctx.Entry(e).State` (get/set), `OriginalValues`/`CurrentValues`/`GetDatabaseValues`, `Property(...).IsModified`, `Reload()`, `ChangeTracker.Entries()`, `HasChanges()`, `DbSet.Local`.
60
+ - **MasterRecord:** state is a raw `__state` string and a `__dirtyFields` name list; **no original-value snapshot** (so "database-wins/merge" concurrency resolution is impossible), no `hasChanges()`, no public `entries()`. Has `reload()` (`entityTrackerModel.js:167`), `attach/attachAll/detach`.
61
+ - **Do:** `ctx.entry(entity)` → `{ state, originalValues, currentValues, isModified(field), reload(), getDatabaseValues() }`, `ctx.hasChanges()`, `ctx.entries([Model])`. Capturing original values at load is also a prerequisite for #1's merge resolution and for a cleaner "only changed columns" UPDATE.
62
+
63
+ ### 10. Context-level interceptors / events — MISSING (only entity hooks exist)
64
+ - **EF:** `SavingChanges`/`SavedChanges`/`SaveChangesFailed` events + `ISaveChangesInterceptor`; `IDbCommandInterceptor` (rewrite/observe SQL, e.g. query tagging, auditing); connection/transaction interceptors; `ChangeTracker.Tracked`/`StateChanged`.
65
+ - **MasterRecord:** only per-entity `beforeSave/afterSave/beforeDelete/afterDelete` (`Entity/entityModelBuilder.js:22`; invoked `context.js:1913,1992,2022,2084,2103,2150`). No way to implement audit columns (`createdBy/updatedAt`) or soft-delete-on-remove **once** for all entities.
66
+ - **Do:** `ctx.on('savingChanges'|'savedChanges'|'saveChangesFailed', fn)` with access to the change set/entries, `ctx.on('command', fn)` for SQL observe/rewrite, `ctx.on('tracked'|'stateChanged')`. (Combined with #4 this gives EF's canonical soft-delete recipe: intercept `delete` → mark `modified` + set `deletedAt`.)
67
+
68
+ ### 11. Query operators — PARTIAL
69
+ Present: `where/and/orderBy/orderByDescending/take/skip/include/select/count/first/last/single/exists/pluck/raw/search/cache/asNoTracking/asTracking`, `IN` via `.includes()`→`any()` (`queryMethods.js:384`).
70
+ Missing vs EF: **`thenInclude`** (nested eager load), explicit loading (`entry.collection(...).load()`), **`thenBy`/`thenByDescending`**, **`distinct`**, aggregates **`sum/avg/min/max`** (only `count`), `groupBy`, `join`/`leftJoin` (EF10 `LeftJoin`/`RightJoin`, EF11 `FullJoin`), DTO projection (`select` returns entity-shaped rows), `any(pred)`/`all(pred)`, split queries, `MaxBy/MinBy` (EF11).
71
+ - **Quick win first:** `join()` and `groupBy()` at `queryMethods.js:101-107` are **empty bodies returning `undefined`** — chaining off them throws a bare `TypeError`. Either implement or make them throw `NotSupportedError('groupBy is not supported yet')`. Remove the underscore-hidden `_____leftJoin`/`______orderByCount*` stubs.
72
+ - Then: `thenInclude`, `thenBy`, `distinct`, `sum/avg/min/max`, DTO `select({...})`, and `groupBy` + `having`.
73
+
74
+ ---
75
+
76
+ ## Tier 3 — Modeling (EF 8–11 direction)
77
+
78
+ | Feature | EF Core | MasterRecord | Notes |
79
+ |---|---|---|---|
80
+ | Composite primary keys | `HasKey(e => new {a,b})` | **No** — `primary()` is a per-field flag, consumers use the *first* one (`queryMethods.js:513-519`) | Needed for join tables / multi-column natural keys |
81
+ | Many-to-many (auto join table) | `HasMany().WithMany()` skip navigation | **No** — `hasManyThrough` (`entityModel.js:282`) requires a hand-declared join entity; DDL skips it (`schema.js:414`) | |
82
+ | Complex / owned types, JSON mapping | EF10 complex types (table-splitting **or** `ToJson()`), value semantics, optional, ExecuteUpdate over JSON; EF11 on TPT/TPC, keys/indexes on complex props | **No** complex types; `json()` column exists (`entityModel.js:136`) but no typed sub-object mapping/querying | JSON-column querying (`WHERE json->>'x'`) is the practical win |
83
+ | Inheritance (TPH discriminator) | Yes (TPH/TPT/TPC) | **No** | |
84
+ | Computed / generated columns, default SQL | `HasComputedColumnSql`, `HasDefaultValueSql` (EF10 named default constraints) | **No** generated columns; `default()` takes a JS literal only (`entityModel.js:179`) | `default(sql\`now()\`)` is cheap |
85
+ | Check constraints | `HasCheckConstraint` | **No** (only a comment, `migrationSQLiteQuery.js:484`) | |
86
+ | Shadow properties | Yes | **No** | low priority |
87
+ | Value converters | `HasConversion` | **Yes** — `transform({toDatabase,fromDatabase})` (`entityModel.js:242`) | parity |
88
+ | Unique / composite / partial indexes | Yes | **Yes** (`unique()`, `compositeIndex()` `context.js:1483`, partial `context.js:1511` PG/SQLite) | parity; MySQL partial throws (correct — MySQL lacks them) |
89
+ | Full-text search | SQL Server FTS (EF11 catalogs/TVFs) | **Yes** (`schema.js:850`, `search()`) | MasterRecord is ahead here for its engines |
90
+ | Cascade delete config | `OnDelete(DeleteBehavior.*)` | **Yes** (`cascadeOnDelete`, `stopCascadeOnDelete`) | parity |
91
+
92
+ ---
93
+
94
+ ## Addendum — additional verified findings from the full inventory
95
+
96
+ A second, exhaustive pass over the code surfaced items the targeted check missed. Each was re-verified by hand.
97
+
98
+ ### Correctness / data-safety (treat as Tier 1)
99
+ - **No foreign-key constraints are ever emitted in DDL.** `REFERENCES` / `FOREIGN KEY` appear only in comments (`migrationSQLiteQuery.js:471,485`, `migrationPostgresQuery.js:333`); `createTable` emits columns only. EF always creates FK constraints (+ an index on the FK). MasterRecord relationships are purely ORM-level — the database enforces nothing, so orphans are possible via raw SQL or any non-ORM writer. **Do:** emit `REFERENCES parent(pk) ON DELETE <behavior>` for `belongsTo`/`hasMany` FKs in all three builders, with `addForeignKey`/`dropForeignKey` on `schema.js`, and EF11's `excludeForeignKeyFromMigrations()` escape hatch for legacy DBs.
100
+ - **`stopCascadeOnDelete()` is a no-op.** `cascadeOnDelete` is read nowhere outside `entityModel.js` (the builders only mention it in a doc-comment example); `deleteManager.js:48-106` cascades purely by relationship type into *loaded* values and never consults the flag. Once FK DDL exists, map this to EF's `OnDelete(Cascade|Restrict|SetNull|NoAction)` and honor it in both DDL and the in-process cascade.
101
+ - **Lazy-loaded navigation properties return an un-awaited Promise.** The lazy getters call `.single()`/`.toList()` without `await` and assign the result (`entityTrackerModel.js:573,634`), so `post.author` is a `Promise`, not an entity; the SQL is also hand-built SQLite-shaped string interpolation (`TODO` at `:563,595`). EF's lazy loading is proxy-based and synchronous-looking by design. **Do:** either make lazy loading an explicit `await entity.load('author')` (EF explicit loading) and remove the broken auto-getter, or keep it off by default — today it is *on* by default (`entityModel.js:43`).
102
+ - **`RedisQueryCache` is broken in the query path.** Its `get`/`set` are `async`, but the read path calls `_queryCache.get(cacheKey)` without `await` and tests truthiness (`queryMethods.js:548,604`) — a Promise is always truthy, so `.cache()` returns a Promise-of-entity. The readme (`:1151-1165`) tells users to swap it in. **Do:** `await` the cache in the read path (the in-memory cache stays sync-compatible), or drop the Redis cache until it is wired.
103
+ - **A column/table rename is diffed as drop + add.** `renameTable` exists on the SQLite builder (`migrationSQLiteQuery.js:224`) but `schema.js` has no wrapper and the differ never emits rename — a renamed column in a generated migration is `dropColumn` + `addColumn`, i.e. **data loss on apply**. _Correction:_ EF Core's differ deliberately does **not** auto-detect renames either (it scaffolds drop+add and tells you to review/change to `RenameColumn`, because a guess can move data under the wrong name). **Done in 1.7.0 (EF-faithful):** drop+add is still emitted, but the generated migration carries a `// POSSIBLE RENAME` advisory with the exact `renameColumn(...)` call when one removed and one added column share a definition; `schema.renameTable` added.
104
+ - **Index create/drop are generated up-only** (`migrations.js:649-663`) — no `down()` for indexes, so rollback leaves indexes behind.
105
+
106
+ ### API / docs integrity
107
+ - **Readme documents APIs that don't exist:** a terminal `.any()` (`readme.md:1452`; the real method is `.exists()`), `context.remove(entity)` / `db.remove(alice)` (`readme.md:340,1415`; only `ctx.Entity.remove()` exists). `docs/METHODS_REFERENCE.md` omits `asNoTracking/asTracking/cache/last/exists/pluck/findById/count/removeRange/track`. Fix the docs (or add the aliases — EF has `context.Remove(entity)`).
108
+ - `pluck(field)` loads full entities then maps in JS (`queryMethods.js:366`) — not a SQL projection. Should emit `SELECT field`.
109
+ - `take/skip` are interpolated into `LIMIT/OFFSET` (validated non-negative int) rather than parameterized — safe, but noted.
110
+ - No `usePostgres()` convenience (Postgres only via `env()`); no `renameTable`, `remove-migration`, `database drop`, migration checksum verification, or command timeout.
111
+ - Health checks exist only for Postgres (`postgresSyncConnect.healthCheck`); nothing for MySQL/SQLite or on the context.
112
+ - The only public transaction wrapper is Postgres-specific `postgresSyncConnect.transaction(cb)` — reinforces Tier 1 #2 (make it engine-agnostic on the context).
113
+
114
+ These addenda raise two items into the "do first" bucket alongside concurrency/transactions: **FK constraint DDL** (EF's baseline referential integrity) and the **rename-as-drop+add migration diff** (silent data loss on apply).
115
+
116
+ ## Deliberately out of scope (EF features that don't map to a JS/SQLite-MySQL-PG ORM)
117
+
118
+ SQL Server vector type / `VECTOR_SEARCH` and JSON indexes, Azure Cosmos DB (full-text, hybrid search, transactional batches, session tokens), temporal tables, `System.Transactions`/ambient transactions, compiled models / Roslyn migration compilation, .NET-specific LINQ translations (`DateOnly`, `DateTimeOffset`, `UInt128`), PowerShell PMC tooling. Don't chase these.
119
+
120
+ ---
121
+
122
+ ## Recommended order
123
+
124
+ 1. **Optimistic concurrency + rows-affected check** (#1) and **explicit transactions** (#2) — they close the only remaining *silent-data-loss* class, and #2 is mostly wiring over existing engine code.
125
+ 2. **`executeUpdate`/`executeDelete`** (#3) — fixes the N+1 `bulkUpdate/bulkDelete` and gives set-based writes.
126
+ 3. **Global (named) query filters** (#4) + **context events/interceptors** (#10) — together they deliver EF's soft-delete/multi-tenant/audit recipes.
127
+ 4. **Logging/redaction** (#6) and **retry** (#5) — production hygiene; the PII-in-dev-logs default is worth fixing soon.
128
+ 5. **Migrations: transactional apply, script, status, --connection** (#7).
129
+ 6. **Query ergonomics** (#8, #9, #11): `find`, `entry()`, `thenInclude`, `thenBy`, `distinct`, aggregates, DTO `select`, `groupBy`; and immediately make the empty `join/groupBy` stubs fail loudly.
130
+ 7. **Modeling** (Tier 3): composite keys → many-to-many → JSON sub-object mapping → computed/default-SQL/check constraints → TPH.
131
+
132
+ Everything above follows EF's design directly; none of it requires inventing non-EF mechanisms.
@@ -60,6 +60,46 @@ context.User.where(u => $$.includes(u.id), [1, 2, 3]).toList();
60
60
  | `.include(lambda)` | Eager load relationships | `.include(u => u.Posts)` |
61
61
  | `.raw(sql)` | Execute raw SQL | `.raw("SELECT * FROM User")` |
62
62
 
63
+ ### Query & context methods added in 1.6–1.12 (Entity Framework parity)
64
+
65
+ | Method | EF Core equivalent | Description |
66
+ |--------|-------------------|-------------|
67
+ | `.find(pk)` / `.find(a, b)` / `.find({ a, b })` | `Find` | Identity-map first (no query if tracked), then database; composite keys (two+ `.primary()` columns = EF `HasKey(a, b)`) |
68
+ | `.include('p => p.tags').thenInclude('t => t.category')` | `Include().ThenInclude()` | Nested eager loading; split query (one batched query per level) |
69
+ | `.asSplitQuery()` (before `include()`) | `AsSplitQuery` | Each include loads as a separate batched query |
70
+ | `.any([lambda, ...args])` | `Any` | Does at least one row match? |
71
+ | `.sum(field)` / `.avg(field)` / `.min(field)` / `.max(field)` | `Sum/Average/Min/Max` | Aggregates over the filtered query (`sum` of nothing → 0, others → null) |
72
+ | `.thenBy(field)` / `.thenByDescending(field)` | `ThenBy` | Secondary sort keys after `orderBy` |
73
+ | `.distinct()` | `Distinct` | `SELECT DISTINCT` |
74
+ | `.groupBy('o => o.status').aggregate({ n: 'count', total: ['sum','amount'] }, { having, orderBy })` | `GroupBy` + `Select(g => new {…})` | `GROUP BY` / `HAVING` SQL; returns plain rows |
75
+ | `.toObjectList([options])` | projection | Plain-object results (not tracked) |
76
+ | `.pluck(field)` | — | One column, as a SQL projection |
77
+ | `.asNoTracking()` / `.asTracking()` | `AsNoTracking/AsTracking` | Per-query tracking control |
78
+ | `.ignoreQueryFilters([names])` | `IgnoreQueryFilters` | Skip global query filters |
79
+ | `.executeUpdate({...})` / `.executeDelete()` | `ExecuteUpdate/ExecuteDelete` | Set-based writes, no tracker |
80
+ | `.cache()`, `.last()`, `.exists()`, `.findById()`, `.count()`, `.removeRange()`, `.track()` | — | (existing, previously undocumented here) |
81
+ | `context.add(e)` / `remove(e)` / `addRange` / `removeRange` | `Add/Remove` | Context-level add/remove |
82
+ | `context.entry(e)` / `entries([model])` / `hasChanges()` | `Entry/Entries/HasChanges` | Change-tracker introspection |
83
+ | `await context.entry(e).load('nav')` / `context.loadNavigation(e, 'nav')` / `entry(e).isLoaded('nav')` | `Reference(n).Load()` / `Collection(n).Load()` | Explicit loading of belongsTo / hasOne / hasMany / hasManyThrough (any engine) |
84
+ | `await entity.nav` (lazy, default) / `.lazyLoadingOff()` → `null` until loaded | lazy loading | Unloaded navigation returns a Promise that loads once and caches; loaded reads are synchronous |
85
+ | `context.transaction(fn)` / `beginTransaction/commit/rollback` / savepoints | `Database.BeginTransaction` | Explicit transactions |
86
+ | `context.queryFilter(model, name, lambda, ...args)` | `HasQueryFilter` | Global (named) query filters |
87
+ | `context.on(event, fn)` | `SavingChanges`/interceptors | `savingChanges`, `savedChanges`, `saveChangesFailed`, `tracked`, `stateChanged`, `command`, `retry` |
88
+ | `context.setRetryOnFailure(opts)` | `EnableRetryOnFailure` | Transient-error retry |
89
+ | `await context.healthCheck()` / `await context.canConnect()` | `Database.CanConnect` / health check | `{ healthy, engine, latencyMs, version, … }`; never throws |
90
+ | `context.setQueryTrackingBehavior('no-track')` / `clearChangeTracker()` / `reset()` / `close()` | `QueryTrackingBehavior` / `ChangeTracker.Clear` / `Dispose` | Tracker lifetime |
91
+ | `db.rowVersion()` / `db.concurrencyToken()` (model builder) | `IsRowVersion` / `IsConcurrencyToken` | Optimistic concurrency (throws `ConcurrencyError`) |
92
+ | `db.belongsTo(...).onDelete('cascade'\|'restrict'\|'setNull'\|'noAction')` / `.excludeForeignKeyFromMigrations()` | `OnDelete` / EF 11 | FK constraint behavior |
93
+ | `db.defaultSql('CURRENT_TIMESTAMP')` | `HasDefaultValueSql` | Database-side default expression (read back after insert) |
94
+ | `db.computed('expr', { stored: true })` | `HasComputedColumnSql` | `GENERATED ALWAYS AS (expr) STORED\|VIRTUAL`; never written, read back after insert |
95
+ | `db.check('qty >= 0', 'CK_name')` | `HasCheckConstraint` | Column CHECK constraint |
96
+ | `db.owned(Address)` / `db.owned()` | `OwnsOne().ToJson()` / `ComplexProperty` | JSON column, hydrated class on read, nested mutations detected at save |
97
+ | `db.manyToMany('Tag', { through?, foreignKey?, otherKey? })` | `HasMany().WithMany()` (skip navigation) | Implicit join entity (`PostTag`) synthesized by the context |
98
+ | `ctx.dbset(Cat, { extends: Animal, discriminator?, value? })` | TPH (`HasDiscriminator().HasValue()`) | One table + discriminator; `ctx.Cat` filtered by type; `ctx.Animal` materializes derived types |
99
+ | `(await post.tags).add(tag)` / `.remove(tag)`; `entry(e).collection(nav).add/remove/load`; `entry(e).reference(nav).load` | `Collection(n).Add/Remove/Load`, `Reference(n).Load` | Tracked; persisted by `saveChanges()` |
100
+
101
+ Not yet supported (throw a clear error): `join()`, `leftJoin()`, `groupBy()`, `thenInclude` (nested include).
102
+
63
103
  ### Lambda Expression Functions
64
104
 
65
105
  | Function | Used Inside | Description | Example |
@@ -301,6 +301,15 @@ await this.createIndex({
301
301
 
302
302
  You can also declare these on the entity/context (`this.compositeIndex(Model, ['scope_id'], { unique: true, where: 'is_default = 1' })`) and `add-migration` will generate the call for you.
303
303
 
304
+ ### Removing a migration (EF `migrations remove`)
305
+
306
+ ```bash
307
+ masterrecord remove-migration AppContext # deletes the latest migration file (must be pending)
308
+ masterrecord remove-migration AppContext --force # applied? revert it (down, transactional) first, then delete
309
+ ```
310
+
311
+ Like Entity Framework, a migration that has already been applied to the database is refused unless `--force`, which runs its `down()` in its own transaction (via the same atomic step as `update-database`), removes its tracking row, updates the snapshot's `latestMigration`, and then deletes the file.
312
+
304
313
  ## Reliability & observability
305
314
 
306
315
  Migrations are designed to fail loudly and be observable — there are no silent no-ops:
@@ -406,8 +415,17 @@ masterrecord update-database <ContextName>
406
415
  masterrecord enable-migrations-all
407
416
  masterrecord add-migration-all <MigrationName>
408
417
  masterrecord update-database-all
418
+
419
+ # Inspect without changing anything
420
+ masterrecord migrations-status <ContextName> # applied (with timestamps) vs pending
421
+ masterrecord script <ContextName> [-o file.sql] # SQL for pending migrations, NOT applied (DBA review)
422
+
423
+ # Override the connection for one run (JSON, optionally keyed by context name)
424
+ masterrecord update-database <ContextName> --connection '{"type":"sqlite","connection":"./tmp/"}'
409
425
  ```
410
426
 
427
+ Each migration is applied **atomically** (its DDL and its tracking-table row commit or roll back together) on SQLite and PostgreSQL; MySQL DDL implicitly commits, so a failed MySQL migration may leave earlier statements of that migration applied — re-run after fixing. A generated migration for a removed+added column with the same definition carries a `// POSSIBLE RENAME` advisory with the `renameColumn(...)` call to use instead of the data-destroying drop+add (like EF, renames are never guessed).
428
+
411
429
  `update-database` applies **every pending migration** in timestamp order (not
412
430
  just the latest file) and records each after it succeeds, so re-running it is a
413
431
  no-op. `update-database-all` does the same for **every context in the project**:
package/errors.js ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Shared error types that must be importable by both the context and its
3
+ * collaborators (insert/delete managers, engines) without creating an import
4
+ * cycle through context.js.
5
+ */
6
+
7
+ /**
8
+ * Thrown by saveChanges() when an UPDATE or DELETE affected 0 rows — the row
9
+ * was modified or deleted by someone else since this context loaded it
10
+ * (optimistic concurrency conflict), or a concurrency-token value no longer
11
+ * matches. Equivalent to EF Core's DbUpdateConcurrencyException.
12
+ *
13
+ * `entries` holds the entities whose writes were rejected so the caller can
14
+ * resolve the conflict (reload and retry, client-wins, database-wins, merge).
15
+ * The transaction is rolled back; the entities stay tracked and dirty.
16
+ */
17
+ class ConcurrencyError extends Error {
18
+ constructor(message, entries = [], details = {}) {
19
+ super(message);
20
+ this.name = 'ConcurrencyError';
21
+ this.code = 'MR_CONCURRENCY_CONFLICT';
22
+ this.entries = Array.isArray(entries) ? entries : [entries];
23
+ this.details = details;
24
+ if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
25
+ }
26
+ }
27
+
28
+ export { ConcurrencyError };
package/insertManager.js CHANGED
@@ -95,6 +95,13 @@ class InsertManager {
95
95
  currentModel[primaryKey] = SQL.id;
96
96
  }
97
97
 
98
+ // Database-generated values — computed columns (EF HasComputedColumnSql)
99
+ // and defaults the entity left unset (HasDefaultValue / HasDefaultValueSql)
100
+ // — are read back so the in-memory entity reflects the stored row (EF
101
+ // fetches generated values after SaveChanges). Without this a later
102
+ // "mark everything modified" update would write NULL over a DB default.
103
+ await this._readBackGeneratedColumns(currentModel, modelEntity, primaryKey);
104
+
98
105
  const proto = Object.getPrototypeOf(currentModel);
99
106
  const props = Object.getOwnPropertyNames(proto);
100
107
  const cleanPropList = tools.returnEntityList(props, modelEntity);
@@ -162,6 +169,43 @@ class InsertManager {
162
169
  return cleanCurrentModel;
163
170
  }
164
171
 
172
+ /**
173
+ * After INSERT, load database-generated (computed) column values onto the
174
+ * entity. Engine-agnostic: goes through the context's query builder.
175
+ * @private
176
+ */
177
+ async _readBackGeneratedColumns(currentModel, modelEntity, primaryKey) {
178
+ const isUnset = (v) => v === undefined || v === null || typeof v === 'function';
179
+ const computedCols = Object.keys(modelEntity).filter(k => {
180
+ const f = modelEntity[k];
181
+ if (!f || typeof f !== 'object' || k.startsWith('__')) return false;
182
+ if (f.computedSql) return true;
183
+ const hasDbDefault = (f.defaultSql !== undefined && f.defaultSql !== null) || (f.default !== undefined && f.default !== null);
184
+ return hasDbDefault && isUnset(tools.dataValue(currentModel, k));
185
+ });
186
+ if (computedCols.length === 0) return;
187
+ const ctx = currentModel.__context;
188
+ const dbset = ctx && modelEntity.__name ? ctx[modelEntity.__name] : null;
189
+ const pkVal = currentModel[primaryKey];
190
+ if (!dbset || typeof dbset.asNoTracking !== 'function' || pkVal === undefined || pkVal === null) return;
191
+ if (!this._isValidIdentifier(primaryKey)) return;
192
+ // (all columns of a composite key)
193
+ const keys = tools.primaryKeys(modelEntity);
194
+ let q = dbset.asNoTracking();
195
+ for (let i = 0; i < keys.length; i++) {
196
+ if (!this._isValidIdentifier(keys[i])) return;
197
+ const v = i === 0 ? pkVal : tools.dataValue(currentModel, keys[i]);
198
+ if (v === undefined || v === null) return;
199
+ q = i === 0 ? q.where(`r => r.${keys[i]} == $$`, v) : q.and(`r => r.${keys[i]} == $$`, v);
200
+ }
201
+ const rows = await q.toObjectList();
202
+ const row = rows && rows[0];
203
+ if (!row) return;
204
+ for (const col of computedCols) {
205
+ if (row[col] !== undefined) currentModel[col] = row[col];
206
+ }
207
+ }
208
+
165
209
  /**
166
210
  * Process hasOne relationship
167
211
  *
@@ -258,6 +302,14 @@ class InsertManager {
258
302
  );
259
303
  }
260
304
 
305
+ // EF 5+ skip navigation (manyToMany): the array holds TARGET entities
306
+ // (or their keys), not join rows — insert new targets first, then one
307
+ // join row per element.
308
+ if (entityProperty.implicitJoin) {
309
+ await this._processImplicitManyToMany(propertyModel, entityProperty, property, currentModel, SQL);
310
+ return;
311
+ }
312
+
261
313
  const propertyKeys = Object.keys(propertyModel);
262
314
  for (const propertykey of propertyKeys) {
263
315
  if (!propertyModel[propertykey]) {
@@ -301,6 +353,53 @@ class InsertManager {
301
353
  * @param {string} targetName - Target entity name
302
354
  * @returns {object|null} Resolved entity or null
303
355
  */
356
+ /**
357
+ * manyToMany() on insert: `post.tags = [tagEntity, tagId, { label: 'new' }]`.
358
+ * Persisted targets are referenced by key; new ones are inserted first
359
+ * (EF cascade insert); then a join row per element.
360
+ * @private
361
+ */
362
+ async _processImplicitManyToMany(propertyModel, entityProperty, property, currentModel, SQL) {
363
+ const joinDef = this._resolveEntityWithFallback(property, entityProperty.foreignTable);
364
+ const targetDef = this._resolveEntityWithFallback(property, entityProperty.targetTable);
365
+ if (!joinDef || !targetDef) {
366
+ throw new RelationshipError(
367
+ `manyToMany '${property}': join entity '${entityProperty.foreignTable}' or target '${entityProperty.targetTable}' is not registered on the context.`,
368
+ property, { joinTable: entityProperty.foreignTable, target: entityProperty.targetTable }
369
+ );
370
+ }
371
+ const isBt = (c) => c && typeof c === 'object' && c.relationshipType === 'belongsTo';
372
+ const toThisField = Object.keys(joinDef).find(k => !k.startsWith('__') && isBt(joinDef[k]) && joinDef[k].foreignKey === entityProperty.joinForeignKey);
373
+ const toTargetField = Object.keys(joinDef).find(k => !k.startsWith('__') && isBt(joinDef[k]) && joinDef[k].foreignKey === entityProperty.joinOtherKey);
374
+ if (!toThisField || !toTargetField) {
375
+ throw new RelationshipError(`manyToMany '${property}': join entity '${joinDef.__name}' lacks belongsTo fields for '${entityProperty.joinForeignKey}' / '${entityProperty.joinOtherKey}'.`, property, {});
376
+ }
377
+ const ownerPkName = tools.getPrimaryKeyObject(currentModel.__entity);
378
+ const ownerKeyRaw = tools.dataValue(currentModel, ownerPkName);
379
+ const ownerKey = (ownerKeyRaw === undefined || ownerKeyRaw === null || typeof ownerKeyRaw === 'function') ? SQL.id : ownerKeyRaw;
380
+ const targetPkName = tools.getPrimaryKeyObject(targetDef);
381
+ for (const key of Object.keys(propertyModel)) {
382
+ const el = propertyModel[key];
383
+ if (el === undefined || el === null) continue;
384
+ let targetKey;
385
+ if (typeof el !== 'object') {
386
+ targetKey = el;
387
+ } else {
388
+ targetKey = tools.dataValue(el, targetPkName);
389
+ if (targetKey === undefined || targetKey === null || typeof targetKey === 'function') {
390
+ el.__entity = targetDef; // new target: insert it first
391
+ await this.runQueries(el);
392
+ targetKey = tools.dataValue(el, targetPkName);
393
+ }
394
+ }
395
+ const row = {};
396
+ row[toThisField] = ownerKey;
397
+ row[toTargetField] = targetKey;
398
+ row.__entity = joinDef;
399
+ await this.runQueries(row);
400
+ }
401
+ }
402
+
304
403
  _resolveEntityWithFallback(property, targetName) {
305
404
  // Try: exact match → capitalized → property name
306
405
  return tools.getEntity(targetName, this._allEntities)
@@ -338,6 +437,16 @@ class InsertManager {
338
437
 
339
438
  // check if model is an object. If so insert the child first then the parent.
340
439
  if (typeof newPropertyModel === 'object' && newPropertyModel !== null) {
440
+ // An already-persisted principal (tracked entity with a key, not
441
+ // pending insert) is NOT re-inserted — EF fix-up: just take its key.
442
+ if (newPropertyModel.__entity && newPropertyModel.__state !== 'insert') {
443
+ const parentPk = tools.getPrimaryKeyObject(newPropertyModel.__entity);
444
+ const parentPkVal = parentPk ? tools.dataValue(newPropertyModel, parentPk) : undefined;
445
+ if (parentPkVal !== undefined && parentPkVal !== null && typeof parentPkVal !== 'function') {
446
+ currentModel[foreignKey] = parentPkVal;
447
+ continue;
448
+ }
449
+ }
341
450
  newPropertyModel.__entity = tools.getEntity(entity, this._allEntities);
342
451
  const propertyCleanCurrentModel = tools.clearAllProto(newPropertyModel);
343
452
  this.validateEntity(propertyCleanCurrentModel, newPropertyModel, newPropertyModel.__entity);