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/CHANGES.md +225 -0
- package/Cache/QueryCache.js +5 -14
- package/Entity/entityModel.js +171 -0
- package/Entity/entityTrackerModel.js +93 -125
- package/MasterRecord.js +11 -0
- package/Migrations/cli.js +252 -6
- package/Migrations/ddlClauses.js +86 -0
- package/Migrations/migrationMySQLQuery.js +26 -7
- package/Migrations/migrationPostgresQuery.js +32 -8
- package/Migrations/migrationSQLiteQuery.js +42 -8
- package/Migrations/migrationTemplate.js +24 -0
- package/Migrations/migrations.js +72 -1
- package/Migrations/schema.js +183 -4
- package/QueryLanguage/queryMethods.js +488 -38
- package/QueryLanguage/rawSql.js +41 -0
- package/SQLLiteEngine.js +188 -61
- package/Tools.js +73 -0
- package/context.js +1372 -98
- package/deleteManager.js +26 -3
- package/docs/CHANGE_TRACKING_AND_CONTEXT_LIFETIME.md +146 -1
- package/docs/EF_CORE_GAP_ANALYSIS.md +132 -0
- package/docs/METHODS_REFERENCE.md +40 -0
- package/docs/MIGRATIONS_GUIDE.md +18 -0
- package/errors.js +28 -0
- package/insertManager.js +109 -0
- package/logging.js +109 -0
- package/mySQLEngine.js +0 -0
- package/package.json +6 -2
- package/postgresEngine.js +142 -27
- package/resilience.js +68 -0
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,230 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
+
## v1.22.0 — owned / complex types as JSON (EF Core `OwnsOne(...).ToJson()` / `ComplexProperty`)
|
|
4
|
+
|
|
5
|
+
- **`db.owned(Address)`** stores the value as JSON in one column and **hydrates it into the class on read**; **`db.owned()`** for plain objects/arrays. Serialization is automatic (a custom `transform()` still wins).
|
|
6
|
+
- **Nested mutations are detected at `saveChanges()`** — `user.address.city = 'Paris'` or `prefs.tags.push('x')` never touch a column setter, so the context compares the serialized value with the loaded one (EF `DetectChanges` on complex properties) and writes only when it differs; replacing the whole value or setting `null` works as before.
|
|
7
|
+
|
|
8
|
+
New tests: `test/owned-types.test.js`.
|
|
9
|
+
|
|
10
|
+
## v1.21.0 — `groupBy().aggregate()` (EF Core GroupBy + Select(g => new { g.Key, g.Count(), g.Sum(…) }))
|
|
11
|
+
|
|
12
|
+
- **`groupBy('o => o.status'[, 'region'…]).aggregate({ n: 'count', total: ['sum', 'amount'], avg: ['avg', 'amount'] }, { having: { n: ['>', 1] }, orderBy: [['total', 'desc']] })`** → `[{ status, region?, n, total, avg }]`, translated to `SELECT <groups>, <aggregates> … GROUP BY … [HAVING …] [ORDER BY …] [LIMIT/OFFSET]` on SQLite, MySQL and Postgres. `where()/and()`, global query filters (and `ignoreQueryFilters()`), `take()/skip()` apply to the groups. Aggregates: `count`, `sum`, `avg`, `min`, `max`; `having` operators `==, !=, >, >=, <, <=` (parameterized); identifiers are validated, unknown columns/aggregates/aliases fail loudly. `groupBy()` used to throw "not supported".
|
|
13
|
+
- `join()` / `leftJoin()` remain unsupported by design — `include()`/`thenInclude()` cover relationship loading; use `ctx.query()` for hand-written joins.
|
|
14
|
+
|
|
15
|
+
New tests: `test/group-by.test.js`.
|
|
16
|
+
|
|
17
|
+
## v1.20.0 — composite primary keys (EF Core `HasKey(a, b)`)
|
|
18
|
+
|
|
19
|
+
- **Two or more `.primary()` columns form a composite key.** DDL on all three engines emits a table-level `PRIMARY KEY (a, b)` (key columns NOT NULL, no inline PRIMARY KEY / auto-increment; an `auto()` column inside a composite key is rejected, as EF rejects identity columns there).
|
|
20
|
+
- **UPDATE and DELETE address the row by every key column** (the extra key columns ride in the WHERE like concurrency tokens); bulk deletes of composite-key entities run per row (a `WHERE IN` on one column cannot address them); rows-affected checks still apply.
|
|
21
|
+
- **`find(a, b)` / `find({ a, b })` / `findById(a, b)`** (EF `Find(a, b)`), identity-map first; `reload()`, `entry().getDatabaseValues()` and the post-insert read-back of generated columns use every key. Wrong arity fails with a clear message naming the key columns.
|
|
22
|
+
- Not supported (documented): FKs *to* a composite-key entity and `manyToMany()` owners with composite keys.
|
|
23
|
+
|
|
24
|
+
New tests: `test/composite-keys.test.js`.
|
|
25
|
+
|
|
26
|
+
## v1.19.0 — table-per-hierarchy inheritance (EF Core's default inheritance mapping)
|
|
27
|
+
|
|
28
|
+
- **`dbset(Cat, { extends: Animal })`** maps a derived model onto its base's table (TPH). The hierarchy table gains a **discriminator column** (`discriminator` by default, values = model names — EF's convention; override with `{ discriminator, value }`) and the derived models' own columns (nullable — rows of other types leave them NULL). Migrations see **one table**; base rows carry the base name.
|
|
29
|
+
- **`ctx.Cat` / `ctx.Dog`** query the base table with the discriminator predicate — part of the type mapping, so `ignoreQueryFilters()` never removes it (EF) — and **inserts / `.new()` stamp the discriminator**; updates, `count`, `executeUpdate/Delete`, `find` etc. all scope to the type. **Base-type global query filters apply to derived sets** (EF), and a derived set can have its own.
|
|
30
|
+
- **`ctx.Animal` returns the whole hierarchy, each row materialized as its derived type** (a Cat read through the Animal set has `lives` and `__entity.__tph.value === 'Cat'`), so updating it persists as a Cat.
|
|
31
|
+
- Misuse fails loudly: derived registered before its base, a derived type declaring its own primary key, conflicting discriminator column names.
|
|
32
|
+
|
|
33
|
+
New tests: `test/tph-inheritance.test.js` (model/DDL/migrations single table; insert via derived/base/.new(); filtered derived queries; base set materialization; updates through both; base filter on derived; set-based delete per type; misuse).
|
|
34
|
+
|
|
35
|
+
## v1.18.0 — global query filters inside include() (EF HasQueryFilter on navigations, IgnoreQueryFilters for the whole query)
|
|
36
|
+
|
|
37
|
+
- **Included navigations honor the target entity's global query filters** (soft delete, tenant…), as in EF Core: `include()` of a navigation whose target has active filters loads through the split loader, whose dbset queries apply them; lazy/explicit loading already did. A filtered-out `belongsTo` parent reads `null`.
|
|
38
|
+
- **`ignoreQueryFilters()` / `ignoreQueryFilters([names])` on the root query propagate to every included level** (EF: `IgnoreQueryFilters` applies to the whole query), including `thenInclude()` levels.
|
|
39
|
+
- Previously only the root entity was filtered; the joined (SQL) include returned soft-deleted / foreign-tenant rows.
|
|
40
|
+
- **SQLite: boolean (and Date / undefined) query parameters are now bindable** — `where('x => x.flag == $$', true)` and boolean query filters threw `SQLite3 can only bind numbers, strings, bigints, buffers, and null`; every statement now normalizes `true/false → 1/0`, `undefined → NULL`, `Date → ISO` (MySQL/Postgres already accepted them).
|
|
41
|
+
|
|
42
|
+
New tests: `test/include-query-filters.test.js`.
|
|
43
|
+
|
|
44
|
+
## v1.17.0 — `thenInclude()` and `asSplitQuery()` (EF Core ThenInclude / AsSplitQuery)
|
|
45
|
+
|
|
46
|
+
- **`include('p => p.tags').thenInclude('t => t.category')`** (chain `thenInclude()` again for deeper levels): implemented as EF's **split query** — after the main query, **one batched query per navigation level** (`IN` on the parent keys, chunked by 500), on every engine; no cartesian explosion, no N+1. Works for belongsTo, hasOne, hasMany, hasManyThrough and manyToMany at any depth; `single()`/`first()` run it too. Levels already hydrated by the eager (SQL) `include()` are reused; the rest are batch-loaded.
|
|
47
|
+
- **`asSplitQuery()`** (call before `include()`): every `include()` of the query loads as a separate batched query instead of one joined statement (EF `AsSplitQuery`). Bare navigation names (`include('author')`) are accepted alongside lambdas.
|
|
48
|
+
- **`include()` of an implicit many-to-many navigation** (`manyToMany()`) goes through the split loader automatically.
|
|
49
|
+
- Loaded collections keep EF's `add()/remove()`; a loaded reference with no related row is `null` (EF) and is **not** lazy-loaded again — `null` in the navigation slot now means "loaded, nothing there", `undefined` means "not loaded".
|
|
50
|
+
- Low-level: `ctx.__batchLoadNavigation(parents, nav)`.
|
|
51
|
+
|
|
52
|
+
New tests: `test/then-include.test.js` (manyToMany → belongsTo with exactly 4 SELECTs for N posts; asSplitQuery hasMany → manyToMany → belongsTo with 5 SELECTs; batched belongsTo include; single()/first(); misuse errors).
|
|
53
|
+
|
|
54
|
+
## v1.16.0 — many-to-many skip navigations (EF Core 5+ `HasMany().WithMany()`) + collection Add/Remove
|
|
55
|
+
|
|
56
|
+
- **`db.manyToMany('Tag')`**: the context **synthesizes the implicit join entity** (EF convention: the two entity names in alphabetical order, e.g. `PostTag`) with an auto primary key, `belongsTo()` to both sides (`post_id`, `tag_id`, FK constraints with ON DELETE CASCADE) and a **unique composite index** — registered through `dbset()` so table prefix, FK type resolution, migrations/snapshot, `ctx.PostTag` and the query builders all see it. Declaring the navigation on both sides maps to the same join entity. Options: `{ through, foreignKey, otherKey }` (self-referencing must pass both keys, as EF names them after the navigations).
|
|
57
|
+
- **Insert:** `post.tags = [tagEntity, tagId, { label: 'new' }]` — persisted targets are linked by key, **new targets are inserted first** (EF cascade insert), then one join row per element.
|
|
58
|
+
- **Load:** `await post.tags`, `ctx.entry(post).collection('tags').load()`, reverse side `await tag.posts` — join → targets, parameterized, every engine.
|
|
59
|
+
- **Collections have EF's `add()` / `remove()`** (non-enumerable, JSON-safe) on loaded `hasMany` and `hasManyThrough`/`manyToMany` navigations, plus `ctx.entry(e).collection(nav)` (`load`, `isLoaded`, `add`, `remove`) and `ctx.entry(e).reference(nav)` (`load`, `isLoaded`) — EF's `Entry(e).Collection(n)` / `Reference(n)`. `add()` tracks a join row (or sets the child's FK; new targets/children are added to the tracker), `remove()` schedules the join row for DELETE (or NULLs a nullable FK / deletes an orphan of a required relationship, like EF); nothing hits the database until `saveChanges()`. Duplicate links fail at save on the unique index (EF throws too). Low-level: `ctx.linkNavigation(owner, nav, item)` / `ctx.unlinkNavigation(owner, nav, item)`.
|
|
60
|
+
- Explicit `hasManyThrough` navigations gain the same collection API; `_joinSides()` resolves both FK sides (explicit keys first, then by table).
|
|
61
|
+
|
|
62
|
+
New tests: `test/many-to-many.test.js` (synthesis once for both sides + model/migrations visibility; insert by entity/id/new object; lazy + explicit load both ways; add/remove incl. new target; duplicate rejected; cascade delete of join rows only; hasMany collection add/remove with nullable FK).
|
|
63
|
+
|
|
64
|
+
## v1.15.0 — health checks on every engine + `remove-migration` (EF `migrations remove`)
|
|
65
|
+
|
|
66
|
+
- **`await context.healthCheck()`** → `{ healthy, engine, latencyMs, version, … }` on SQLite, MySQL and Postgres (pool counters / server time where the driver exposes them); **never throws** — on failure `{ healthy: false, engine, error }`. **`await context.canConnect()`** (EF `Database.CanConnect()`). Previously only the Postgres sync-connect helper had a health check.
|
|
67
|
+
- **`masterrecord remove-migration <context>`** (alias `rm`; EF `dotnet ef migrations remove`): deletes the latest migration file. Like EF it **refuses an applied migration** with instructions, unless **`--force`**, which reverts it first (down, in its own transaction via the atomic step) and updates the snapshot's `latestMigration` to the previous applied one. A pending migration is simply deleted — the snapshot needs no rewrite because masterrecord's snapshot reflects the *applied* database state.
|
|
68
|
+
|
|
69
|
+
New tests: `test/health-check.test.js`, `remove-migration` cases in `test/migrations-tooling.test.js`.
|
|
70
|
+
|
|
71
|
+
## v1.14.0 — DDL modeling parity: defaultSql / computed / check (EF HasDefaultValueSql, HasComputedColumnSql, HasCheckConstraint)
|
|
72
|
+
|
|
73
|
+
Closes the Tier-3 "computed columns / default SQL / check constraints" gap on all three engines.
|
|
74
|
+
|
|
75
|
+
- **`db.defaultSql('CURRENT_TIMESTAMP')`** (EF `HasDefaultValueSql`): a database-side default *expression*, emitted verbatim (parenthesized when it is not a literal/`CURRENT_*`; on MySQL always parenthesized except literals, because masterrecord maps temporal types to TEXT and MySQL only accepts expression defaults there). Postgres `alterColumn` emits `SET DEFAULT (expr)`. The SQLite schema sync compares the stored expression so a `defaultSql` column no longer looks "changed" on every run.
|
|
76
|
+
- **`db.computed('CAST(ROUND(price * 100) AS INTEGER)', { stored })`** (EF `HasComputedColumnSql`): renders `GENERATED ALWAYS AS (expr) STORED|VIRTUAL` (Postgres: STORED only). The ORM **never writes** a computed column — it is skipped on INSERT and UPDATE in all three engines, even when `entry(e).state = 'modified'` marks everything — and its value is **read back onto the entity after INSERT** (EF fetches generated values after `SaveChanges`). SQLite introspection now uses `PRAGMA table_xinfo` so generated columns are seen by schema sync (`table_info` hides them); adding a computed column to an existing SQLite table rebuilds it (SQLite cannot `ADD` a STORED generated column — EF's SQLite provider rebuilds too), and the rebuild's data copy excludes generated columns.
|
|
77
|
+
- **`db.check('qty >= 0', 'CK_Product_qty')`** (EF `HasCheckConstraint`): `[CONSTRAINT name] CHECK (expr)` on the column, all engines; violations surface as the engine's constraint error on `saveChanges()`.
|
|
78
|
+
- **DB defaults are read back after INSERT** when the entity left the column unset (`default()` / `defaultSql()`), so a later full `Update()` writes the real value instead of NULL over the database default.
|
|
79
|
+
- Contradictory modeling (`computed()` + `default()`/`defaultSql()`/primary/auto) fails loudly, naming the column.
|
|
80
|
+
- **Bug fixed (1.12.0):** `entry(e).state = 'modified'` marked entity metadata (`__compositeIndexes`) as a dirty column (`no such column: __compositeIndexes`) and used the FK *column* name for `belongsTo` fields, which the engines could not resolve. New `_scalarFields()` marks exactly the writable fields.
|
|
81
|
+
- Shared `Migrations/ddlClauses.js` renders the clauses for SQLite / MySQL / Postgres identically.
|
|
82
|
+
|
|
83
|
+
New tests: `test/ddl-modeling.test.js` (all three builders: DEFAULT expr / GENERATED ALWAYS AS STORED|VIRTUAL / CHECK with and without name, Postgres STORED-only and `SET DEFAULT (expr)`, contradictory options; SQLite end-to-end: default applied, computed derived + read back + never written on INSERT/UPDATE incl. full `Update()`, recomputed, DB default preserved, CHECK enforced, schema sync sees the generated column and is idempotent without losing rows).
|
|
84
|
+
|
|
85
|
+
## v1.13.0 — navigation loading done the EF way (explicit/lazy loading, fix-up) + async query cache
|
|
86
|
+
|
|
87
|
+
Closes the three "outright bugs" from the EF gap analysis addendum.
|
|
88
|
+
|
|
89
|
+
- **Explicit loading** (EF `Entry(e).Reference(n).Load()` / `Collection(n).Load()`): `await ctx.entry(e).load('nav')`, `ctx.loadNavigation(e, 'nav')`, `ctx.entry(e).isLoaded('nav')` / `ctx.isNavigationLoaded(e, 'nav')`. Works for `belongsTo`, `hasOne`, `hasMany` and `hasManyThrough` on **every engine**, through the normal parameterized query builder (the old getter issued SQLite-shaped SQL with the key *value* interpolated into the lambda — a string key with a quote broke it, and it was an injection surface).
|
|
90
|
+
- **Lazy loading adapted to async drivers:** reading an unloaded navigation with lazy loading on (default) returns a Promise that loads it **once** and caches it (`await post.author`); after that (or after `include()`/explicit load) the read is synchronous. With `lazyLoadingOff()` an unloaded navigation reads `null` (EF). Errors are thrown, not returned as strings. An un-awaited lazy read can no longer crash the process with an unhandled rejection.
|
|
91
|
+
- **Relationship fix-up (EF):** `post.author = someAuthor` sets `post.author_id` and marks the entity dirty; changing `post.author_id` invalidates a previously loaded `post.author` so the next read re-resolves instead of returning a stale parent; the legacy idiom `post.author = authorId` still works and keeps the FK column in sync.
|
|
92
|
+
- **Engines never persist a navigation object.** All three engines read the FK value for a `belongsTo` field through one helper (`Tools.foreignKeyValue`) — an assigned entity → its key, an assigned primitive, or the FK column — and never through the navigation getter. Previously a loaded navigation (or the lazy Promise) could leak into the UPDATE (`Type mismatch … got object`), and invoking the getter on the engines' derived clean model wrote the lazily-loaded parent as an own property on the real entity, shadowing the slot (saves then wrote the *old* key).
|
|
93
|
+
- **Inserts** accept a parent entity, an id on the navigation, or the FK column, on plain `new Model()`, `.new()` and `add()`-ed objects; an already-persisted parent assigned to a `.new()` entity is no longer re-INSERTed (`INSERT failed: No columns to insert`) — its key is used (EF fix-up). `.new()` no longer assigns a random `__ID` (same identity-map collision class fixed for queried entities in 1.5.12).
|
|
94
|
+
- **`RedisQueryCache` actually works:** `.cache()` reads now `await` the cache `get()`, so an async cache returns the entity rather than a Promise-of-entity being treated as a hit.
|
|
95
|
+
|
|
96
|
+
New tests: `test/navigation-loading.test.js` (lazy belongsTo via a string PK containing a quote, caching, fix-up on entity assignment and persisted FK; explicit `entry().load()` for hasMany/hasOne/hasManyThrough incl. empty; `lazyLoadingOff()` → null then explicit load; FK-column change invalidating a loaded parent; legacy id assignment; inserts via entity/id/FK column on plain and `.new()` objects). Full suite green (0 fail, 370 pass, 20 gated skipped); 0 lint errors.
|
|
97
|
+
|
|
98
|
+
## v1.12.0 — query & change-tracker ergonomics (EF Find, Entry, aggregates, ThenBy, Distinct, Any, context.Add/Remove)
|
|
99
|
+
|
|
100
|
+
Closes gap-analysis #8, #9 and most of #11.
|
|
101
|
+
|
|
102
|
+
- **`ctx.Model.find(pk)`** (EF `Find`): checks the identity map first and returns the tracked instance **without a query**; otherwise loads (and tracks). `findById` remains the always-query form.
|
|
103
|
+
- **`ctx.entry(entity)`** (EF `DbContext.Entry`): `state` (get/set: `track`/`modified`/`insert`/`delete`/`detached`; setting `modified` with no dirty fields marks every column like EF `Update()`), `originalValues`, `currentValues`, `isModified(field?)`, `reload()`, `getDatabaseValues()` (live row, ignores query filters, doesn't touch the entity), `detach()`. **`ctx.hasChanges()`** (EF `ChangeTracker.HasChanges`) and **`ctx.entries([model])`** (EF `ChangeTracker.Entries`).
|
|
104
|
+
- **Aggregates `sum/avg/min/max(field)`** on any query (EF `Sum/Average/Min/Max`), honoring `where`/`and` and global query filters; `sum` of no rows is `0`, the others `null`. Engines gain `getAggregate`.
|
|
105
|
+
- **`thenBy(field|lambda)` / `thenByDescending`** (EF `ThenBy`): secondary sort keys with independent directions on all three engines; **`distinct()`** (EF `Distinct` → `SELECT DISTINCT`); **`any([predicate, ...args])`** (EF `Any`) — the readme documented `.any()` for years but it never existed; **`toObjectList(options)`** (plain-object DTO list, not tracked).
|
|
106
|
+
- **`pluck(field)` is now a SQL projection** (`SELECT <field>` with no tracking) instead of loading full entities and mapping in JS.
|
|
107
|
+
- **`ctx.add(entity)` / `ctx.remove(entity)` / `addRange` / `removeRange`** (EF `DbContext.Add/Remove`) — the readme documented `context.remove(entity)` which did not exist; they resolve the owning dbset by entity metadata or constructor name.
|
|
108
|
+
- **`join()`, `groupBy()`, `leftJoin()` now throw a clear `not supported yet` error** with the alternative to use — they were empty bodies returning `undefined`, so chaining off them threw a bare `TypeError`.
|
|
109
|
+
- Not in this release (documented limitation): `thenInclude`, `groupBy`/`join` translation.
|
|
110
|
+
|
|
111
|
+
New tests: `test/query-ergonomics.test.js` (identity-map `find` with no SQL; entry state/original/current/isModified/getDatabaseValues/detach, hasChanges, entries; aggregates incl. empty-set semantics and invalid column; orderBy+thenBy/thenByDescending ordering, distinct, any, toObjectList, pluck selects only its column; context add/remove; loud stubs). Full suite green (0 fail, 366 pass, 20 gated skipped); 0 lint errors.
|
|
112
|
+
|
|
113
|
+
## v1.11.0 — migrations tooling: atomic apply, `script`, `migrations-status`, `--connection`, latest-migration id (EF parity)
|
|
114
|
+
|
|
115
|
+
Closes gap-analysis #7.
|
|
116
|
+
|
|
117
|
+
- **Each migration now applies atomically** (EF Core: one transaction per migration). The migration's DDL/DML **and its tracking-table row** commit or roll back together, so a failing migration can no longer leave a half-applied schema. PostgreSQL: `BEGIN…COMMIT`. SQLite: transactional too, with FK enforcement switched off *before* the transaction and restored after (SQLite's `PRAGMA foreign_keys` is a no-op inside a transaction and the table-rebuild path depends on it — exactly EF's SQLite approach). MySQL: DDL implicitly commits, so atomicity isn't possible there (EF documents the same); it runs as before. Used by `update-database` and `update-database-all`.
|
|
118
|
+
- **`masterrecord script <ctx> [-o file]`** (EF `migrations script`): prints the SQL that `update-database` *would* run for pending migrations — DDL plus the tracking-table insert, per migration — **without applying anything**. Introspection still runs against the live database so the plan is accurate; execution is captured instead of performed.
|
|
119
|
+
- **`masterrecord migrations-status <ctx>`** (EF `migrations list`): applied migrations with timestamps, pending ones, recorded-but-missing files, and the snapshot's latest migration.
|
|
120
|
+
- **`--connection <json>`** global option (EF `--connection`): a JSON connection config (optionally keyed by context name) overriding the environment file for that run, e.g. `update-database AppContext --connection '{"type":"sqlite","connection":"./tmp/"}'`. Honored by `context.env()` via `MASTERRECORD_CONNECTION_OVERRIDE`.
|
|
121
|
+
- **Snapshot records `latestMigration`** (EF 11): two branches that each add a migration now conflict on merge, surfacing a divergent migration tree instead of silently diverging.
|
|
122
|
+
- Internals: `__applyMigrationStep`, `__resolveMigrationPlan`, `__getAppliedMigrationRows` helpers in the CLI.
|
|
123
|
+
|
|
124
|
+
New tests: `test/migrations-tooling.test.js` (status before/after + snapshot latest id; `script` emits DDL + tracking insert and leaves the DB untouched, `--output` file; a failing migration is rolled back atomically with nothing recorded; `--connection` override creates the DB at the overridden location). Full suite green (0 fail, 360 pass, 20 gated skipped); 0 lint errors.
|
|
125
|
+
|
|
126
|
+
## v1.10.0 — pluggable logging with parameter redaction (EF LogTo/EnableSensitiveDataLogging) + retry on transient failures (EF EnableRetryOnFailure)
|
|
127
|
+
|
|
128
|
+
Closes gap-analysis #5 (resiliency) and #6 (logging/diagnostics), the way EF Core does them.
|
|
129
|
+
|
|
130
|
+
**Logging (`logging.js`, `masterrecord.configureLogging(...)`)**
|
|
131
|
+
- **Behavior change (security):** SQL is **no longer logged by default**. Previously every SQL statement **with its parameter values** was printed whenever `NODE_ENV !== 'production'` — PII and secrets in dev logs. Like EF, nothing is logged unless you ask (`configureLogging({ logSql: true })` or `LOG_SQL=true`), and **parameter values are redacted to `?` by default** — opt in with `sensitiveData: true` / `MR_SENSITIVE_LOGGING=true` (EF `EnableSensitiveDataLogging`).
|
|
132
|
+
- Pluggable `logger` (`{ debug, info, warn, error }`, default `console`) and min `level`; `slowQueryMs` warns on slow commands **even when SQL logging is off** (`MR_SLOW_QUERY_MS`); migration DDL logged at `info` unless `migrations: false` / `MR_SILENT_MIGRATIONS=true`; failed commands logged at `error` with duration.
|
|
133
|
+
- All three engines route **every** command (reads, writes, DDL, raw) through one timed path that feeds the logger and the `command` event; the SQLite no-param `_execute` path (previously unobserved) is included. Query-cache debug chatter now goes through the logger at `debug` instead of `console.debug` in non-production.
|
|
134
|
+
- `masterrecord.getLoggingConfig()`; exports `masterrecord/logging`.
|
|
135
|
+
|
|
136
|
+
**Connection resiliency (`resilience.js`, `ctx.setRetryOnFailure(...)`, `masterrecord.configureRetry(...)`)**
|
|
137
|
+
- Retries operations on **transient** errors with capped exponential backoff + jitter (EF's execution strategy): SQLite `SQLITE_BUSY`/`LOCKED`, MySQL deadlock/lock-wait-timeout/too-many-connections, Postgres `40001`/`40P01`/`57P0x`/`08xxx`, and network `ECONNRESET`/`ETIMEDOUT`/`PROTOCOL_CONNECTION_LOST` on any engine. Non-transient errors (constraints, syntax, `ConcurrencyError`) are never retried.
|
|
138
|
+
- Applies to queries (`toList`/`single`/`count`…), `saveChanges()` (the whole unit of work is re-run; a failed attempt rolled back and left entities dirty) and `executeUpdate`/`executeDelete`. **Not** inside an explicit transaction (EF: the transaction is the retry unit). Off by default (EF default); per-context `setRetryOnFailure({ maxRetries, maxDelayMs, baseDelayMs, onRetry })` or `false`; process-wide default via `masterrecord.configureRetry(...)`. A `retry` event `{ attempt, maxRetries, delayMs, error }` fires before each wait. `masterrecord.isTransientError(err, engine)`; exports `masterrecord/resilience`.
|
|
139
|
+
|
|
140
|
+
New tests: `test/logging-redaction.test.js` (nothing logged by default; SQL logged with redacted params; values only when opted in; slow-query warning with logSql off; migration DDL at info / silenced; failed command at error; config validation) and `test/retry-on-failure.test.js` (classifier per engine; query retry with `retry` events and exhaustion; non-transient not retried; no retry inside a transaction; saveChanges retry commits exactly once; global default + per-context override). Full suite green (0 fail, 356 pass, 20 gated skipped); 0 lint errors.
|
|
141
|
+
|
|
142
|
+
## v1.9.0 — named global query filters (EF HasQueryFilter) + context events/interceptors
|
|
143
|
+
|
|
144
|
+
Closes gap-analysis #4 (query filters) and #10 (context-level interceptors) — together they deliver EF's soft-delete, multi-tenancy and audit recipes.
|
|
145
|
+
|
|
146
|
+
**Global query filters (EF Core `HasQueryFilter`, named filters in EF 10, `IgnoreQueryFilters`)**
|
|
147
|
+
- `this.dbset(Blog).queryFilter('softDelete', 'b => b.deletedAt == null').queryFilter('tenant', 'b => b.tenantId == $$', ctx => ctx.tenantId)` (or `ctx.queryFilter('Blog', name, lambda, ...args)`; omit the name for a single unnamed filter). The predicate is a normal where-lambda.
|
|
148
|
+
- Applied to **every** query on the entity: `toList`/`single`/`first`/`last`/`exists`/`findById`/`count` **and** `executeUpdate`/`executeDelete` (EF applies filters to ExecuteUpdate/Delete too). Composes with the user's `where()`/`and()` regardless of lambda alias.
|
|
149
|
+
- **Named**: several coexist; `query.ignoreQueryFilters()` drops all for that query, `ignoreQueryFilters(['softDelete'])` drops only those (EF 10). `ctx.removeQueryFilter(model, name)`.
|
|
150
|
+
- Args may be **functions evaluated at query time with the context** — the EF pattern of a filter referencing a DbContext field (`tenantId`).
|
|
151
|
+
- Known limitation (documented): filters apply to the root entity of a query, not yet inside `include()`d navigations.
|
|
152
|
+
|
|
153
|
+
**Events / interceptors (EF `SavingChanges`/`SavedChanges`/`SaveChangesFailed`, `ChangeTracker.Tracked`/`StateChanged`, `IDbCommandInterceptor`)**
|
|
154
|
+
- `ctx.on(event, handler)` / `once` / `off` (returns an unsubscribe fn). Events:
|
|
155
|
+
- `savingChanges { context, entries }` — runs **before** the flush and may mutate entities (audit columns) or convert a delete into a soft-delete (`entity.__state = 'modified'; entity.deletedAt = …`); the change set is **re-collected afterwards** so those edits ship in the same save. Async handlers are awaited.
|
|
156
|
+
- `savedChanges { context, entries }` after commit; `saveChangesFailed { context, entries, error }` before the error is rethrown.
|
|
157
|
+
- `tracked { context, entity }` when an entity enters tracking; `stateChanged { context, entity, state }` when it becomes dirty.
|
|
158
|
+
- `command { sql, params, durationMs, engine, error? }` for **every** SQL statement — engines now carry a command-observer set (`addCommandObserver`/`removeCommandObserver`); contexts attach on `on('command')` (also after init) and detach on `close()`. This is the hook Phase 5 logging/slow-query reporting builds on.
|
|
159
|
+
|
|
160
|
+
New tests: `test/query-filters.test.js` (apply to list/count/single/findById, compose with user where incl. different alias, ignore all / ignore by name, query-time function args, executeUpdate/executeDelete respect filters, removeQueryFilter + ctx.queryFilter form) and `test/context-events.test.js` (audit-column stamping via savingChanges + savedChanges, delete→soft-delete conversion, saveChangesFailed with error, tracked/stateChanged, command observer with timing, once/unsubscribe). Full suite green (0 fail, 348 pass, 20 gated skipped); 0 lint errors.
|
|
161
|
+
|
|
162
|
+
## v1.8.0 — executeUpdate / executeDelete (EF ExecuteUpdate/ExecuteDelete) + set-based bulk ops
|
|
163
|
+
|
|
164
|
+
Closes gap-analysis #3. Set-based writes that run **one SQL statement** over the rows a query selects, **bypass the change tracker**, execute immediately, and return rows affected — exactly EF Core's `ExecuteUpdate`/`ExecuteDelete`.
|
|
165
|
+
|
|
166
|
+
- **`query.executeDelete()`** — `DELETE … WHERE <the query's own compiled WHERE>`; returns rows affected.
|
|
167
|
+
- **`query.executeUpdate({ col: value, … })`** — `UPDATE … SET … WHERE <compiled WHERE>`; values are parameterized and run through the column's transformer; returns rows affected. To reference existing values (EF's `SetProperty(b => b.Views, b => b.Views + 1)`) use the new **`sql`** tag: `executeUpdate({ views: sql\`views + 1\` })` (`masterrecord.sql` / `import { sql } from 'masterrecord/sql'`). The tag **refuses interpolations** so raw fragments can't smuggle values — dynamic values go in ordinary (parameterized) setters. Validates columns; refuses to update the primary key; `include()`/`raw()` are rejected.
|
|
168
|
+
- Both reuse the engine's own WHERE compiler (same alias, same parameters), so the affected rows are exactly what the equivalent `toList()` would return. Inside `ctx.transaction()` they join the transaction; otherwise each is an autocommit statement (EF semantics). They invalidate the query cache for the table and serialize with other units of work on the shared connection.
|
|
169
|
+
- Engines: `executeUpdate(query, entity, setters)` / `executeDelete(query, entity)` on all three (MySQL uses the multi-table `DELETE alias FROM t AS alias` form so it works on every version; Postgres renumbers SET params after the WHERE's `$n`).
|
|
170
|
+
- **`ctx.bulkUpdate` / `ctx.bulkDelete` are now genuinely set-based**: `bulkDelete` is one `DELETE … WHERE pk IN (…)` (returns rows affected); `bulkUpdate` is one UPDATE per item in a single transaction with rows-affected checks — **no per-row SELECT**, no tracker round-trip (previously `findById` + `saveChanges()` per id: N SELECTs and N transactions, despite the docstring).
|
|
171
|
+
- `masterrecord` now also exposes `ConcurrencyError` and `RawSql`.
|
|
172
|
+
|
|
173
|
+
New tests: `test/execute-update-delete.test.js` (exact-row update with parameterized + `sql` setters and no tracker involvement; whole-table update; `sql` interpolation refused; column/PK validation; exact-row delete; join/rollback inside a transaction; cache invalidation; bulk ops issue no SELECTs and still fail on a missing id). Full suite green (0 fail, 339 pass, 20 gated skipped); 0 lint errors.
|
|
174
|
+
|
|
175
|
+
## v1.7.0 — FOREIGN KEY constraints in DDL (EF referential integrity) + rename advisories in migrations
|
|
176
|
+
|
|
177
|
+
Closes gap-analysis items "no FK constraints", "cascade config is a no-op", and "rename diffed as drop+add", the way EF Core does.
|
|
178
|
+
|
|
179
|
+
**FOREIGN KEY constraints** — relationships were ORM-only; no `REFERENCES`/`FOREIGN KEY` was ever emitted, so the database enforced nothing. Now every `belongsTo` column gets a FK constraint (EF always creates FK constraints for relationships):
|
|
180
|
+
- **SQLite:** inline `CONSTRAINT fk_<table>_<col> FOREIGN KEY (...) REFERENCES parent(pk) ON DELETE …` in `CREATE TABLE` (SQLite has no `ADD CONSTRAINT`); the connection now enables **`PRAGMA foreign_keys = ON`** so constraints are enforced (`MR_SQLITE_FOREIGN_KEYS=off` opts out). The SQLite table rebuild in `syncTable` preserves FKs. New `belongsTo` columns added via `addColumn` get an inline `REFERENCES` when nullable/defaulted.
|
|
181
|
+
- **MySQL/Postgres:** `ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY` is issued **after** the table — immediately if the referenced table exists, otherwise **deferred** and flushed by the new **`schema.finalize()`**, which the CLI calls after each migration's `up()`/`down()`. Table creation order and cycles therefore never matter; a still-missing referenced table is reported as a clear model error.
|
|
182
|
+
- **ON DELETE follows the model** (EF `OnDelete(DeleteBehavior.*)`): `CASCADE` by default; **`stopCascadeOnDelete()` is now honored** → `SET NULL` (nullable) / `RESTRICT` (required); new **`.onDelete('cascade'|'restrict'|'setNull'|'noAction')`** for explicit control.
|
|
183
|
+
- New **`.excludeForeignKeyFromMigrations()`** (EF 11): keep the relationship in the ORM but emit no DB constraint (legacy DBs, data-sync).
|
|
184
|
+
- An **index is created on every FK column** (SQLite/Postgres; MySQL auto-indexes FKs), as EF does.
|
|
185
|
+
- New `schema.addForeignKey(fk)` / `schema.dropForeignKey(fk)` (MySQL/Postgres) for hand-written migrations — e.g. to add constraints to tables created before this release (the snapshot does not record constraints, so existing tables are not retrofitted automatically; write a migration calling `addForeignKey`).
|
|
186
|
+
|
|
187
|
+
**Rename advisories (EF parity, not auto-rename)** — a renamed column was diffed as `dropColumn` + `addColumn`, which **destroys the column's data** on apply. EF Core's differ deliberately does *not* auto-detect renames (it cannot tell a rename from an unrelated drop+add — guessing wrong moves data under the wrong name) and tells you to review and change the scaffold to `RenameColumn`. MasterRecord now matches EF: drop+add is still emitted, but when exactly one removed and one added column share an identical definition, the generated migration carries a **`// POSSIBLE RENAME`** advisory with the exact `await this.renameColumn({...})` call to swap in, and `add-migration` prints a warning. Ambiguous cases get no advisory. New `schema.renameTable({tableName,newName})`; `renameColumn` now validates its spec.
|
|
188
|
+
|
|
189
|
+
New tests: `test/foreign-key-constraints.test.js` (SQLite inline FK + ON DELETE variants incl. `onDelete`/`stopCascadeOnDelete`/`excludeForeignKeyFromMigrations`; MySQL/PG `ADD CONSTRAINT` SQL; end-to-end SQLite enforcement: pragma on, orphan insert rejected, CASCADE delete, FK index; `finalize()` error on a missing referenced table) and `test/migration-rename-detection.test.js` (advisory emitted with drop+add intact; none when ambiguous or when definitions differ). Full suite green (0 fail, 333 pass, 20 gated skipped); 0 lint errors.
|
|
190
|
+
|
|
191
|
+
## v1.6.0 — optimistic concurrency (EF concurrency tokens) + explicit transactions
|
|
192
|
+
|
|
193
|
+
Closes the last **silent lost-write** class identified in `docs/EF_CORE_GAP_ANALYSIS.md` (#1 and #2), implemented the way Entity Framework Core does.
|
|
194
|
+
|
|
195
|
+
**Optimistic concurrency**
|
|
196
|
+
- `db.field().concurrencyToken()` — the column's **original** (as-loaded) value is added to every UPDATE/DELETE `WHERE` (EF `IsConcurrencyToken`). You rotate the value when you change the row.
|
|
197
|
+
- `db.rowVersion()` — an ORM-managed integer token bumped **atomically** in the same statement (`SET v = v + 1 … WHERE v = <original>`), mirrored onto the entity and re-snapshotted as the new original after a successful save. Portable across SQLite/MySQL/PostgreSQL (EF `IsRowVersion`, application-managed).
|
|
198
|
+
- **Rows-affected is now always checked** on UPDATE and DELETE (previously never): a row that was concurrently modified (token mismatch) or deleted affects 0 rows → `saveChanges()` rolls the batch back and throws **`ConcurrencyError`** (EF `DbUpdateConcurrencyException`; `err.entries` = conflicting entities, `err.code = 'MR_CONCURRENCY_CONFLICT'`). Before, such saves returned `true` and silently overwrote or no-op'd.
|
|
199
|
+
- Entities now carry **original values** (`__originalValues`, non-enumerable) captured at load / after insert / after save; `reload()` resets them (EF `Reload()`), which is what makes "reload and retry" resolution work. `reload()` also no longer leaves a duplicate tracked instance behind.
|
|
200
|
+
- Engines expose `affectedRows(result)` (SQLite `changes`, mysql2 `affectedRows` — mysql2 connects with `FOUND_ROWS`, so this is rows *matched*, as required; pg `rowCount`). Bulk deletes check total rows affected; entities with tokens are deleted per-row.
|
|
201
|
+
- New module `errors.js` (`ConcurrencyError`), also re-exported from `context.js`.
|
|
202
|
+
|
|
203
|
+
**Explicit transactions**
|
|
204
|
+
- `ctx.transaction(async tx => { … })` — begin → run → commit, rollback + rethrow on error (recommended form).
|
|
205
|
+
- `ctx.beginTransaction()` / `ctx.commit()` / `ctx.rollback()` (+ `commitTransaction`/`rollbackTransaction` aliases), `ctx.inTransaction`.
|
|
206
|
+
- `ctx.createSavepoint(name)` / `rollbackToSavepoint(name)` / `releaseSavepoint(name)` (names validated as identifiers).
|
|
207
|
+
- 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 (EF semantics). Nested `beginTransaction()` is rejected.
|
|
208
|
+
- The engine save queue is now an explicit async mutex (`_withEngineLock`); a transaction holds it for its duration so another unit of work on the same pooled connection waits instead of interleaving statements into the transaction.
|
|
209
|
+
|
|
210
|
+
**Internals:** per-entity UPDATEs (the engines' "bulk" update was already a per-row loop) so each statement carries its own tokens and rows-affected check. Docs: new "Optimistic concurrency" and "Transactions" sections in `docs/CHANGE_TRACKING_AND_CONTEXT_LIFETIME.md`.
|
|
211
|
+
|
|
212
|
+
New tests: `test/optimistic-concurrency.test.js` (rowVersion bump/mirror, conflict → `ConcurrencyError` + no overwrite + reload-and-retry, app-managed token, rows-affected on update/delete of a vanished row, batch rollback on conflict) and `test/transactions-api.test.js` (transaction(fn) commit/rollback, manual begin/commit/rollback, nested rejection + savepoints, failed save inside tx keeps tx usable, lock serializes a sibling save). Full suite green (0 fail, 326 pass, 20 gated skipped); 0 lint errors.
|
|
213
|
+
|
|
214
|
+
## v1.5.17 — connections stay warm across close/reopen (ADO.NET-style pooling; no reconnect churn)
|
|
215
|
+
|
|
216
|
+
`close()` physically closed a pooled connection the moment its refcount reached zero. So a request-scoped context (or a background job that builds a scope per run and disposes it) reconnected on every cycle whenever it was the sole holder — the exact churn that scoping was supposed to avoid.
|
|
217
|
+
|
|
218
|
+
EF/ADO.NET doesn't do this: disposing a `DbContext` returns its connection to the pool **kept physically open and idle**, and the next context reuses it warm. MasterRecord's `_pools` now behaves the same:
|
|
219
|
+
|
|
220
|
+
- At refcount zero the connection is **kept open and idle** (not closed). The next context that needs the same database reuses the warm connection with no reconnect. Verified: `close()` then `new Ctx()` yields the *same* engine instance.
|
|
221
|
+
- A background **reaper** physically closes connections idle longer than `MR_POOL_IDLE_MS` (default `60000`), so idle connections are reclaimed, not leaked. The reaper timer is `unref()`-ed and never keeps the process alive; `closeAll()` stops it.
|
|
222
|
+
- **`MR_POOL_IDLE_MS=0`** opts out — the old behavior (close immediately at refcount zero).
|
|
223
|
+
|
|
224
|
+
This makes per-request contexts and per-run background scopes genuinely cheap: `new AppContext()` allocates a tracking map and points at the already-open connection; `close()` returns it to the pool warm.
|
|
225
|
+
|
|
226
|
+
New tests: `test/pool-idle-retention.test.js` — a closed connection is reused warm (no reconnect); the reaper closes a connection idle past the timeout; `MR_POOL_IDLE_MS=0` closes immediately. Full suite green (0 fail, 315 pass, 20 gated skipped); 0 lint errors.
|
|
227
|
+
|
|
3
228
|
## v1.5.16 — context pooling (EF's AddDbContextPool) + reset(); change-tracking/lifetime docs
|
|
4
229
|
|
|
5
230
|
Completes the EF-faithful context-lifetime story so request-scoped contexts are affordable even with many contexts registered.
|
package/Cache/QueryCache.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import crypto from 'node:crypto';
|
|
2
|
+
import { log } from '../logging.js';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Production-Grade Query Result Cache
|
|
@@ -57,10 +58,7 @@ class QueryCache {
|
|
|
57
58
|
entry.lastAccess = Date.now();
|
|
58
59
|
this.hitCount++;
|
|
59
60
|
|
|
60
|
-
|
|
61
|
-
if (process.env.NODE_ENV !== 'production') {
|
|
62
|
-
console.debug(`[QueryCache HIT] Key: ${cacheKey.substring(0, 8)}... (${entry.hits} hits)`);
|
|
63
|
-
}
|
|
61
|
+
log('debug', `[QueryCache HIT] Key: ${cacheKey.substring(0, 8)}... (${entry.hits} hits)`);
|
|
64
62
|
|
|
65
63
|
return entry.data;
|
|
66
64
|
}
|
|
@@ -84,10 +82,7 @@ class QueryCache {
|
|
|
84
82
|
tableName: tableName
|
|
85
83
|
});
|
|
86
84
|
|
|
87
|
-
|
|
88
|
-
if (process.env.NODE_ENV !== 'production') {
|
|
89
|
-
console.debug(`[QueryCache SET] Key: ${cacheKey.substring(0, 8)}... Table: ${tableName}`);
|
|
90
|
-
}
|
|
85
|
+
log('debug', `[QueryCache SET] Key: ${cacheKey.substring(0, 8)}... Table: ${tableName}`);
|
|
91
86
|
}
|
|
92
87
|
|
|
93
88
|
/**
|
|
@@ -103,9 +98,7 @@ class QueryCache {
|
|
|
103
98
|
}
|
|
104
99
|
}
|
|
105
100
|
|
|
106
|
-
|
|
107
|
-
console.debug(`[QueryCache INVALIDATE] Table: ${tableName} (${invalidated} entries)`);
|
|
108
|
-
}
|
|
101
|
+
log('debug', `[QueryCache INVALIDATE] Table: ${tableName} (${invalidated} entries)`);
|
|
109
102
|
}
|
|
110
103
|
|
|
111
104
|
/**
|
|
@@ -169,9 +162,7 @@ class QueryCache {
|
|
|
169
162
|
}
|
|
170
163
|
}
|
|
171
164
|
|
|
172
|
-
if (cleaned > 0
|
|
173
|
-
console.debug(`[QueryCache CLEANUP] Removed ${cleaned} expired entries`);
|
|
174
|
-
}
|
|
165
|
+
if (cleaned > 0) log('debug', `[QueryCache CLEANUP] Removed ${cleaned} expired entries`);
|
|
175
166
|
}, 60000);
|
|
176
167
|
if (typeof timer.unref === 'function') timer.unref();
|
|
177
168
|
this._cleanupTimer = timer;
|
package/Entity/entityModel.js
CHANGED
|
@@ -138,6 +138,41 @@ class EntityModel {
|
|
|
138
138
|
return this;
|
|
139
139
|
}
|
|
140
140
|
|
|
141
|
+
/**
|
|
142
|
+
* Owned / complex type stored as JSON in one column — Entity Framework Core
|
|
143
|
+
* `OwnsOne(e => e.Address, b => b.ToJson())` / `ComplexProperty`.
|
|
144
|
+
*
|
|
145
|
+
* address(db){ db.owned(Address); } // class with fields; hydrated on read
|
|
146
|
+
* meta(db){ db.owned(); } // plain object / array
|
|
147
|
+
*
|
|
148
|
+
* The value is serialized with JSON on write and parsed on read (into an
|
|
149
|
+
* instance of the class when one is given). Nested mutations
|
|
150
|
+
* (`user.address.city = 'x'`) are detected at saveChanges() by comparing
|
|
151
|
+
* the serialized value to the loaded one (EF DetectChanges on complex
|
|
152
|
+
* properties). A custom transform() still wins if you set one.
|
|
153
|
+
*/
|
|
154
|
+
owned(OwnedClass){
|
|
155
|
+
if (OwnedClass !== undefined && OwnedClass !== null && typeof OwnedClass !== 'function') {
|
|
156
|
+
throw new Error('masterrecord: owned(Class) expects a class (or no argument for a plain object).');
|
|
157
|
+
}
|
|
158
|
+
this.obj.type = "json";
|
|
159
|
+
this.obj.owned = true;
|
|
160
|
+
this.obj.ownedType = OwnedClass || null;
|
|
161
|
+
if (!this.obj.transform) {
|
|
162
|
+
const hydrate = (o) => (OwnedClass && o && typeof o === 'object' && !Array.isArray(o)) ? Object.assign(new OwnedClass(), o) : o;
|
|
163
|
+
this.obj.transform = {
|
|
164
|
+
toDatabase: (v) => (v === undefined || v === null) ? v : (typeof v === 'string' ? v : JSON.stringify(v)),
|
|
165
|
+
fromDatabase: (v) => {
|
|
166
|
+
if (v === undefined || v === null) return v;
|
|
167
|
+
if (typeof v !== 'string') return hydrate(v);
|
|
168
|
+
if (v === '') return null;
|
|
169
|
+
try { return hydrate(JSON.parse(v)); } catch (_) { return v; }
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
return this;
|
|
174
|
+
}
|
|
175
|
+
|
|
141
176
|
// Universally-unique identifier column (TEXT on SQLite).
|
|
142
177
|
uuid(){
|
|
143
178
|
this.obj.type = "uuid";
|
|
@@ -175,12 +210,80 @@ class EntityModel {
|
|
|
175
210
|
return this;
|
|
176
211
|
}
|
|
177
212
|
|
|
213
|
+
/**
|
|
214
|
+
* Mark this column as an optimistic-concurrency token (EF Core's
|
|
215
|
+
* IsConcurrencyToken / [ConcurrencyCheck]). Its ORIGINAL value (as loaded)
|
|
216
|
+
* is added to the WHERE clause of every UPDATE/DELETE of the row:
|
|
217
|
+
* UPDATE ... WHERE id = ? AND <col> = <original>
|
|
218
|
+
* If the row was changed by someone else since it was loaded, 0 rows match
|
|
219
|
+
* and saveChanges() throws ConcurrencyError instead of silently overwriting.
|
|
220
|
+
* The application is responsible for setting a new value when it changes
|
|
221
|
+
* the row (e.g. a GUID) — or use rowVersion() to have the ORM do it.
|
|
222
|
+
*/
|
|
223
|
+
concurrencyToken(){
|
|
224
|
+
this.obj.concurrencyToken = true;
|
|
225
|
+
return this;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* An ORM-managed integer version column (EF Core's IsRowVersion, but
|
|
230
|
+
* application-managed so it works identically on SQLite, MySQL and
|
|
231
|
+
* PostgreSQL). It is a concurrency token that saveChanges() increments
|
|
232
|
+
* atomically on every UPDATE (`SET <col> = <col> + 1 ... WHERE <col> =
|
|
233
|
+
* <original>`); you never set it yourself. Defaults to 0, NOT NULL.
|
|
234
|
+
*/
|
|
235
|
+
rowVersion(){
|
|
236
|
+
if (!this.obj.type) this.obj.type = 'integer';
|
|
237
|
+
this.obj.concurrencyToken = true;
|
|
238
|
+
this.obj.rowVersion = true;
|
|
239
|
+
this.obj.nullable = false;
|
|
240
|
+
if (this.obj.default === undefined || this.obj.default === null) this.obj.default = 0;
|
|
241
|
+
return this;
|
|
242
|
+
}
|
|
243
|
+
|
|
178
244
|
// sets the default value in the DB
|
|
179
245
|
default(value){
|
|
180
246
|
this.obj.default = value;
|
|
181
247
|
return this;
|
|
182
248
|
}
|
|
183
249
|
|
|
250
|
+
/**
|
|
251
|
+
* Database-side default EXPRESSION (EF Core `HasDefaultValueSql`), e.g.
|
|
252
|
+
* `db.datetime().defaultSql('CURRENT_TIMESTAMP')` or `defaultSql("gen_random_uuid()")`.
|
|
253
|
+
* Unlike default(value) the SQL is emitted verbatim (parenthesized when it is
|
|
254
|
+
* not a literal / CURRENT_*), so it can be any expression the engine accepts.
|
|
255
|
+
*/
|
|
256
|
+
defaultSql(sql){
|
|
257
|
+
if (typeof sql !== 'string' || !sql.trim()) throw new Error('masterrecord: defaultSql(sql) requires a non-empty SQL string.');
|
|
258
|
+
this.obj.defaultSql = sql.trim();
|
|
259
|
+
return this;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Computed column (EF Core `HasComputedColumnSql`): the database derives the
|
|
264
|
+
* value from an expression — `GENERATED ALWAYS AS (<sql>) STORED|VIRTUAL`.
|
|
265
|
+
* The ORM never writes it (skipped on INSERT/UPDATE) and reads it back after
|
|
266
|
+
* insert. `stored` defaults to true; Postgres supports STORED only.
|
|
267
|
+
* @example priceCents(db){ db.integer().computed('CAST(price * 100 AS INTEGER)'); }
|
|
268
|
+
*/
|
|
269
|
+
computed(sql, { stored = true } = {}){
|
|
270
|
+
if (typeof sql !== 'string' || !sql.trim()) throw new Error('masterrecord: computed(sql) requires a non-empty SQL expression.');
|
|
271
|
+
this.obj.computedSql = sql.trim();
|
|
272
|
+
this.obj.computedStored = stored !== false;
|
|
273
|
+
return this;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* CHECK constraint on this column (EF Core `HasCheckConstraint`):
|
|
278
|
+
* `db.integer().check('qty >= 0', 'CK_Product_qty')`. The name is optional.
|
|
279
|
+
*/
|
|
280
|
+
check(sql, name){
|
|
281
|
+
if (typeof sql !== 'string' || !sql.trim()) throw new Error('masterrecord: check(sql) requires a non-empty SQL predicate.');
|
|
282
|
+
this.obj.check = sql.trim();
|
|
283
|
+
this.obj.checkName = name || null;
|
|
284
|
+
return this;
|
|
285
|
+
}
|
|
286
|
+
|
|
184
287
|
get(func){
|
|
185
288
|
this.obj.get = func;
|
|
186
289
|
return this;
|
|
@@ -291,6 +394,46 @@ class EntityModel {
|
|
|
291
394
|
return this;
|
|
292
395
|
}
|
|
293
396
|
|
|
397
|
+
/**
|
|
398
|
+
* Many-to-many with an IMPLICIT join entity — Entity Framework Core 5+ skip
|
|
399
|
+
* navigations (`HasMany(p => p.Tags).WithMany(t => t.Posts)`).
|
|
400
|
+
*
|
|
401
|
+
* The context synthesizes the join entity (named by the two entity names in
|
|
402
|
+
* alphabetical order, e.g. `PostTag`) with an auto primary key, `belongsTo()`
|
|
403
|
+
* to both sides (`post_id`, `tag_id`, ON DELETE CASCADE) and a unique
|
|
404
|
+
* composite index, so migrations create it and loading / inserting /
|
|
405
|
+
* `collection.add()`/`remove()` go through it. Declaring the navigation on
|
|
406
|
+
* both sides is optional and maps to the same join entity.
|
|
407
|
+
*
|
|
408
|
+
* @param {string} foreignTable the other entity, e.g. 'Tag'
|
|
409
|
+
* @param {{through?: string, foreignKey?: string, otherKey?: string}} [opts]
|
|
410
|
+
* through: join entity name; foreignKey: this side's FK column in the
|
|
411
|
+
* join (default `<this>_id`); otherKey: the other side's (default `<other>_id`).
|
|
412
|
+
* Self-referencing many-to-many must pass both keys.
|
|
413
|
+
* @example tags(db){ db.manyToMany('Tag'); } // on Post
|
|
414
|
+
* posts(db){ db.manyToMany('Post'); } // on Tag (optional)
|
|
415
|
+
*/
|
|
416
|
+
manyToMany(foreignTable, opts = {}){
|
|
417
|
+
if (typeof foreignTable !== 'string' || !foreignTable.trim()) throw new Error('masterrecord: manyToMany(target) requires the target entity name.');
|
|
418
|
+
const owner = this.obj.name; // during model build this is the declaring entity's name
|
|
419
|
+
const target = foreignTable.trim();
|
|
420
|
+
const selfRef = owner === target;
|
|
421
|
+
if (selfRef && !(opts.foreignKey && opts.otherKey)) {
|
|
422
|
+
throw new Error(`masterrecord: self-referencing manyToMany('${target}') must pass { foreignKey, otherKey } (EF names them after the navigations, e.g. followers_id / following_id).`);
|
|
423
|
+
}
|
|
424
|
+
const [a, b] = [owner, target].sort();
|
|
425
|
+
this.obj.type = "hasManyThrough";
|
|
426
|
+
this.obj.relationshipType = "hasManyThrough";
|
|
427
|
+
this.obj.isNavigational = true;
|
|
428
|
+
this.obj.implicitJoin = true;
|
|
429
|
+
this.obj.foreignTable = opts.through || `${a}${b}`; // the join entity
|
|
430
|
+
this.obj.targetTable = target; // the other side
|
|
431
|
+
this.obj.joinForeignKey = opts.foreignKey || `${owner.toLowerCase()}_id`;
|
|
432
|
+
this.obj.joinOtherKey = opts.otherKey || `${target.toLowerCase()}_id`;
|
|
433
|
+
this.obj.foreignKey = this.obj.joinForeignKey;
|
|
434
|
+
return this;
|
|
435
|
+
}
|
|
436
|
+
|
|
294
437
|
// will get info
|
|
295
438
|
belongsTo(foreignTable, foreignKey){
|
|
296
439
|
|
|
@@ -313,6 +456,34 @@ class EntityModel {
|
|
|
313
456
|
return this
|
|
314
457
|
}
|
|
315
458
|
|
|
459
|
+
/**
|
|
460
|
+
* Referential action for this belongsTo's FOREIGN KEY constraint (EF Core's
|
|
461
|
+
* OnDelete(DeleteBehavior.*)): 'cascade' | 'restrict' | 'setNull' | 'noAction'.
|
|
462
|
+
* Default: CASCADE when cascadeOnDelete is on (the default), otherwise
|
|
463
|
+
* SET NULL for a nullable column or RESTRICT for a required one.
|
|
464
|
+
*/
|
|
465
|
+
onDelete(behavior){
|
|
466
|
+
const map = { cascade: 'CASCADE', restrict: 'RESTRICT', setnull: 'SET NULL', 'set null': 'SET NULL', noaction: 'NO ACTION', 'no action': 'NO ACTION' };
|
|
467
|
+
const key = String(behavior || '').toLowerCase();
|
|
468
|
+
if (!map[key]) {
|
|
469
|
+
throw new Error(`masterrecord: onDelete expects 'cascade' | 'restrict' | 'setNull' | 'noAction', got ${JSON.stringify(behavior)}`);
|
|
470
|
+
}
|
|
471
|
+
this.obj.onDelete = map[key];
|
|
472
|
+
this.obj.cascadeOnDelete = map[key] === 'CASCADE';
|
|
473
|
+
return this;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Keep the relationship in the ORM (queries, includes, change tracking) but
|
|
478
|
+
* do NOT create a FOREIGN KEY constraint in the database (EF Core 11's
|
|
479
|
+
* ExcludeForeignKeyFromMigrations). For legacy databases without
|
|
480
|
+
* constraints or data-sync scenarios where constraint order conflicts.
|
|
481
|
+
*/
|
|
482
|
+
excludeForeignKeyFromMigrations(){
|
|
483
|
+
this.obj.fkConstraint = false;
|
|
484
|
+
return this;
|
|
485
|
+
}
|
|
486
|
+
|
|
316
487
|
foreignTable(foreignTable){
|
|
317
488
|
this.obj.foreignTable = foreignTable;
|
|
318
489
|
this.obj.nullable = false;
|