@voltro/sql-mssql 0.20.2 → 0.21.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/CHANGELOG.md CHANGED
@@ -39,6 +39,155 @@ _Changes staged for the next release accumulate here (rolled up from
39
39
 
40
40
  ---
41
41
 
42
+ ## [0.21.0] — 2026-07-31
43
+
44
+ ### ⚠ BREAKING
45
+
46
+ - **@voltro/database, @voltro/runtime, @voltro/workflow, @voltro/voltro** — `text().maxLength(n)` on an EXISTING column now actually applies. It planned zero operations and reported "schema is up to date" while the live column stayed `longtext` — the documented remedy for MariaDB's hash long-unique was a silent no-op, which is worse than no remedy because you stop looking.
47
+
48
+ **The differ was not comparing lengths wrongly — it could not see them.** `maxLength` was absent from the schema snapshot entirely: it lived on the column definition, was read only when rendering CREATE DDL, and never reached the comparison. A consumer pinned the mechanism with a contrast: a column bounded AT CREATION was `varchar(64)` (DDL path, fine); one bounded afterwards stayed `longtext` (diff path, blind).
49
+
50
+ It is now carried on both sides — declared from the definition, live from introspection — compared as its own dimension, and rendered by the applier from the declared snapshot (a bare `text` tag would emit DDL that applies successfully and changes nothing, the silent no-op the applier's convergence check exists to catch).
51
+
52
+ **Three guards against the real risk, which is not missing a change but re-emitting one forever:**
53
+
54
+ - Only the VARCHAR family contributes a live length. MariaDB reports `character_maximum_length = 4294967295` for `longtext` and 65535 for `text`; postgres reports NULL. Reading a type's theoretical maximum would make a declared `text()` differ from its own live column on every boot. - Only `text()` columns are compared. `id()` renders as `VARCHAR(64)` on mysql/mariadb while its declaration carries no length — measured on live MariaDB while building this, and it would have emitted an ALTER for every id column, forever. - Never on sqlite (no length-enforced type), and never when the caller omitted the dialect — an unknown dialect behaves exactly as before this field existed.
55
+
56
+ Proven by round-trip suites against live MariaDB and live Postgres: the same schema re-plans to NOTHING, a length change produces exactly one operation on the right column, applying it lands the new width, and re-planning after that is clean.
57
+
58
+ Classification follows the nullability precedent: **widening is `safe`** (no data can be lost), **narrowing is `needs-backfill`** and says so, with the count query to run first. Narrowing is deliberately not blocked — blocking it would leave the remedy just as unusable as the silence did.
59
+
60
+ **Also: `_voltro_api_keys.hashedKey` is now bounded at 64**, since the value is `sha256Hex(token)` and narrowing it can never fail. The other four unbounded unique columns in framework tables are deliberately left alone, each with the reason at the column: `_voltro_kv.key` is the caller's own key, `idempotencyKey` comes from a user-supplied function, and the two workflow `executionId`s have no shape the framework guarantees. A narrowing ALTER that fails on existing data during a framework upgrade is a worse outcome than the index-size concern it would fix — and the MariaDB hash long-unique is harmless on those tables anyway, since `_voltro_*` is filtered out of the binlog reader's include list.
61
+
62
+ **Migration** — `voltro update` prints it (`0.21.0/01_maxlength-now-migrates`, `manual`, and it fires only for projects that declare a bound). Your source does not change; every `.maxLength(n)` already written keeps compiling. What changes is that the next `voltro db apply` — or a `voltro dev` / `voltro serve` boot with auto-migrate — emits ALTERs it used to skip. Run `voltro db plan` first: it prints exactly which columns would be altered without touching anything, and an empty plan means this does not affect you. Widening is `safe` and can simply run; narrowing is `needs-backfill` and the plan carries the count query to run before it.
63
+
64
+ *Why this is `BREAKING` and not `Fixed`: the API is compatible — nothing is removed, renamed or narrowed, and the same call compiles. But an upgrade now performs DDL against YOUR tables that the previous version silently skipped, and on MariaDB `longtext → varchar(n)` is a full table rebuild that locks. The DB-changes-need-no-codemod exemption is written for `_voltro_*` tables riding the differ; this reaches user tables, so the operator deserves the warning at `voltro update` time rather than in a changelog section they may never open.*
65
+
66
+ ### Added
67
+
68
+ - **@voltro/cli, @voltro/voltro** — **`voltro schedule run <name>`** fires one scheduled job on demand, against `voltro dev` or `voltro serve`.
69
+
70
+ Asked for by a consumer whose nightly jobs correct business data and whose workaround was: edit the cron expression to a minute out, wait for the reload, put it back. "Run it once now and watch" is a normal thing to want.
71
+
72
+ **Most of it already existed, and that is why it took a measurement to find the gap.** `SchedulerHandle.fireNow` has been there, and so has `POST /_voltro/inspect/schedules/:name/fire`. What was missing was the way in: no CLI verb, and — the part that mattered — **`voltro serve` mounted no inspect surface at all**. Every `/_voltro/inspect/*` route existed only under `voltro dev`, which is the one place a nightly data-correcting job is not running.
73
+
74
+ So production now mounts it. Two things make that safe rather than a new attack surface, and both were checked rather than assumed:
75
+
76
+ - `handleInspectRequest` is **closed by default**: with no `VOLTRO_INSPECT_TOKEN` every request is 401 carrying the remedy, the compare is constant-time, and the token is never minted outside dev. Opening it is an operator's deliberate act. - Only the handlers production can answer TRUTHFULLY are wired. Everything else stays absent and replies "not configured" — an empty array would claim the app has no procedures. `inspectSchedules` is deliberately still absent: dev computes `nextFiringAt` and the EFFECTIVE coordination from its own boot closure, and reporting a guessed coordination mode to a post-deploy gate is worse than reporting nothing.
77
+
78
+ The manifest's `rpc` / `workflows` entries come from a builder both boot paths now share (`inspectEntries.ts`). They are the same facts on both sides, and a second hand-written copy of the descriptor→entry mapping is the shape this repo keeps paying for.
79
+
80
+ **A run id of `null` is reported as its own outcome**, not as success: the run was coordinated away — another replica holds the lock, or `onOverlap: 'skip'` found the previous run still going. Printing "ok" would claim work that never started.
81
+
82
+ **Also fixed, and it affects every command in the inspect family.** `fetchJson` collapsed a non-2xx into the body's `error` field alone, discarding `message`. The surface answers `{ error: <category>, message: <what happened> }`, so firing an unknown schedule printed "fire failed" while the server had said `scheduler.fireNow: unknown schedule "…"`, and a closed surface printed "unauthorized" while the body named the missing env var. It now prefers `message`, then `reason`, then `error` — fixed in the shared fetch rather than per command.
83
+
84
+ Verified end to end against `voltro-starter/apps/v-api-durable`: the fire returns a run id and the job's own output appears in the server log; an unknown name reports the server's reason; `--format json` round-trips.
85
+
86
+ ### Fixed
87
+
88
+ - **@voltro/database, @voltro/sql-postgres, @voltro/sql-mysql, @voltro/sql-sqlite, @voltro/sql-mssql, @voltro/voltro** — <!-- apiSurface: compatible — reasoned, not rubber-stamped. `attributionFields()` gained an OPTIONAL parameter and `withCapturedAttribution` is new. Both are additive, and it was CHECKED rather than assumed, because this repo has already paid once for a narrowing that read as additive: a zero-arg call still compiles, the value is still assignable to the old `() => …` type, and it still passes as a callback typed with the old shape. All three probed under `--strict`. Nothing was removed. -->
89
+
90
+ Write attribution is now CARRIED down the write path instead of re-read from the ambient async-local scope, so a connection-pool handoff can no longer strand a write's `traceId` / `subjectId`.
91
+
92
+ `routeEvent` read the identity with `attributionFields()`, and it runs after `await runPromise(...)`. `AsyncLocalStorage` propagates through continuations the current context CREATES; one scheduled by ANOTHER context — exactly what a pool handoff does when an acquisition queues — resumes with that other context's store. So under contention the write landed with the identity absent. Absent is a LEGAL value there meaning "no request behind this write", so the result does not look like a defect: it looks like a schedule. In a compliance trail that asymmetry is the whole problem, and it is why this is closed structurally rather than left as unlikely.
93
+
94
+ The value is captured ONCE at each public store method, before any await (`withCapturedAttribution`), and threaded explicitly through every `execute*` and into `routeEvent` — in all four dialect stores, including the transactional view, which is the path every framework mutation takes. The ambient scope is kept as a FALLBACK: a site that has not been threaded behaves exactly as before rather than worse, which is what made the change verifiable site by site.
95
+
96
+ **On what is and is not proven.** A pool handoff cannot be reproduced deterministically from a test — the resume context is the driver's choice. Two attempts are worth recording because both produced misleading green: a load-based regression test passed in isolation and failed in the full gate twice (a coin flip that also blocked releases), and a "deterministic" replacement that left the scope before the write finished PASSED against the unthreaded store, because the store re-enters its own scope internally. It proved nothing while looking like proof, so it was deleted.
97
+
98
+ What is proven: the pure semantics (`writeAttributionCapture.test.ts` — explicit wins over the ambient scope, explicit wins over ANOTHER request's scope, "no request" stays "no request", keys omitted rather than `undefined`), and the threading itself (`attributionThreadingParity.test.ts` — every store accepts and uses the carried value, no store still calls a bare `attributionFields()`, every transactional view carries it). The guarantee is structural, and it is stated that way rather than dressed up as a reproduction.
99
+
100
+ Raised by a consumer who could NOT reproduce the loss across 2700 writes at 96-way concurrency with every core saturated, and who asked for the fix anyway on the right grounds: *"impossible beats unlikely when the failure is invisible."*
101
+ - **@voltro/database, @voltro/sql-postgres, @voltro/sql-mysql, @voltro/voltro** — <!-- apiSurface: compatible — `beginLocalWrite`, `endLocalWrite` and `resolveEchoAttribution` are new exports on `@voltro/database`; nothing was removed, renamed or narrowed. Checked rather than assumed, because this repo has already paid once for a narrowing that read as additive. -->
102
+
103
+ Under CDC, a plain `store.insert(...)` could deliver its change with `traceId` and `subjectId` ABSENT — not always, and more often the busier the process.
104
+
105
+ **The registration was racing the echo, and only winning on a margin.** The write path registers the request identity so the transport echo (a postgres NOTIFY, a mysql binlog row) can be re-united with it, and `pendingAttribution.ts` stated the ordering as a guarantee: the registration happens "BEFORE the transport can possibly echo it, because a NOTIFY fires at COMMIT". That is true INSIDE a transaction, where `routeEvent` runs before COMMIT. It is false for a plain write, whose statement commits ITSELF — the trigger fires while the write path is still awaiting the driver, and the registration lands afterwards. The echo has to make a round trip through the LISTEN/binlog connection, and that round trip was the only thing keeping the order right.
106
+
107
+ **Why it stayed hidden.** An unattributed event is a LEGAL event meaning "no request behind this write", so a lost identity is indistinguishable from a background job — there is no error, no warning, and nothing that looks wrong in a trace. It surfaced as one failing assertion in the full test suite, which is the only place this machine is loaded enough to flip the order, and it passed on every isolated re-run.
108
+
109
+ **Closed by construction, not by widening the margin.** A store now brackets each non-transactional write (`beginLocalWrite` / `endLocalWrite`) and delivers echoes through `resolveEchoAttribution`. An echo arriving while a write to that table is mid-registration is HELD until that write has had its chance, then answered. Held echoes keep arrival order — a subscriber seeing an update before the insert it updates would be worse off than one missing a `traceId` — and a write that never registers releases the table after a bound rather than parking its stream.
110
+
111
+ Three narrowings, each deliberate:
112
+
113
+ - **Only under `cdc`.** Nothing is injected in `inline` mode, so there is no echo to order against. - **Only non-transactional writes.** `transactional()` registers before COMMIT already; bracketing it would hold OTHER replicas' echoes for the length of the transaction to fix a race that path does not have. Asserted, so the narrowing is on the record rather than something a later reader "fixes". - **A remote write is still never attributed.** The barrier may delay an answer; it must never invent one. Nothing is registered locally for another replica's write, and that stays true while echoes are held.
114
+
115
+ **Both CDC stores had a hand-written copy of the claim-and-emit tail**, which is the shape of the previous three attribution defects in this package. The decision now lives in one function both call, and `echoBarrierParity.test.ts` fails if either store claims for itself, leaves a public write outside the bracket, or brackets the transactional path. The ordering itself is proven against the primitive (`pendingAttribution.test.ts`) — a live suite cannot force it, because the resume point is the driver's choice, and the four barrier tests were verified to go red against the pre-fix behaviour before being trusted.
116
+
117
+ Also fixed: `mysql`'s `updateMany` / `deleteMany` route their events after their transaction commits, so they carried the same race despite not going through the per-row write path. They are bracketed too.
118
+ - **@voltro/cli, @voltro/voltro** — `voltro build` could fail to build the **start bundle** with `Could not resolve "@voltro/cli/startEntry"`, degrading `voltro start` to the slower per-module boot. The serve bundle carried the identical latent failure.
119
+
120
+ Both bundles generate an entry importing a narrow CLI export and build it with `absWorkingDir: <app root>` — so esbuild resolved that bare specifier from the APP's `node_modules`. Under strict pnpm the app has `@voltro/cli` there only if it DECLARES it, and an app normally depends on `voltro` / `@voltro/web` and gets the CLI transitively. The CLI now resolves its own entry from `import.meta.url` and hands esbuild an absolute alias.
121
+
122
+ Same shape as the tsx bug (`tsxLoader.ts`): a package that is OUR dependency, resolved from the user's directory, invisible under strict pnpm. Same answer — the CLI knows where it lives, so it stops asking the app.
123
+
124
+ **The published export was not the problem.** It is present in the tarball — checked against the real 0.20.1 and 0.20.2 packages, `./startEntry` → `./dist/startEntry.js`, file included. Only resolution failed, which is why re-adding the export would have changed nothing.
125
+
126
+ This monorepo hoists everything, so the bare specifier resolves here and the build passes with or without the alias. The test therefore asserts the alias directly rather than inferring it from a green build — the hoisted layout is exactly what hid the strict-pnpm failure in the first place.
127
+
128
+ **Also pinned, after a wrong turn worth recording.** A consumer reported that the framework provides no Suspense boundary, so any suspend during SSR throws. The obvious repair — a root `<Suspense>` — was implemented, measured, and REVERTED:
129
+
130
+ - With a root boundary, a page that THROWS answered **200** with `<template data-msg="Switched to client rendering">`. React downgrades an errored boundary to client rendering, which silently undid the hard failure shipped moments earlier. - Without one, a suspending page renders fine anyway: `renderToPipeableStream` treats the root as an implicit boundary, so a suspend delays the shell flush rather than failing.
131
+
132
+ So the reported problem does not exist on the streaming path, and the obvious fix for it breaks something that does. Both halves are now fixtures with assertions side by side (`ssr-suspends` must render, `ssr-throws` must 500) — adding a root boundary flips the second, and that pair is what makes it visible instead of shipping it. Docs corrected in both languages, including the two places a suspend genuinely is unsupported (`renderToString` behind static prerender, and the client render), neither of which is the framework's choice.
133
+ - **@voltro/cli, @voltro/voltro** — <!-- apiSurface: compatible — `CliRuntime` keeps its exported signature and its behaviour (NodeContext + logger); only `runCli`'s internal composition changed. `loggerConfig` is module-private. -->
134
+
135
+ Every one-shot `voltro` command printed each log line TWICE. Measured on `voltro agents-md`: 76 lines for 38 events.
136
+
137
+ `runCli` installed two loggers. It provided `CliRuntime` (which contains a `LoggerLayer`) to the program, then provided a second `LoggerLayer` around the `matchCauseEffect` wrapping it — so the program ran inside both. Two `LoggerLayer`s in one fiber do not compose the way the name suggests: `LoggerLayer` is `Logger.replace(Logger.defaultLogger, …)`, which removes the DEFAULT logger and adds its own. The second one finds no default left to remove, the removal is a no-op, and the add still happens. Replace composes as replace only against the default — never against another replace.
138
+
139
+ The duplicates were distinguishable only because the outer layer was built without the command's `defaultScope`, so half the output carried `scope` and half did not. Had both been configured identically the output would have been byte-identical pairs, which is a good deal harder to notice than a stray field.
140
+
141
+ **The failure branch is the half that survives a partial fix**, and it did. Moving the second layer from around `matchCauseEffect` onto the error handler repairs the success path and leaves the failure path doubling, because that branch runs while the program's scope is still open and INHERITS its logger. Verified by measuring three shapes rather than reasoning about scopes: handler-provides → 2 lines, handler-inherits → 1, provide-once-outermost → 1.
142
+
143
+ The last is what shipped. The logger is a FiberRef, not a service the program requires, so it is provided ONCE at the outermost boundary and the program gets only `NodeContext`. That covers both branches by construction, rather than by the handler happening to still be inside a scope that has not closed yet. `CliRuntime` is unchanged and still used by `runCliMain`, which provides it once and never had the problem.
144
+
145
+ Guarded by `cliRuntime.test.ts`, which asserts the COUNT (any second provision doubles it regardless of what it logs) and that every line carries the command scope. It was checked against the reverted fix in both of its shapes before being trusted. Its capture spies on stdout AND stderr, deliberately: diagnostics route to stderr by level, and a stdout-only capture reported zero lines for the failure path — reading as "nothing was logged" when the truth was "logged on the other stream", which had the test accusing the fix it was written to protect.
146
+ - **@voltro/cli, @voltro/voltro** — Three corrections to the `db drift` baseline shipped in 0.20.2, all reported by the consumer who verified the fix — and all of them defects in that fix rather than in older code.
147
+
148
+ **1. The first `db drift` after upgrading CRASHED.** `liveFingerprint` is a new column and does not exist until a `db apply` adds it, so naming it in the ledger read died on `SqlError: Failed to execute statement` instead of reaching the "no baseline yet" branch written for exactly that moment. The documented sequence was `0 → apply → clean`; the real one was `crash → apply → clean`, with the crash landing in the first CI run after an upgrade. Proven by dropping and re-adding the column: absent → exit 1 and a driver error, present → exit 0 and the honest message. The read is now `SELECT *`, which cannot go stale against an older ledger.
149
+
150
+ **2. A no-op `db apply` established no baseline.** The baseline is written per applied plan row, so an already-current schema produced none — and "cannot compare" then persisted indefinitely rather than for one run, for any app whose schema was current when it upgraded. A no-op apply now backfills the latest row's `liveFingerprint` instead of inserting a history entry for a migration that did not happen.
151
+
152
+ **3. "No baseline" gets its own exit code: 3.** Previously it exited 0, so a CI gate could not distinguish "compared and matched" from "did not compare" — and on a stable schema the second could persist forever. The consumer named that as their reason for NOT adding a drift gate: it would pass vacuously, which is the failure this whole thread is about. Now `0` = matched, `3` = no baseline, `4` = diverged.
153
+
154
+ **And the SQL-error reporter added in the same release did not work on this path.** It walked `.cause`, and an `Effect` `FiberFailure` has none — its cause hides behind `Symbol(effect/Runtime/FiberFailure/Cause)`, with only `stack`, `message` and `name` as own keys. So the helper returned `undefined` and not even its "no statement attached" fallback fired. The consumer reproduced that against an empty database and checked field by field; all absent.
155
+
156
+ The reason the tests missed it is worth recording: every fixture was a hand-built object WITH a `.cause` — the shape assumed, not the shape the runtime produces. The suite now builds a real `FiberFailure` through `Effect.runPromise`, and the walk unwraps the symbol and flattens the `Cause` tree (`Fail`/`Die`/`Sequential`).
157
+
158
+ Their note on the irony is fair and is the reason this is one entry rather than two: defect 1 above IS the "next DB-shaped error in your CI" that the reporter existed to make readable, and it arrived as a bare wrapper plus a driver stack. With the statement printed it would have named the missing column immediately.
159
+
160
+ **A FOURTH copy of both defects was found in `voltro dev`'s migrations inspect endpoint, and it was the worst one.** It carried the same postgres-only `::text` casts, wrapped in `orElseSucceed(() => [])` — so on every non-postgres dialect the syntax error became an EMPTY history rather than a failure: the devtools migrations panel showed nothing, and with no history row the drift verdict came out `false`. A silent, permanent "no drift" on every mysql/mariadb/mssql/sqlite app. It also compared the declared hash against a live one, exactly like the CLI did.
161
+
162
+ Both are fixed there too, and `ledgerReadPortability.test.ts` now fails if any query touching `_voltro_migration_plans` grows a `::type` cast again. Three copies were fixed in one change and the fourth was missed in the same change, which is the argument for the test rather than another paragraph in a maintainer note.
163
+ - **@voltro/cli, @voltro/voltro** — `voltro dev` served a client-only shell — with a **200** — whenever a `renderMode: 'ssr'` page failed to render on the server. It now answers 500 with the cause, exactly as `voltro start` does.
164
+
165
+ **Reported as "voltro dev does not SSR". It does**, and has since before 0.20.0 — the middleware, its intent stated in a comment ("mirroring what `voltro start` does in production"), is an ancestor of every 0.20.x tag. What the reporter saw was the masking: their pages suspended during the server render (a lazily-loaded i18n catalog above any Suspense boundary), all 225 degraded to Vite's SPA shell, and an empty `<div id="root">` is indistinguishable from a framework that never server-renders. Their conclusion was the only one the evidence supported.
166
+
167
+ **The 200 is the part that mattered.** The same render is a hard 500 under `voltro start`, so those pages were down in production while dev reported success — the inverse of the usual "works in dev, breaks in prod", and worse, because nothing prompts you to look. Measured before the fix: `HTTP 200`, no `x-voltro-rendered-by` header at all, and the thrown error present in the dev log but nowhere in the response.
168
+
169
+ Three sites did this (both streaming `onShellError` handlers and the outer catch); all three now fail through one helper. The pattern was already in the file — the `isDeferralNotSupported` branch refuses rather than degrades and says why in the same words ("falling through would leave the developer with an unstyled page and a log line, which is exactly the silent degradation the hard error exists to prevent"). One of the removed fallbacks sat directly under a comment stating that falling through would mask the bug.
170
+
171
+ Dev puts the cause and stack in the response body; production keeps its bare `server error`, so a stack never reaches a public response. That is a difference in what the failure says, never in whether it fails.
172
+
173
+ **Also fixed, found while reproducing it: a page added while `voltro dev` runs was never server-rendered.** The middleware matched against a route table built once at boot, so a new page missed matching entirely and returned before its module was ever loaded — Vite's SPA shell, 200, and *no log line at all*, because the middleware never ran. The page tree the middleware reads is now refreshed by the same regeneration that rewrites the route table (`dirs` too, or a layout added after boot would be invisible to the spa-shell decision).
174
+
175
+ Both are covered by `webDevSsrLayoutLoader.test.ts` against a real dev server: `/ssr-throws` must answer 500 + `x-voltro-rendered-by: ssr-dev-failed` + the cause and must never contain the empty shell, and a page written while the server runs must be server-rendered without a restart. Each assertion was verified red against its own reverted fix — separately, because the first failure aborts the test and would have left the second unproven.
176
+
177
+ One thing this does NOT change: the framework still provides a Suspense boundary only for its own deferral (`<Await>`), not a blanket one at the root. Code that suspends outside it needs a boundary you mount yourself. That is now documented next to the failure behaviour, since a hard 500 is how you will meet it.
178
+
179
+ ### Internal (no consumer-facing effect)
180
+
181
+ - **@voltro/cli** — Maintainer notes only — no shipped behaviour changes.
182
+
183
+ `mssqlClusterPatch.ts`'s header said the `@effect/cluster` patch covers "two mssql-only bugs" (it is four: the `deliver_at` INT-overflow, the MERGE…OUTPUT with correlated sub-SELECTs, `FOR UPDATE`, and `USING (SELECT * FROM (VALUES …))`) and implied that a version bump needs nothing but a re-key, because 0.59.0 → 0.60.0 happened to apply unchanged. On 0.60.2 the same patch fails on 3 of its 6 files — upstream refactored `SqlMessageStorage` and moved the context the hunks match on. A bump can require REGENERATING the patch.
184
+
185
+ The regeneration recipe now lives in `packages/sql-mssql/CLAUDE.md`, together with the two measurements that produced confidently wrong answers while working this out: reading an already-patched `node_modules/.pnpm/*patch_hash=*` copy and concluding upstream had fixed it, and un-patching one of the several installed copies and concluding the patch was not load-bearing. Both look like evidence.
186
+
187
+ Also recorded there: verify by BREAKING it. `git apply --check` proves the patch lands, not that it still fixes anything. Un-patched, the mssql cluster suite fails with `Incorrect syntax near ')'`; patched, 5/5 against the live fixture.
188
+
189
+ ---
190
+
42
191
  ## [0.20.2] — 2026-07-30
43
192
 
44
193
  ### Fixed
@@ -485,7 +485,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
485
485
  SOFTWARE.
486
486
  ```
487
487
 
488
- ## @effect/sql@0.51.1
488
+ ## @effect/sql@0.52.0
489
489
 
490
490
  License: MIT
491
491
 
@@ -513,7 +513,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
513
513
  SOFTWARE.
514
514
  ```
515
515
 
516
- ## @effect/sql-mssql@0.52.0
516
+ ## @effect/sql-mssql@0.53.0
517
517
 
518
518
  License: MIT
519
519
 
@@ -581,7 +581,7 @@ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
581
581
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
582
582
  ```
583
583
 
584
- ## @types/node@26.1.1
584
+ ## @types/node@26.1.2
585
585
 
586
586
  License: MIT
587
587
 
package/dist/index.d.ts CHANGED
@@ -24,6 +24,7 @@ import { SqlDialect } from '@voltro/database';
24
24
  import { SqlError } from '@effect/sql';
25
25
  import { TransactionConnection } from '@effect/sql/SqlClient';
26
26
  import { _voltroMssqlCdcOffsetsTable } from '@voltro/database';
27
+ import { WriteAttribution } from '@voltro/database';
27
28
 
28
29
  export { CDC_OFFSETS_TABLE }
29
30
 
package/dist/index.js CHANGED
@@ -3,14 +3,14 @@ import { Config as t, Effect as n, Layer as r, ManagedRuntime as i, Option as a,
3
3
  import { EventEmitter as c } from "node:events";
4
4
  import { createLogger as l } from "@voltro/logger";
5
5
  import { SqlClient as u, TransactionConnection as d } from "@effect/sql/SqlClient";
6
- import { CDC_OFFSETS_TABLE as f, EagerCardinalityError as p, _voltroMssqlCdcOffsetsTable as m, attachEagerLoads as h, attributionFields as g, compileEagerJson as _, compilePredicate as v, compileRawFragment as y, compileSelect as b, currentWriteAttribution as x, decodeRowsFromSchema as S, hasEagerLoads as C, isTableReactive as w, qualifyTable as T, raiseChangeListenerCeiling as E, recordsTable as D, requireTable as O, runWithWriteAttribution as ee, runWriteRecorders as k, settleTransactionExit as A, stampGeneratedId as j, stampGeneratedIds as M } from "@voltro/database";
6
+ import { CDC_OFFSETS_TABLE as f, EagerCardinalityError as p, _voltroMssqlCdcOffsetsTable as m, attachEagerLoads as h, attributionFields as g, compileEagerJson as _, compilePredicate as v, compileRawFragment as y, compileSelect as b, currentWriteAttribution as x, decodeRowsFromSchema as S, hasEagerLoads as ee, isTableReactive as C, qualifyTable as w, raiseChangeListenerCeiling as T, recordsTable as E, requireTable as D, runWithWriteAttribution as O, runWriteRecorders as k, settleTransactionExit as A, stampGeneratedId as j, stampGeneratedIds as M, withCapturedAttribution as N } from "@voltro/database";
7
7
  //#region src/sqlLayer.ts
8
- var N = {
8
+ var P = {
9
9
  ...e.defaultParameterTypes,
10
10
  null: e.defaultParameterTypes.object
11
- }, P = (n) => e.layerConfig({
11
+ }, F = (n) => e.layerConfig({
12
12
  server: t.succeed(n.server),
13
- parameterTypes: t.succeed(N),
13
+ parameterTypes: t.succeed(P),
14
14
  ...n.port === void 0 ? {} : { port: t.succeed(n.port) },
15
15
  ...n.database === void 0 ? {} : { database: t.succeed(n.database) },
16
16
  ...n.username === void 0 ? {} : { username: t.succeed(n.username) },
@@ -18,7 +18,7 @@ var N = {
18
18
  ...n.encrypt === void 0 ? {} : { encrypt: t.succeed(n.encrypt) },
19
19
  ...n.trustServer === void 0 ? {} : { trustServer: t.succeed(n.trustServer) },
20
20
  ...n.maxConnections === void 0 ? {} : { maxConnections: t.succeed(n.maxConnections) }
21
- }), F = (e) => {
21
+ }), I = (e) => {
22
22
  if (e.url) {
23
23
  let t = new URL(e.url);
24
24
  return {
@@ -40,7 +40,7 @@ var N = {
40
40
  trustServer: !0,
41
41
  ...e.maxConnections === void 0 ? {} : { maxConnections: e.maxConnections }
42
42
  };
43
- }, I = (e) => P(F(e)), L = /* @__PURE__ */ new Set(["1205"]), R = (e) => {
43
+ }, L = (e) => F(I(e)), R = /* @__PURE__ */ new Set(["1205"]), z = (e) => {
44
44
  let t = e;
45
45
  for (let e = 0; e < 5 && typeof t == "object" && t; e++) {
46
46
  let e = t.number;
@@ -49,17 +49,17 @@ var N = {
49
49
  if (typeof n == "string") return n;
50
50
  t = t.cause;
51
51
  }
52
- }, z = (e) => {
53
- let t = R(e);
54
- return t !== void 0 && L.has(t);
55
- }, B = /* @__PURE__ */ new Set(["2601", "2627"]), V = (e) => {
56
- let t = R(e);
57
- return t !== void 0 && B.has(t);
58
- }, H = (e) => z(e) ? "retry" : "noRetry", U = {
52
+ }, B = (e) => {
53
+ let t = z(e);
54
+ return t !== void 0 && R.has(t);
55
+ }, V = /* @__PURE__ */ new Set(["2601", "2627"]), H = (e) => {
56
+ let t = z(e);
57
+ return t !== void 0 && V.has(t);
58
+ }, U = (e) => B(e) ? "retry" : "noRetry", W = {
59
59
  I: "insert",
60
60
  U: "update",
61
61
  D: "delete"
62
- }, W = (e, t) => e(n.gen(function* () {
62
+ }, G = (e, t) => e(n.gen(function* () {
63
63
  let e = yield* u;
64
64
  if (((yield* e`
65
65
  SELECT COUNT(*) AS ${e("on")}
@@ -67,18 +67,18 @@ var N = {
67
67
  WHERE database_id = DB_ID()`)[0]?.on ?? 0) === 0) return yield* n.fail(/* @__PURE__ */ Error("mssql Change Tracking CDC requires CT enabled on the database. Run `ALTER DATABASE <db> SET CHANGE_TRACKING = ON (CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON)`, or set CDC=0 for inline emit."));
68
68
  for (let n of t) yield* e.unsafe(`IF NOT EXISTS (
69
69
  SELECT 1 FROM sys.change_tracking_tables
70
- WHERE object_id = OBJECT_ID(${G(n)})
70
+ WHERE object_id = OBJECT_ID(${K(n)})
71
71
  )
72
- ALTER TABLE ${K(n)} ENABLE CHANGE_TRACKING WITH (TRACK_COLUMNS_UPDATED = OFF)`);
73
- })).then(() => void 0), G = (e) => `'${e.replace(/'/g, "''")}'`, K = (e) => `[${e.replace(/\]/g, "]]")}]`, q = async (e) => {
72
+ ALTER TABLE ${q(n)} ENABLE CHANGE_TRACKING WITH (TRACK_COLUMNS_UPDATED = OFF)`);
73
+ })).then(() => void 0), K = (e) => `'${e.replace(/'/g, "''")}'`, q = (e) => `[${e.replace(/\]/g, "]]")}]`, J = async (e) => {
74
74
  let t = l({ scope: "voltro:mssql:cdc" }), r = e.pollIntervalMs ?? 500;
75
- await W(e.run, e.tables);
75
+ await G(e.run, e.tables);
76
76
  let i = async () => (await e.run(n.gen(function* () {
77
77
  return yield* (yield* u)`SELECT CONVERT(VARCHAR(40), CHANGE_TRACKING_CURRENT_VERSION()) AS v`;
78
78
  })))[0]?.v ?? "0", a = e.startVersion ?? await i(), o = !1, s = null, c = !1, d = (e, t) => BigInt(e) > BigInt(t), f = async (r, o) => {
79
79
  let s = await e.run(n.gen(function* () {
80
- let e = yield* u, t = e.unsafe(K(r)), n = (yield* e`
81
- SELECT CONVERT(VARCHAR(40), CHANGE_TRACKING_MIN_VALID_VERSION(OBJECT_ID(${e.unsafe(G(r))}))) AS floor`)[0]?.floor;
80
+ let e = yield* u, t = e.unsafe(q(r)), n = (yield* e`
81
+ SELECT CONVERT(VARCHAR(40), CHANGE_TRACKING_MIN_VALID_VERSION(OBJECT_ID(${e.unsafe(K(r))}))) AS floor`)[0]?.floor;
82
82
  return n != null && BigInt(o) < BigInt(n) ? {
83
83
  resync: !0,
84
84
  rows: []
@@ -96,7 +96,7 @@ var N = {
96
96
  return;
97
97
  }
98
98
  for (let t of s.rows) {
99
- let n = U[t.__ct_op];
99
+ let n = W[t.__ct_op];
100
100
  if (!n) continue;
101
101
  let { __ct_op: i, __ct_id: a, ...o } = t;
102
102
  if (n === "delete") e.onChange({
@@ -147,15 +147,15 @@ var N = {
147
147
  },
148
148
  currentVersion: () => a
149
149
  };
150
- }, J = l({ scope: "voltro:mssql" }), Y = async (e) => {
150
+ }, Y = l({ scope: "voltro:mssql" }), X = async (e) => {
151
151
  let t = e.changeStrategy ?? "inline", n = t;
152
- t === "cdc" && !e.cdcConfig && (J.warn("changeStrategy='cdc' requires cdcConfig (replicaId + includeTables); falling back to 'inline'."), n = "inline");
153
- let a = e.tracerLayer ? r.mergeAll(e.sqlLayer, e.tracerLayer) : e.sqlLayer, o = i.make(a), s = new Z(await o.runPromise(u), o, n);
152
+ t === "cdc" && !e.cdcConfig && (Y.warn("changeStrategy='cdc' requires cdcConfig (replicaId + includeTables); falling back to 'inline'."), n = "inline");
153
+ let a = e.tracerLayer ? r.mergeAll(e.sqlLayer, e.tracerLayer) : e.sqlLayer, o = i.make(a), s = new Q(await o.runPromise(u), o, n);
154
154
  return n === "cdc" && e.cdcConfig && await s.startCdcConsumer(e.cdcConfig), s;
155
- }, X = () => {
155
+ }, Z = () => {
156
156
  let e = x();
157
- return e === void 0 ? (e) => e() : (t) => ee(e, t);
158
- }, Z = class e {
157
+ return e === void 0 ? (e) => e() : (t) => O(e, t);
158
+ }, Q = class e {
159
159
  sql;
160
160
  runtime;
161
161
  changeStrategy;
@@ -168,7 +168,7 @@ var N = {
168
168
  cdcReplicaId = "";
169
169
  cdcStreamName = "default";
170
170
  constructor(e, t, n = "inline", r = null, i) {
171
- this.sql = e, this.runtime = t, this.changeStrategy = n, this.namespace = r, this.emitter = i ?? new c(), E(this.emitter);
171
+ this.sql = e, this.runtime = t, this.changeStrategy = n, this.namespace = r, this.emitter = i ?? new c(), T(this.emitter);
172
172
  }
173
173
  get inlineEmit() {
174
174
  return this.changeStrategy === "inline";
@@ -177,61 +177,61 @@ var N = {
177
177
  return t === this.namespace ? this : new e(this.sql, this.runtime, this.changeStrategy, t, this.emitter);
178
178
  }
179
179
  nsT(e) {
180
- return T(this.namespace, e);
180
+ return w(this.namespace, e);
181
181
  }
182
182
  __mssqlReplicationFriend = { runEffect: (e) => this.runtime.runPromise(e) };
183
183
  async executeQuery(e, t) {
184
184
  let r = b(e, this.sql, this.namespace), i = t ? n.provideService(r, d, t) : r;
185
185
  return S(await this.runtime.runPromise(i), e.table, "mssql");
186
186
  }
187
- async executeInsert(e, t, r, i) {
187
+ async executeInsert(e, t, r, i, a) {
188
188
  t = j(e, t);
189
- let a = this.sql, o = a`INSERT INTO ${a(this.nsT(e))} ${a.insert(t).returning("*")}`, s = r ? n.provideService(o, d, r) : o, c = (await this.runtime.runPromise(s))[0];
190
- if (!c) throw Error(`MssqlStore.insert: row not returned post-insert in '${e}'`);
189
+ let o = this.sql, s = o`INSERT INTO ${o(this.nsT(e))} ${o.insert(t).returning("*")}`, c = r ? n.provideService(s, d, r) : s, l = (await this.runtime.runPromise(c))[0];
190
+ if (!l) throw Error(`MssqlStore.insert: row not returned post-insert in '${e}'`);
191
191
  return await this.routeEvent({
192
192
  table: e,
193
193
  op: "insert",
194
194
  old: null,
195
- new: c
196
- }, i, r), c;
195
+ new: l
196
+ }, i, r, a), l;
197
197
  }
198
- async executeUpdate(e, t, r, i, a) {
199
- let o = this.sql, s = o`UPDATE ${o(this.nsT(e))} SET ${o.update(r).returning("*")} WHERE ${o("id")} = ${t}`, c = i ? n.provideService(s, d, i) : s, l = (await this.runtime.runPromise(c))[0];
200
- return l ? (await this.routeEvent({
198
+ async executeUpdate(e, t, r, i, a, o) {
199
+ let s = this.sql, c = s`UPDATE ${s(this.nsT(e))} SET ${s.update(r).returning("*")} WHERE ${s("id")} = ${t}`, l = i ? n.provideService(c, d, i) : c, u = (await this.runtime.runPromise(l))[0];
200
+ return u ? (await this.routeEvent({
201
201
  table: e,
202
202
  op: "update",
203
203
  old: null,
204
- new: l
205
- }, a, i), l) : null;
204
+ new: u
205
+ }, a, i, o), u) : null;
206
206
  }
207
- async executeInsertMany(e, t, r, i) {
207
+ async executeInsertMany(e, t, r, i, a) {
208
208
  if (t = M(e, t), t.length === 0) return [];
209
- let a = this.sql, o = a`INSERT INTO ${a(this.nsT(e))} ${a.insert(t).returning("*")}`, s = r ? n.provideService(o, d, r) : o, c = await this.runtime.runPromise(s), l = t.map((e) => e.id), u = new Map(c.map((e) => [e.id, e])), f = l.map((e) => u.get(e)).filter((e) => e !== void 0), p = f.length === c.length ? f : [...c];
210
- for (let t of p) await this.routeEvent({
209
+ let o = this.sql, s = o`INSERT INTO ${o(this.nsT(e))} ${o.insert(t).returning("*")}`, c = r ? n.provideService(s, d, r) : s, l = await this.runtime.runPromise(c), u = t.map((e) => e.id), f = new Map(l.map((e) => [e.id, e])), p = u.map((e) => f.get(e)).filter((e) => e !== void 0), m = p.length === l.length ? p : [...l];
210
+ for (let t of m) await this.routeEvent({
211
211
  table: e,
212
212
  op: "insert",
213
213
  old: null,
214
214
  new: t
215
- }, i, r);
216
- return p;
215
+ }, i, r, a);
216
+ return m;
217
217
  }
218
- async executePatchJson(e, t, r, i, a, o) {
219
- let s = this.sql, c = r.split("."), l = c[0], u = c.slice(1), f = u.length === 0 ? "$" : `$.${u.join(".")}`, p = JSON.stringify(i ?? null), m = s`UPDATE ${s(this.nsT(e))} SET ${s(l)} = JSON_MODIFY(${s(l)}, ${f}, JSON_QUERY(${p})) OUTPUT INSERTED.* WHERE ${s("id")} = ${t}`, h = a ? n.provideService(m, d, a) : m, g = (await this.runtime.runPromise(h))[0];
220
- return g ? (await this.routeEvent({
218
+ async executePatchJson(e, t, r, i, a, o, s) {
219
+ let c = this.sql, l = r.split("."), u = l[0], f = l.slice(1), p = f.length === 0 ? "$" : `$.${f.join(".")}`, m = JSON.stringify(i ?? null), h = c`UPDATE ${c(this.nsT(e))} SET ${c(u)} = JSON_MODIFY(${c(u)}, ${p}, JSON_QUERY(${m})) OUTPUT INSERTED.* WHERE ${c("id")} = ${t}`, g = a ? n.provideService(h, d, a) : h, _ = (await this.runtime.runPromise(g))[0];
220
+ return _ ? (await this.routeEvent({
221
221
  table: e,
222
222
  op: "update",
223
223
  old: null,
224
- new: g
225
- }, o, a), g) : null;
224
+ new: _
225
+ }, o, a, s), _) : null;
226
226
  }
227
- async executeDelete(e, t, r, i) {
228
- let a = this.sql, o = a`DELETE FROM ${a(this.nsT(e))} OUTPUT DELETED.* WHERE ${a("id")} = ${t}`, s = r ? n.provideService(o, d, r) : o, c = (await this.runtime.runPromise(s))[0];
229
- return c ? (await this.routeEvent({
227
+ async executeDelete(e, t, r, i, a) {
228
+ let o = this.sql, s = o`DELETE FROM ${o(this.nsT(e))} OUTPUT DELETED.* WHERE ${o("id")} = ${t}`, c = r ? n.provideService(s, d, r) : s, l = (await this.runtime.runPromise(c))[0];
229
+ return l ? (await this.routeEvent({
230
230
  table: e,
231
231
  op: "delete",
232
- old: c,
232
+ old: l,
233
233
  new: null
234
- }, i, r), !0) : !1;
234
+ }, i, r, a), !0) : !1;
235
235
  }
236
236
  async appendInTxn(e, t, r) {
237
237
  let i = this.sql, a = i`INSERT INTO ${i(this.nsT(e))} ${i.insert(t)}`;
@@ -241,11 +241,11 @@ var N = {
241
241
  let a = this.sql, o = Object.entries(r).map(([e, t]) => a`${a(e)} = ${t}`), s = a`SELECT MAX(${a(t)}) AS ${a("m")} FROM ${a(this.nsT(e))} WHERE ${a.and(o)}`, c = (await this.runtime.runPromise(i ? n.provideService(s, d, i) : s))[0]?.m;
242
242
  return c == null ? null : Number(c);
243
243
  }
244
- async routeEvent(e, t, n = null) {
244
+ async routeEvent(e, t, n = null, r) {
245
245
  e = {
246
- ...g(),
246
+ ...g(r),
247
247
  ...e
248
- }, D(e.table) && await k({
248
+ }, E(e.table) && await k({
249
249
  append: (e, t) => this.appendInTxn(e, t, n),
250
250
  maxOf: (e, t, r) => this.maxInTxn(e, t, r, n)
251
251
  }, {
@@ -255,7 +255,7 @@ var N = {
255
255
  prev: e.old,
256
256
  traceId: e.traceId,
257
257
  subjectId: e.subjectId
258
- }), w(e.table) && (t === null ? this.inlineEmit && this.emitter.emit("change", e) : t.push(e));
258
+ }), C(e.table) && (t === null ? this.inlineEmit && this.emitter.emit("change", e) : t.push(e));
259
259
  }
260
260
  query(e) {
261
261
  return this.runWithEager(e, null);
@@ -265,34 +265,34 @@ var N = {
265
265
  return this.runtime.runPromise(n);
266
266
  }
267
267
  async runWithEager(e, t) {
268
- if (!C(e)) return this.executeQuery(e, t);
268
+ if (!ee(e)) return this.executeQuery(e, t);
269
269
  let r = this.namespace === null ? _(e, this.sql, "mssql") : null;
270
270
  if (r !== null) try {
271
271
  let e = t ? n.provideService(r.fragment, d, t) : r.fragment, i = await this.runtime.runPromise(e);
272
272
  return r.decode(i);
273
273
  } catch (e) {
274
274
  if (e instanceof p) throw e;
275
- J.warn("mssql JSON-agg eager-load failed; falling back to walker", { err: e });
275
+ Y.warn("mssql JSON-agg eager-load failed; falling back to walker", { err: e });
276
276
  }
277
- return h(await this.executeQuery(e, t), e.eager, e.sourceTable ?? O(e.table), (e) => this.executeQuery(e, t));
277
+ return h(await this.executeQuery(e, t), e.eager, e.sourceTable ?? D(e.table), (e) => this.executeQuery(e, t));
278
278
  }
279
279
  getInternalRunWithEager() {
280
280
  return this.runWithEager.bind(this);
281
281
  }
282
282
  insert(e, t) {
283
- return X()(() => this.executeInsert(e, t, null, null));
283
+ return N((n) => this.executeInsert(e, t, null, null, n));
284
284
  }
285
285
  insertMany(e, t) {
286
- return X()(() => this.executeInsertMany(e, t, null, null));
286
+ return N((n) => this.executeInsertMany(e, t, null, null, n));
287
287
  }
288
288
  patchJson(e, t, n, r) {
289
- return X()(() => this.executePatchJson(e, t, n, r, null, null));
289
+ return N((i) => this.executePatchJson(e, t, n, r, null, null, i));
290
290
  }
291
291
  update(e, t, n) {
292
- return X()(() => this.executeUpdate(e, t, n, null, null));
292
+ return N((r) => this.executeUpdate(e, t, n, null, null, r));
293
293
  }
294
294
  delete(e, t) {
295
- return X()(() => this.executeDelete(e, t, null, null));
295
+ return N((n) => this.executeDelete(e, t, null, null, n));
296
296
  }
297
297
  async updateMany(e, t, n) {
298
298
  let r = this.sql, i = v(n.where, r, this.namespace), a = r`UPDATE ${r(this.nsT(e))} SET ${r.update(t)} OUTPUT INSERTED.* WHERE ${i}`, o = await this.runtime.runPromise(a);
@@ -315,10 +315,10 @@ var N = {
315
315
  return a.length;
316
316
  }
317
317
  upsert(e, t, n) {
318
- return X()(() => this.executeUpsert(e, t, n, null, null));
318
+ return N((r) => this.executeUpsert(e, t, n, null, null, r));
319
319
  }
320
320
  insertIgnore(e, t, n) {
321
- return X()(() => this.executeInsertIgnore(e, t, n, null, null));
321
+ return N((r) => this.executeInsertIgnore(e, t, n, null, null, r));
322
322
  }
323
323
  upsertPatch(e, t, n) {
324
324
  if (typeof n.update == "function") return n.update(t);
@@ -331,17 +331,17 @@ var N = {
331
331
  for (let [t, i] of Object.entries(e)) t !== "id" && (n.conflictColumns.includes(t) || (r[t] = i));
332
332
  return r;
333
333
  }
334
- async executeUpsert(e, t, n, r, i) {
334
+ async executeUpsert(e, t, n, r, i, a) {
335
335
  if (typeof n.update != "function" && n.conflictColumns.length > 0) return this.mergeUpsert(e, t, {
336
336
  conflictColumns: n.conflictColumns,
337
337
  ...n.update ? { update: n.update } : {}
338
338
  }, r, i);
339
- let a = await this.findByConflict(e, t, n.conflictColumns, r);
340
- if (a) return await this.executeUpdate(e, a.id, this.upsertPatch(t, a, n), r, i) ?? a;
339
+ let o = await this.findByConflict(e, t, n.conflictColumns, r);
340
+ if (o) return await this.executeUpdate(e, o.id, this.upsertPatch(t, o, n), r, i) ?? o;
341
341
  try {
342
342
  return await this.executeInsert(e, t, r, i);
343
343
  } catch (a) {
344
- if (!V(a)) throw a;
344
+ if (!H(a)) throw a;
345
345
  let o = await this.findByConflict(e, t, n.conflictColumns, r);
346
346
  if (!o) throw a;
347
347
  return await this.executeUpdate(e, o.id, this.upsertPatch(t, o, n), r, i) ?? o;
@@ -364,14 +364,14 @@ var N = {
364
364
  new: x
365
365
  }, a), x;
366
366
  }
367
- async executeInsertIgnore(e, t, n, r, i) {
367
+ async executeInsertIgnore(e, t, n, r, i, a) {
368
368
  t = j(e, t);
369
- let a = await this.findByConflict(e, t, n.conflictColumns, r);
370
- if (a) return a;
369
+ let o = await this.findByConflict(e, t, n.conflictColumns, r);
370
+ if (o) return o;
371
371
  try {
372
372
  return await this.executeInsert(e, t, r, i);
373
373
  } catch (i) {
374
- if (!V(i)) throw i;
374
+ if (!H(i)) throw i;
375
375
  let a = await this.findByConflict(e, t, n.conflictColumns, r);
376
376
  if (!a) throw i;
377
377
  return a;
@@ -389,9 +389,9 @@ var N = {
389
389
  if (this.cdcHandle) return;
390
390
  this.cdcReplicaId = e.replicaId;
391
391
  let t = e.includeTables ?? [];
392
- t.length === 0 && J.warn("cdc: no reactive tables to tail; Change Tracking reader idle. Set includeTables to enable.");
392
+ t.length === 0 && Y.warn("cdc: no reactive tables to tail; Change Tracking reader idle. Set includeTables to enable.");
393
393
  let n = await this.readCdcOffset(e.replicaId);
394
- this.cdcHandle = await q({
394
+ this.cdcHandle = await J({
395
395
  run: this.__mssqlReplicationFriend.runEffect,
396
396
  tables: t,
397
397
  startVersion: n,
@@ -399,9 +399,9 @@ var N = {
399
399
  onVersion: (e) => {
400
400
  this.cdcPendingVersion = e;
401
401
  },
402
- onError: (e) => J.warn("cdc: consumer error", {}, e),
402
+ onError: (e) => Y.warn("cdc: consumer error", {}, e),
403
403
  onResync: () => {
404
- J.warn("cdc: resynced to current CT version after retention gap — subscriptions self-heal on the next change");
404
+ Y.warn("cdc: resynced to current CT version after retention gap — subscriptions self-heal on the next change");
405
405
  }
406
406
  }), this.cdcCheckpointTimer = setInterval(() => {
407
407
  this.flushCdcOffset();
@@ -412,12 +412,12 @@ var N = {
412
412
  let t = this.sql, n = (await this.runtime.runPromise(t`
413
413
  SELECT TOP 1 ${t("ctVersion")} FROM ${t(f)}
414
414
  WHERE ${t("id")} = ${e}`))[0]?.ctVersion;
415
- return n ? (J.info("cdc: resuming from persisted CT version", {
415
+ return n ? (Y.info("cdc: resuming from persisted CT version", {
416
416
  replicaId: e,
417
417
  version: n
418
418
  }), n) : null;
419
419
  } catch (t) {
420
- return J.warn("cdc: no readable offset; starting at current CT version", { replicaId: e }, t), null;
420
+ return Y.warn("cdc: no readable offset; starting at current CT version", { replicaId: e }, t), null;
421
421
  }
422
422
  }
423
423
  async flushCdcOffset() {
@@ -437,7 +437,7 @@ var N = {
437
437
  update: ["ctVersion", "updatedAt"]
438
438
  }, null, null);
439
439
  } catch (t) {
440
- this.cdcPendingVersion = e, J.warn("cdc: checkpoint write failed", {}, t);
440
+ this.cdcPendingVersion = e, Y.warn("cdc: checkpoint write failed", {}, t);
441
441
  }
442
442
  }
443
443
  }
@@ -467,26 +467,26 @@ var N = {
467
467
  }
468
468
  async transactional(e) {
469
469
  this.inflightTxns++;
470
- let t = X(), r = 0, i = n.suspend(() => {
471
- let i = ++r;
472
- return this.sql.withTransaction(n.flatMap(n.serviceOption(d), (r) => {
473
- if (a.isNone(r)) return n.fail(/* @__PURE__ */ Error("MssqlStore.transactional: TransactionConnection missing."));
474
- let o = new Q(this, r.value);
470
+ let t = x(), r = Z(), i = 0, o = n.suspend(() => {
471
+ let o = ++i;
472
+ return this.sql.withTransaction(n.flatMap(n.serviceOption(d), (i) => {
473
+ if (a.isNone(i)) return n.fail(/* @__PURE__ */ Error("MssqlStore.transactional: TransactionConnection missing."));
474
+ let s = new te(this, i.value, t);
475
475
  return n.tryPromise({
476
- try: () => t(() => e(o)).then((e) => ({
476
+ try: () => r(() => e(s)).then((e) => ({
477
477
  result: e,
478
- view: o,
479
- attempt: i
478
+ view: s,
479
+ attempt: o
480
480
  })),
481
481
  catch: (e) => e
482
482
  });
483
483
  }));
484
- }), o = s.exponential("10 millis").pipe(s.compose(s.recurs(3)), s.whileInput(z)), c = i.pipe(n.retry(o), n.withSpan("store.transactional", { attributes: {
484
+ }), c = s.exponential("10 millis").pipe(s.compose(s.recurs(3)), s.whileInput(B)), l = o.pipe(n.retry(c), n.withSpan("store.transactional", { attributes: {
485
485
  "db.system": "mssql",
486
486
  "db.operation": "transaction"
487
487
  } }));
488
488
  try {
489
- let e = A(await this.runtime.runPromiseExit(c));
489
+ let e = A(await this.runtime.runPromiseExit(l));
490
490
  return e.view.commitEvents(), e.result;
491
491
  } finally {
492
492
  this.inflightTxns--;
@@ -501,7 +501,7 @@ var N = {
501
501
  return this.changeStrategy === "cdc" ? "fleet" : "local";
502
502
  }
503
503
  injectExternalChange(e) {
504
- w(e.table) && this.emitter.emit("change", {
504
+ C(e.table) && this.emitter.emit("change", {
505
505
  ...e,
506
506
  origin: "injected"
507
507
  });
@@ -517,7 +517,7 @@ var N = {
517
517
  if (this.inflightTxns > 0) {
518
518
  let t = Date.now() + e;
519
519
  for (; this.inflightTxns > 0 && Date.now() < t;) await new Promise((e) => setTimeout(e, 25));
520
- this.inflightTxns > 0 && J.warn("close: grace period expired with in-flight transactions", {
520
+ this.inflightTxns > 0 && Y.warn("close: grace period expired with in-flight transactions", {
521
521
  gracePeriodMs: e,
522
522
  inflight: this.inflightTxns
523
523
  });
@@ -527,31 +527,32 @@ var N = {
527
527
  async ping() {
528
528
  await this.runtime.runPromise(this.sql`SELECT 1`);
529
529
  }
530
- }, Q = class {
530
+ }, te = class {
531
531
  parent;
532
532
  txn;
533
+ attr;
533
534
  events = [];
534
535
  committed = !1;
535
- constructor(e, t) {
536
- this.parent = e, this.txn = t;
536
+ constructor(e, t, n = void 0) {
537
+ this.parent = e, this.txn = t, this.attr = n;
537
538
  }
538
539
  query(e) {
539
540
  return this.parent.getInternalRunWithEager()(e, this.txn);
540
541
  }
541
542
  insert(e, t) {
542
- return this.parent.getInternalExecuteInsert()(e, t, this.txn, this.events);
543
+ return this.parent.getInternalExecuteInsert()(e, t, this.txn, this.events, this.attr);
543
544
  }
544
545
  insertMany(e, t) {
545
- return this.parent.getInternalExecuteInsertMany()(e, t, this.txn, this.events);
546
+ return this.parent.getInternalExecuteInsertMany()(e, t, this.txn, this.events, this.attr);
546
547
  }
547
548
  patchJson(e, t, n, r) {
548
- return this.parent.getInternalExecutePatchJson()(e, t, n, r, this.txn, this.events);
549
+ return this.parent.getInternalExecutePatchJson()(e, t, n, r, this.txn, this.events, this.attr);
549
550
  }
550
551
  update(e, t, n) {
551
- return this.parent.getInternalExecuteUpdate()(e, t, n, this.txn, this.events);
552
+ return this.parent.getInternalExecuteUpdate()(e, t, n, this.txn, this.events, this.attr);
552
553
  }
553
554
  delete(e, t) {
554
- return this.parent.getInternalExecuteDelete()(e, t, this.txn, this.events);
555
+ return this.parent.getInternalExecuteDelete()(e, t, this.txn, this.events, this.attr);
555
556
  }
556
557
  async updateMany(e, t, n) {
557
558
  let r = await this.query({
@@ -578,10 +579,10 @@ var N = {
578
579
  return r;
579
580
  }
580
581
  upsert(e, t, n) {
581
- return this.parent.getInternalExecuteUpsert()(e, t, n, this.txn, this.events);
582
+ return this.parent.getInternalExecuteUpsert()(e, t, n, this.txn, this.events, this.attr);
582
583
  }
583
584
  insertIgnore(e, t, n) {
584
- return this.parent.getInternalExecuteInsertIgnore()(e, t, n, this.txn, this.events);
585
+ return this.parent.getInternalExecuteInsertIgnore()(e, t, n, this.txn, this.events, this.attr);
585
586
  }
586
587
  transactional(e) {
587
588
  return Promise.reject(/* @__PURE__ */ Error("MssqlStore.transactional: nested transactions are not supported."));
@@ -599,7 +600,7 @@ var N = {
599
600
  this.events.length = 0;
600
601
  }
601
602
  }
602
- }, $ = (e) => e.__mssqlReplicationFriend ?? null, te = (e, t) => e === t ? 0 : e < t ? -1 : 1, ne = () => ({
603
+ }, $ = (e) => e.__mssqlReplicationFriend ?? null, ne = (e, t) => e === t ? 0 : e < t ? -1 : 1, re = () => ({
603
604
  async capturePrimaryPosition(e) {
604
605
  let t = $(e);
605
606
  if (t === null) throw Error("mssqlReplicationAdapter: primary is not an MssqlStore (missing __mssqlReplicationFriend).");
@@ -626,14 +627,14 @@ var N = {
626
627
  }));
627
628
  },
628
629
  compare(e, t) {
629
- return te(t, e) >= 0 ? "caught-up" : "behind";
630
+ return ne(t, e) >= 0 ? "caught-up" : "behind";
630
631
  }
631
- }), re = {
632
+ }), ie = {
632
633
  id: "mssql",
633
- makeSqlLayer: (e) => I(e),
634
- makeStore: (e) => Y(e),
634
+ makeSqlLayer: (e) => L(e),
635
+ makeStore: (e) => X(e),
635
636
  compileContains: (e, t, n) => n`${e} LIKE ${`%${t.replace(/[\\%_[\]]/g, (e) => `\\${e}`)}%`} ESCAPE '\\'`,
636
- retryFilter: H
637
+ retryFilter: U
637
638
  };
638
639
  //#endregion
639
- export { f as CDC_OFFSETS_TABLE, e as MssqlClient, m as _voltroMssqlCdcOffsetsTable, F as connectionFromConfig, W as ensureChangeTracking, P as makeMssqlSqlLayer, I as makeMssqlSqlLayerFromConfig, Y as makeMssqlStore, re as mssqlDialect, ne as mssqlReplicationAdapter, H as mssqlRetryFilter, q as startChangeTrackingCdc };
640
+ export { f as CDC_OFFSETS_TABLE, e as MssqlClient, m as _voltroMssqlCdcOffsetsTable, I as connectionFromConfig, G as ensureChangeTracking, F as makeMssqlSqlLayer, L as makeMssqlSqlLayerFromConfig, X as makeMssqlStore, ie as mssqlDialect, re as mssqlReplicationAdapter, U as mssqlRetryFilter, J as startChangeTrackingCdc };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/sql-mssql",
3
- "version": "0.20.2",
3
+ "version": "0.21.0",
4
4
  "description": "SQL Server (mssql) dialect adapter for Voltro's cross-dialect DataStore (OUTPUT-clause returning, OFFSET/FETCH paging, inline reactivity).",
5
5
  "keywords": [
6
6
  "voltro",
@@ -32,13 +32,13 @@
32
32
  "node": ">=24.0.0"
33
33
  },
34
34
  "dependencies": {
35
- "@effect/sql": "^0.51.1",
36
- "@effect/sql-mssql": "^0.52.0",
37
- "@voltro/database": "0.20.2",
38
- "@voltro/logger": "0.20.2"
35
+ "@effect/sql": "^0.52.0",
36
+ "@effect/sql-mssql": "^0.53.0",
37
+ "@voltro/database": "0.21.0",
38
+ "@voltro/logger": "0.21.0"
39
39
  },
40
40
  "peerDependencies": {
41
- "effect": "^3.21.4"
41
+ "effect": "^3.22.0"
42
42
  },
43
43
  "publishConfig": {
44
44
  "access": "public"