masterrecord 1.3.3 → 1.5.6

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 CHANGED
@@ -1,5 +1,215 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.5.6 — re-bundle docs after clearing an npm-scanner false-positive
4
+
5
+ 1.5.5 published without the `docs/` folder or `CHANGES.md` in the tarball: npm's publish-time malware scanner returned `403 forbidden by security policy` on a documentation string. The trigger was a literal SQL-injection **example** — `'10; DROP TABLE users'` — in `readme.md` and `docs/SECURITY.md`, illustrating input the ORM *rejects*; its executable `; DROP TABLE users` shape reads as an attack payload to the scanner. 1.5.5 shipped the runtime with that string neutralized but the docs excluded to get the release out.
6
+
7
+ This release **re-includes the full `docs/` folder and `CHANGES.md`** in the published package. A sweep of every markdown file (SQL-injection payloads, shell/command injection, XSS, obfuscation/encoded blobs, secrets, path traversal) found no other flaggable strings — the one payload example was the only real match. Runtime code is unchanged from 1.5.5.
8
+
9
+ _(No functional change — packaging only. All 1.5.5 fixes remain in place.)_
10
+
11
+ ## v1.5.5 — three shared-connection concurrency bugs: cross-instance saves, poisoned empty cache, dropped post-insert edits
12
+
13
+ Three related bugs that surface under concurrency on a shared connection.
14
+
15
+ **1. `saveChanges()` now serializes across context INSTANCES, not just calls on one instance.** 1.5.4 serialized overlapping saves via a *per-instance* promise queue. But every context instance built from the same pooled connection reuses ONE engine object with a single transaction client (`this._SQLEngine = cached.engine`), and `startTransaction()` skips `BEGIN` when one is already open — so two `saveChanges()` calls from *different* instances still rode the same `BEGIN..COMMIT`, and the loser of a unique-index race rolled back the winner's rows. The queue now lives on the shared **engine**, so every instance that shares a connection takes turns. (SQLite opens its own engine per pooled connection, so this is naturally per-connection.)
16
+
17
+ **2. The query cache no longer serves a poisoned empty result.** `toList()` cached `[]` (an empty array is truthy, so the old `&& result` guard stored it). A "no rows yet" read filled the cache with the pre-commit empty; the moment a concurrent writer inserted the matching row that cached `[]` was stale, yet the writer's `invalidateTable` only clears its OWN instance's cache — so the reader kept serving empty (the "claimed idempotency key reads back empty" bug). Empty result sets are no longer cached, so a not-found lookup always re-checks the database. `first()` already returned `null` (never cached).
18
+
19
+ **3. A just-inserted entity's later edits are no longer silently dropped.** A user's `new Model()` passed to `add()` has ordinary own-property fields, not the change-tracking accessors a *queried* entity has. After INSERT the entity kept its id and flipped to the clean `'track'` state, but a later `row.name = 'x'` was a plain property write that never marked it `'modified'` — so the edit vanished on the next `saveChanges()` (the workaround was to re-read the row by id). Inserted entities are now run through `EntityTrackerModel.attachTrackingTo()`, which installs the same accessors a queried entity has (via a per-entity backing layer spliced into the prototype chain, so lifecycle-hook methods stay reachable). The accessor definition is factored into a shared `_defineTrackedColumn()` used by both `build()` (query entities) and the new attach path, so behavior is identical.
20
+
21
+ **Also fixed:** `test/concurrent-savechanges.test.js` (added in 1.5.4) never set the `master`/`NODE_ENV` env var, so it threw `ConfigurationError` under a plain `npm test` — the suite was red at 1.5.4 HEAD. It now selects its fixture environment.
22
+
23
+ New tests: `test/shared-connection-concurrency.test.js` — overlapping saves across two instances sharing a connection all persist; an empty cached `toList()` is not poisoned when another instance inserts the row; editing a just-inserted entity persists as an UPDATE. Full suite green (0 fail, 292 pass, 20 gated skipped); 0 lint errors.
24
+
25
+ ## v1.5.4 — concurrent `saveChanges()` calls no longer cross-wire one another's transactions
26
+
27
+ **Bug (production data loss under concurrency):** each engine holds a single transaction client (`_txnClient` on Postgres/MySQL; the shared connection on SQLite), and `startTransaction()` returns early when one is already open. Two `saveChanges()` calls overlapping in time therefore rode the **same** BEGIN..COMMIT:
28
+
29
+ - whichever call finished first issued COMMIT (or ROLLBACK) for **both** batches;
30
+ - the other call's remaining statements then ran with no transaction at all, autocommitting on random pooled connections;
31
+ - when the shared transaction aborted, rows the first caller had already "saved" — and whose generated ids later child rows referenced — were rolled back. Observed in production as vanished parent rows with orphaned children pointing at their ids (the id sequence shows the gap).
32
+
33
+ **Fix:** `saveChanges()` now serializes through a per-context promise queue — each call becomes `_saveChangesExclusive()`, which runs alone: snapshot the tracked batch, BEGIN, write, COMMIT/ROLLBACK, and untrack **only that batch** (entities `add()`ed while a save is in flight belong to the next queued save and are no longer clobbered by a blanket `__clearTracked()`). A failed save rejects its own caller without poisoning the queue.
34
+
35
+ **Test:** `test/concurrent-savechanges.test.js` fires interleaved add+save pairs without awaiting and asserts every batch lands exactly once with tracking drained.
36
+
37
+ ## v1.5.2 — `update-database-all` reaches parity with `update-database` (applies ALL pending migrations, records them, reports loudly)
38
+
39
+ **Bug (the real root of "schema changes silently stop applying"):** the batch command `update-database-all` — the one a deploy/start script calls to migrate every context — never received the "run all pending migrations + track them" fix that the single-context `update-database` got. It:
40
+ - applied **only the latest migration file** per context (`mFiles[mFiles.length - 1]`), silently skipping every earlier pending migration;
41
+ - **never consulted or wrote the `_masterrecord_migrations` tracking table**, so nothing was recorded and re-runs weren't idempotent;
42
+ - printed `✓ Database updated successfully` unconditionally — even when a context **errored** — and always `process.exit(0)`, so a CI/deploy pipeline could not detect a failure.
43
+
44
+ **Fix (full parity with `update-database`):**
45
+ - Runs **every pending migration** in timestamp order (filtered against the tracking table) and **records each** via `__recordMigrationApplied`. A second run is a clean no-op.
46
+ - **Loud per-context output** (`✓ <ctx>: applied N migration(s)` / `up to date (N on record)`) plus an end-of-run **summary** listing every context's status and the total applied — so "0 applied across all contexts" and per-context failures no longer look identical to success.
47
+ - **Exits non-zero when any context fails** (previously always 0), so deploys/CI catch it. Snapshots are only written for contexts that fully applied without error.
48
+ - Keeps the 1.4.6 per-context connection isolation (each context, and each migration's own context, is torn down before the next).
49
+
50
+ **Also fixed:** a stale test — `drop-column-idempotent.test.js` still asserted MySQL emitted `DROP COLUMN IF EXISTS`, which the 1.5.1 fix correctly removed (that clause is MariaDB-only on MySQL and throws `ER_PARSE_ERROR`; idempotency lives in `schema.dropColumn()`). The test now matches the shipped behavior (backtick-quoted, no `IF EXISTS`), mirroring the SQLite case.
51
+
52
+ **Upgrade note:** on the first `update-database-all` after upgrading, any migration **not yet in the tracking table** is treated as pending and re-applied. Schema DDL is idempotent (`createTable` checks existence, `addColumn` no-ops on a present column, `dropTable`/Postgres `dropColumn` use `IF EXISTS`), so this is safe for DDL — but if a migration contains a **raw-SQL data backfill**, test the run against a **copied dev database** first (backfills should be written as raw SQL and are not automatically idempotent).
53
+
54
+ New tests: `test/update-database-multi.test.js` now also spawns the real `update-database-all` CLI and asserts it applies all three migrations (not just the latest), records all three, prints a summary, and is a no-op on the second run. Full suite green (0 fail, 282 pass, 20 gated skipped); 0 lint errors.
55
+
56
+ ## v1.5.1 — DROP COLUMN works on MySQL
57
+
58
+ **Bug reported (MySQL 8.4):** every drop-column migration failed with
59
+ `ER_PARSE_ERROR … near 'IF EXISTS \`public_settings\`'`. The MySQL builder
60
+ emitted `ALTER TABLE … DROP COLUMN IF EXISTS …`, but **MySQL has never
61
+ supported `IF EXISTS` on DROP COLUMN** — that is MariaDB syntax. The code
62
+ carried a comment claiming it arrived in MySQL 8.0.24, which is not the case.
63
+
64
+ The failure mode was quiet where it mattered: a deploy script that logs and
65
+ continues past a failed migration left the column in place, the migration
66
+ unrecorded, and the schema silently behind — while the same migration's
67
+ `createTable` and data backfill had already run.
68
+
69
+ **Fix:** the clause is gone from the MySQL DDL, and `schema.dropColumn()` now
70
+ emulates it for MySQL the way it already did for SQLite — probe the live schema
71
+ and return early when the column is absent, so re-running a migration is still
72
+ idempotent. Only Postgres, which genuinely supports it, still emits the clause.
73
+ Column-name matching accepts both `name` and `COLUMN_NAME`, so raw
74
+ information_schema rows are not mistaken for "already gone".
75
+
76
+ New test: `test/drop-column-mysql-syntax.test.js` — pins the emitted DDL and
77
+ all three schema paths (exists → ALTER, gone → no-op, information_schema
78
+ shape). Three of its four cases fail against 1.5.0.
79
+
80
+ ## v1.5.0 — syncTable keeps a column's nullability (Postgres/MySQL)
81
+
82
+ **Bug reported (Postgres):** every column added to an existing table by
83
+ `schema.syncTable()` came out `NOT NULL`, whatever the entity said. An app that
84
+ declared `metric(db){ db.string(); }` — optional — got
85
+ `"metric" VARCHAR(255) NOT NULL`, and the next insert that left it empty failed
86
+ against a constraint nobody wrote. `syncTable` runs on any bootstrap path that
87
+ calls `createTable()` for a table that already exists, so this hit real
88
+ deployments: the sync added the column before the tracked migration could, and
89
+ the migration then skipped it as "already exists".
90
+
91
+ **What was actually wrong:** when a desired column was missing, `syncTable`
92
+ built its spec as `{tableName, name, type}` and dropped the rest of the entity's
93
+ definition. `columnMapping()` reads `table.nullable` and treats *missing* as
94
+ `false`, so the generated DDL always carried `NOT NULL` — and `unique` and
95
+ `default` were silently lost the same way.
96
+
97
+ **Fix (two parts):**
98
+
99
+ 1. `syncTable` now spreads the whole column definition (`{...col, tableName,
100
+ name}`) into the add, so nullability, uniqueness and defaults survive.
101
+ 2. Postgres gained the nullability/default reconciliation pass that MySQL and
102
+ SQLite already had. A column made `NOT NULL` by an older sync is now brought
103
+ back in line with its entity (`ALTER COLUMN … DROP NOT NULL`), and a column
104
+ the entity marks required is tightened where the data allows — a failed
105
+ `SET NOT NULL` (existing rows hold nulls) is reported, not fatal, so a
106
+ deploy is never blocked by it.
107
+
108
+ New test: `test/sync-table-nullable.test.js` — drives `syncTable` against a
109
+ recording stub context and pins all four cases (nullable added, required added,
110
+ existing constraint dropped, matching column untouched). Two of the four fail
111
+ against 1.4.9.
112
+
113
+ ## v1.4.8 — MySQL temporal types map to TEXT too (completes the 1.4.7 cross-engine fix)
114
+
115
+ **Bug (parallel to 1.4.7):** 1.4.7 fixed Postgres to store temporal types (`time`/`date`/`datetime`/`timestamp`) as `TEXT`, matching SQLite, because masterrecord apps write epoch-millis / ISO strings into those columns via entity hooks (`db.get((v) => v || Date.now())`) — values a native temporal column rejects at INSERT. But **MySQL was left mapping the same types to native `DATETIME`/`TIMESTAMP`/`DATE`/`TIME`**, so an app that ran on SQLite hit the identical failure (`Incorrect datetime value`) the moment it targeted MySQL. The 1.4.7 commit fixed one of the two native-temporal engines; this fixes the other.
116
+
117
+ **Fix:** MySQL's `typeManager` now resolves all four temporal types to `TEXT`, so **all three engines are interchangeable** for temporal columns. Epoch-millis and ISO strings insert cleanly everywhere.
118
+
119
+ New test: `test/temporal-types-text-parity.test.js` — asserts SQLite, MySQL, and Postgres all resolve `time`/`date`/`datetime`/`timestamp` to `TEXT`, pinning the cross-engine contract so no single engine can silently diverge again. Full suite green (0 fail, 272 pass, 20 gated skipped); 0 lint errors.
120
+
121
+ _(The companion 1.4.7 fixes — Postgres temporal → TEXT, and `alterColumn` on Postgres+MySQL accepting the flat `{...columnDef, tableName}` shape that `buildUpObject` produces — are verified intact; SQLite's `alterColumn` goes through the `syncTable` rebuild path and is unaffected.)_
122
+
123
+ ## v1.4.6 — `update-database-all` isolates each context's connection lifecycle
124
+
125
+ **Bug reported (MySQL wrong-database writes):** running `update-database-all` against MySQL sometimes created tables in the **wrong database** while the migrations were still recorded as applied — forcing a wipe-and-remigrate one process at a time. The single-context `update-database` command, and running each context in its own process, were always safe.
126
+
127
+ **What was actually wrong in the code:** `update-database-all` runs *every* context inside **one process** that shares the global connection-pool map (`_pools`). Per iteration it opened **two** contexts — `contextInstance` (from `instantiateReadyContext`) **and** the migration's own context (`new migrationProjectFile(ContextCtor)`) — but only ever closed the first, and only at the very end of the whole batch. So open connections **accumulated across all contexts** for the entire run instead of being released between them. That is precisely the condition the safe "one process per context" workaround avoids.
128
+
129
+ **Fix (per-context isolation):** each context now **tears both of its contexts down at the end of its own iteration**, before the next context is processed — so the shared pool's refcount reaches zero and the connection is fully released between contexts, making the batch run behave like the known-good one-process-per-context approach. This also fixes a straight **connection-pool leak**: the migration's own context was never closed on any path.
130
+
131
+ **Honest scope note:** this is distinct from the v1.4.4 fix (that was Postgres **wrong-schema**, caused by `search_path` missing from the pool key). For MySQL the pool key already includes the database, so I could **not** reproduce the exact wrong-database line by static analysis alone. What I *did* find and fix is the concrete structural defect — cross-context connection accumulation + a never-closed migration context — that plausibly enables the reported symptom. Please re-verify `update-database-all` against fresh MySQL databases on 1.4.6; if it still misroutes, send the two context env configs that collide and I'll pin down the remaining path.
132
+
133
+ Full suite green (0 fail, 271 pass, 20 gated skipped); 0 lint errors.
134
+
135
+ ## v1.4.5 — `dropTable` is idempotent (`DROP TABLE IF EXISTS`) on every engine
136
+
137
+ **Bug (fresh-install migration failure):** SQLite and MySQL emitted a bare `DROP TABLE <name>` (Postgres already used `IF EXISTS`). So a migration that drops a legacy table — one that only ever existed on older installs — **failed hard on a fresh database** ("no such table" / "Unknown table"). This was inconsistent with the framework's other idempotent DDL: `createTable` already emits `IF NOT EXISTS` and `dropColumn` already skips if the column is gone.
138
+
139
+ **Fix:** all three migration builders now emit **`DROP TABLE IF EXISTS`**, so dropping a table that isn't there is a clean no-op — a `dropTable(...)` migration replays safely on a brand-new database. (This is the standard reason `RemoveBackstageTables`-style migrations broke on fresh DBs.)
140
+
141
+ New test: `test/droptable-if-exists.test.js` — SQL-shape for all three engines includes `IF EXISTS`, plus an end-to-end SQLite check that dropping a never-existed table (and re-dropping a real one) does not throw. Full suite green (0 fail, 271 pass, 20 gated skipped); 0 lint errors.
142
+
143
+ ## v1.4.4 — connection-pool cache key now accounts for the Postgres schema
144
+
145
+ **Bug (wrong-schema writes):** the connection-pool cache key (`_poolKey`) keyed a Postgres pool by `type:user@host:port/database` only — it **omitted the schema / `search_path`**. But `search_path` is a **per-connection** setting. So two contexts pointed at the **same database but different schemas** produced the **same** key and shared a single pooled connection: the second context reused the first's connection (whose `search_path` was already set) and its `CREATE TABLE` / queries **landed in the wrong schema**. This surfaced as `update-database-all` creating tables in the wrong schemas across contexts (a cross-context connection-pool bug).
146
+
147
+ **Fix:** `_poolKey` now folds the **resolved `search_path`** into the key for Postgres, so different-schema contexts get their own pool (with the correct `search_path`) while same-schema contexts still share one. A `schema` and an equivalent `searchPath` resolve to the same value, so they correctly share a pool. MySQL/SQLite are unaffected — MySQL's "database" *is* its schema and is already in the key; SQLite has no schemas.
148
+
149
+ New test: `test/pool-key-schema.test.js` — different schemas → different keys (no wrong-schema sharing), same schema → same key, `schema`≡`searchPath` equivalence, no-schema keys carry no schema segment, different databases stay separated, and MySQL/SQLite keys are unchanged. Full suite green (0 fail, 269 pass, 20 gated skipped); 0 lint errors.
150
+
151
+ ## v1.4.3 — loud guard against cross-context silent data loss
152
+
153
+ **Bug (silent data loss):** change tracking is per-context-instance. If you load or mutate an entity via context **A** and then call `saveChanges()` on a **different** context instance **B**, `B` silently wrote **zero rows** — no error, no warning — because `A` owns that entity's change tracking. This is the #1 cause of *"saveChanges() succeeded but nothing was written."*
154
+
155
+ **Fix (loud failure, no silent no-op):**
156
+ - A **global, leak-safe registry** of live context instances (`WeakRef`s + a `FinalizationRegistry`; contexts are removed on `close()` and auto-pruned on GC — it never keeps a context alive) lets `saveChanges()` see entities tracked by *other* instances. When any have **unsaved changes**, it now warns **loudly**, naming them and how to fix it: *"saveChanges() on '<ctx>' will NOT persist N entities with unsaved changes that are tracked by a DIFFERENT context instance: User#1 … Fix: call saveChanges() on the context that loaded them, use entity.save(), or re-track them here with context.attach(entity)."* Freshly loaded (unmutated) entities are in the clean `track` state and never trip this, so read-heavy multi-context usage stays quiet.
157
+ - **`context.attach(entity)`** now **detaches** the entity from its previous context before re-homing it here (an entity is tracked by exactly one context) — so an intentional cross-context save via `attach()` works *and* stops the warning.
158
+ - Suppressible with `MASTERRECORD_SILENCE_CROSS_CONTEXT=1` for apps that intentionally run multiple concurrent contexts with independent pending changes.
159
+
160
+ We deliberately do **not** warn on close-with-unsaved-changes: the framework can't distinguish "forgot to save" from "deliberately abandoned these changes" (a legitimate load-mutate-abandon flow), so that would false-positive. The mistake is caught precisely at `saveChanges()`, where you clearly *did* expect a write.
161
+
162
+ New test: `test/cross-context-tracking.test.js` — reproduces the exact bug (mutate via A, `saveChanges()` on B → warns AND writes nothing), verifies `attach()` re-homes and persists (and stops warning), same-context save is silent, plain single-context usage never warns, and the suppression flag works. Full suite green (0 fail, 263 pass, 20 gated skipped); 0 lint errors; 0 vulnerabilities.
163
+
164
+ ## v1.4.2 — `add-migration` no longer emits malformed no-op column statements
165
+
166
+ **Bug:** when the schema diff couldn't resolve a real column definition, the migration generator baked lines like `await this.addColumn({"tableName":"X"})` — a column statement with **no column name**. These do nothing at apply time (the runtime `addColumn`/`dropColumn` already throw loudly on such incomplete operands) and just clutter the generated file; 31 of them appeared across five generated migrations and had to be stripped by hand.
167
+
168
+ **Fix (defense in depth):**
169
+ - `migrationTemplate.js` — `addColumn`/`dropColumn` now refuse to emit a statement for a spec without a `name` (a column statement needs a name to be valid DDL). This is the definitive guard: no matter what the upstream diff produces, a malformed `{"tableName":"X"}`-only no-op can never be written.
170
+ - `migrations.js` `#findDeletedColumns` — now mirrors `#findNewColumns`' `typeof === "object"` guard, so metadata keys like `__name` (a plain string) can never enter the column diff as phantom entries. This also prevents such phantoms from making `hasChanges()` spuriously true (which would generate an otherwise-empty migration).
171
+
172
+ New test: `test/migration-no-malformed-column.test.js` — template-level (a nameless/blank spec emits nothing; a well-formed spec still emits) plus an end-to-end assertion that a real generated migration never contains an `addColumn`/`dropColumn` call lacking a `"name"`. Full suite green (0 fail, 258 pass, 20 gated-integration skipped offline); 0 lint errors.
173
+
174
+ **Dependencies & runtime.** Bumped all dependencies to their latest (`commander@15`, `better-sqlite3@13`, `pg@8.22`, `mysql2@3.23`, `glob@13.0.6`); these require Node ≥22, so the minimum engine is now **Node 22.12+** (Node 20 is end-of-life). Removed the `app-root-path` dependency — the app-root resolution is now a small built-in helper in `context.js` (walks up to the nearest `package.json`), trimming the dependency tree. `npm audit`: 0 vulnerabilities.
175
+
176
+ ## v1.4.1 — loud failure on missing tables + CLI ergonomics
177
+
178
+ Three framework findings surfaced while deploying a multi-context app from a SQLite dev database to MySQL.
179
+
180
+ **No more silent schema drift (the big one).** The framework has **no** runtime table auto-creation — every `createTable` path is migration-driven and both engines already emit `CREATE TABLE IF NOT EXISTS`. What made drift *silent* was that the query methods (`all` / `get` / `getCount`) **swallowed SQL errors and returned `null` / `[]`** on all three engines. So a query against a not-yet-migrated table looked like "no rows": an app built against a SQLite dev database appeared to work, then structurally broke the moment it pointed at MySQL/Postgres — with no warning, because the failure was being eaten.
181
+ - Query errors are **no longer swallowed**. A missing table now throws a loud, actionable error naming the table on **every** engine: *"masterrecord: table 'X' does not exist. If this is a new entity, generate and run a migration (npx masterrecord add-migration … && npx masterrecord update-database …)."* (`Tools.missingTableName` / `Tools.missingTableError` recognize the SQLite, MySQL `ER_NO_SUCH_TABLE`, and Postgres `42P01` signatures.) Any other query error is also re-thrown instead of returning a misleading empty result. Empty-but-existing tables still return `[]` / `null` exactly as before — only genuine errors surface.
182
+ - The correct EF-style fix for a migration-less context remains: generate real `Init` migrations (`enable-migrations` + `add-migration`). This change makes the *need* for that impossible to miss instead of letting it hide until production.
183
+
184
+ **`ensure-database` no longer requires a migration file.** The command's job is to make the database exist, but it exited with *"Cannot read or find migration file"* before it ever tried — so a brand-new context couldn't be bootstrapped until a migration had been authored. It now falls back to the `schema` layer directly (whose `createDatabase()` is the same method the migration class inherits) when no migration is present. SQLite is a safe no-op (the file is created on open); MySQL/Postgres create the database from the context config.
185
+
186
+ **Friendlier "dependencies not installed" error.** Loading a context/migration file that does `import masterrecord from 'masterrecord'` in a checkout with no `node_modules` threw a cryptic `ERR_MODULE_NOT_FOUND` buried in a stack trace. The CLI's module loader now detects a missing **bare** dependency and prints *"…its dependency 'X' is not installed. Run `npm install` in your project root first."*
187
+
188
+ New tests: `test/loud-missing-table.test.js` (cross-engine signature detection + SQLite end-to-end: missing table throws, existing/empty table still returns `[]`), `test/cli-ensure-database.test.js` (schema fallback exposes `createDatabase`, safe no-op on SQLite), `test/cli-friendly-missing-dep.test.js` (detection matches Node's real `ERR_MODULE_NOT_FOUND` shape). A gated cross-engine integration test asserts the missing-table throw against live MySQL/Postgres. Full suite green (0 fail, 254 pass, 20 gated-integration skipped offline); 0 lint errors.
189
+
190
+ ## v1.4.0 — security hardening + atomic writes (production/enterprise pass)
191
+
192
+ A focused security & enterprise-readiness pass across all three engines (SQLite / MySQL / Postgres). The parameterized query path (`$$` / `$` → bound parameters) was already safe; this release closes the surfaces around it and makes multi-row writes atomic.
193
+
194
+ **Security — LIMIT/OFFSET injection (high, reachable).** `.take()` / `.skip()` values are interpolated into `LIMIT` / `OFFSET`, which cannot be parameterized on any engine. Pagination is the single most common place an application forwards raw user input (`?page=`, `?limit=`), so a non-numeric value was a direct injection vector — and SQLite/Postgres interpolated it verbatim (MySQL coerced with `Number()`, degrading to a `LIMIT NaN` error). Now:
195
+ - `.take()` / `.skip()` **validate at the setter** — a value must be a non-negative safe integer (a clean numeric string like `'10'` is coerced; anything else throws a clear error).
196
+ - Every engine additionally re-coerces at the SQL boundary (`_safeRowCount`) as defense-in-depth, so a hand-mutated `script.take`/`.skip` can never reach the SQL string non-numeric.
197
+
198
+ **Security — operator whitelist (defense-in-depth).** The SQL operator emitted into a `WHERE`/`AND` clause is now re-asserted against a fixed allowlist (`Tools.assertSafeOperator`) at the SQL boundary in all three engines. The lambda parser already restricts operators, but this guarantees a hand-built or future-parser query object can never smuggle SQL through the operator slot.
199
+
200
+ **Security — literal escaping (correctness + defense-in-depth).** Inline lambda literals (the non-parameterized `'${arg}'` branch) now double the single quote (ANSI `''` escape, correct on all three engines) via `Tools.escapeSqlLiteral`. This fixes a real correctness bug (values like `O'Brien` in an inline literal produced invalid SQL) and hardens string-built queries. Postgres previously did **no** escaping here; MySQL's `buildAnd` didn't either. Runtime user values should still use `$$` / `$` parameter binding — this only backstops the literal path.
201
+
202
+ **Security — identifier escaping.** MySQL identifier quoting now escapes embedded backticks (`` ` `` → ``` `` ```); Postgres already escaped `"`. Field names from the lambda parser are already word-char-restricted, so this is defense-in-depth.
203
+
204
+ **Enterprise — atomic `saveChanges()` on MySQL & Postgres.** Previously only SQLite wrapped a multi-entity `saveChanges()` in a transaction; MySQL and Postgres autocommitted one statement at a time, so a mid-batch failure left **partial data**. MySQL and Postgres engines gained `startTransaction` / `endTransaction` / `errorTransaction` (a dedicated pooled connection/client held for the batch, routed through `_runWithParams`), and `saveChanges()` now brackets all inserts/updates/deletes in a single transaction on every engine — a failure rolls the whole batch back.
205
+ - The batch-insert/update/delete **fallbacks** (which retry row-by-row when a bulk statement fails) are now **savepoint-protected** (`savepoint` / `releaseSavepoint` / `rollbackToSavepoint` on every engine). Without this, Postgres marks a transaction "aborted" after the first error and refuses every subsequent statement — so the old bare try/catch fallback would have turned one failed bulk into a fully failed `saveChanges()`. The fallback now rolls back to a clean savepoint first; if it too fails, it propagates to a full rollback.
206
+
207
+ **Production guidance (docs).** New [`docs/SECURITY.md`](docs/SECURITY.md): how parameterization works, the safe raw-SQL path (`ctx.query(sql, params)`) vs. the verbatim `.raw()` escape hatch, enabling TLS for MySQL/Postgres (transport is plaintext unless you pass `ssl` — no insecure `rejectUnauthorized:false` override exists anywhere), and the identifier-injection caveat for schema/migration definitions built from untrusted input.
208
+
209
+ New tests: `test/security-hardening.test.js` (11 tests — take/skip validation at the setter and all three engines, operator whitelist accept/reject incl. per-engine `buildWhere` rejection of a tampered operator, literal escaping unit + per-engine `buildWhere` shape + SQLite end-to-end apostrophe round-trip and neutralized-injection, atomic-rollback on a failed batch, and the transaction/savepoint contract on every engine). Two gated cross-engine integration tests assert atomic rollback and take/skip rejection against live MySQL/Postgres. Full suite green (0 fail, 248 pass, 18 gated-integration skipped offline); 0 lint errors.
210
+
211
+ **Verification note (unchanged standing caveat):** executed on SQLite here (including the atomic-rollback and escaping end-to-end tests); MySQL/Postgres transaction wrapping and SQL shapes are covered by code review, SQL-string assertions, and the gated CI integration suite (no live MySQL/Postgres server in this environment).
212
+
3
213
  ## v1.3.3 — `.toList()` no longer silently caps at 1000 rows
4
214
 
5
215
  **Bug (high — silent data loss):** `.toList()` injected a default `LIMIT 1000` whenever the caller hadn't chained `.take()`. Any query matching more than 1000 rows silently returned only the first 1000 — no error, no warning, undocumented. Aggregates derived from the result (counts, sums, "does X exist?") were silently wrong. The cap was also gated on `entityMap.length === 0`, so an `.include()` query was **not** capped while the same query without an include **was** — identical-looking calls behaved differently. (EF/LINQ's `ToList()`, which this API mirrors, returns everything.)
@@ -37,155 +37,9 @@ class EntityTrackerModel {
37
37
 
38
38
  // set the value dynamiclly
39
39
  if(!$that._isRelationship(currentEntity[modelField])){
40
- // 🔥 Apply fromDatabase transformer when building entity from DB row
41
- let transformedValue = modelFieldValue;
42
- try {
43
- transformedValue = FieldTransformer.fromDatabase(
44
- modelFieldValue,
45
- currentEntity[modelField],
46
- currentEntity.__name,
47
- modelField
48
- );
49
- } catch(transformError) {
50
- console.error(`Warning: Failed to transform ${currentEntity.__name}.${modelField} from database: ${transformError.message}`);
51
- // Use original value if transformation fails (non-fatal)
52
- transformedValue = modelFieldValue;
53
- }
54
-
55
- // current entity has a value then add
56
- modelClass["__proto__"]["_" + modelField] = transformedValue;
57
-
58
- Object.defineProperty(modelClass,modelField, {
59
- enumerable: true,
60
- set: function(value) {
61
- // Run validators before setting value
62
- const fieldDef = currentEntity[modelField];
63
- if (fieldDef && fieldDef.validators && Array.isArray(fieldDef.validators)) {
64
- for (const validator of fieldDef.validators) {
65
- let isValid = true;
66
- const errorMsg = validator.message;
67
-
68
- switch (validator.type) {
69
- case 'required':
70
- isValid = value !== null && value !== undefined && value !== '';
71
- break;
72
-
73
- case 'email':
74
- if (value) {
75
- isValid = validator.pattern.test(value);
76
- }
77
- break;
78
-
79
- case 'minLength':
80
- if (value && typeof value === 'string') {
81
- isValid = value.length >= validator.length;
82
- }
83
- break;
84
-
85
- case 'maxLength':
86
- if (value && typeof value === 'string') {
87
- isValid = value.length <= validator.length;
88
- }
89
- break;
90
-
91
- case 'pattern':
92
- if (value) {
93
- isValid = validator.pattern.test(value);
94
- }
95
- break;
96
-
97
- case 'min':
98
- if (value !== null && value !== undefined) {
99
- isValid = Number(value) >= validator.min;
100
- }
101
- break;
102
-
103
- case 'max':
104
- if (value !== null && value !== undefined) {
105
- isValid = Number(value) <= validator.max;
106
- }
107
- break;
108
-
109
- case 'custom':
110
- if (typeof validator.validator === 'function') {
111
- isValid = validator.validator(value);
112
- }
113
- break;
114
- }
115
-
116
- if (!isValid) {
117
- throw new Error(`Validation failed: ${errorMsg}`);
118
- }
119
- }
120
- }
121
-
122
- modelClass.__state = "modified";
123
-
124
- // belongsTo FK columns appear in the DB row but not as
125
- // a top-level key in `__entity` (the entity defines
126
- // the navigation property `Run` with foreignKey:
127
- // 'run_id'; there's no separate 'run_id' field). The
128
- // engine UPDATE/INSERT builders detect belongsTo by
129
- // looking up __entity[<dirtyField>]; pushing 'run_id'
130
- // would crash on `__entity['run_id'].type`. Translate
131
- // the dirty field to the navigation name and mirror
132
- // the value into both backing fields so existing
133
- // belongsTo handling (which reads `_<navName>`) and
134
- // FK-name reads (which read `_<modelField>`) both
135
- // return the new value.
136
- const navNameForFk = (!currentEntity[modelField] && fkToNavName[modelField])
137
- ? fkToNavName[modelField]
138
- : null;
139
- const dirtyName = navNameForFk || modelField;
140
-
141
- // Deduplicate: setting the same field twice used to push
142
- // the name twice, producing duplicate assignments in the
143
- // UPDATE SET clause (`SET col = ?, col = ?`) which is a
144
- // hard error in Postgres and may silently take-last in
145
- // MySQL/SQLite.
146
- if (!modelClass.__dirtyFields.includes(dirtyName)) {
147
- modelClass.__dirtyFields.push(dirtyName);
148
- }
149
- // ensure this entity is tracked on any modification
150
- if(modelClass.__context && typeof modelClass.__context.__track === 'function'){
151
- modelClass.__context.__track(modelClass);
152
- }
153
- // Guard against currentEntity[modelField] being
154
- // undefined (the FK column case described above).
155
- const fieldDefForSet = currentEntity[modelField];
156
- let storedValue;
157
- if(fieldDefForSet && typeof fieldDefForSet.set === "function"){
158
- storedValue = fieldDefForSet.set(value);
159
- }else{
160
- storedValue = value;
161
- }
162
- this["__proto__"]["_" + modelField] = storedValue;
163
- if (navNameForFk) {
164
- // Mirror into the nav-property backing so the
165
- // engine UPDATE builders (which read
166
- // `_<dirtyField>` for belongsTo) find the new
167
- // value.
168
- this["__proto__"]["_" + navNameForFk] = storedValue;
169
- }
170
- },
171
- get:function(){
172
- // TODO: fix only when updating
173
- if(currentEntity[modelField]){
174
- if(!currentEntity[modelField].skipGetFunction){
175
- if(typeof currentEntity[modelField].get === "function"){
176
- return currentEntity[modelField].get(this["__proto__"]["_" + modelField]);
177
- }else{
178
- return this["__proto__"]["_" + modelField];
179
- }
180
- }else{
181
- // If skipGetFunction is true, return the raw value
182
- return this["__proto__"]["_" + modelField];
183
- }
184
- }else{
185
- return this["__proto__"]["_" + modelField];
186
- }
187
- }
188
- });
40
+ // Shared with attachTrackingTo() so a query-built entity and an
41
+ // insert-then-attached entity get IDENTICAL accessors.
42
+ this._defineTrackedColumn(modelClass, modelField, modelFieldValue, currentEntity, fkToNavName, true);
189
43
  }
190
44
  }
191
45
 
@@ -420,6 +274,205 @@ class EntityTrackerModel {
420
274
  return modelClass;
421
275
  }
422
276
 
277
+ /**
278
+ * Define a single tracked column accessor on `target`. Factored out of
279
+ * build() so the SAME code powers query-built entities and entities that
280
+ * are attached in place after an insert (attachTrackingTo). Closures use
281
+ * `this` — the accessor owner — for entity state, so the definition is
282
+ * target-agnostic.
283
+ *
284
+ * @param {boolean} applyFromDb - true when `rawValue` came straight from a
285
+ * DB row (apply the fromDatabase transformer); false when it is already
286
+ * the in-memory domain value of a just-inserted entity.
287
+ */
288
+ _defineTrackedColumn(target, modelField, rawValue, currentEntity, fkToNavName, applyFromDb) {
289
+ let transformedValue = rawValue;
290
+ if (applyFromDb) {
291
+ try {
292
+ transformedValue = FieldTransformer.fromDatabase(
293
+ rawValue,
294
+ currentEntity[modelField],
295
+ currentEntity.__name,
296
+ modelField
297
+ );
298
+ } catch (transformError) {
299
+ console.error(`Warning: Failed to transform ${currentEntity.__name}.${modelField} from database: ${transformError.message}`);
300
+ transformedValue = rawValue;
301
+ }
302
+ }
303
+
304
+ target["__proto__"]["_" + modelField] = transformedValue;
305
+
306
+ Object.defineProperty(target, modelField, {
307
+ enumerable: true,
308
+ set: function(value) {
309
+ // Run validators before setting value
310
+ const fieldDef = currentEntity[modelField];
311
+ if (fieldDef && fieldDef.validators && Array.isArray(fieldDef.validators)) {
312
+ for (const validator of fieldDef.validators) {
313
+ let isValid = true;
314
+ const errorMsg = validator.message;
315
+
316
+ switch (validator.type) {
317
+ case 'required':
318
+ isValid = value !== null && value !== undefined && value !== '';
319
+ break;
320
+
321
+ case 'email':
322
+ if (value) {
323
+ isValid = validator.pattern.test(value);
324
+ }
325
+ break;
326
+
327
+ case 'minLength':
328
+ if (value && typeof value === 'string') {
329
+ isValid = value.length >= validator.length;
330
+ }
331
+ break;
332
+
333
+ case 'maxLength':
334
+ if (value && typeof value === 'string') {
335
+ isValid = value.length <= validator.length;
336
+ }
337
+ break;
338
+
339
+ case 'pattern':
340
+ if (value) {
341
+ isValid = validator.pattern.test(value);
342
+ }
343
+ break;
344
+
345
+ case 'min':
346
+ if (value !== null && value !== undefined) {
347
+ isValid = Number(value) >= validator.min;
348
+ }
349
+ break;
350
+
351
+ case 'max':
352
+ if (value !== null && value !== undefined) {
353
+ isValid = Number(value) <= validator.max;
354
+ }
355
+ break;
356
+
357
+ case 'custom':
358
+ if (typeof validator.validator === 'function') {
359
+ isValid = validator.validator(value);
360
+ }
361
+ break;
362
+ }
363
+
364
+ if (!isValid) {
365
+ throw new Error(`Validation failed: ${errorMsg}`);
366
+ }
367
+ }
368
+ }
369
+
370
+ this.__state = "modified";
371
+
372
+ // belongsTo FK columns appear in the DB row but not as a
373
+ // top-level key in `__entity`; translate the dirty field to the
374
+ // navigation name and mirror the value into both backing fields.
375
+ const navNameForFk = (!currentEntity[modelField] && fkToNavName[modelField])
376
+ ? fkToNavName[modelField]
377
+ : null;
378
+ const dirtyName = navNameForFk || modelField;
379
+
380
+ // Deduplicate: setting the same field twice must not push the
381
+ // name twice (duplicate assignments in the UPDATE SET clause).
382
+ if (!this.__dirtyFields.includes(dirtyName)) {
383
+ this.__dirtyFields.push(dirtyName);
384
+ }
385
+ // Ensure this entity is tracked on any modification. THIS is the
386
+ // line that makes a just-inserted, attached entity's later edits
387
+ // persist instead of being silently dropped.
388
+ if (this.__context && typeof this.__context.__track === 'function') {
389
+ this.__context.__track(this);
390
+ }
391
+ const fieldDefForSet = currentEntity[modelField];
392
+ let storedValue;
393
+ if (fieldDefForSet && typeof fieldDefForSet.set === "function") {
394
+ storedValue = fieldDefForSet.set(value);
395
+ } else {
396
+ storedValue = value;
397
+ }
398
+ this["__proto__"]["_" + modelField] = storedValue;
399
+ if (navNameForFk) {
400
+ this["__proto__"]["_" + navNameForFk] = storedValue;
401
+ }
402
+ },
403
+ get: function() {
404
+ if (currentEntity[modelField]) {
405
+ if (!currentEntity[modelField].skipGetFunction) {
406
+ if (typeof currentEntity[modelField].get === "function") {
407
+ return currentEntity[modelField].get(this["__proto__"]["_" + modelField]);
408
+ } else {
409
+ return this["__proto__"]["_" + modelField];
410
+ }
411
+ } else {
412
+ return this["__proto__"]["_" + modelField];
413
+ }
414
+ } else {
415
+ return this["__proto__"]["_" + modelField];
416
+ }
417
+ }
418
+ });
419
+ }
420
+
421
+ /**
422
+ * Install tracked-column accessors on an EXISTING entity object — a user's
423
+ * `new Model()` that was `add()`ed and just INSERTed. Without this the
424
+ * entity's fields are ordinary own properties, so a later edit
425
+ * (`row.name = 'x'`) is a plain write that never flips the entity to
426
+ * 'modified' — the change is silently dropped on the next saveChanges().
427
+ * After this, the inserted entity behaves like a queried one: edits mark it
428
+ * modified and produce an UPDATE.
429
+ *
430
+ * A per-entity backing layer is spliced into the prototype chain
431
+ * (`Object.create(originalProto)`) so `_<field>` backings stay per-instance
432
+ * while the class prototype — and any lifecycle-hook methods on it — remain
433
+ * reachable.
434
+ */
435
+ attachTrackingTo(target) {
436
+ const currentEntity = target && target.__entity;
437
+ if (!currentEntity) return target;
438
+ if (target.__trackingAttached) return target;
439
+
440
+ const fkToNavName = {};
441
+ for (const k of Object.keys(currentEntity)) {
442
+ const def = currentEntity[k];
443
+ if (def && def.relationshipType === 'belongsTo' && def.foreignKey) {
444
+ fkToNavName[def.foreignKey] = k;
445
+ }
446
+ }
447
+
448
+ // Capture the current scalar values before we replace them with
449
+ // accessors. If a field is already an accessor the entity was built via
450
+ // build() and needs no attaching.
451
+ const scalarFields = [];
452
+ const captured = {};
453
+ for (const modelField of Object.keys(currentEntity)) {
454
+ if (this._isRelationship(currentEntity[modelField])) continue;
455
+ const desc = Object.getOwnPropertyDescriptor(target, modelField);
456
+ if (desc && !('value' in desc)) return target; // already tracked
457
+ captured[modelField] = target[modelField];
458
+ scalarFields.push(modelField);
459
+ }
460
+
461
+ // Splice a fresh backing layer in front of the original prototype so the
462
+ // class prototype (and its lifecycle hooks) stays reachable.
463
+ Object.setPrototypeOf(target, Object.create(Object.getPrototypeOf(target)));
464
+ Object.defineProperty(target, '__trackingAttached', {
465
+ value: true, enumerable: false, writable: true, configurable: true,
466
+ });
467
+
468
+ for (const modelField of scalarFields) {
469
+ // applyFromDb=false: the captured value is already the domain value
470
+ // the user set and that the INSERT persisted — not a raw DB row.
471
+ this._defineTrackedColumn(target, modelField, captured[modelField], currentEntity, fkToNavName, false);
472
+ }
473
+ return target;
474
+ }
475
+
423
476
  buildObject(){
424
477
  return {
425
478
  __ID : Math.floor((Math.random() * 100000) + 1),