@voltro/sql-postgres 0.20.1 → 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,177 @@ _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
+
191
+ ## [0.20.2] — 2026-07-30
192
+
193
+ ### Fixed
194
+
195
+ - **@voltro/database, @voltro/cli, @voltro/voltro** — `voltro db drift` could never report clean. It compared the LIVE schema's fingerprint against `_voltro_migration_plans.fingerprint` — which is the **declared** snapshot's hash. The two are not comparable: introspection cannot recover everything a declaration carries (generated expressions, `maxLength`, sensitivity markers), so hashing a live snapshot never equals hashing the declaration it came from. The command was therefore RED on a provably clean database, permanently.
196
+
197
+ Fixing the postgres-only cast in the previous release is what made this visible — before that, `db drift` crashed before it could compute a wrong answer.
198
+
199
+ A consumer measured it precisely: three different fingerprints for one database (`apply` recorded `b1078b73…`, `drift` computed `8dcc9c5e…`, `plan` computed `0c376108…`), stable across runs, with `db plan` reporting 0 operations in between.
200
+
201
+ **The fix is a second, comparable baseline.** `_voltro_migration_plans` gains `liveFingerprint` — the post-apply LIVE fingerprint, taken from the convergence re-plan's `fromFingerprint` (that re-plan runs AFTER the apply, so its "pre-state" is our post-state; it is already computed, so this costs nothing). `db drift` compares against that, and hashes the live snapshot WHOLE, exactly as the applier did.
202
+
203
+ It used to strip `_voltro_*` tables before hashing, which sounds reasonable and was half the incomparability. A framework upgrade that adds a `_voltro_*` column will now show as drift until the next `db apply` records a new baseline — honest, since the live schema did change, and it self-heals on the apply an upgrade needs anyway.
204
+
205
+ Rows written before the column exists have no baseline. `db drift` says so and exits 0, instead of comparing a live hash against a declared one and calling the difference drift. `_voltro_*` table changes ride the declarative differ, so no codemod.
206
+
207
+ **The "Probable causes" list is gone.** It named out-of-band DDL and a missing ledger row, and the consumer hit it with neither being true — the row was right there in `db plans`. A diagnosis that asserts a cause it cannot know is the same defect as the `ALTER TABLE FORCE` repair line retracted in the same release, and it costs more here because it is confident: it sends the reader hunting through somebody's shell history. The command now says what it can actually see — that the schema changed, not what or who — and points at `db plan` for the real difference.
208
+
209
+ Worth recording what the pair of defects cost together, in the consumer's framing: `db drift` exists to catch a divergence between declared and live, and the one real divergence they have (`sessions.tokenHash` declared `varchar(64)`, live `longtext`) is invisible to it — while it loudly reported a divergence that did not exist. False negative on the real thing, false positive on nothing. The false negative is the still-open `maxLength`-in-the-snapshot item.
210
+
211
+ ---
212
+
42
213
  ## [0.20.1] — 2026-07-30
43
214
 
44
215
  ### Changed
@@ -9,7 +9,7 @@ Generated from the resolved runtime dependency closure (24 packages).
9
9
 
10
10
  ---
11
11
 
12
- ## @effect/sql@0.51.1
12
+ ## @effect/sql@0.52.0
13
13
 
14
14
  License: MIT
15
15
 
@@ -37,7 +37,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
37
37
  SOFTWARE.
38
38
  ```
39
39
 
40
- ## @effect/sql-pg@0.52.1
40
+ ## @effect/sql-pg@0.53.0
41
41
 
42
42
  License: MIT
43
43
 
package/dist/index.d.ts CHANGED
@@ -206,6 +206,19 @@ export declare class PostgresDataStore implements DataStore {
206
206
  /** Friend accessor for the transactional view — same eager-aware
207
207
  * path as the public `query()` but pinned to the view's txn. */
208
208
  getInternalRunWithEager(): (d: QueryDescriptor, txn: TxnContext | null) => Promise<ReadonlyArray<Row>>;
209
+ /**
210
+ * Bracket a NON-transactional write: capture the request identity before the
211
+ * first await (`withCapturedAttribution`), and hold this table's transport
212
+ * echoes until the write has registered that identity.
213
+ *
214
+ * Both narrowings are deliberate. Under `inline` nothing is ever injected, so
215
+ * there is no echo to order against. Inside `transactional()` the registration
216
+ * already precedes COMMIT, so bracketing it would hold OTHER replicas' echoes
217
+ * for the length of the transaction to close a race that path does not have.
218
+ * The gap being closed is specific: a plain write's statement commits ITSELF,
219
+ * so the transport fires while this is still awaiting the driver.
220
+ */
221
+ private localWrite;
209
222
  insert(table: string, row: Row): Promise<Row>;
210
223
  insertMany(table: string, rows: ReadonlyArray<Row>): Promise<ReadonlyArray<Row>>;
211
224
  patchJson(table: string, primaryKey: string, path: string, value: unknown): Promise<Row | null>;
package/dist/index.js CHANGED
@@ -4,9 +4,9 @@ import d from "pg";
4
4
  import { EventEmitter as f } from "node:events";
5
5
  import { createLogger as p } from "@voltro/logger";
6
6
  import { SqlClient as m, TransactionConnection as h } from "@effect/sql/SqlClient";
7
- import { EagerCardinalityError as g, attachEagerLoads as _, attributionFields as v, attributionKey as y, claimPendingAttribution as b, compileEagerJson as x, compilePredicate as S, compileRawFragment as C, compileSelect as w, currentWriteAttribution as T, encodeRowForSchema as E, hasEagerLoads as D, isTableReactive as O, raiseChangeListenerCeiling as k, recordsTable as A, registerPendingAttribution as j, requireTable as M, runWithWriteAttribution as N, runWriteRecorders as P, settleTransactionExit as ee, stampGeneratedId as F, stampGeneratedIds as I } from "@voltro/database";
7
+ import { EagerCardinalityError as g, attachEagerLoads as _, attributionFields as v, attributionKey as y, beginLocalWrite as b, compileEagerJson as x, compilePredicate as S, compileRawFragment as C, compileSelect as w, currentWriteAttribution as T, encodeRowForSchema as E, endLocalWrite as D, hasEagerLoads as O, isTableReactive as k, raiseChangeListenerCeiling as A, recordsTable as j, registerPendingAttribution as M, requireTable as N, resolveEchoAttribution as P, runWithWriteAttribution as ee, runWriteRecorders as te, settleTransactionExit as ne, stampGeneratedId as F, stampGeneratedIds as I, withCapturedAttribution as L } from "@voltro/database";
8
8
  //#region src/sqlLayer.ts
9
- var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*$/, z = (t) => {
9
+ var R = (e) => e ? { rejectUnauthorized: !1 } : !1, z = /^[A-Za-z_][A-Za-z0-9_]*$/, B = (t) => {
10
10
  if (t.schema === void 0) return e.layerConfig({
11
11
  host: n.succeed(t.host),
12
12
  port: n.succeed(t.port),
@@ -14,9 +14,9 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
14
14
  password: n.succeed(c.make(t.password)),
15
15
  database: n.succeed(t.database),
16
16
  ...t.maxConnections === void 0 ? {} : { maxConnections: n.succeed(t.maxConnections) },
17
- ...t.ssl === void 0 ? {} : { ssl: n.succeed(L(t.ssl)) }
17
+ ...t.ssl === void 0 ? {} : { ssl: n.succeed(R(t.ssl)) }
18
18
  });
19
- if (!R.test(t.schema)) throw Error(`DB_SCHEMA '${t.schema}' is not a valid postgres identifier (expected ${R}).`);
19
+ if (!z.test(t.schema)) throw Error(`DB_SCHEMA '${t.schema}' is not a valid postgres identifier (expected ${z}).`);
20
20
  let i = t.schema, a = r.acquireRelease(r.sync(() => new d.Pool({
21
21
  host: t.host,
22
22
  port: t.port,
@@ -24,11 +24,11 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
24
24
  password: t.password,
25
25
  database: t.database,
26
26
  ...t.maxConnections === void 0 ? {} : { max: t.maxConnections },
27
- ...t.ssl === void 0 ? {} : { ssl: L(t.ssl) },
27
+ ...t.ssl === void 0 ? {} : { ssl: R(t.ssl) },
28
28
  options: `-c search_path="${i}"`
29
29
  })), (e) => r.promise(() => e.end()));
30
30
  return e.layerFromPool({ acquire: a });
31
- }, B = (e) => {
31
+ }, V = (e) => {
32
32
  let t = e.get("sslmode");
33
33
  if (t !== null) {
34
34
  if (t === "require") return !0;
@@ -41,10 +41,10 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
41
41
  if (n === "false" || n === "0") return !1;
42
42
  throw Error(`DB_URL '?ssl=${n}' is not supported by the postgres dialect — use 'true'/'1' or 'false'/'0'.`);
43
43
  }
44
- }, V = (e) => {
44
+ }, H = (e) => {
45
45
  let t = e.schema === void 0 ? {} : { schema: e.schema };
46
46
  if (e.url) {
47
- let n = new URL(e.url), r = e.ssl ?? B(n.searchParams);
47
+ let n = new URL(e.url), r = e.ssl ?? V(n.searchParams);
48
48
  return {
49
49
  host: n.hostname || "localhost",
50
50
  port: n.port ? Number(n.port) : 5432,
@@ -66,23 +66,23 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
66
66
  ...e.ssl === void 0 ? {} : { ssl: e.ssl },
67
67
  ...t
68
68
  };
69
- }, H = (e) => z(V(e)), U = /* @__PURE__ */ new Set(["40001", "40P01"]), W = (e) => {
69
+ }, U = (e) => B(H(e)), W = /* @__PURE__ */ new Set(["40001", "40P01"]), G = (e) => {
70
70
  let t = e;
71
71
  for (let e = 0; e < 5 && typeof t == "object" && t; e++) {
72
72
  let e = t.code;
73
73
  if (typeof e == "string") return e;
74
74
  t = t.cause;
75
75
  }
76
- }, G = (e) => {
77
- let t = W(e);
78
- return t !== void 0 && U.has(t);
79
- }, K = (e) => G(e) ? "retry" : "noRetry", q = ["json"], J = p({ scope: "voltro:postgres" }), Y = async (e) => {
80
- let t = e.tracerLayer ? a.mergeAll(e.sqlLayer, e.tracerLayer) : e.sqlLayer, n = o.make(t), r = await n.runPromise(m), i = e.changeStrategy ?? "inline", s = new Z(r, n, i, e.cdcChannel ?? "framework_changes");
76
+ }, K = (e) => {
77
+ let t = G(e);
78
+ return t !== void 0 && W.has(t);
79
+ }, q = (e) => K(e) ? "retry" : "noRetry", J = ["json"], Y = p({ scope: "voltro:postgres" }), X = async (e) => {
80
+ let t = e.tracerLayer ? a.mergeAll(e.sqlLayer, e.tracerLayer) : e.sqlLayer, n = o.make(t), r = await n.runPromise(m), i = e.changeStrategy ?? "inline", s = new re(r, n, i, e.cdcChannel ?? "framework_changes");
81
81
  return i === "cdc" && await s.startCdcConsumer(), s;
82
- }, X = () => {
82
+ }, Z = () => {
83
83
  let e = T();
84
- return e === void 0 ? (e) => e() : (t) => N(e, t);
85
- }, Z = class {
84
+ return e === void 0 ? (e) => e() : (t) => ee(e, t);
85
+ }, re = class {
86
86
  sql;
87
87
  runtime;
88
88
  changeStrategy;
@@ -91,20 +91,20 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
91
91
  cdcFiber = null;
92
92
  inflightTxns = 0;
93
93
  constructor(e, t, n, r) {
94
- this.sql = e, this.runtime = t, this.changeStrategy = n, this.cdcChannel = r, k(this.emitter);
94
+ this.sql = e, this.runtime = t, this.changeStrategy = n, this.cdcChannel = r, A(this.emitter);
95
95
  }
96
96
  withNamespace(e) {
97
- return e === null ? this : new te(this, e);
97
+ return e === null ? this : new ie(this, e);
98
98
  }
99
99
  async runInNamespace(e, t) {
100
100
  this.inflightTxns++;
101
- let n = X(), i = this.sql, a = this.sql.withTransaction(r.flatMap(r.serviceOption(h), (a) => {
102
- if (s.isNone(a)) return r.fail(/* @__PURE__ */ Error("PostgresDataStore.runInNamespace: TransactionConnection missing."));
103
- let o = a.value, c = r.provideService(i`SET LOCAL search_path TO ${i(e)}`, h, o), l = new Q(this, o);
104
- return r.flatMap(c, () => r.tryPromise({
105
- try: () => n(() => t(l)).then((e) => ({
101
+ let n = T(), i = Z(), a = this.sql, o = this.sql.withTransaction(r.flatMap(r.serviceOption(h), (o) => {
102
+ if (s.isNone(o)) return r.fail(/* @__PURE__ */ Error("PostgresDataStore.runInNamespace: TransactionConnection missing."));
103
+ let c = o.value, l = r.provideService(a`SET LOCAL search_path TO ${a(e)}`, h, c), u = new Q(this, c, n);
104
+ return r.flatMap(l, () => r.tryPromise({
105
+ try: () => i(() => t(u)).then((e) => ({
106
106
  result: e,
107
- view: l
107
+ view: u
108
108
  })),
109
109
  catch: (e) => e
110
110
  }));
@@ -113,7 +113,7 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
113
113
  "db.operation": "namespace.transaction"
114
114
  } }));
115
115
  try {
116
- let e = await this.runtime.runPromise(a);
116
+ let e = await this.runtime.runPromise(o);
117
117
  return e.view.commitEvents(), e.result;
118
118
  } finally {
119
119
  this.inflightTxns--;
@@ -124,110 +124,110 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
124
124
  let n = w(e, this.sql), i = t ? r.provideService(n, h, t) : n;
125
125
  return this.runtime.runPromise(i);
126
126
  }
127
- async executeInsert(e, t, n, i) {
127
+ async executeInsert(e, t, n, i, a) {
128
128
  t = F(e, t);
129
- let a = this.sql, o = a`INSERT INTO ${a(e)} ${a.insert(E(t, e, q))} RETURNING *`, s = n ? r.provideService(o, h, n) : o, c = (await this.runtime.runPromise(s))[0];
130
- if (!c) throw Error(`PostgresDataStore.insert: no row returned for table '${e}'`);
129
+ let o = this.sql, s = o`INSERT INTO ${o(e)} ${o.insert(E(t, e, J))} RETURNING *`, c = n ? r.provideService(s, h, n) : s, l = (await this.runtime.runPromise(c))[0];
130
+ if (!l) throw Error(`PostgresDataStore.insert: no row returned for table '${e}'`);
131
131
  return await this.routeEvent({
132
132
  table: e,
133
133
  op: "insert",
134
134
  old: null,
135
- new: c
136
- }, i, n), c;
135
+ new: l
136
+ }, i, n, a), l;
137
137
  }
138
- async executeUpdate(e, t, n, i, a) {
139
- let o = this.sql, s = o`UPDATE ${o(e)} SET ${o.update(E(n, e, q))} WHERE ${o("id")} = ${t} RETURNING *`, c = i ? r.provideService(s, h, i) : s, l = (await this.runtime.runPromise(c))[0];
140
- return l ? (await this.routeEvent({
138
+ async executeUpdate(e, t, n, i, a, o) {
139
+ let s = this.sql, c = s`UPDATE ${s(e)} SET ${s.update(E(n, e, J))} WHERE ${s("id")} = ${t} RETURNING *`, l = i ? r.provideService(c, h, i) : c, u = (await this.runtime.runPromise(l))[0];
140
+ return u ? (await this.routeEvent({
141
141
  table: e,
142
142
  op: "update",
143
143
  old: null,
144
- new: l
145
- }, a, i), l) : null;
144
+ new: u
145
+ }, a, i, o), u) : null;
146
146
  }
147
- async executeUpsert(e, t, n, i, a) {
148
- let o = this.sql;
147
+ async executeUpsert(e, t, n, i, a, o) {
148
+ let c = this.sql;
149
149
  if (typeof n.update == "function") {
150
- let c = n.update, u = n.conflictColumns.map((e) => o`${o(e)} = ${t[e]}`), d = (n) => {
151
- let i = o`SELECT * FROM ${o(e)} WHERE ${o.and(u)} LIMIT 1 FOR UPDATE`;
152
- return this.runtime.runPromise(r.flatMap(r.provideService(i, h, n), (i) => r.promise(() => i[0] ? this.executeUpdate(e, i[0].id, c(i[0]), n, a).then((e) => e) : this.executeInsert(e, t, n, a))));
150
+ let o = n.update, u = n.conflictColumns.map((e) => c`${c(e)} = ${t[e]}`), d = (n) => {
151
+ let i = c`SELECT * FROM ${c(e)} WHERE ${c.and(u)} LIMIT 1 FOR UPDATE`;
152
+ return this.runtime.runPromise(r.flatMap(r.provideService(i, h, n), (i) => r.promise(() => i[0] ? this.executeUpdate(e, i[0].id, o(i[0]), n, a).then((e) => e) : this.executeInsert(e, t, n, a))));
153
153
  };
154
154
  if (i) return d(i);
155
155
  this.inflightTxns++;
156
156
  try {
157
- let e = r.suspend(() => this.sql.withTransaction(r.flatMap(r.serviceOption(h), (e) => s.isNone(e) ? r.fail(/* @__PURE__ */ Error("PostgresDataStore.upsert: TransactionConnection missing.")) : r.promise(() => d(e.value))))), t = l.exponential("10 millis").pipe(l.compose(l.recurs(3)), l.whileInput(G));
157
+ let e = r.suspend(() => this.sql.withTransaction(r.flatMap(r.serviceOption(h), (e) => s.isNone(e) ? r.fail(/* @__PURE__ */ Error("PostgresDataStore.upsert: TransactionConnection missing.")) : r.promise(() => d(e.value))))), t = l.exponential("10 millis").pipe(l.compose(l.recurs(3)), l.whileInput(K));
158
158
  return await this.runtime.runPromise(e.pipe(r.retry(t)));
159
159
  } finally {
160
160
  this.inflightTxns--;
161
161
  }
162
162
  }
163
- let c = n.conflictColumns.map((e) => o`${o(e)}`), u = Object.keys(t).filter((e) => t[e] !== void 0), d = n.update === void 0 ? u.filter((e) => e !== "id" && !n.conflictColumns.includes(e)) : n.update, f = d.length > 0 ? o.csv(d.map((e) => o`${o(e)} = EXCLUDED.${o(e)}`)) : o`${o(n.conflictColumns[0])} = EXCLUDED.${o(n.conflictColumns[0])}`, p = o`INSERT INTO ${o(e)} ${o.insert(E(t, e, q))} ON CONFLICT (${o.csv(c)}) DO UPDATE SET ${f} RETURNING *`, m = i ? r.provideService(p, h, i) : p, g = (await this.runtime.runPromise(m))[0];
164
- if (!g) throw Error(`PostgresDataStore.upsert: no row returned for table '${e}'`);
163
+ let u = n.conflictColumns.map((e) => c`${c(e)}`), d = Object.keys(t).filter((e) => t[e] !== void 0), f = n.update === void 0 ? d.filter((e) => e !== "id" && !n.conflictColumns.includes(e)) : n.update, p = f.length > 0 ? c.csv(f.map((e) => c`${c(e)} = EXCLUDED.${c(e)}`)) : c`${c(n.conflictColumns[0])} = EXCLUDED.${c(n.conflictColumns[0])}`, m = c`INSERT INTO ${c(e)} ${c.insert(E(t, e, J))} ON CONFLICT (${c.csv(u)}) DO UPDATE SET ${p} RETURNING *`, g = i ? r.provideService(m, h, i) : m, _ = (await this.runtime.runPromise(g))[0];
164
+ if (!_) throw Error(`PostgresDataStore.upsert: no row returned for table '${e}'`);
165
165
  {
166
- let n = t.id !== void 0 && t.id === g.id ? "insert" : "update";
166
+ let n = t.id !== void 0 && t.id === _.id ? "insert" : "update";
167
167
  await this.routeEvent({
168
168
  table: e,
169
169
  op: n,
170
170
  old: null,
171
- new: g
172
- }, a, i);
171
+ new: _
172
+ }, a, i, o);
173
173
  }
174
- return g;
174
+ return _;
175
175
  }
176
- async executeInsertIgnore(e, t, n, i, a) {
176
+ async executeInsertIgnore(e, t, n, i, a, o) {
177
177
  t = F(e, t);
178
- let o = this.sql, s = n.conflictColumns.map((e) => o`${o(e)}`), c = o`INSERT INTO ${o(e)} ${o.insert(E(t, e, q))} ON CONFLICT (${o.csv(s)}) DO NOTHING RETURNING *`, l = i ? r.provideService(c, h, i) : c, u = (await this.runtime.runPromise(l))[0];
179
- if (u) return await this.routeEvent({
178
+ let s = this.sql, c = n.conflictColumns.map((e) => s`${s(e)}`), l = s`INSERT INTO ${s(e)} ${s.insert(E(t, e, J))} ON CONFLICT (${s.csv(c)}) DO NOTHING RETURNING *`, u = i ? r.provideService(l, h, i) : l, d = (await this.runtime.runPromise(u))[0];
179
+ if (d) return await this.routeEvent({
180
180
  table: e,
181
181
  op: "insert",
182
182
  old: null,
183
- new: u
184
- }, a, i), u;
185
- let d = n.conflictColumns.map((e) => o`${o(e)} = ${t[e]}`), f = o`SELECT * FROM ${o(e)} WHERE ${o.and(d)} LIMIT 1`, p = i ? r.provideService(f, h, i) : f, m = await this.runtime.runPromise(p);
186
- if (!m[0]) throw Error(`PostgresDataStore.insertIgnore: the insert was skipped as a conflict, but no existing row matches conflictColumns [${n.conflictColumns.join(", ")}] on '${e}'. A DIFFERENT unique constraint fired — a second unique index, or the primary key when you named something else. insertIgnore models ONE conflict target: name the columns of the constraint that actually collides, or handle the unique violation yourself.`);
187
- return m[0];
183
+ new: d
184
+ }, a, i, o), d;
185
+ let f = n.conflictColumns.map((e) => s`${s(e)} = ${t[e]}`), p = s`SELECT * FROM ${s(e)} WHERE ${s.and(f)} LIMIT 1`, m = i ? r.provideService(p, h, i) : p, g = await this.runtime.runPromise(m);
186
+ if (!g[0]) throw Error(`PostgresDataStore.insertIgnore: the insert was skipped as a conflict, but no existing row matches conflictColumns [${n.conflictColumns.join(", ")}] on '${e}'. A DIFFERENT unique constraint fired — a second unique index, or the primary key when you named something else. insertIgnore models ONE conflict target: name the columns of the constraint that actually collides, or handle the unique violation yourself.`);
187
+ return g[0];
188
188
  }
189
- async executeInsertMany(e, t, n, i) {
189
+ async executeInsertMany(e, t, n, i, a) {
190
190
  if (t = I(e, t), t.length === 0) return [];
191
- let a = this.sql, o = a`INSERT INTO ${a(e)} ${a.insert(t.map((t) => E(t, e, q)))} RETURNING *`, s = n ? r.provideService(o, h, n) : o, c = await this.runtime.runPromise(s);
192
- for (let t of c) await this.routeEvent({
191
+ let o = this.sql, s = o`INSERT INTO ${o(e)} ${o.insert(t.map((t) => E(t, e, J)))} RETURNING *`, c = n ? r.provideService(s, h, n) : s, l = await this.runtime.runPromise(c);
192
+ for (let t of l) await this.routeEvent({
193
193
  table: e,
194
194
  op: "insert",
195
195
  old: null,
196
196
  new: t
197
- }, i, n);
198
- return c;
197
+ }, i, n, a);
198
+ return l;
199
199
  }
200
- async executePatchJson(e, t, n, i, a, o) {
201
- let s = this.sql, c = n.split("."), l = c[0], u = c.slice(1), d = JSON.stringify(i ?? null), f = u.length === 0 ? s`${s(l)} = COALESCE(${s(l)}, '{}'::jsonb) || ${d}::jsonb` : s`${s(l)} = jsonb_set(COALESCE(${s(l)}, '{}'::jsonb), ${`{${u.join(",")}}`}, ${d}::jsonb, true)`, p = s`UPDATE ${s(e)} SET ${f} WHERE ${s("id")} = ${t} RETURNING *`, m = a ? r.provideService(p, h, a) : p, g = (await this.runtime.runPromise(m))[0];
202
- return g ? (await this.routeEvent({
200
+ async executePatchJson(e, t, n, i, a, o, s) {
201
+ let c = this.sql, l = n.split("."), u = l[0], d = l.slice(1), f = JSON.stringify(i ?? null), p = d.length === 0 ? c`${c(u)} = COALESCE(${c(u)}, '{}'::jsonb) || ${f}::jsonb` : c`${c(u)} = jsonb_set(COALESCE(${c(u)}, '{}'::jsonb), ${`{${d.join(",")}}`}, ${f}::jsonb, true)`, m = c`UPDATE ${c(e)} SET ${p} WHERE ${c("id")} = ${t} RETURNING *`, g = a ? r.provideService(m, h, a) : m, _ = (await this.runtime.runPromise(g))[0];
202
+ return _ ? (await this.routeEvent({
203
203
  table: e,
204
204
  op: "update",
205
205
  old: null,
206
- new: g
207
- }, o, a), g) : null;
206
+ new: _
207
+ }, o, a, s), _) : null;
208
208
  }
209
- async executeDelete(e, t, n, i) {
210
- let a = this.sql, o = a`DELETE FROM ${a(e)} WHERE ${a("id")} = ${t} RETURNING *`, s = n ? r.provideService(o, h, n) : o, c = (await this.runtime.runPromise(s))[0];
211
- return c ? (await this.routeEvent({
209
+ async executeDelete(e, t, n, i, a) {
210
+ let o = this.sql, s = o`DELETE FROM ${o(e)} WHERE ${o("id")} = ${t} RETURNING *`, c = n ? r.provideService(s, h, n) : s, l = (await this.runtime.runPromise(c))[0];
211
+ return l ? (await this.routeEvent({
212
212
  table: e,
213
213
  op: "delete",
214
- old: c,
214
+ old: l,
215
215
  new: null
216
- }, i, n), !0) : !1;
216
+ }, i, n, a), !0) : !1;
217
217
  }
218
218
  async appendInTxn(e, t, n) {
219
- let i = this.sql, a = i`INSERT INTO ${i(e)} ${i.insert(E(t, e, q))}`;
219
+ let i = this.sql, a = i`INSERT INTO ${i(e)} ${i.insert(E(t, e, J))}`;
220
220
  await this.runtime.runPromise(n ? r.provideService(a, h, n) : a);
221
221
  }
222
222
  async maxInTxn(e, t, n, i) {
223
223
  let a = this.sql, o = Object.entries(n).map(([e, t]) => a`${a(e)} = ${t}`), s = a`SELECT MAX(${a(t)}) AS ${a("m")} FROM ${a(e)} WHERE ${a.and(o)}`, c = (await this.runtime.runPromise(i ? r.provideService(s, h, i) : s))[0]?.m;
224
224
  return c == null ? null : Number(c);
225
225
  }
226
- async routeEvent(e, t, n = null) {
226
+ async routeEvent(e, t, n = null, r) {
227
227
  if (e = {
228
- ...v(),
228
+ ...v(r),
229
229
  ...e
230
- }, A(e.table) && await P({
230
+ }, j(e.table) && await te({
231
231
  append: (e, t) => this.appendInTxn(e, t, n),
232
232
  maxOf: (e, t, r) => this.maxInTxn(e, t, r, n)
233
233
  }, {
@@ -237,10 +237,10 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
237
237
  prev: e.old,
238
238
  traceId: e.traceId,
239
239
  subjectId: e.subjectId
240
- }), O(e.table)) {
240
+ }), k(e.table)) {
241
241
  if (this.changeStrategy === "cdc") {
242
242
  let t = (e.op === "delete" ? e.old : e.new)?.id;
243
- t != null && j(y(e.table, e.op, t), {
243
+ t != null && M(y(e.table, e.op, t), {
244
244
  ...e.traceId === void 0 ? {} : { traceId: e.traceId },
245
245
  ...e.subjectId === void 0 ? {} : { subjectId: e.subjectId }
246
246
  });
@@ -257,66 +257,75 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
257
257
  return this.runtime.runPromise(n);
258
258
  }
259
259
  async runWithEager(e, t) {
260
- if (!D(e)) return this.executeQuery(e, t);
260
+ if (!O(e)) return this.executeQuery(e, t);
261
261
  let n = x(e, this.sql, "postgres");
262
262
  if (n !== null) try {
263
263
  let e = t ? r.provideService(n.fragment, h, t) : n.fragment, i = await this.runtime.runPromise(e);
264
264
  return n.decode(i);
265
265
  } catch (e) {
266
266
  if (e instanceof g) throw e;
267
- J.warn("postgres JSON-agg eager-load failed; falling back to walker", { err: e });
267
+ Y.warn("postgres JSON-agg eager-load failed; falling back to walker", { err: e });
268
268
  }
269
- return _(await this.executeQuery(e, t), e.eager, e.sourceTable ?? M(e.table), (e) => this.executeQuery(e, t));
269
+ return _(await this.executeQuery(e, t), e.eager, e.sourceTable ?? N(e.table), (e) => this.executeQuery(e, t));
270
270
  }
271
271
  getInternalRunWithEager() {
272
272
  return (e, t) => this.runWithEager(e, t);
273
273
  }
274
+ async localWrite(e, t) {
275
+ if (this.changeStrategy !== "cdc") return L(t);
276
+ b(e);
277
+ try {
278
+ return await L(t);
279
+ } finally {
280
+ D(e);
281
+ }
282
+ }
274
283
  insert(e, t) {
275
- return X()(() => this.executeInsert(e, t, null, null));
284
+ return this.localWrite(e, (n) => this.executeInsert(e, t, null, null, n));
276
285
  }
277
286
  insertMany(e, t) {
278
- return X()(() => this.executeInsertMany(e, t, null, null));
287
+ return this.localWrite(e, (n) => this.executeInsertMany(e, t, null, null, n));
279
288
  }
280
289
  patchJson(e, t, n, r) {
281
- return X()(() => this.executePatchJson(e, t, n, r, null, null));
290
+ return this.localWrite(e, (i) => this.executePatchJson(e, t, n, r, null, null, i));
282
291
  }
283
292
  update(e, t, n) {
284
- return X()(() => this.executeUpdate(e, t, n, null, null));
293
+ return this.localWrite(e, (r) => this.executeUpdate(e, t, n, null, null, r));
285
294
  }
286
295
  delete(e, t) {
287
- return X()(() => this.executeDelete(e, t, null, null));
296
+ return this.localWrite(e, (n) => this.executeDelete(e, t, null, null, n));
288
297
  }
289
298
  async updateMany(e, t, n) {
290
- return X()(() => this.executeUpdateMany(e, t, n, null, null));
299
+ return this.localWrite(e, (r) => this.executeUpdateMany(e, t, n, null, null, r));
291
300
  }
292
301
  async deleteMany(e, t) {
293
- return X()(() => this.executeDeleteMany(e, t, null, null));
302
+ return this.localWrite(e, (n) => this.executeDeleteMany(e, t, null, null, n));
294
303
  }
295
- async executeUpdateMany(e, t, n, i, a) {
296
- let o = this.sql, s = S(n.where, o), c = o`UPDATE ${o(e)} SET ${o.update(E(t, e, q))} WHERE ${s} RETURNING *`, l = i ? r.provideService(c, h, i) : c, u = await this.runtime.runPromise(l);
297
- for (let t of u) await this.routeEvent({
304
+ async executeUpdateMany(e, t, n, i, a, o) {
305
+ let s = this.sql, c = S(n.where, s), l = s`UPDATE ${s(e)} SET ${s.update(E(t, e, J))} WHERE ${c} RETURNING *`, u = i ? r.provideService(l, h, i) : l, d = await this.runtime.runPromise(u);
306
+ for (let t of d) await this.routeEvent({
298
307
  table: e,
299
308
  op: "update",
300
309
  old: null,
301
310
  new: t
302
- }, a, i);
303
- return u.length;
311
+ }, a, i, o);
312
+ return d.length;
304
313
  }
305
- async executeDeleteMany(e, t, n, i) {
306
- let a = this.sql, o = S(t.where, a), s = a`DELETE FROM ${a(e)} WHERE ${o} RETURNING *`, c = n ? r.provideService(s, h, n) : s, l = await this.runtime.runPromise(c);
307
- for (let t of l) await this.routeEvent({
314
+ async executeDeleteMany(e, t, n, i, a) {
315
+ let o = this.sql, s = S(t.where, o), c = o`DELETE FROM ${o(e)} WHERE ${s} RETURNING *`, l = n ? r.provideService(c, h, n) : c, u = await this.runtime.runPromise(l);
316
+ for (let t of u) await this.routeEvent({
308
317
  table: e,
309
318
  op: "delete",
310
319
  old: t,
311
320
  new: null
312
- }, i, n);
313
- return l.length;
321
+ }, i, n, a);
322
+ return u.length;
314
323
  }
315
324
  upsert(e, t, n) {
316
- return X()(() => this.executeUpsert(e, t, n, null, null));
325
+ return this.localWrite(e, (r) => this.executeUpsert(e, t, n, null, null, r));
317
326
  }
318
327
  insertIgnore(e, t, n) {
319
- return X()(() => this.executeInsertIgnore(e, t, n, null, null));
328
+ return this.localWrite(e, (r) => this.executeInsertIgnore(e, t, n, null, null, r));
320
329
  }
321
330
  emitChange(e) {
322
331
  this.emitter.emit("change", e);
@@ -352,8 +361,8 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
352
361
  return this.executeInsertIgnore.bind(this);
353
362
  }
354
363
  async transactional(e) {
355
- this.inflightTxns++;
356
- let t = X(), n = 0, i = r.suspend(() => {
364
+ this.inflightTxns++, T();
365
+ let t = Z(), n = 0, i = r.suspend(() => {
357
366
  let i = ++n;
358
367
  return this.sql.withTransaction(r.flatMap(r.serviceOption(h), (n) => {
359
368
  if (s.isNone(n)) return r.fail(/* @__PURE__ */ Error("PostgresDataStore.transactional: TransactionConnection unexpectedly missing inside withTransaction."));
@@ -367,12 +376,12 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
367
376
  catch: (e) => e
368
377
  });
369
378
  }));
370
- }), a = l.exponential("10 millis").pipe(l.compose(l.recurs(3)), l.whileInput(G)), o = i.pipe(r.retry(a), r.withSpan("store.transactional", { attributes: {
379
+ }), a = l.exponential("10 millis").pipe(l.compose(l.recurs(3)), l.whileInput(K)), o = i.pipe(r.retry(a), r.withSpan("store.transactional", { attributes: {
371
380
  "db.system": "postgresql",
372
381
  "db.operation": "transaction"
373
382
  } }));
374
383
  try {
375
- let e = ee(await this.runtime.runPromiseExit(o));
384
+ let e = ne(await this.runtime.runPromiseExit(o));
376
385
  return e.view.commitEvents(), e.result;
377
386
  } finally {
378
387
  this.inflightTxns--;
@@ -387,12 +396,14 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
387
396
  return this.changeStrategy === "cdc" ? "fleet" : "local";
388
397
  }
389
398
  injectExternalChange(e) {
390
- if (!O(e.table)) return;
391
- let t = (e.op === "delete" ? e.old : e.new)?.id, n = t == null ? void 0 : b(y(e.table, e.op, t));
392
- this.emitter.emit("change", {
393
- ...n,
394
- ...e,
395
- origin: "injected"
399
+ if (!k(e.table)) return;
400
+ let t = (e.op === "delete" ? e.old : e.new)?.id;
401
+ P(e.table, e.op, t, (t) => {
402
+ this.emitter.emit("change", {
403
+ ...t,
404
+ ...e,
405
+ origin: "injected"
406
+ });
396
407
  });
397
408
  }
398
409
  run(e) {
@@ -402,7 +413,7 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
402
413
  if (this.inflightTxns > 0) {
403
414
  let t = Date.now() + e;
404
415
  for (; this.inflightTxns > 0 && Date.now() < t;) await new Promise((e) => setTimeout(e, 25));
405
- this.inflightTxns > 0 && J.warn("close: grace period expired with in-flight transactions — forcing dispose", {
416
+ this.inflightTxns > 0 && Y.warn("close: grace period expired with in-flight transactions — forcing dispose", {
406
417
  gracePeriodMs: e,
407
418
  inflight: this.inflightTxns
408
419
  });
@@ -418,7 +429,7 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
418
429
  let t = JSON.parse(e);
419
430
  this.injectExternalChange(t);
420
431
  } catch (e) {
421
- J.warn("cdc: bad payload", { channel: this.cdcChannel }, e);
432
+ Y.warn("cdc: bad payload", { channel: this.cdcChannel }, e);
422
433
  }
423
434
  };
424
435
  this.cdcFiber = this.runtime.runFork(e.pipe(u.runForEach((e) => r.sync(() => n(e)))));
@@ -426,40 +437,41 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
426
437
  }, Q = class {
427
438
  parent;
428
439
  txn;
440
+ attr;
429
441
  events = [];
430
442
  committed = !1;
431
- constructor(e, t) {
432
- this.parent = e, this.txn = t;
443
+ constructor(e, t, n = void 0) {
444
+ this.parent = e, this.txn = t, this.attr = n;
433
445
  }
434
446
  query(e) {
435
447
  return this.parent.getInternalRunWithEager()(e, this.txn);
436
448
  }
437
449
  insert(e, t) {
438
- return this.parent.getInternalExecuteInsert()(e, t, this.txn, this.events);
450
+ return this.parent.getInternalExecuteInsert()(e, t, this.txn, this.events, this.attr);
439
451
  }
440
452
  insertMany(e, t) {
441
- return this.parent.getInternalExecuteInsertMany()(e, t, this.txn, this.events);
453
+ return this.parent.getInternalExecuteInsertMany()(e, t, this.txn, this.events, this.attr);
442
454
  }
443
455
  patchJson(e, t, n, r) {
444
- return this.parent.getInternalExecutePatchJson()(e, t, n, r, this.txn, this.events);
456
+ return this.parent.getInternalExecutePatchJson()(e, t, n, r, this.txn, this.events, this.attr);
445
457
  }
446
458
  update(e, t, n) {
447
- return this.parent.getInternalExecuteUpdate()(e, t, n, this.txn, this.events);
459
+ return this.parent.getInternalExecuteUpdate()(e, t, n, this.txn, this.events, this.attr);
448
460
  }
449
461
  delete(e, t) {
450
- return this.parent.getInternalExecuteDelete()(e, t, this.txn, this.events);
462
+ return this.parent.getInternalExecuteDelete()(e, t, this.txn, this.events, this.attr);
451
463
  }
452
464
  updateMany(e, t, n) {
453
- return this.parent.getInternalExecuteUpdateMany()(e, t, n, this.txn, this.events);
465
+ return this.parent.getInternalExecuteUpdateMany()(e, t, n, this.txn, this.events, this.attr);
454
466
  }
455
467
  deleteMany(e, t) {
456
- return this.parent.getInternalExecuteDeleteMany()(e, t, this.txn, this.events);
468
+ return this.parent.getInternalExecuteDeleteMany()(e, t, this.txn, this.events, this.attr);
457
469
  }
458
470
  upsert(e, t, n) {
459
- return this.parent.getInternalExecuteUpsert()(e, t, n, this.txn, this.events);
471
+ return this.parent.getInternalExecuteUpsert()(e, t, n, this.txn, this.events, this.attr);
460
472
  }
461
473
  insertIgnore(e, t, n) {
462
- return this.parent.getInternalExecuteInsertIgnore()(e, t, n, this.txn, this.events);
474
+ return this.parent.getInternalExecuteInsertIgnore()(e, t, n, this.txn, this.events, this.attr);
463
475
  }
464
476
  transactional(e) {
465
477
  return Promise.reject(/* @__PURE__ */ Error("PostgresDataStore.transactional: nested transactions are not supported. Mutations should execute a single top-level transaction."));
@@ -477,7 +489,7 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
477
489
  this.events.length = 0;
478
490
  }
479
491
  }
480
- }, te = class {
492
+ }, ie = class {
481
493
  parent;
482
494
  namespace;
483
495
  constructor(e, t) {
@@ -531,12 +543,12 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
531
543
  return r === void 0 ? Promise.reject(/* @__PURE__ */ Error("PostgresNamespaceView.raw: underlying store has no raw()")) : r(e, t);
532
544
  });
533
545
  }
534
- }, $ = (e) => e.__postgresReplicationFriend ?? null, ne = (e, t) => {
546
+ }, $ = (e) => e.__postgresReplicationFriend ?? null, ae = (e, t) => {
535
547
  let [n, r] = e.split("/"), [i, a] = t.split("/");
536
548
  if (!n || !r || !i || !a) throw Error(`postgres LSN compare: invalid format (${e} vs ${t})`);
537
549
  let o = parseInt(n, 16), s = parseInt(r, 16), c = parseInt(i, 16);
538
550
  return o === c ? s - parseInt(a, 16) : o - c;
539
- }, re = () => ({
551
+ }, oe = () => ({
540
552
  async capturePrimaryPosition(e) {
541
553
  let t = $(e);
542
554
  if (t === null) throw Error("postgresReplicationAdapter: primary is not a PostgresDataStore (missing __postgresReplicationFriend). Pass the postgres store directly.");
@@ -556,14 +568,14 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
556
568
  }));
557
569
  },
558
570
  compare(e, t) {
559
- return ne(t, e) >= 0 ? "caught-up" : "behind";
571
+ return ae(t, e) >= 0 ? "caught-up" : "behind";
560
572
  }
561
- }), ie = {
573
+ }), se = {
562
574
  id: "postgres",
563
- makeSqlLayer: (e) => H(e),
564
- makeStore: (e) => Y(e),
575
+ makeSqlLayer: (e) => U(e),
576
+ makeStore: (e) => X(e),
565
577
  compileContains: (e, t, n) => n`${e} ILIKE ${`%${t.replace(/[\\%_]/g, (e) => `\\${e}`)}%`} ESCAPE '\\'`,
566
- retryFilter: K
578
+ retryFilter: q
567
579
  };
568
580
  //#endregion
569
- export { e as PgClient, V as connectionFromConfig, Y as makePostgresDataStore, z as makePostgresSqlLayer, H as makePostgresSqlLayerFromConfig, ie as postgresDialect, re as postgresReplicationAdapter, K as postgresRetryFilter };
581
+ export { e as PgClient, H as connectionFromConfig, X as makePostgresDataStore, B as makePostgresSqlLayer, U as makePostgresSqlLayerFromConfig, se as postgresDialect, oe as postgresReplicationAdapter, q as postgresRetryFilter };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/sql-postgres",
3
- "version": "0.20.1",
3
+ "version": "0.21.0",
4
4
  "description": "PostgreSQL dialect adapter for Voltro's cross-dialect DataStore (LISTEN/NOTIFY reactivity, logical-replication CDC).",
5
5
  "keywords": [
6
6
  "voltro",
@@ -32,14 +32,14 @@
32
32
  "node": ">=24.0.0"
33
33
  },
34
34
  "dependencies": {
35
- "@effect/sql": "^0.51.1",
36
- "@effect/sql-pg": "^0.52.1",
37
- "@voltro/database": "0.20.1",
38
- "@voltro/logger": "0.20.1",
35
+ "@effect/sql": "^0.52.0",
36
+ "@effect/sql-pg": "^0.53.0",
37
+ "@voltro/database": "0.21.0",
38
+ "@voltro/logger": "0.21.0",
39
39
  "pg": "^8.22.0"
40
40
  },
41
41
  "peerDependencies": {
42
- "effect": "^3.21.4"
42
+ "effect": "^3.22.0"
43
43
  },
44
44
  "publishConfig": {
45
45
  "access": "public"