@voltro/sql-mysql 0.44.1 → 0.46.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,285 @@ _Changes staged for the next release accumulate here (rolled up from
39
39
 
40
40
  ---
41
41
 
42
+ ## [0.46.0] — 2026-08-22
43
+
44
+ ### ⚠ BREAKING
45
+
46
+ - **@voltro/runtime, @voltro/cli** — An aggregate's `incremental.source` is a table name, and is now typed and audited like one.
47
+
48
+ 0.45.0 narrowed a query's and a stream's `source:` for a specific failure: a name matching no table does not error, it produces a subscription that serves once and goes quiet. An aggregate's CDC source misses the same way and is quieter still — the runner subscribes to a table nothing writes, no delta arrives, and the aggregate stops tracking its input while every read of it succeeds and returns a number.
49
+
50
+ It stayed `string` in that change, and not because anyone weighed it. It reads differently — `incremental.source`, a single name on a definition, rather than a list on a descriptor — so it did not fit the loop, and a shape that does not fit reads as a type mismatch instead of a gap.
51
+
52
+ Both halves close now. The field is `TableName`, so a name no table carries is a compile error from the next `voltro dev`. And the boot audit takes aggregates alongside queries and streams, so a stale one is named in the same warning — the runtime half matters because a source can be correct at the type level and still be a table the deployment does not have.
53
+
54
+ The audit's aggregate half runs on both boot paths and needed its OWN call on each, since aggregates are discovered several hundred lines after the existing one — which is precisely the shape that ends up wired on one path only, so it is asserted by name over both files.
55
+
56
+ A recompute-only aggregate declares no `incremental` at all and is not audited: reporting an absence as an unresolved source would report a choice as a defect.
57
+
58
+ **`voltro update` carries you across this** — codemod `0.46.0/01_typed-aggregate-source`.
59
+
60
+ ### Added
61
+
62
+ - **@voltro/data-transfer, @voltro/cli** — A foreign-key cycle is caught BEFORE a staged `replace` loads, and leftover staging tables have a command.
63
+
64
+ Two things the staged swap left open, closed.
65
+
66
+ **The cycle.** The swap inserts parents first, so two tables referencing each other cannot both be satisfied by a bulk copy on postgres, sqlite or SQL Server — and `SET CONSTRAINTS ALL DEFERRED` does not rescue it, because postgres only defers a constraint declared `DEFERRABLE` and the framework declares none. Until now that surfaced as a FAILED SWAP after the whole bundle had loaded: minutes of work, then a refusal. `topo.ts` already orders parents-first and breaks a cycle at its closing edge, so a cycle is exactly a reference pointing FORWARD in that order — cheap to see before anything is loaded. Such a run says so and takes the row-by-row path, whose deferred-FK pass exists for that shape. A table referencing ITSELF is deliberately not a cycle: one statement carries the whole table, measured on all five engines, and treating it as one would cost every app with an `audit()` mixin the staged path.
67
+
68
+ **The leftovers.** A staged run drops-then-creates, so it collects its own; what survives is staging for a table set a later run does not touch. `voltro data clear-staging --yes` lists them and drops them.
69
+
70
+ It is a COMMAND and not a boot sweep, which is the decision worth recording: a booting process cannot tell a leftover from a staging table another replica is loading into right now, and with several replicas that is not a rare race — one booting pod would delete an import in flight. The refusal without `--yes` says so, and names the tables so the operator can check before answering.
71
+
72
+ **And `--no-atomic` stages too now, which is where the change is largest.** The flag exists for resumability on a large bundle, and it used to be the mode with the WORST failure: the target emptied and partially refilled, in neither state — the kill test measured 889 rows of 8 000. Staged, the ledger keeps its exact meaning (a recorded table is one fully loaded; it just lands in staging) while the target stays untouched until the swap. Resumable AND all-or-nothing, which the two flags could not be at once before.
73
+
74
+ Three things came out of wiring it, and none was visible from the design. Dropping staging in the `finally` destroyed exactly what a resume needs, so a second run read from tables that no longer existed — found by the resume test, not by reasoning; staging is dropped only after a successful swap now, and a run that kept its rows says so. The SUCCESS case needed its own guard: after a completed run the ledger still says every table is done while staging is gone, so a re-run would have copied nothing over the target — `ledger.truncated` has always meant "the destructive step already happened" and the old path is guarded by exactly that flag, so it guards this one too. And the test lever was wrong at first: withholding the snapshot disables staging but also fail-closes the rollback capture, so the run refuses before loading — the unstaged case is now driven by the real reason, a registered write recorder.
75
+
76
+ Two existing assertions inverted, and BOTH truths are kept rather than one replaced: `--no-atomic` now keeps the target when it can stage, and still costs exactly what it always did when it cannot. A killed staged run leaves the target's rows intact and writes no interrupted-replace marker — that state cannot arise on the staged path, so there is nothing for a boot to refuse over.
77
+ - **@voltro/runtime, @voltro/cli** — `voltro dev` says when a query reads a table it did not declare in `source:`.
78
+
79
+ The other half of the `source:` problem, and the one no static tool can see. A stale name is a compile error now, and the boot warns about one that resolves to nothing. A name that is simply ABSENT has never had an observer: the write lands, the row is in the database, a reload shows it, and the open panel does not move. The type is satisfied, the audit is satisfied, the write path is correct and its tests are green.
80
+
81
+ So while `voltro dev` runs, every read is attributed to the query that made it and compared against that query's own `source:`. The finding names the table and what will not happen, once per query per boot.
82
+
83
+ **The design question was never the recording, it was compose-vs-restrict.** Only a read that CONTRIBUTES rows belongs in `source:` — a restricting read re-running on every unrelated write puts every list back on the wire. An app that scanned its own source for this needed two hand-written exceptions to get from a thousand findings to thirty, and a rule needing an exception list on a correct codebase has already spent its attention.
84
+
85
+ Neither exception is a list here. A table reached only through a predicate subquery is narrowing BY CONSTRUCTION — it returns no column to anybody — so it classifies itself off the descriptor, on every app, with nothing to maintain. And the framework's own restricting reads are ours: they are issued below the wrapper, or, where the framework runs APP code to decide access (a row filter's loader), marked at the call site we control instead of at the ones we do not.
86
+
87
+ Deliberately narrow, and each edge is a decision rather than a limitation: it reports what it SAW and never claims a declaration is otherwise complete; a query with no `source:` at all is left alone, because the finding is about an incomplete list and not a missing one; and it says which tables it did not count, so the classification can be checked rather than trusted.
88
+
89
+ Dev only. `voltro serve` installs no sink, which makes every part of it inert — no wrapper, no async-local write, no comparison. `VOLTRO_SOURCE_RECORDER=off` turns it off in dev.
90
+
91
+ `restrictingReads` (`@voltro/runtime`) is the escape for an app helper that resolves access somewhere the framework does not call it. It is a no-op outside a recording session, so it can be left in place.
92
+
93
+ Measured against a running `voltro dev`, not only in tests: a query declaring one table while reading two is reported once across eleven requests, and the correct queries beside it produce nothing.
94
+
95
+ **Eager-loaded relations count, and they were the hole.** `.with({ subTasks: true })` issues no second read — `compileEagerJson` folds the whole spec into ONE round trip — so the loaded table is never a read's own table and never a join. It is a relation NAME on the descriptor, and the recorder resolves it through the relation registry: the target, and for a many-to-many the JUNCTION as well, since a write there changes membership, which is precisely the change a user makes. Nested `with:` recurses against the target's relations, the same walk the compiler does; an unresolvable name yields nothing rather than an invented table, and a throwing target thunk cannot take the request down with it.
96
+
97
+ This was the reported failure's own shape, so the first version of the recorder could not see the case it was built for.
98
+
99
+ Measured against a running `voltro dev` and real `POST /rpc` calls: twelve requests across four queries produced exactly two findings — the two deliberately-incomplete ones. The SAME eager load declared correctly beside them is silent, and so is a query with no `source:` at all. A check that only ever fires is not evidence that it fires for a reason.
100
+ - **@voltro/cli** — `--rollback-key <key>` — a `replace` over `--target api` has the INSTANCE store the target's current rows in its own object storage before deleting them.
101
+
102
+ The direct path already captured beside the bundle. That is useless on this transport, and the reason is the whole point: the process that would roll a transaction back IS the instance, so a capture in the pod's filesystem goes away with exactly the failure it exists for — a deployment lost 240 172 rows to a run whose api pod disappeared nine minutes in. Object storage is durable, is already configured wherever the storage-push export works, and is reachable afterwards from anywhere.
103
+
104
+ Pushed BEFORE the first delete, through the same archive sink the export uses — one sink, not two, because two is how an instance comes to push a bundle and fail to keep one. A failure to store it stops the import with the target untouched.
105
+
106
+ Fail-closed in both directions, deliberately:
107
+
108
+ - asked for and impossible (no storage configured) → **409**, naming the fix. The request is the operator saying "I cannot afford to lose this", and serving them anyway is the one answer that removes their precaution while looking like agreement. - not asked for → the run proceeds and says what it did not keep. A `replace` into a scratch environment is legitimate, and refusing it would push people to the flag that turns the safety off everywhere.
109
+
110
+ The decision is made from the headers alone, before a byte of the bundle is read: a run that cannot take the capture it was asked for must not cost an upload first.
111
+ - **@voltro/database, @voltro/data-transfer, @voltro/cli** — An interrupted `replace` cannot be silent any more.
112
+
113
+ The capture only helps if somebody knows to reach for it, and a half-replaced database is indistinguishable from an empty one FROM THE INSIDE — every table exists, every constraint holds, every query returns nothing without erroring. A deployment served over one for ninety minutes and only found out through an unrelated fingerprint mismatch.
114
+
115
+ So a `replace` writes one row (`_voltro_replace_in_progress`) before the first delete and removes it after the last insert, and finding it at boot is a REFUSAL — on both boot paths, out of one function. The message names how many tables, how long ago, over which transport, and the capture to restore from, with the command spelled out.
116
+
117
+ The row lives in the SAME transaction as the emptying, so it is present exactly when the emptying is: a run that rolls back cleanly takes the marker with it, and a boot over a database nothing happened to is not refused. A completed `replace` clears its own marker and every older one, so the recovery import restores the data and silences the alarm in one command.
118
+
119
+ Nothing expires — a half-replaced database does not become whole with time, so `voltro data clear-replace-marker --yes` is a decision somebody makes.
120
+
121
+ Measured against a live mariadb by killing a run mid-load: the marker is there, the refusal names the capture, and a completing run clears it.
122
+ - **@voltro/data-transfer** — The staged-swap primitive for `replace` — load somewhere else, then swap the content in one short transaction.
123
+
124
+ `--mode replace` empties the target and loads into it inside ONE transaction, held open for the whole network-bound load. A deployment measured nine minutes for 242 950 rows, and the promise that the target is left as it was found rests entirely on a live process being there to roll it back. A promise that rests on the process surviving is a promise about the weather.
125
+
126
+ **The design the plan carried was wrong, and measurably so.** Shadow tables plus a final `RENAME` moves every inbound foreign key WITH the renamed table — postgres 17 by OID, MariaDB 11 and MySQL 8.4 by tracking the rename, including inside MySQL's atomic multi-pair `RENAME TABLE`. After the swap every key points at the table the design then DROPS. The atomicity of the rename, which that design reasoned about carefully, was never the hard part.
127
+
128
+ Keeping the table OBJECTS and swapping the CONTENT has none of that: every constraint stays pointed at the same object, and the long client-driven load moves OUT of the destructive transaction, which then holds only server-side bulk SQL.
129
+
130
+ **Four of five engines need no integrity switch, which inverts what the design assumed.** Three self-referencing rows — `actors.createdBy → actors`, the framework's own pattern — inserted by one `INSERT … SELECT`: postgres, SQLite and SQL Server take all three (they check at STATEMENT end); MariaDB and MySQL answer `ERROR 1452` (they check per ROW) and need the switch their own `emptyTables` already uses. Measured on each, and measured again after: a genuine violation attempted following the swap is still refused on all five, so the suspension does not leak past it.
131
+
132
+ The statement builders refuse a table name outside the framework's identifier class. This module concatenates SQL and its names arrive from a bundle MANIFEST — a file an operator can edit — so the rule applied at declaration is re-asserted where the concatenation happens rather than assumed to have survived the round trip. Staging tables are `_voltro_staging_<t>`, so the boot differ's framework-table asymmetry treats them as ours instead of planning them as user tables somebody forgot to declare.
133
+
134
+ **The importer does not use it yet**, and attempting that integration is what surfaced two blockers worth stating: a staged write would fire a change event (waking reactivity, CDC and the analytics mirror for tables nobody declared), and it would miss the target's column metadata (`encodeRowForSchema` looks the table up by NAME, so a `json()` column would be written unencoded — a wrong value, not an error). Both are tractable; neither is a line-level change. Until then the two protections already shipped — the capture written before the first delete, and the marker that refuses the next boot after an interrupted run — remain what covers the reported outcome.
135
+ - **@voltro/data-transfer, @voltro/cli** — `--mode replace` writes down what it is about to destroy.
136
+
137
+ Before the first delete it exports the target's CURRENT rows — exactly the tables it will empty — as an ordinary bundle beside yours, and says where:
138
+
139
+ rollback capture: 240172 row(s) across 75 table(s) → ./out.rollback-2026-… If this run does not finish, restore with: voltro data import ./out.rollback-… --mode replace
140
+
141
+ It is on disk BEFORE anything is destroyed, so it depends on no transaction and on no process being alive to roll one back. That is the whole point: a deployment lost 240 172 rows to a `replace` whose api pod disappeared nine minutes in, and recovered from an export they had taken twenty minutes earlier out of HABIT. This is that habit as behaviour. It is NOT the fix for the class — the emptying must not become visible until the load stands, which is a rebuild — it is the small half that covers the reported outcome today.
142
+
143
+ **Fail-closed.** A capture that cannot be taken stops the import before it starts, target untouched. A net you believe in and do not have is worse than none: the belief is what stops you taking your own export.
144
+
145
+ The capture is a COMPLETE bundle over a snapshot narrowed to the emptied tables, not a `tables`-scoped one over the whole schema. Same files, different manifest — and the manifest decides whether it can be restored at all, since `replace` refuses a partial bundle for a reason that is exactly false here.
146
+
147
+ `--no-rollback` opts out, `--rollback-dir <path>` relocates it. Only `replace` takes one: `upsert` and `append` destroy nothing.
148
+
149
+ **Not on `--target api`, and it says so.** The capture would live inside the instance — the thing that can go away, which is the failure it exists for. A replace over that transport warns and names the export to take first.
150
+ - **@voltro/database, @voltro/data-transfer** — Staging clones — the load-side half of the staged swap for `replace`.
151
+
152
+ The swap primitive shipped without the importer using it, and two things stood in the way. Both are solved by ONE answer.
153
+
154
+ A typed write resolves its table by NAME: `encodeRowForSchema` and `stampGeneratedId` both look it up in the registry. Writing to `_voltro_staging_notes` therefore found nothing — and the failure mode is not an error, it is a `json()` column written UNENCODED. Separately, every dialect store's insert ends in `routeEvent`, whose reactive guard reads `isTableReactive`, which is `isReactive !== false` — so an UNREGISTERED name counts as reactive, and loading a large bundle into staging would emit an event per row for tables nobody declared.
155
+
156
+ A staging table registered as a CLONE of its target, marked `isReactive: false`, answers both: the columns resolve, and the guard the framework already has returns before the emit. `.nonReactive()` is the documented way to say exactly that, so nothing at the store needed a special case — and it is the clone rather than the absence that makes the load quiet, which is the part worth remembering if this is ever simplified.
157
+
158
+ `registerStagingClones` returns a REQUIRED undo instead of trusting a caller to remember one. `allRegisteredTables()` feeds the declared set, the boot differ and `voltro doctor`, so a clone left in the registry reads as a table the app declares and nobody created. A failure part-way through registers nothing at all.
159
+
160
+ `unregisterTable` is new in `@voltro/database` for this: narrow on purpose. `clearTableRegistry` wipes everything and exists for tests; this removes ONE name a bounded operation owns for its duration.
161
+
162
+ **The precision is recovered, and it is strictly better than what it replaces.** Staging carries no foreign keys — required, since a staged row whose parent has not been staged yet must not be refused — so a violation moves from load time to swap time, where the database answers with one message naming a constraint. `stagedReferences` reads the edges INSIDE the replaced set off the snapshot the importer already holds (deliberately not `incomingForeignKeys`, which answers the already-answered question of keys pointing in from OUTSIDE), and `danglingProbeSql` asks STAGING the question the database was asking — against the STAGED parent set, because the swap inserts parents from staging and what matters is whether the reference resolves AFTER it.
163
+
164
+ Measured against a live postgres with four staged children — one good, one NULL, two dangling — driven through a real failing swap: the database named `ghost`; the probe named `ghost` AND `phantom`, skipping the NULL and the good row. The row-by-row path stops at the FIRST failure, so a bundle with four bad references costs four round trips; this reports all of them in one pass. The target was verified unchanged afterwards, which is the first thing the message says.
165
+
166
+ **The importer uses it now.** `--mode replace` stages when it can: create a staging table per table, load into those OUTSIDE any transaction, then swap the content across in one short transaction of server-side SQL. A process that dies during the load leaves the target exactly as it was, because nothing has been deleted yet — the destructive window shrinks from the length of the load to the length of a copy.
167
+
168
+ Wiring it surfaced two more things, and neither was visible from the design.
169
+
170
+ `INSERT … SELECT *` fails the moment the target has a STORED generated column — `CREATE TABLE … (LIKE t)` copies such a column as a PLAIN one (measured: `is_generated: NEVER`), so the select hands the target a value for a column it computes itself: `cannot insert a non-DEFAULT value into column "slug"`. The swap names its columns now, minus the generated ones, and `swapStatements` REFUSES an empty column list rather than falling back to `SELECT *`, so the trap cannot return by omission.
171
+
172
+ And a WRITE RECORDER on any table in the set rules staging out. A recorder is keyed by table NAME, so a staged write looks up `_voltro_staging_notes`, finds none, and never runs — `versioningPlugin({ timing: 'in-transaction' })` promises "if the change committed, the entry is there", and the swap's bulk SQL has no per-row hook to keep that with. Measured, not guessed: the recorder went from more than one call to zero. Such a run keeps the path that honours it and SAYS why, as does a `--no-atomic` run or a store the framework cannot send DDL to.
173
+
174
+ Every staged run says it staged. The two paths are indistinguishable from outside — both end with the target holding the bundle — and an operator deciding whether they can afford to interrupt needs to know which one is running.
175
+
176
+ Verified through the real importer, and falsified before being kept: with staging off, the assertion that the target still holds its own rows WHILE the bundle loads goes red. On real postgres the staged path runs the existing foreign-key replace suite unchanged.
177
+
178
+ ### Fixed
179
+
180
+ - **@voltro/protocol, @voltro/voltro** — A `_voltro_*` name in `source:` is no longer narrowed against the generated table declaration.
181
+
182
+ Which framework tables an app declares is DEPLOYMENT-dependent. The measurement is already in the maintainer notes: at one `NODE_ENV`, on one dialect, flipping a single flag adds or removes `_voltro_traces`, `_voltro_undo_log` or `_voltro_cdc_offsets` from the declared set. The generated `voltro-tables.generated.d.ts` is written by ONE `voltro dev` run, on one machine, with one set of those inputs.
183
+
184
+ Narrowing framework names against it therefore made `source: '_voltro_traces'` compile for whoever generated the file and fail for a colleague — a type error decided by an environment variable, which is the exact class the declared-schema rule forbids one layer up. An app's own tables are unaffected: `_voltro_` is a reserved prefix, so every name a user writes for their own data narrows exactly as before.
185
+
186
+ **How it surfaced is the part worth recording.** Until now `keyof VoltroTableNames` was always `never` inside this repo, so `TableName` was always `string`, so the narrow and wide types were the same type and every rule about them held vacuously. The first time an augmentation was ever present — a fixture that boots a real server writing the declaration beside its generated rpc group — four framework source files stopped compiling. The split had shipped without once being exercised in the direction that matters.
187
+
188
+ Two things now stop that from going quiet again. A type-test program compiles the framework's own sources under an augmentation that deliberately declares NONE of its tables, and it lives in its OWN tsconfig: `declare module` merging is program-global, so a sibling type test's augmentation had silently rescued the very assertion this one exists to make. And `scripts/check-type-tests.mjs` (CI + `pnpm gate`) DISCOVERS type-test programs and runs them — because nothing did. The existing narrowing assertions had never been compiled once: excluded from their package's tsconfig for a good reason, and picked up by nothing else. It refuses a zero-program run, and a program that compiles zero `*.test-d.ts` files, for the same reason every other check here carries a floor.
189
+
190
+ **Why `apiSurface: compatible`, and how to check it rather than take it.** The gate flagged the golden line as CHANGED and asked the right question — can this turn code that compiled into code that does not? Here it cannot, because the edit WIDENS a union, and every public position the type appears in is an INPUT: `source?:` on a descriptor, and `normalizeSource`'s parameter. Nothing in the published surface RETURNS `TableName` or `ReactivitySource`, which is the only direction in which widening breaks a consumer — an assignment FROM the type into something narrower. `@voltro/voltro` is listed beside `@voltro/protocol` because it re-exports the type, so its golden moved too; the gate matches per package, and one package's classification must not vouch for another's.
191
+ - **@voltro/sql-mssql** — A `json()` column could not take a value on mssql. At all.
192
+
193
+ store.insert(t, { payload: { a: 1 } }) -> TypeError: Invalid string. [EPARAM] store.insert(t, { payload: null }) -> OK
194
+
195
+ So the column worked only while it held nothing. Reached first through `@voltro/plugin-versioning`, whose history row carries a full-row snapshot in exactly such a column: the versioning recorder could not write on that dialect, and therefore neither could any write to a table it covers.
196
+
197
+ The store handed the caller's row straight to `sql.insert(row)`. The mysql store runs `encodeRowForSchema` first — the schema-driven step that turns a json value into text a driver can bind — and mssql had no equivalent anywhere on its write path, so tedious received a JS object for an NVARCHAR parameter and refused it.
198
+
199
+ **Encoding alone would have been worse than the bug.** A value written as text and handed back as text means a WRITE returns a string where a READ of the same row returns an object, and nothing errors — the caller gets a different type depending on how it got there. So every `OUTPUT INSERTED.*` path decodes too (insert, insertMany, update, updateMany, patchJson, the delete old-image, and the MERGE upsert), and the test asserts the ROUND TRIP rather than the absence of an error, against a live SQL Server.
200
+
201
+ With it, the mssql case is back in the versioning key-length suite — the bound on `id()` exists on that dialect too, and it was absent for one release only because nothing could write there.
202
+ - **@voltro/data-transfer, @voltro/cli** — A `scope: all` bundle carried the exporting deployment's own bookkeeping, and `replace` wrote it into the target. The target's next boot refused to start:
203
+
204
+ auto-migrate: SCHEMA FINGERPRINT MISMATCH — declared=6e2c61081a9ed80c live=28af9a54414f22f1
205
+
206
+ The refusal was correct and the row was the defect. A migration-ledger row is not DATA — it states which schema THIS deployment applied — and the fingerprint is computed over the declared table set, which legitimately differs per environment (`NODE_ENV=production` declares `_voltro_traces` and `_voltro_undo_log`; a `development` run does not). So the imported row was not stale, it was FOREIGN. The environment was down for ninety minutes, and the ledger row also HID the incident it travelled with: the api would not start, and the reason looked like the failed import rather than a row in a bookkeeping table.
207
+
208
+ Ten framework tables are now classified as environment-local — the migration ledger, the file-migration and seed records, CDC offsets, schedule claims, wakeups, workflow watermarks / pending starts / admissions / pauses. They are dropped from an export's `all` scope, skipped on import, and never emptied by a `replace`, each with the reason a foreign row would be wrong stated beside it. Two of them would have made the target ACT: a pending start runs a workflow somebody queued elsewhere, a pause silently stops one here.
209
+
210
+ `all` is the only scope filtered. A caller who NAMES one of these tables gets it — an explicit name is an expectation, and this module already refuses to drop those silently.
211
+
212
+ The classification refuses to be incomplete: a guard scans every framework table and fails until a new one is decided either way. A hand-list rots by omission, and the omission cost ninety minutes.
213
+
214
+ Also fixed, found while reading that path: the admin import endpoint spread `atomic` only when truthy, so an explicit `atomic: false` was dropped and the importer applied its own default — which for `replace` is `true`. The one value a caller can only express by asking for it was the one the wire discarded.
215
+
216
+ ---
217
+
218
+ ## [0.45.0] — 2026-08-21
219
+
220
+ ### ⚠ BREAKING
221
+
222
+ - **@voltro/protocol, @voltro/cli, @voltro/voltro** — `source:` on a query is now typed against the app's own tables, so a typo or a missed rename is a compile error instead of a subscription that goes quiet.
223
+
224
+ A `source:` is matched by NAME against change events, so a name matching nothing does not break the query — it makes it permanently silent: it compiles, boots, serves its first snapshot and never updates. From the outside that reads as a feature that does nothing, with a correct write path and green tests behind it. The boot has warned about this since 0.26.0, on both paths; a warning is read once, and a rename lands in a diff where nobody is checking strings.
225
+
226
+ `voltro dev` writes `voltro-tables.generated.d.ts` beside the generated rpc group, augmenting `VoltroTableNames` with the FULL live set — app entities, plugin `extendSchema.tables` and the framework's own — from the same binding the boot audit resolves against, so the type and the warning cannot disagree about which tables exist. `source:` narrows to those names.
227
+
228
+ Nothing changes at runtime: these are still string literals, so a descriptor carrying them is as browser-loadable as before. That is what ruled out accepting the table VALUE — a descriptor is loaded value-level by the web client, and a table value drags `@voltro/database` across that boundary.
229
+
230
+ **Breaking, and filed that way after being written up as additive.** The test is not whether a symbol disappeared, it is whether code that compiled can stop: `['tasks', 'agent_messages']` was assignable and is not, which is the whole point where the name is stale and an obstacle where the source is genuinely computed. `normalizeSource`'s parameter narrowed with it. The wide shape stays public as `ReactivitySourceValue` for the computed case.
231
+
232
+ The break does NOT land at upgrade time, which is why the codemod is a written note rather than a transform: right after `voltro update` the generated file does not exist, `keyof VoltroTableNames` is `never`, `TableName` falls back to `string`, and everything compiles as before. The narrowing switches on at the next `voltro dev` — a different command, by which point the change that caused it is no longer what the reader is looking at. A transform could not have found the sites either, since the type that rejects them has not been generated yet. And the two things `tsc` flags — a stale name versus a runtime-computed one — want opposite fixes, so the mechanical one (widen the annotation) would convert every defect this surfaces back into the quiet subscription it exists to expose.
233
+
234
+ Delete the generated file and `source:` widens back to `string`.
235
+
236
+ One deliberate asymmetry, stated because it is one: runtime READERS of a descriptor's source stay wide (`ReactivitySourceValue`). Narrow where an author writes, stay wide where the framework reads — a reader that refused an unknown name would be asserting a fact it cannot check, and the first thing it would reject is the stale name it exists to report.
237
+
238
+ ### Added
239
+
240
+ - **@voltro/cli** — `voltro doctor` reports a query that eager-loads a relation and does not declare its table in `source:` — the failure that looks like a broken feature and is not.
241
+
242
+ The write lands, a reload shows it, every test of the write path is green, the name in `source:` is spelled right and the table exists. So neither the typed `source:` nor the boot audit has anything to say, and the only observer is a user watching a panel that does not move.
243
+
244
+ ```
245
+ ✗ 1 query loads a relation it does not declare:
246
+ tasks.getById: eager-loads `subTasks` from 'tasks' but does not declare
247
+ 'task_sub_tasks' in `source:` — the view will not update when 'task_sub_tasks' changes.
248
+ ```
249
+
250
+ No exception list, deliberately. An eager-loaded relation is composition by definition — its rows are IN the result — and its table comes from the relation registry, so the missing name is a fact rather than an inference. A many-to-many is reported twice when needed: adding or removing a link writes only the JUNCTION row, so declaring the target alone leaves the list stale on exactly the operation a user performs to change it. A computed `.with()` key yields nothing rather than a guess.
251
+
252
+ The general question — every table an executor reads — is NOT answered, on purpose: it needs a compose-versus-restrict judgement a scan can only infer from syntax, and a rule that guesses on a correct codebase teaches its reader to ignore it. Design in `plans/open/framework/source-completeness.md`.
253
+
254
+ Two things around it:
255
+
256
+ - **The stale-`source:` audit covered queries only, on both boot paths.** A stream carries a `source:` too, and a stale one there is the same permanently quiet subscription with a longer-lived connection behind it. Both paths now take the set from one `auditableSources`. - **`voltro codegen` writes the typed-`source:` declaration too**, from the same shared `declaredTableNames` merge the boots use. Letting it lag was the bad direction: a table added since the last `voltro dev` would make a CORRECT `source:` a type error. Both commands now say what they wrote — the narrowing has a silent no-op if the app's tsconfig does not pick the file up, so the write has to be loud enough that a reader can check.
257
+
258
+ ### Fixed
259
+
260
+ - **@voltro/database, @voltro/sql-mysql** — A binding failure names the TYPE of every value, so the culprit is read rather than guessed.
261
+
262
+ `ER_WRONG_ARGUMENTS` / 1210 reads like a count problem and often is not: a statement with twelve columns and twelve placeholders is internally consistent, and the driver is refusing one VALUE it cannot bind. Measured against a live mariadb 11.8 and mysql 8.4 (mysql2 3.22), binding to a PREPARED statement:
263
+
264
+ | value | mariadb | mysql | |---|---|---| | plain object | **1210** | accepted | | array | **1210** | accepted | | bigint | accepted | accepted | | Invalid Date | accepted | 1292 |
265
+
266
+ So the same row binds on one engine of the family and not the other — which is how a suite comes to fail on mariadb and pass on mysql in the SAME run, and why the type of each binding is the diagnosis rather than a detail.
267
+
268
+ `describeDriverError` now reports `bindings: id:string data:Object changedAt:Date …` beside the placeholder count and the statement. Types only; a value there would be row data in a log line, the same reason the statement is carried only in its placeholder form.
269
+
270
+ The types travel as a FIELD, not in a message. That is load-bearing: a failing write recorder rethrows with its own sentence, so anything said only in text is dropped exactly where it is needed. `extractDbCause` collects it like any driver field, so it survives every wrapper between the failing statement and the log.
271
+ - **@voltro/database, @voltro/testing** — A driver error now carries the two numbers a binding failure is made of.
272
+
273
+ `ER_WRONG_ARGUMENTS` / errno 1210 means the parameter count did not match the placeholder count — reproduced against mariadb 11.8 by sending one parameter for two `?` — and the message says only `Incorrect arguments to mysqld_stmt_execute`. Neither number was reachable from the error, so an investigation into one of these starts by eliminating hypotheses instead of subtracting.
274
+
275
+ `describeDriverError` reports `placeholders=N` and the statement, and the statement is carried ONLY in its placeholder form. That restriction is measured, not cautious: against mysql2 3.22 the prepared path (`execute`) leaves `?` in `err.sql` because the server did the binding, while the text path (`query`) interpolates and the same field then holds row DATA. The placeholder is the discriminator, and the form that keeps it is exactly the form 1210 arises in.
276
+
277
+ Alongside it, `reportEngineVersion` (`@voltro/testing`): a dialect suite prints the engine BUILD it ran against. A suite that is green on a developer machine and red in CI is only comparable if both name their software, and the test compose file uses moving tags — so "the same tag" is not the same build, and checking the tag locally observes what it points at today rather than what the runner resolved.
278
+ - **@voltro/database, @voltro/plugin-versioning, @voltro/plugin-flags** — A versioned table whose NAME was long enough could not be written to at all.
279
+
280
+ `id()` is `VARCHAR(64)` on mysql / mariadb and `NVARCHAR(64)` on mssql, and unbounded `TEXT` on postgres and sqlite. The versioning recorder built its history key by concatenation — `rowver_<tableName>_<rowId>_<version>`, which is `42 + len(tableName)` characters for a 32-character row id — so a 22-character table name fit and a 23-character one produced `ERROR 1406 (22001): Data too long for column 'id' at row 1`. A recorder runs on EVERY write, so this was not a refused import: it was a table nobody could write to, on three of five dialects, at a boundary no one can see when naming a table.
281
+
282
+ `derivedRowId(prefix, …parts)` (`@voltro/database`) derives a deterministic key of CONSTANT width — `rowver_<32 hex>`, 39 characters whatever goes in — joined over a `\u0000` separator so the parts stay injective (a `_`-joined key cannot tell `('a_b','c')` from `('a','b_c')`). Widening the column was the alternative and moves the wall rather than removing it; `id()` is also every user table's PK type. Nothing legible is lost: every table deriving a key this way already stores the parts in their own columns.
283
+
284
+ The same construction was in `plugin-flags` (`flag_<key>`, over an unbounded user-chosen flag key) and is fixed with it. A guard scans framework sources for an `id:` composed by interpolation and requires the helper, with an allowlist whose entries each name why their parts cannot grow — and which fails if an entry stops matching.
285
+
286
+ Also fixed: the versioning suite's live coverage was postgres-only, and postgres is one of the two dialects where that column is unbounded, so it was structurally incapable of seeing this. `@voltro/sql-mysql` is a test devDep of `@voltro/plugin-versioning` now, with a mysql+mariadb case driving an ordinary insert and update against a 33-character table name.
287
+ - **@voltro/database, @voltro/cli** — Two gaps on the `--target api` path, both about a failure that is present and unreadable.
288
+
289
+ **The driver was unreachable behind a WRAPPED rejection.** `extractDbCause` unwrapped a `FiberFailure` at the root only, so one reached through a `.cause` link stopped the walk — it carries `stack`, `message` and `name` and nothing else, which is indistinguishable from "no driver under this". That is exactly the shape a failing write recorder produces: it rethrows `new Error(<what it was doing>, { cause: err })` where `err` is the rejection its own insert made. So the same database refusal classified where no recorder runs and degraded to the bare runtime rendering where one does — which is the difference between the direct importer and an import through a running app with versioning or audit on. The walk now unwraps at every link.
290
+
291
+ **And the refusal report was never printed on that transport.** A refusal that crossed HTTP arrives as a 500 whose message embeds the `RowsRefusedError` as JSON; the CLI printed that body raw. So the operator on the transport that exists for "the database is somewhere you cannot open a shell" got the one output that has to be triaged by hand — and tallying the capped row list is how a per-table distribution gets reported that is not the real one. `--target api` now prints the same report as the direct path, `byTable` line and cap notice included.
292
+ - **@voltro/data-transfer, @voltro/cli** — Two reporting defects that made a refused import unreadable, both of the shape "the payload is present and property access is not the way to it".
293
+
294
+ **A refusal lost its tag on the mode that raises it most.** `--mode replace` runs in one transaction by default, and rolling that back needs a rejection — which the atomic wrapper obtained by throwing `new Error(Cause.pretty(cause))`, a rendering rather than the failure. From there the typed error could not come back: it was re-wrapped as a `BundleError` carrying itself as text. So `Effect.catchTag('RowsRefusedError', …)` matched nothing on the default path, `ImportError`'s union was a claim that path could not honour, and the CLI's refusal report — which branches on the tag — printed nothing at all. The typed error is thrown and passed through now; `asImportError` is exported for callers who catch the rejection rather than the effect.
295
+
296
+ **And the report read the tag off a `FiberFailure`.** What `Effect.runPromise` rejects with does not expose `_tag` by property access, so the renderer took its "not my error" branch on every direct-path run while being wired, tested and correct — the test drove the renderer with the error object, which is not the shape the call site produces. A reported refusal now also ENDS the command instead of being rethrown into `fatal unhandled cli error`: a refusal is a condition with a named cause, not a framework defect.
297
+
298
+ **An api host is no longer reported as an unreachable database.** A connect failure carries an address, a port and an errno — the same shape a database driver's carries — and one global handler renders that shape, so `--target api --api-url https://…` against a stopped instance printed `the database is not reachable at <api-host>:443 … Configured by: DB_URL` with `DB_URL` not in play. The transport names its own failure now (`InstanceUnreachable`), and the database explainer declines an endpoint whose PORT cannot be a database — judged by port because a driver reports the resolved address, so a host comparison would silence the real message for anyone naming their database by hostname.
299
+
300
+ ### Internal (no consumer-facing effect)
301
+
302
+ - **@voltro/sql-postgres** — A test teardown terminated connections its own pool was still closing, and the resulting error failed the RUN rather than any test.
303
+
304
+ `clusterColdStart` drops a per-run database, and the runners it spawned are killed with SIGKILL, so their backends never close — hence the deliberate `pg_terminate_backend` before the `DROP`. But `pool.end()` resolves once it has ASKED the pool to close, not once every socket is down, so the terminate could also land on a connection belonging to the test itself. `pg` reports that as an `error` event on the idle client, and an unhandled one takes down the process.
305
+
306
+ The shape it took on a release gate is the reason this is written down: **36 of 36 test files green, and the suite exiting 1.** Nothing points at the teardown — the failure is attributed to whichever suite happened to run last, which is a different one each time. A connection error while we are tearing the database down carries no signal, so it is handled where it arises.
307
+
308
+ Test-only; no product code changed.
309
+ - **@voltro/plugin-auth** — The TOTP skew-window test uses a fixed secret. Test-only; no product code changed, and the assertion is unchanged.
310
+
311
+ It failed once on a release gate — `expected true to be false`, meaning a code two steps outside the ±1 window verified. That is the shape of a security defect, so it was treated as one until measured:
312
+
313
+ - `TOTP_SKEW` is 1 and the verify loop checks exactly three counters, compared with `timingSafeEqual`; - `T0` is a constant and the clock is injected, so the only varying input was `generateTotpSecret()`; - over **50 000 fresh secrets**: zero collisions between the ±2 codes and the ±1 window (pure chance predicts ~0.3), zero degenerate secrets, uniform length; - **60 consecutive runs** of the file: green.
314
+
315
+ So the implementation is sound and that red was two 6-digit codes coinciding — about six in a million per run. Worth stating plainly: that makes the observed failure a one-in-167 000 event, which fits every measurement and is still remarkable. It was not reproduced.
316
+
317
+ The fix is to remove the coin flip rather than to re-run until green. A random secret buys this test nothing — the property under test is the WIDTH of the window, which does not depend on which secret is used. It only buys a rare red that costs a diagnosis cycle and teaches the reader to re-run. Pinned, so the next failure there means the window moved.
318
+
319
+ ---
320
+
42
321
  ## [0.44.1] — 2026-08-19
43
322
 
44
323
  ### Fixed
@@ -877,7 +1156,7 @@ _Changes staged for the next release accumulate here (rolled up from
877
1156
  It is derived from `publishConfig.exports` inside the generator's own loop — not a curated list and not a second copy of the derivation — so a package that joins the workspace is covered without anyone remembering to add it. It carries a floor (60 packages) for the reason every check in `scripts/` has one: the failure mode of a wiring check is a green line over a walk that found nothing.
878
1157
 
879
1158
  Verified by injecting each defect and watching it go red (missing golden, empty golden), confirming exit code 1, and confirming `--check` mutates no file. Internal: tooling only.
880
- - **@voltro/cli** — `rpcSurfaceFingerprint.ts` wrote its composite-key separator as a literal NUL byte instead of ``. Same runtime value, no behaviour change — the file's own 16 tests pass identically before and after.
1159
+ - **@voltro/cli** — `rpcSurfaceFingerprint.ts` wrote its composite-key separator as a literal NUL byte instead of the `\u0000` escape. Same runtime value, no behaviour change — the file's own 16 tests pass identically before and after.
881
1160
 
882
1161
  It matters because of what the byte does to the FILE rather than to the hash: a source file containing a NUL is binary to every text tool, so `grep` skips it and prints nothing, which is indistinguishable from a clean file. This repo has been bitten by exactly that — a 1020-line module that every grep-based audit had silently skipped, including one searching for a string that file declares.
883
1162
 
package/dist/index.d.ts CHANGED
@@ -390,6 +390,15 @@ export declare class MysqlStore implements DataStore {
390
390
  * an in-transaction recorder is handed. NOT `executeInsert`: that would
391
391
  * re-enter `routeEvent` and emit a change event for the trail's own table.
392
392
  */
393
+ /**
394
+ * Re-throw with the row's binding TYPES attached — values never.
395
+ *
396
+ * A new `Error` with `cause` rather than a mutation: the driver error is a
397
+ * shared object the SQL layer may hold, and the cause chain is what
398
+ * `extractDbCause` already walks, so the driver's own fields stay reachable
399
+ * through it.
400
+ */
401
+ private static bindingContextFor;
393
402
  private appendInTxn;
394
403
  /**
395
404
  * The other half of the recorder port: ONE aggregate on the caller's
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { MysqlClient as e } from "@effect/sql-mysql2";
2
2
  import { Config as t, Effect as n, Layer as r, ManagedRuntime as i, Option as a, Redacted as o, Schedule as s } from "effect";
3
- import { CDC_OFFSETS_TABLE as c, DEFAULT_ACQUIRE_TIMEOUT_MS as l, EagerCardinalityError as u, _voltroCdcOffsetsTable as d, attachEagerLoads as f, attributionFields as p, attributionKey as m, beginLocalWrite as h, bulkInsertLimitsFor as g, chunkRowsForInsert as _, compileEagerJson as v, compilePredicate as y, compileRawFragment as b, compileSelect as x, decodeRowsFromSchema as S, encodeRowForSchema as C, endLocalWrite as w, externalChangeEvent as T, getTable as E, hasEagerLoads as D, isTableReactive as O, makeEagerFallbackReporter as k, observeDbOp as A, qualifyTable as j, raiseChangeListenerCeiling as M, recordsTable as N, registerPendingAttribution as ee, requireTable as te, resolveEchoAttribution as ne, runStoreTransaction as re, runWriteRecorders as ie, stampGeneratedId as P, stampGeneratedIds as ae, withCapturedAttribution as F } from "@voltro/database";
3
+ import { CDC_OFFSETS_TABLE as c, DEFAULT_ACQUIRE_TIMEOUT_MS as l, EagerCardinalityError as u, _voltroCdcOffsetsTable as d, attachEagerLoads as f, attributionFields as p, attributionKey as m, beginLocalWrite as h, bulkInsertLimitsFor as g, chunkRowsForInsert as _, compileEagerJson as v, compilePredicate as y, compileRawFragment as b, compileSelect as x, decodeRowsFromSchema as S, describeRowBindings as C, encodeRowForSchema as w, endLocalWrite as T, externalChangeEvent as E, getTable as D, hasEagerLoads as O, isTableReactive as k, makeEagerFallbackReporter as ee, observeDbOp as A, qualifyTable as te, raiseChangeListenerCeiling as ne, recordsTable as j, registerPendingAttribution as M, requireTable as N, resolveEchoAttribution as re, runStoreTransaction as ie, runWriteRecorders as ae, stampGeneratedId as P, stampGeneratedIds as F, withCapturedAttribution as I } from "@voltro/database";
4
4
  import { EventEmitter as oe } from "node:events";
5
- import { createLogger as I } from "@voltro/logger";
6
- import { SqlClient as L, TransactionConnection as R } from "@effect/sql/SqlClient";
5
+ import { createLogger as L } from "@voltro/logger";
6
+ import { SqlClient as R, TransactionConnection as z } from "@effect/sql/SqlClient";
7
7
  //#region src/sqlLayer.ts
8
8
  var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
9
9
  let t = e.acquireTimeoutMs ?? l;
@@ -18,7 +18,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
18
18
  ...n === void 0 ? {} : { connectTimeout: n },
19
19
  ...r === void 0 ? {} : { queueLimit: r }
20
20
  };
21
- }, z = (n) => e.layerConfig({
21
+ }, B = (n) => e.layerConfig({
22
22
  host: t.succeed(n.host),
23
23
  port: t.succeed(n.port),
24
24
  username: t.succeed(n.username),
@@ -26,7 +26,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
26
26
  database: t.succeed(n.database),
27
27
  poolConfig: t.succeed(ue(n)),
28
28
  ...n.maxConnections === void 0 ? {} : { maxConnections: t.succeed(n.maxConnections) }
29
- }), B = (e) => {
29
+ }), V = (e) => {
30
30
  let t = e.get("sslmode");
31
31
  if (t !== null) {
32
32
  if (t === "require") return !0;
@@ -39,13 +39,13 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
39
39
  if (n === "false" || n === "0") return !1;
40
40
  throw Error(`DB_URL '?ssl=${n}' is not supported by the mysql/mariadb dialect — use 'true'/'1' or 'false'/'0'.`);
41
41
  }
42
- }, V = (e) => {
42
+ }, H = (e) => {
43
43
  let t = {
44
44
  ...e.acquireTimeoutMs === void 0 ? {} : { acquireTimeoutMs: e.acquireTimeoutMs },
45
45
  ...e.acquireQueueLimit === void 0 ? {} : { acquireQueueLimit: e.acquireQueueLimit }
46
46
  };
47
47
  if (e.url) {
48
- let n = new URL(e.url), r = e.ssl ?? B(n.searchParams);
48
+ let n = new URL(e.url), r = e.ssl ?? V(n.searchParams);
49
49
  return {
50
50
  host: n.hostname || "localhost",
51
51
  port: n.port ? Number(n.port) : 3306,
@@ -67,10 +67,10 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
67
67
  ...e.ssl === void 0 ? {} : { ssl: e.ssl },
68
68
  ...t
69
69
  };
70
- }, H = (e) => z(V(e)), U = (e, t) => e === null ? !1 : t === null ? !0 : e.filename === t.filename ? e.position > t.position : e.filename > t.filename, de = (e) => e.msSinceProgress < e.stallThresholdMs ? "healthy" : e.primary !== null && !U(e.primary, e.reader) ? "idle-caught-up" : "reconnect", fe = (e) => (e instanceof Error ? e.message : String(e ?? "")).includes("schema changed between binlog event and metadata fetch"), pe = (e) => {
70
+ }, U = (e) => B(H(e)), de = (e, t) => e === null ? !1 : t === null ? !0 : e.filename === t.filename ? e.position > t.position : e.filename > t.filename, fe = (e) => e.msSinceProgress < e.stallThresholdMs ? "healthy" : e.primary !== null && !de(e.primary, e.reader) ? "idle-caught-up" : "reconnect", pe = (e) => (e instanceof Error ? e.message : String(e ?? "")).includes("schema changed between binlog event and metadata fetch"), me = (e) => {
71
71
  let t = e instanceof Error ? e.message : String(e ?? "");
72
72
  return /Table\s+[^\s.]+\.(\S+)\s+schema changed between binlog event and metadata fetch/.exec(t)?.[1] ?? null;
73
- }, me = "\n SELECT DISTINCT s.TABLE_NAME AS tableName\n FROM information_schema.STATISTICS s\n JOIN information_schema.COLUMNS c\n ON c.TABLE_SCHEMA = s.TABLE_SCHEMA\n AND c.TABLE_NAME = s.TABLE_NAME\n AND c.COLUMN_NAME = s.COLUMN_NAME\n WHERE s.TABLE_SCHEMA = DATABASE()\n AND s.NON_UNIQUE = 0\n AND s.SUB_PART IS NULL\n AND c.DATA_TYPE IN ('text','tinytext','mediumtext','longtext','blob','tinyblob','mediumblob','longblob')\n", he = "This verdict is the schema as read when the reader attached; applying the remedy does not lift it by itself. A boot that migrates in-process re-checks it once its schema work is done and re-admits the table in the same run; otherwise it holds until the process restarts.", W = (e) => `cdc: table '${e}' is EXCLUDED from binlog capture — its row image carries a hidden column the reader cannot account for. Cause: a UNIQUE constraint on an UNBOUNDED text column, which MariaDB backs with a HASH long-unique index; that index adds a hidden DB_ROW_HASH_n column to the row, present in the binlog and absent from information_schema.COLUMNS. Remedy: bound the column — text().maxLength(n) — so the constraint becomes an ordinary B-tree index with no hidden column. ALTER TABLE FORCE does NOT help: the rebuild recreates the index and the hidden column. Until then, cross-instance change events for this table are lost; own-node reactivity is unaffected (writes still emit inline). ${he}`, ge = (e) => `cdc: table '${e}' looks undecodable (a UNIQUE on an UNBOUNDED text column → MariaDB hash long-unique → a hidden DB_ROW_HASH_n column in the row image). Held OUT of binlog capture for now and re-checked after this boot's schema work — a migration that bounds the column re-admits it in the same run. Not a verdict yet; the definitive line follows.`, _e = (e) => `cdc: table '${e}' re-admitted to binlog capture — the hidden-column condition is gone (the schema moved since the reader attached). Cross-instance change events for it flow again.`, ve = 12e4, ye = (e, t = ve) => {
73
+ }, he = "\n SELECT DISTINCT s.TABLE_NAME AS tableName\n FROM information_schema.STATISTICS s\n JOIN information_schema.COLUMNS c\n ON c.TABLE_SCHEMA = s.TABLE_SCHEMA\n AND c.TABLE_NAME = s.TABLE_NAME\n AND c.COLUMN_NAME = s.COLUMN_NAME\n WHERE s.TABLE_SCHEMA = DATABASE()\n AND s.NON_UNIQUE = 0\n AND s.SUB_PART IS NULL\n AND c.DATA_TYPE IN ('text','tinytext','mediumtext','longtext','blob','tinyblob','mediumblob','longblob')\n", W = "This verdict is the schema as read when the reader attached; applying the remedy does not lift it by itself. A boot that migrates in-process re-checks it once its schema work is done and re-admits the table in the same run; otherwise it holds until the process restarts.", G = (e) => `cdc: table '${e}' is EXCLUDED from binlog capture — its row image carries a hidden column the reader cannot account for. Cause: a UNIQUE constraint on an UNBOUNDED text column, which MariaDB backs with a HASH long-unique index; that index adds a hidden DB_ROW_HASH_n column to the row, present in the binlog and absent from information_schema.COLUMNS. Remedy: bound the column — text().maxLength(n) — so the constraint becomes an ordinary B-tree index with no hidden column. ALTER TABLE FORCE does NOT help: the rebuild recreates the index and the hidden column. Until then, cross-instance change events for this table are lost; own-node reactivity is unaffected (writes still emit inline). ${W}`, ge = (e) => `cdc: table '${e}' looks undecodable (a UNIQUE on an UNBOUNDED text column → MariaDB hash long-unique → a hidden DB_ROW_HASH_n column in the row image). Held OUT of binlog capture for now and re-checked after this boot's schema work — a migration that bounds the column re-admits it in the same run. Not a verdict yet; the definitive line follows.`, _e = (e) => `cdc: table '${e}' re-admitted to binlog capture — the hidden-column condition is gone (the schema moved since the reader attached). Cross-instance change events for it flow again.`, ve = 12e4, ye = (e, t = ve) => {
74
74
  let n = null, r = [], i = () => {
75
75
  n &&= (clearTimeout(n), null), r = [];
76
76
  };
@@ -78,21 +78,21 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
78
78
  announce: (a, o) => {
79
79
  if (i(), a.length !== 0) {
80
80
  if (!o) {
81
- for (let t of a) e("error", W(t));
81
+ for (let t of a) e("error", G(t));
82
82
  return;
83
83
  }
84
84
  for (let t of a) e("warn", ge(t));
85
85
  r = a, n = setTimeout(() => {
86
86
  let i = r;
87
87
  n = null, r = [];
88
- for (let n of i) e("error", `${W(n)} (Held provisionally for ${Math.round(t / 1e3)}s awaiting a post-migration re-check that never ran; standing by the reading taken at attach.)`);
88
+ for (let n of i) e("error", `${G(n)} (Held provisionally for ${Math.round(t / 1e3)}s awaiting a post-migration re-check that never ran; standing by the reading taken at attach.)`);
89
89
  }, t), n.unref && n.unref();
90
90
  }
91
91
  },
92
92
  settle: (t) => {
93
93
  i();
94
- for (let n of t.stillExcluded) e("error", W(n));
95
- for (let n of t.newlyExcluded) e("error", W(n));
94
+ for (let n of t.stillExcluded) e("error", G(n));
95
+ for (let n of t.newlyExcluded) e("error", G(n));
96
96
  for (let n of t.readmitted) e("info", _e(n));
97
97
  },
98
98
  dispose: i
@@ -114,8 +114,8 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
114
114
  "writerows",
115
115
  "updaterows",
116
116
  "deleterows"
117
- ]), Te = /\b(alter|rename|drop|create)\s+(table|column)?/i, G = (e) => new Promise((t) => setTimeout(t, e)), K = async (e) => {
118
- let t = I({ scope: `voltro:${e.variant}:cdc` }), n;
117
+ ]), Te = /\b(alter|rename|drop|create)\s+(table|column)?/i, K = (e) => new Promise((t) => setTimeout(t, e)), q = async (e) => {
118
+ let t = L({ scope: `voltro:${e.variant}:cdc` }), n;
119
119
  try {
120
120
  n = (await import("@vlasky/zongji")).default;
121
121
  } catch (t) {
@@ -214,11 +214,11 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
214
214
  try {
215
215
  l?.stop();
216
216
  } catch {}
217
- if (d++, await G(Math.min(3e4, 500 * 2 ** Math.min(d, 6))), u) return;
218
- let i = s, a = w(n), c = !a && fe(n), f = !1;
217
+ if (d++, await K(Math.min(3e4, 500 * 2 ** Math.min(d, 6))), u) return;
218
+ let i = s, a = w(n), c = !a && pe(n), f = !1;
219
219
  if (c) {
220
- let e = pe(n), i = e ?? "<unknown>", { verdict: a, hits: o } = Ce(h.get(i) ?? [], Date.now());
221
- h.set(i, o), f = a === "persistent", f && !g.has(i) && (g.add(i), e !== null && r.add(e), t.error(W(i)));
220
+ let e = me(n), i = e ?? "<unknown>", { verdict: a, hits: o } = Ce(h.get(i) ?? [], Date.now());
221
+ h.set(i, o), f = a === "persistent", f && !g.has(i) && (g.add(i), e !== null && r.add(e), t.error(G(i)));
222
222
  }
223
223
  (a || c) && (f || t.warn(c ? "cdc: un-replayable backlog event (schema moved past it) — jumping to current end + self-heal" : "cdc: binlog gap (purged/failover) — jumping to current end + self-heal"), i = e.resolveStartPosition ? await e.resolveStartPosition().catch(() => null) : null, o = i?.filename ?? null, s = i, f || e.onResync?.());
224
224
  try {
@@ -243,14 +243,14 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
243
243
  l?.stop();
244
244
  } catch {}
245
245
  let n = e.resolveStartPosition ? await e.resolveStartPosition().catch(() => null) : null;
246
- o = n?.filename ?? null, s = n, e.onResync?.(), await G(500), await T(n);
246
+ o = n?.filename ?? null, s = n, e.onResync?.(), await K(500), await T(n);
247
247
  } else throw n;
248
248
  }
249
249
  let O = async () => {
250
250
  if (u || p || Date.now() - f < v) return;
251
251
  let n = null;
252
252
  if (e.resolveStartPosition && (n = await e.resolveStartPosition().catch(() => null)), u || p) return;
253
- let r = de({
253
+ let r = fe({
254
254
  msSinceProgress: Date.now() - f,
255
255
  stallThresholdMs: v,
256
256
  primary: n,
@@ -290,7 +290,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
290
290
  try {
291
291
  l?.stop();
292
292
  } catch {}
293
- return await G(500), !u && (s === null && e.onResync?.(), await T(s), b(), !0);
293
+ return await K(500), !u && (s === null && e.onResync?.(), await T(s), b(), !0);
294
294
  } catch (e) {
295
295
  return p = !1, await D("re-attach after an exclusion refresh failed", e), !1;
296
296
  } finally {
@@ -307,20 +307,20 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
307
307
  if (typeof n == "string") return n;
308
308
  t = t.cause;
309
309
  }
310
- }, q = (e) => {
310
+ }, J = (e) => {
311
311
  let t = De(e);
312
312
  return t !== void 0 && Ee.has(t);
313
- }, J = (e) => q(e) ? "retry" : "noRetry", Y = (e) => {
313
+ }, Y = (e) => J(e) ? "retry" : "noRetry", X = (e) => {
314
314
  if (e == null) return "null";
315
315
  let t = typeof e;
316
316
  if (t === "bigint") return `${e}n`;
317
317
  if (t !== "object") return JSON.stringify(e);
318
318
  if (e instanceof Date) return `"${e.toISOString()}"`;
319
- if (Array.isArray(e)) return `[${e.map(Y).join(",")}]`;
319
+ if (Array.isArray(e)) return `[${e.map(X).join(",")}]`;
320
320
  let n = e;
321
- return `{${Object.keys(n).sort().map((e) => `${JSON.stringify(e)}:${Y(n[e])}`).join(",")}}`;
321
+ return `{${Object.keys(n).sort().map((e) => `${JSON.stringify(e)}:${X(n[e])}`).join(",")}}`;
322
322
  }, Oe = (e) => {
323
- let t = Y(e), n = 2166136261;
323
+ let t = X(e), n = 2166136261;
324
324
  for (let e = 0; e < t.length; e++) n ^= t.charCodeAt(e), n = Math.imul(n, 16777619);
325
325
  return (n >>> 0).toString(36);
326
326
  }, ke = (e, t) => {
@@ -360,16 +360,16 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
360
360
  get pending() {
361
361
  return this.seen.size;
362
362
  }
363
- }, X = /* @__PURE__ */ new Set([
363
+ }, Z = /* @__PURE__ */ new Set([
364
364
  1022,
365
365
  1062,
366
366
  1586
367
- ]), Z = async (e) => {
368
- let t = e.variant ?? "mysql", n = I({ scope: `voltro:${t}` }), a = e.changeStrategy ?? "inline", o = a;
367
+ ]), Q = async (e) => {
368
+ let t = e.variant ?? "mysql", n = L({ scope: `voltro:${t}` }), a = e.changeStrategy ?? "inline", o = a;
369
369
  a === "cdc" && !e.cdcConfig && (n.warn("changeStrategy='cdc' requires cdcConfig (serverId + connection); falling back to 'inline'."), o = "inline");
370
- let s = e.tracerLayer ? r.mergeAll(e.sqlLayer, e.tracerLayer) : e.sqlLayer, c = i.make(s), l = new Q(await c.runPromise(L), c, t, o);
370
+ let s = e.tracerLayer ? r.mergeAll(e.sqlLayer, e.tracerLayer) : e.sqlLayer, c = i.make(s), l = new je(await c.runPromise(R), c, t, o);
371
371
  return o === "cdc" && e.cdcConfig && await l.startCdcConsumer(e.cdcConfig), l;
372
- }, Q = class e {
372
+ }, je = class e {
373
373
  sql;
374
374
  runtime;
375
375
  variant;
@@ -390,15 +390,15 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
390
390
  cdcGate;
391
391
  reportEagerFallback;
392
392
  constructor(e, t, n, r = "inline", i = null, a, o) {
393
- this.sql = e, this.runtime = t, this.variant = n, this.changeStrategy = r, this.namespace = i, this.log = I({ scope: `voltro:${n}` }), this.cdcReporter = ye((e, t) => {
393
+ this.sql = e, this.runtime = t, this.variant = n, this.changeStrategy = r, this.namespace = i, this.log = L({ scope: `voltro:${n}` }), this.cdcReporter = ye((e, t) => {
394
394
  e === "error" ? this.log.error(t) : e === "warn" ? this.log.warn(t) : this.log.info(t);
395
- }), this.reportEagerFallback = k(this.log), this.emitter = a ?? new oe(), M(this.emitter), this.cdcGate = o ?? new Ae(n);
395
+ }), this.reportEagerFallback = ee(this.log), this.emitter = a ?? new oe(), ne(this.emitter), this.cdcGate = o ?? new Ae(n);
396
396
  }
397
397
  withNamespace(t) {
398
398
  return t === this.namespace ? this : new e(this.sql, this.runtime, this.variant, this.changeStrategy, t, this.emitter, this.cdcGate);
399
399
  }
400
400
  nsT(e) {
401
- return j(this.namespace, e);
401
+ return te(this.namespace, e);
402
402
  }
403
403
  get dialectId() {
404
404
  return this.variant;
@@ -410,7 +410,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
410
410
  };
411
411
  }
412
412
  async executeQuery(e, t, r) {
413
- let i = x(e, this.sql, this.namespace), a = t ? n.provideService(i, R, t) : i, o = await A(this.variant, "select", () => this.runtime.runPromise(a));
413
+ let i = x(e, this.sql, this.namespace), a = t ? n.provideService(i, z, t) : i, o = await A(this.variant, "select", () => this.runtime.runPromise(a));
414
414
  return S(o, e.table, this.variant);
415
415
  }
416
416
  get supportsInsertReturning() {
@@ -426,7 +426,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
426
426
  t = P(e, t);
427
427
  let o = this.sql;
428
428
  if (this.supportsInsertReturning) {
429
- let s = o`INSERT INTO ${o(this.nsT(e))} ${o.insert(C(t, e))} RETURNING *`, c = r ? n.provideService(s, R, r) : s, l = (await this.runtime.runPromise(c))[0];
429
+ let s = o`INSERT INTO ${o(this.nsT(e))} ${o.insert(w(t, e))} RETURNING *`, c = r ? n.provideService(s, z, r) : s, l = (await this.runtime.runPromise(c))[0];
430
430
  if (!l) throw Error(`MysqlStore.insert: no row returned for table '${e}'`);
431
431
  return await this.routeEvent({
432
432
  table: e,
@@ -435,7 +435,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
435
435
  new: l
436
436
  }, i, r, a), l;
437
437
  }
438
- let s = C(t, e), c = t.id;
438
+ let s = w(t, e), c = t.id;
439
439
  if (c === void 0) {
440
440
  let t = await this.insertRecoverAutoId(e, s, r);
441
441
  return await this.routeEvent({
@@ -445,9 +445,9 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
445
445
  new: t
446
446
  }, i, r, a), t;
447
447
  }
448
- let l = o`INSERT INTO ${o(this.nsT(e))} ${o.insert(s)}`, u = r ? n.provideService(l, R, r) : l;
448
+ let l = o`INSERT INTO ${o(this.nsT(e))} ${o.insert(s)}`, u = r ? n.provideService(l, z, r) : l;
449
449
  await this.runtime.runPromise(u);
450
- let d = o`SELECT * FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${c}`, f = r ? n.provideService(d, R, r) : d, p = (await this.runtime.runPromise(f))[0];
450
+ let d = o`SELECT * FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${c}`, f = r ? n.provideService(d, z, r) : d, p = (await this.runtime.runPromise(f))[0];
451
451
  if (!p) throw Error(`MysqlStore.insert: row not found post-insert in '${e}'`);
452
452
  return await this.routeEvent({
453
453
  table: e,
@@ -460,16 +460,16 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
460
460
  let i = this.sql;
461
461
  return this.runPinned(r, (r) => n.gen(this, function* () {
462
462
  let a = i`INSERT INTO ${i(this.nsT(e))} ${i.insert(t)}`;
463
- yield* n.provideService(a, R, r);
464
- let o = (yield* n.provideService(i`SELECT LAST_INSERT_ID() AS ${i("lastId")}`, R, r))[0]?.lastId;
465
- return o === void 0 || Number(o) === 0 ? yield* n.fail(/* @__PURE__ */ Error(`MysqlStore.insert: LAST_INSERT_ID() returned no id for '${e}' — is the primary key AUTO_INCREMENT?`)) : (yield* n.provideService(i`SELECT * FROM ${i(this.nsT(e))} WHERE ${i("id")} = ${o}`, R, r))[0] || (yield* n.fail(/* @__PURE__ */ Error(`MysqlStore.insert: row not found post-insert in '${e}'`)));
463
+ yield* n.provideService(a, z, r);
464
+ let o = (yield* n.provideService(i`SELECT LAST_INSERT_ID() AS ${i("lastId")}`, z, r))[0]?.lastId;
465
+ return o === void 0 || Number(o) === 0 ? yield* n.fail(/* @__PURE__ */ Error(`MysqlStore.insert: LAST_INSERT_ID() returned no id for '${e}' — is the primary key AUTO_INCREMENT?`)) : (yield* n.provideService(i`SELECT * FROM ${i(this.nsT(e))} WHERE ${i("id")} = ${o}`, z, r))[0] || (yield* n.fail(/* @__PURE__ */ Error(`MysqlStore.insert: row not found post-insert in '${e}'`)));
466
466
  }), "insert");
467
467
  }
468
468
  async runPinned(e, t, r) {
469
469
  if (e) return this.runtime.runPromise(t(e));
470
470
  this.inflightTxns++;
471
471
  try {
472
- let e = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(R), (e) => a.isNone(e) ? n.fail(/* @__PURE__ */ Error(`MysqlStore.${r}: TransactionConnection missing.`)) : t(e.value)))), i = s.exponential("10 millis").pipe(s.compose(s.recurs(3)), s.whileInput(q)), o = e.pipe(n.retry(i), n.withSpan(`store.${r}`, { attributes: {
472
+ let e = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(z), (e) => a.isNone(e) ? n.fail(/* @__PURE__ */ Error(`MysqlStore.${r}: TransactionConnection missing.`)) : t(e.value)))), i = s.exponential("10 millis").pipe(s.compose(s.recurs(3)), s.whileInput(J)), o = e.pipe(n.retry(i), n.withSpan(`store.${r}`, { attributes: {
473
473
  "db.system": this.variant,
474
474
  "db.operation": r
475
475
  } }));
@@ -479,16 +479,16 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
479
479
  }
480
480
  }
481
481
  async executeInsertMany(e, t, r, i, a) {
482
- if (t = ae(e, t), t.length === 0) return [];
483
- let o = this.sql, s = t.map((t) => C(t, e)), c = _(s, g(this.variant));
482
+ if (t = F(e, t), t.length === 0) return [];
483
+ let o = this.sql, s = t.map((t) => w(t, e)), c = _(s, g(this.variant));
484
484
  if (this.supportsInsertReturning) {
485
485
  let t = (t) => o`INSERT INTO ${o(this.nsT(e))} ${o.insert(t)} RETURNING *`, s;
486
486
  if (c.length === 1) {
487
- let e = t(c[0]), i = r ? n.provideService(e, R, r) : e;
487
+ let e = t(c[0]), i = r ? n.provideService(e, z, r) : e;
488
488
  s = await this.runtime.runPromise(i);
489
489
  } else if (r) {
490
490
  let e = [];
491
- for (let i of c) e.push(...await this.runtime.runPromise(n.provideService(t(i), R, r)));
491
+ for (let i of c) e.push(...await this.runtime.runPromise(n.provideService(t(i), z, r)));
492
492
  s = e;
493
493
  } else s = await this.runtime.runPromise(o.withTransaction(n.map(n.forEach(c, t, { concurrency: 1 }), (e) => e.flat())));
494
494
  for (let t of s) await this.routeEvent({
@@ -513,16 +513,16 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
513
513
  if (l.some((e) => e === void 0)) throw Error("MysqlStore.insertMany: rows mix client-supplied and missing 'id's — supply an id for every row or none (AUTO_INCREMENT recovery).");
514
514
  let u = (t) => o`INSERT INTO ${o(this.nsT(e))} ${o.insert(t)}`;
515
515
  if (c.length === 1) {
516
- let e = r ? n.provideService(u(c[0]), R, r) : u(c[0]);
516
+ let e = r ? n.provideService(u(c[0]), z, r) : u(c[0]);
517
517
  await this.runtime.runPromise(e);
518
- } else if (r) for (let e of c) await this.runtime.runPromise(n.provideService(u(e), R, r));
518
+ } else if (r) for (let e of c) await this.runtime.runPromise(n.provideService(u(e), z, r));
519
519
  else await this.runtime.runPromise(o.withTransaction(n.forEach(c, u, {
520
520
  concurrency: 1,
521
521
  discard: !0
522
522
  })));
523
523
  let d = _(l.map((e) => ({ id: e })), g(this.variant)), f = [];
524
524
  for (let t of d) {
525
- let i = o`SELECT * FROM ${o(this.nsT(e))} WHERE ${o("id")} IN ${o.in(t.map((e) => e.id))}`, a = r ? n.provideService(i, R, r) : i;
525
+ let i = o`SELECT * FROM ${o(this.nsT(e))} WHERE ${o("id")} IN ${o.in(t.map((e) => e.id))}`, a = r ? n.provideService(i, z, r) : i;
526
526
  f.push(...await this.runtime.runPromise(a));
527
527
  }
528
528
  let p = new Map(f.map((e) => [e.id, e])), m = l.map((e) => p.get(e)).filter((e) => e !== void 0);
@@ -540,19 +540,19 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
540
540
  let a = [];
541
541
  for (let o of t) {
542
542
  let t = i`INSERT INTO ${i(this.nsT(e))} ${i.insert(o)}`;
543
- yield* n.provideService(t, R, r);
544
- let s = (yield* n.provideService(i`SELECT LAST_INSERT_ID() AS ${i("firstId")}`, R, r))[0]?.firstId;
543
+ yield* n.provideService(t, z, r);
544
+ let s = (yield* n.provideService(i`SELECT LAST_INSERT_ID() AS ${i("firstId")}`, z, r))[0]?.firstId;
545
545
  if (s === void 0 || Number(s) === 0) return yield* n.fail(/* @__PURE__ */ Error(`MysqlStore.insertMany: LAST_INSERT_ID() returned no id for '${e}' — is the primary key AUTO_INCREMENT?`));
546
- let c = Number(s), l = yield* n.provideService(i`SELECT * FROM ${i(this.nsT(e))} WHERE ${i("id")} BETWEEN ${c} AND ${c + o.length - 1} ORDER BY ${i("id")} ASC`, R, r);
546
+ let c = Number(s), l = yield* n.provideService(i`SELECT * FROM ${i(this.nsT(e))} WHERE ${i("id")} BETWEEN ${c} AND ${c + o.length - 1} ORDER BY ${i("id")} ASC`, z, r);
547
547
  a.push(...l);
548
548
  }
549
549
  return a;
550
550
  }), "insert");
551
551
  }
552
552
  async executePatchJson(e, t, r, i, a, o, s) {
553
- let c = this.sql, l = r.split("."), u = l[0], d = l.slice(1), f = JSON.stringify(i ?? null), p = d.length === 0 ? "$" : `$.${d.join(".")}`, m = c`UPDATE ${c(this.nsT(e))} SET ${c(u)} = JSON_SET(COALESCE(${c(u)}, '{}'), ${p}, CAST(${f} AS JSON)) WHERE ${c("id")} = ${t}`, h = a ? n.provideService(m, R, a) : m, g = await this.runtime.runPromise(h);
553
+ let c = this.sql, l = r.split("."), u = l[0], d = l.slice(1), f = JSON.stringify(i ?? null), p = d.length === 0 ? "$" : `$.${d.join(".")}`, m = c`UPDATE ${c(this.nsT(e))} SET ${c(u)} = JSON_SET(COALESCE(${c(u)}, '{}'), ${p}, CAST(${f} AS JSON)) WHERE ${c("id")} = ${t}`, h = a ? n.provideService(m, z, a) : m, g = await this.runtime.runPromise(h);
554
554
  if (g && typeof g.affectedRows == "number" && g.affectedRows === 0) return null;
555
- let _ = c`SELECT * FROM ${c(this.nsT(e))} WHERE ${c("id")} = ${t}`, v = a ? n.provideService(_, R, a) : _, y = (await this.runtime.runPromise(v))[0];
555
+ let _ = c`SELECT * FROM ${c(this.nsT(e))} WHERE ${c("id")} = ${t}`, v = a ? n.provideService(_, z, a) : _, y = (await this.runtime.runPromise(v))[0];
556
556
  return y ? (await this.routeEvent({
557
557
  table: e,
558
558
  op: "update",
@@ -563,7 +563,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
563
563
  async executeUpdate(e, t, r, i, a, o) {
564
564
  let s = this.sql;
565
565
  if (this.supportsUpdateReturning) {
566
- let c = s`UPDATE ${s(this.nsT(e))} SET ${s.update(C(r, e))} WHERE ${s("id")} = ${t} RETURNING *`, l = i ? n.provideService(c, R, i) : c, u = (await this.runtime.runPromise(l))[0];
566
+ let c = s`UPDATE ${s(this.nsT(e))} SET ${s.update(w(r, e))} WHERE ${s("id")} = ${t} RETURNING *`, l = i ? n.provideService(c, z, i) : c, u = (await this.runtime.runPromise(l))[0];
567
567
  return u ? (await this.routeEvent({
568
568
  table: e,
569
569
  op: "update",
@@ -571,9 +571,9 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
571
571
  new: u
572
572
  }, a, i, o), u) : null;
573
573
  }
574
- let c = s`UPDATE ${s(this.nsT(e))} SET ${s.update(C(r, e))} WHERE ${s("id")} = ${t}`, l = i ? n.provideService(c, R, i) : c, u = await this.runtime.runPromise(l);
574
+ let c = s`UPDATE ${s(this.nsT(e))} SET ${s.update(w(r, e))} WHERE ${s("id")} = ${t}`, l = i ? n.provideService(c, z, i) : c, u = await this.runtime.runPromise(l);
575
575
  if (u && typeof u.affectedRows == "number" && u.affectedRows === 0) return null;
576
- let d = s`SELECT * FROM ${s(this.nsT(e))} WHERE ${s("id")} = ${t}`, f = i ? n.provideService(d, R, i) : d, p = (await this.runtime.runPromise(f))[0];
576
+ let d = s`SELECT * FROM ${s(this.nsT(e))} WHERE ${s("id")} = ${t}`, f = i ? n.provideService(d, z, i) : d, p = (await this.runtime.runPromise(f))[0];
577
577
  return p ? (await this.routeEvent({
578
578
  table: e,
579
579
  op: "update",
@@ -584,7 +584,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
584
584
  async executeDelete(e, t, r, i, a) {
585
585
  let o = this.sql;
586
586
  if (this.supportsDeleteReturning) {
587
- let s = o`DELETE FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t} RETURNING *`, c = r ? n.provideService(s, R, r) : s, l = (await this.runtime.runPromise(c))[0];
587
+ let s = o`DELETE FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t} RETURNING *`, c = r ? n.provideService(s, z, r) : s, l = (await this.runtime.runPromise(c))[0];
588
588
  return l ? (await this.routeEvent({
589
589
  table: e,
590
590
  op: "delete",
@@ -592,9 +592,9 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
592
592
  new: null
593
593
  }, i, r, a), !0) : !1;
594
594
  }
595
- let s = o`SELECT * FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t}`, c = r ? n.provideService(s, R, r) : s, l = (await this.runtime.runPromise(c))[0];
595
+ let s = o`SELECT * FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t}`, c = r ? n.provideService(s, z, r) : s, l = (await this.runtime.runPromise(c))[0];
596
596
  if (!l) return !1;
597
- let u = o`DELETE FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t}`, d = r ? n.provideService(u, R, r) : u;
597
+ let u = o`DELETE FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t}`, d = r ? n.provideService(u, z, r) : u;
598
598
  return await this.runtime.runPromise(d), await this.routeEvent({
599
599
  table: e,
600
600
  op: "delete",
@@ -602,19 +602,26 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
602
602
  new: null
603
603
  }, i, r, a), !0;
604
604
  }
605
- async appendInTxn(e, t, r) {
606
- let i = this.sql, a = i`INSERT INTO ${i(this.nsT(e))} ${i.insert(C(t, e))}`;
607
- await this.runtime.runPromise(r ? n.provideService(a, R, r) : a);
605
+ static bindingContextFor(e, t, n) {
606
+ return Object.assign(Error(`binding ${t}`, { cause: e }), { voltroBindings: C(n) });
607
+ }
608
+ async appendInTxn(t, r, i) {
609
+ let a = this.sql, o = w(r, t), s = a`INSERT INTO ${a(this.nsT(t))} ${a.insert(o)}`;
610
+ try {
611
+ await this.runtime.runPromise(i ? n.provideService(s, z, i) : s);
612
+ } catch (n) {
613
+ throw e.bindingContextFor(n, t, o);
614
+ }
608
615
  }
609
616
  async maxInTxn(e, t, r, i) {
610
- 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, R, i) : s))[0]?.m;
617
+ 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, z, i) : s))[0]?.m;
611
618
  return c == null ? null : Number(c);
612
619
  }
613
620
  async routeEvent(e, t, n = null, r) {
614
621
  if (e = {
615
622
  ...p(r),
616
623
  ...e
617
- }, N(e.table) && await ie({
624
+ }, j(e.table) && await ae({
618
625
  append: (e, t) => this.appendInTxn(e, t, n),
619
626
  maxOf: (e, t, r) => this.maxInTxn(e, t, r, n)
620
627
  }, {
@@ -626,7 +633,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
626
633
  subjectId: e.subjectId
627
634
  }), this.changeStrategy === "cdc") {
628
635
  let t = (e.op === "delete" ? e.old : e.new)?.id;
629
- t != null && ee(m(e.table, e.op, t), {
636
+ t != null && M(m(e.table, e.op, t), {
630
637
  ...e.traceId === void 0 ? {} : { traceId: e.traceId },
631
638
  ...e.subjectId === void 0 ? {} : { subjectId: e.subjectId }
632
639
  });
@@ -638,7 +645,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
638
645
  this.emitChange(e);
639
646
  }
640
647
  isCompleteInsertRow(e, t) {
641
- let n = E(e);
648
+ let n = D(e);
642
649
  if (n === void 0) return !0;
643
650
  let r = n.fields;
644
651
  for (let [e, n] of Object.entries(r)) if (n !== void 0 && n.nullable !== !0 && n.hasDefault !== !0 && n.defaultValue === void 0 && n.defaultFactory === void 0 && n.computed === void 0 && n.generatedAs === void 0 && n.idScheme === void 0 && t[e] === void 0) return !1;
@@ -664,12 +671,12 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
664
671
  }
665
672
  return await this.executeUpdate(e, o.id, a, r, i) ?? o;
666
673
  }
667
- return F((n) => this.executeInsert(e, t, r, i, n));
674
+ return I((n) => this.executeInsert(e, t, r, i, n));
668
675
  }
669
676
  async executeMariadbUpsert(e, t, r, i, a, o) {
670
- let s = this.sql, c = C(t, e), l = Object.keys(c).filter((e) => c[e] !== void 0), u = r.update === void 0 ? l.filter((e) => e !== "id" && !r.conflictColumns.includes(e)) : r.update, d = u.length > 0 ? s.csv(u.map((e) => s`${s(e)} = VALUES(${s(e)})`)) : s`${s(r.conflictColumns[0])} = VALUES(${s(r.conflictColumns[0])})`, f = await this.runPinned(i, (i) => n.tryPromise({
677
+ let s = this.sql, c = w(t, e), l = Object.keys(c).filter((e) => c[e] !== void 0), u = r.update === void 0 ? l.filter((e) => e !== "id" && !r.conflictColumns.includes(e)) : r.update, d = u.length > 0 ? s.csv(u.map((e) => s`${s(e)} = VALUES(${s(e)})`)) : s`${s(r.conflictColumns[0])} = VALUES(${s(r.conflictColumns[0])})`, f = await this.runPinned(i, (i) => n.tryPromise({
671
678
  try: async () => {
672
- let a = s`INSERT INTO ${s(this.nsT(e))} ${s.insert(c)} ON DUPLICATE KEY UPDATE ${d} RETURNING *`, o = (await this.runtime.runPromise(n.provideService(a, R, i)))[0];
679
+ let a = s`INSERT INTO ${s(this.nsT(e))} ${s.insert(c)} ON DUPLICATE KEY UPDATE ${d} RETURNING *`, o = (await this.runtime.runPromise(n.provideService(a, z, i)))[0];
673
680
  if (!o) throw Error(`MysqlStore.upsert: no row returned for table '${e}'`);
674
681
  let l = t.id;
675
682
  if (l != null && o.id !== l) throw Error(`MysqlStore.upsert: the row written to '${e}' is not the row that was passed in. Upserting id '${String(l)}' matched an existing row with id '${String(o.id)}' on a DIFFERENT unique constraint than the conflictColumns [${r.conflictColumns.join(", ")}] you named, so that row would have been updated and yours never written. Nothing was changed. Name the constraint that actually collides, or resolve the duplicate first.`);
@@ -685,7 +692,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
685
692
  }, a, i, o), f;
686
693
  }
687
694
  async executeInsertIgnore(e, t, r, i, a, o) {
688
- if (t = P(e, t), t.id === void 0) return await this.findByConflict(e, t, r.conflictColumns, i) || F((n) => this.executeInsert(e, t, i, a, n));
695
+ if (t = P(e, t), t.id === void 0) return await this.findByConflict(e, t, r.conflictColumns, i) || I((n) => this.executeInsert(e, t, i, a, n));
689
696
  let s = await this.runPinned(i, (i) => n.tryPromise({
690
697
  try: () => this.decideInsertIgnore(e, t, r, i),
691
698
  catch: (e) => e
@@ -698,7 +705,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
698
705
  }, a, i, o), s.row;
699
706
  }
700
707
  async decideInsertIgnore(e, t, r, i) {
701
- let a = this.sql, o = C(t, e), s = (e) => this.runtime.runPromise(n.provideService(e, R, i));
708
+ let a = this.sql, o = w(t, e), s = (e) => this.runtime.runPromise(n.provideService(e, z, i));
702
709
  if (this.supportsInsertReturning) {
703
710
  let n = (await s(a`INSERT IGNORE INTO ${a(this.nsT(e))} ${a.insert(o)} RETURNING *`))[0];
704
711
  if (n) return {
@@ -713,7 +720,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
713
720
  }
714
721
  await s(a`INSERT IGNORE INTO ${a(this.nsT(e))} ${a.insert(o)}`);
715
722
  let c = await this.readWarnings(i);
716
- if (!c.some((e) => X.has(e.code))) {
723
+ if (!c.some((e) => Z.has(e.code))) {
717
724
  let n = (await s(a`SELECT * FROM ${a(this.nsT(e))} WHERE ${a("id")} = ${t.id}`))[0];
718
725
  if (n) return {
719
726
  kind: "landed",
@@ -726,7 +733,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
726
733
  };
727
734
  }
728
735
  async resolveSkippedInsertIgnore(e, t, n, r, i) {
729
- let a = r.find((e) => !X.has(e.code));
736
+ let a = r.find((e) => !Z.has(e.code));
730
737
  if (a !== void 0) throw Error(`MysqlStore.insertIgnore: the insert into '${e}' was REJECTED, not skipped as a conflict. INSERT IGNORE downgrades every error to a warning, and the warning was: [${a.code}] ${a.message}. Nothing was written and nothing conflicted — fix the cause above.`, { cause: {
731
738
  errno: a.code,
732
739
  sqlMessage: a.message
@@ -739,7 +746,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
739
746
  async findUndecodableCdcTables(e) {
740
747
  if (this.variant !== "mariadb") return [];
741
748
  try {
742
- let t = (await this.runtime.runPromise(this.sql.unsafe(me))).map((e) => String(e.tableName ?? e.TABLE_NAME ?? "")).filter((e) => e !== "");
749
+ let t = (await this.runtime.runPromise(this.sql.unsafe(he))).map((e) => String(e.tableName ?? e.TABLE_NAME ?? "")).filter((e) => e !== "");
743
750
  return e === void 0 ? t : t.filter((t) => e.includes(t));
744
751
  } catch (e) {
745
752
  return this.log.debug(`cdc: could not probe for undecodable tables — ${e?.message ?? String(e)}`), [];
@@ -749,7 +756,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
749
756
  if (e === null) return [];
750
757
  try {
751
758
  let t = this.sql`SHOW WARNINGS`.unprepared;
752
- return (await this.runtime.runPromise(n.provideService(t, R, e))).map((e) => ({
759
+ return (await this.runtime.runPromise(n.provideService(t, z, e))).map((e) => ({
753
760
  code: Number(e.Code ?? e.code ?? 0),
754
761
  message: String(e.Message ?? e.message ?? "")
755
762
  }));
@@ -759,7 +766,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
759
766
  }
760
767
  async findByConflict(e, t, r, i) {
761
768
  if (r.length === 0) return;
762
- let a = this.sql, o = r.map((e) => a`${a(e)} = ${t[e]}`), s = a`SELECT * FROM ${a(this.nsT(e))} WHERE ${a.and(o)} LIMIT 1`, c = i ? n.provideService(s, R, i) : s;
769
+ let a = this.sql, o = r.map((e) => a`${a(e)} = ${t[e]}`), s = a`SELECT * FROM ${a(this.nsT(e))} WHERE ${a.and(o)} LIMIT 1`, c = i ? n.provideService(s, z, i) : s;
763
770
  return (await this.runtime.runPromise(c))[0];
764
771
  }
765
772
  query(e) {
@@ -770,10 +777,10 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
770
777
  return A(this.variant, "raw", () => this.runtime.runPromise(n));
771
778
  }
772
779
  async runWithEager(e, t) {
773
- if (!D(e)) return this.executeQuery(e, t);
780
+ if (!O(e)) return this.executeQuery(e, t);
774
781
  let r = this.variant === "mariadb" ? "mariadb" : "mysql", i = this.namespace === null ? v(e, this.sql, r) : null;
775
782
  if (i !== null) try {
776
- let e = t ? n.provideService(i.fragment, R, t) : i.fragment, r = await A(this.variant, "select", () => this.runtime.runPromise(e));
783
+ let e = t ? n.provideService(i.fragment, z, t) : i.fragment, r = await A(this.variant, "select", () => this.runtime.runPromise(e));
777
784
  return i.decode(r);
778
785
  } catch (t) {
779
786
  if (t instanceof u) throw t;
@@ -790,7 +797,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
790
797
  reason: "not-compilable"
791
798
  });
792
799
  let a = await this.executeQuery(e, t);
793
- return f(a, e.eager, e.sourceTable ?? te(e.table), (e) => this.executeQuery(e, t));
800
+ return f(a, e.eager, e.sourceTable ?? N(e.table), (e) => this.executeQuery(e, t));
794
801
  }
795
802
  getInternalRunWithEager() {
796
803
  return this.runWithEager.bind(this);
@@ -804,14 +811,14 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
804
811
  return i;
805
812
  }
806
813
  async localWrite(e, t, n) {
807
- let r = (e) => N(t) ? this.writeWithRecorders(n, e) : n(e, null, null);
814
+ let r = (e) => j(t) ? this.writeWithRecorders(n, e) : n(e, null, null);
808
815
  return A(this.variant, e, async () => {
809
- if (this.changeStrategy !== "cdc") return F(r);
816
+ if (this.changeStrategy !== "cdc") return I(r);
810
817
  h(t);
811
818
  try {
812
- return await F(r);
819
+ return await I(r);
813
820
  } finally {
814
- w(t);
821
+ T(t);
815
822
  }
816
823
  });
817
824
  }
@@ -838,7 +845,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
838
845
  }
839
846
  async updateMany(e, t, r) {
840
847
  if (this.supportsUpdateReturning) {
841
- let n = this.sql, i = y(r.where, n, this.namespace), a = n`UPDATE ${n(this.nsT(e))} SET ${n.update(C(t, e))} WHERE ${i} RETURNING *`, o = await this.runtime.runPromise(a);
848
+ let n = this.sql, i = y(r.where, n, this.namespace), a = n`UPDATE ${n(this.nsT(e))} SET ${n.update(w(t, e))} WHERE ${i} RETURNING *`, o = await this.runtime.runPromise(a);
842
849
  for (let t of o) await this.routeEvent({
843
850
  table: e,
844
851
  op: "update",
@@ -850,15 +857,15 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
850
857
  let i = this.sql, o = y(r.where, i, this.namespace);
851
858
  this.changeStrategy === "cdc" && h(e), this.inflightTxns++;
852
859
  try {
853
- let r = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(R), (r) => {
860
+ let r = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(z), (r) => {
854
861
  if (a.isNone(r)) return n.fail(/* @__PURE__ */ Error("MysqlStore.updateMany: TransactionConnection missing."));
855
- let s = r.value, c = i`SELECT id FROM ${i(this.nsT(e))} WHERE ${o} FOR UPDATE`, l = i`UPDATE ${i(this.nsT(e))} SET ${i.update(C(t, e))} WHERE ${o}`;
856
- return n.flatMap(n.provideService(c, R, s), (t) => {
862
+ let s = r.value, c = i`SELECT id FROM ${i(this.nsT(e))} WHERE ${o} FOR UPDATE`, l = i`UPDATE ${i(this.nsT(e))} SET ${i.update(w(t, e))} WHERE ${o}`;
863
+ return n.flatMap(n.provideService(c, z, s), (t) => {
857
864
  if (t.length === 0) return n.succeed([]);
858
865
  let r = t.map((e) => e.id), a = i`SELECT * FROM ${i(this.nsT(e))} WHERE ${i("id")} IN ${i.in(r)}`;
859
- return n.flatMap(n.provideService(l, R, s), () => n.provideService(a, R, s));
866
+ return n.flatMap(n.provideService(l, z, s), () => n.provideService(a, z, s));
860
867
  });
861
- }))), c = s.exponential("10 millis").pipe(s.compose(s.recurs(3)), s.whileInput(q)), l = r.pipe(n.retry(c), n.withSpan("store.updateMany", { attributes: {
868
+ }))), c = s.exponential("10 millis").pipe(s.compose(s.recurs(3)), s.whileInput(J)), l = r.pipe(n.retry(c), n.withSpan("store.updateMany", { attributes: {
862
869
  "db.system": this.variant,
863
870
  "db.operation": "update"
864
871
  } })), u = await this.runtime.runPromise(l);
@@ -872,7 +879,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
872
879
  }, null, null);
873
880
  return d.length;
874
881
  } finally {
875
- this.inflightTxns--, this.changeStrategy === "cdc" && w(e);
882
+ this.inflightTxns--, this.changeStrategy === "cdc" && T(e);
876
883
  }
877
884
  }
878
885
  async deleteMany(e, t) {
@@ -889,11 +896,11 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
889
896
  }
890
897
  this.changeStrategy === "cdc" && h(e), this.inflightTxns++;
891
898
  try {
892
- let t = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(R), (t) => {
899
+ let t = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(z), (t) => {
893
900
  if (a.isNone(t)) return n.fail(/* @__PURE__ */ Error("MysqlStore.deleteMany: TransactionConnection missing."));
894
901
  let o = t.value, s = r`SELECT * FROM ${r(this.nsT(e))} WHERE ${i} FOR UPDATE`, c = r`DELETE FROM ${r(this.nsT(e))} WHERE ${i}`;
895
- return n.flatMap(n.provideService(s, R, o), (e) => e.length === 0 ? n.succeed(e) : n.as(n.provideService(c, R, o), e));
896
- }))), o = s.exponential("10 millis").pipe(s.compose(s.recurs(3)), s.whileInput(q)), c = t.pipe(n.retry(o), n.withSpan("store.deleteMany", { attributes: {
902
+ return n.flatMap(n.provideService(s, z, o), (e) => e.length === 0 ? n.succeed(e) : n.as(n.provideService(c, z, o), e));
903
+ }))), o = s.exponential("10 millis").pipe(s.compose(s.recurs(3)), s.whileInput(J)), c = t.pipe(n.retry(o), n.withSpan("store.deleteMany", { attributes: {
897
904
  "db.system": this.variant,
898
905
  "db.operation": "delete"
899
906
  } })), l = await this.runtime.runPromise(c);
@@ -907,22 +914,22 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
907
914
  }, null, null);
908
915
  return u.length;
909
916
  } finally {
910
- this.inflightTxns--, this.changeStrategy === "cdc" && w(e);
917
+ this.inflightTxns--, this.changeStrategy === "cdc" && T(e);
911
918
  }
912
919
  }
913
920
  emitChange(e) {
914
- O(e.table) && (this.changeStrategy === "cdc" && !this.cdcGate.admit(e) || this.emitter.emit("change", e));
921
+ k(e.table) && (this.changeStrategy === "cdc" && !this.cdcGate.admit(e) || this.emitter.emit("change", e));
915
922
  }
916
923
  async startCdcConsumer(e) {
917
924
  if (this.cdcHandle) return;
918
- await this.assertBinlogConfig(), this.cdcReplicaId = e.replicaId, this.cdcAdminRuntime = i.make(z({
925
+ await this.assertBinlogConfig(), this.cdcReplicaId = e.replicaId, this.cdcAdminRuntime = i.make(B({
919
926
  ...e.connection,
920
927
  maxConnections: 1
921
928
  }));
922
929
  let t = await this.readCdcOffset(e.replicaId), n = t !== null && await this.binlogFileExists(t.filename);
923
930
  t !== null && !n && this.log.warn(`cdc: the persisted offset points at ${t.filename}, which the server no longer has (the binlog was purged or rotated away while this replica was down). Starting at the current end instead — changes written in the gap are not replayed, and subscriptions self-heal on the next change.`);
924
931
  let r = (n ? t : null) ?? await this.resolveBinlogEnd(), a = await this.findUndecodableCdcTables(e.includeTables);
925
- this.cdcIncludeTables = e.includeTables, this.cdcExcluded = a, this.cdcReporter.announce(a, e.exclusionRefreshFollows === !0), this.cdcHandle = await K({
932
+ this.cdcIncludeTables = e.includeTables, this.cdcExcluded = a, this.cdcReporter.announce(a, e.exclusionRefreshFollows === !0), this.cdcHandle = await q({
926
933
  connection: e.connection,
927
934
  serverId: e.serverId,
928
935
  variant: this.variant,
@@ -956,7 +963,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
956
963
  let t = this.cdcAdminRuntime;
957
964
  if (t === null) return !0;
958
965
  try {
959
- let r = await t.runPromise(n.flatMap(L, (e) => e`SHOW BINARY LOGS`.unprepared));
966
+ let r = await t.runPromise(n.flatMap(R, (e) => e`SHOW BINARY LOGS`.unprepared));
960
967
  return r.length === 0 || r.some((t) => (t.Log_name ?? t.log_name) === e);
961
968
  } catch (e) {
962
969
  return this.log.debug(`cdc: could not list binary logs (${e?.message ?? String(e)}) — trusting the persisted offset`), !0;
@@ -984,7 +991,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
984
991
  async resolveBinlogEndOverCdc() {
985
992
  let e = this.cdcAdminRuntime;
986
993
  if (e === null) return null;
987
- let t = (e) => n.flatMap(L, (t) => t`${t.unsafe(e)}`.unprepared);
994
+ let t = (e) => n.flatMap(R, (t) => t`${t.unsafe(e)}`.unprepared);
988
995
  for (let n of this.variant === "mysql" ? ["SHOW BINARY LOG STATUS", "SHOW MASTER STATUS"] : ["SHOW MASTER STATUS", "SHOW BINARY LOG STATUS"]) try {
989
996
  let r = (await e.runPromise(t(n)))[0];
990
997
  if (r?.File) return {
@@ -1080,16 +1087,16 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
1080
1087
  }
1081
1088
  async emptyTablesOn(e, t) {
1082
1089
  if (e.length === 0) return;
1083
- let r = this.sql, i = (e) => this.nsT(e), a = (e) => r.unsafe(`SET FOREIGN_KEY_CHECKS = ${+!!e}`).unprepared, o = n.acquireUseRelease(a(!1), () => n.forEach(e, (e) => r`DELETE FROM ${r(i(e))}`, { discard: !0 }), () => n.orDie(n.ignore(a(!0)))), s = t === null ? r.withTransaction(o) : n.provideService(o, R, t);
1090
+ let r = this.sql, i = (e) => this.nsT(e), a = (e) => r.unsafe(`SET FOREIGN_KEY_CHECKS = ${+!!e}`).unprepared, o = n.acquireUseRelease(a(!1), () => n.forEach(e, (e) => r`DELETE FROM ${r(i(e))}`, { discard: !0 }), () => n.orDie(n.ignore(a(!0)))), s = t === null ? r.withTransaction(o) : n.provideService(o, z, t);
1084
1091
  await this.runtime.runPromise(s);
1085
1092
  }
1086
1093
  async transactional(e) {
1087
1094
  this.inflightTxns++;
1088
1095
  try {
1089
- return await re({
1096
+ return await ie({
1090
1097
  ...this.txnSpec("MysqlStore.transactional"),
1091
1098
  work: e,
1092
- makeView: (e, t) => new je(this, e, t)
1099
+ makeView: (e, t) => new Me(this, e, t)
1093
1100
  });
1094
1101
  } finally {
1095
1102
  this.inflightTxns--;
@@ -1101,7 +1108,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
1101
1108
  dialect: this.variant === "mariadb" ? "mariadb" : "mysql",
1102
1109
  withTransaction: (e) => this.sql.withTransaction(e),
1103
1110
  runPromiseExit: (e) => this.runtime.runPromiseExit(e),
1104
- isRetryable: q,
1111
+ isRetryable: J,
1105
1112
  span: {
1106
1113
  name: "store.transactional",
1107
1114
  attributes: {
@@ -1120,10 +1127,10 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
1120
1127
  return this.changeStrategy === "cdc" ? "fleet" : "local";
1121
1128
  }
1122
1129
  injectExternalChange(e) {
1123
- if (this.changeStrategy === "cdc" && !this.cdcGate.admit(e) || !O(e.table)) return;
1130
+ if (this.changeStrategy === "cdc" && !this.cdcGate.admit(e) || !k(e.table)) return;
1124
1131
  let t = (e.op === "delete" ? e.old : e.new)?.id;
1125
- ne(e.table, e.op, t, (t) => {
1126
- this.emitter.emit("change", T(e, t));
1132
+ re(e.table, e.op, t, (t) => {
1133
+ this.emitter.emit("change", E(e, t));
1127
1134
  });
1128
1135
  }
1129
1136
  run(e) {
@@ -1160,7 +1167,7 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
1160
1167
  async ping() {
1161
1168
  await this.runtime.runPromise(this.sql`SELECT 1`);
1162
1169
  }
1163
- }, je = class {
1170
+ }, Me = class {
1164
1171
  parent;
1165
1172
  txn;
1166
1173
  attr;
@@ -1236,12 +1243,12 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
1236
1243
  this.events.length = 0;
1237
1244
  }
1238
1245
  }
1239
- }, $ = (e) => e.__mysqlReplicationFriend ?? null, Me = () => ({
1246
+ }, $ = (e) => e.__mysqlReplicationFriend ?? null, Ne = () => ({
1240
1247
  async capturePrimaryPosition(e) {
1241
1248
  let t = $(e);
1242
1249
  if (t === null) throw Error("mysqlReplicationAdapter: primary is not a MysqlStore (missing __mysqlReplicationFriend).");
1243
1250
  return t.runEffect(n.gen(function* () {
1244
- let e = yield* L, r = (t.variant === "mariadb" ? yield* e`SELECT @@global.gtid_current_pos AS gtid` : yield* e`SELECT @@global.gtid_executed AS gtid`)[0]?.gtid;
1251
+ let e = yield* R, r = (t.variant === "mariadb" ? yield* e`SELECT @@global.gtid_current_pos AS gtid` : yield* e`SELECT @@global.gtid_executed AS gtid`)[0]?.gtid;
1245
1252
  return typeof r == "string" ? r : yield* n.die("mysql/mariadb did not return a GTID set");
1246
1253
  }));
1247
1254
  },
@@ -1249,31 +1256,31 @@ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
1249
1256
  let t = $(e);
1250
1257
  if (t === null) throw Error("mysqlReplicationAdapter: replica is not a MysqlStore.");
1251
1258
  return t.runEffect(n.gen(function* () {
1252
- let e = yield* L, r = (t.variant === "mariadb" ? yield* e`SELECT @@global.gtid_current_pos AS gtid` : yield* e`SELECT @@global.gtid_executed AS gtid`)[0]?.gtid;
1259
+ let e = yield* R, r = (t.variant === "mariadb" ? yield* e`SELECT @@global.gtid_current_pos AS gtid` : yield* e`SELECT @@global.gtid_executed AS gtid`)[0]?.gtid;
1253
1260
  return typeof r == "string" ? r : yield* n.die("mysql/mariadb replica did not return a GTID set");
1254
1261
  }));
1255
1262
  },
1256
1263
  compare(e, t) {
1257
1264
  return "behind";
1258
1265
  }
1259
- }), Ne = {
1266
+ }), Pe = {
1260
1267
  id: "mysql",
1261
- makeSqlLayer: (e) => H(e),
1262
- makeStore: (e) => Z({
1268
+ makeSqlLayer: (e) => U(e),
1269
+ makeStore: (e) => Q({
1263
1270
  ...e,
1264
1271
  variant: "mysql"
1265
1272
  }),
1266
1273
  compileContains: (e, t, n) => n`${e} LIKE ${`%${t.replace(/[\\%_]/g, (e) => `\\${e}`)}%`} ESCAPE '\\'`,
1267
- retryFilter: J
1268
- }, Pe = {
1274
+ retryFilter: Y
1275
+ }, Fe = {
1269
1276
  id: "mariadb",
1270
- makeSqlLayer: (e) => H(e),
1271
- makeStore: (e) => Z({
1277
+ makeSqlLayer: (e) => U(e),
1278
+ makeStore: (e) => Q({
1272
1279
  ...e,
1273
1280
  variant: "mariadb"
1274
1281
  }),
1275
1282
  compileContains: (e, t, n) => n`${e} LIKE ${`%${t.replace(/[\\%_]/g, (e) => `\\${e}`)}%`} ESCAPE '\\'`,
1276
- retryFilter: J
1283
+ retryFilter: Y
1277
1284
  };
1278
1285
  //#endregion
1279
- export { c as CDC_OFFSETS_TABLE, e as MysqlClient, d as _voltroCdcOffsetsTable, V as connectionFromConfig, z as makeMysqlSqlLayer, H as makeMysqlSqlLayerFromConfig, Z as makeMysqlStore, Pe as mariadbDialect, Ne as mysqlDialect, Me as mysqlReplicationAdapter, J as mysqlRetryFilter, K as startBinlogCdc };
1286
+ export { c as CDC_OFFSETS_TABLE, e as MysqlClient, d as _voltroCdcOffsetsTable, H as connectionFromConfig, B as makeMysqlSqlLayer, U as makeMysqlSqlLayerFromConfig, Q as makeMysqlStore, Fe as mariadbDialect, Pe as mysqlDialect, Ne as mysqlReplicationAdapter, Y as mysqlRetryFilter, q as startBinlogCdc };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/sql-mysql",
3
- "version": "0.44.1",
3
+ "version": "0.46.0",
4
4
  "description": "MySQL/MariaDB dialect adapter for Voltro's cross-dialect DataStore (mariadb binlog CDC; mysql inline reactivity).",
5
5
  "keywords": [
6
6
  "voltro",
@@ -35,8 +35,8 @@
35
35
  "dependencies": {
36
36
  "@effect/sql": "^0.52.0",
37
37
  "@effect/sql-mysql2": "^0.53.0",
38
- "@voltro/database": "0.44.1",
39
- "@voltro/logger": "0.44.1"
38
+ "@voltro/database": "0.46.0",
39
+ "@voltro/logger": "0.46.0"
40
40
  },
41
41
  "optionalDependencies": {
42
42
  "@vlasky/zongji": "^0.9.0"