@voltro/sql-mysql 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -39,6 +39,177 @@ _Changes staged for the next release accumulate here (rolled up from
39
39
 
40
40
  ---
41
41
 
42
+ ## [0.42.0] — 2026-08-17
43
+
44
+ ### ⚠ BREAKING
45
+
46
+ - **@voltro/cli, @voltro/data-transfer** — **Two security defects on the data-transfer surface, both found by using the feature rather than by reading it.**
47
+
48
+ **A `{ profile }` in an admin-export request could name a PATH.** `loadProfile` resolved the client's string with `resolve(cwd, x)` — which returns an absolute path unchanged and lets `../` traverse — and the resolved file is `await import()`ed, which RUNS it. So a holder of the data-transfer secret could make the api process execute any file on the pod: an escalation from "can export prod data" to "can run code", and chainable on an instance whose object storage is a filesystem the same caller can write to.
49
+
50
+ `POST /_voltro/admin/export` now accepts a NAME only — `[A-Za-z0-9_-]{1,64}`, resolved under `data-profiles/` and checked to be contained there. **Migration: if you passed a path over `--target api`, move the file to `data-profiles/<name>.ts` and pass `<name>`.** `voltro data export --profile` on a DIRECT target still accepts a path: it runs on the operator's own machine, where a path is not an escalation. No user-authored code changes, so `codemod: none`.
51
+
52
+ **An unrecognised masking action copied the value through.** `applyAction` ended in `return input.value`, so a profile with a typo in the action shape (`{ action: 'fake', kind: 'email' }` instead of `{ fake: 'email' }`) exported every row of a `.sensitive()` column verbatim — with a 200 and an audit line counting the column as masked. Measured against a live instance: a masked export of two users came back carrying both real addresses.
53
+
54
+ The applier now throws, and `planMasking` refuses the policy BEFORE a row is read: `MaskingError` gained `invalidActions`, reported separately from `unclassified` because the fixes differ — one needs a classification, the other needs the policy corrected.
55
+
56
+ ### Added
57
+
58
+ - **@voltro/runtime** — A write the database refuses on an integrity rule now raises a typed `ConstraintViolation` instead of an opaque `SqlError`. It carries `{ kind, table, operation, constraint?, column? }`, where `kind` is one of `foreignKey` · `foreignKeyInUse` · `unique` · `notNull` · `check`. Declare it in a procedure's `error:` to pattern-match it; undeclared it still reaches the client as an `InternalError` carrying its own sentence rather than `Failed to execute statement`.
59
+
60
+ It carries NAMES and never the driver's message, which on most engines contains row data — postgres attaches the complete failing row to a not-null and a check violation, mysql and mssql echo the duplicate value. Classification is measured against live postgres 17, MySQL 8.4, MariaDB 11, SQL Server 2022 and sqlite.
61
+
62
+ Raised from one guard covering every write op (insert · insertMany · upsert · insertIgnore · update · updateMany · delete · deleteMany · hardDelete · patchJson); the tenant-FK case still resolves to `TenantScopeViolation` first.
63
+
64
+ ### Fixed
65
+
66
+ - **@voltro/cli, @voltro/data-transfer** — `voltro data import|export` — four defects on the `--target api` path, all found by a consumer seeding a fresh cluster from a bundle.
67
+
68
+ **A flag this command does not read is now an ERROR.** `--dry-run` and `--tables` were accepted on the import path and dropped in silence: a preview against a production-shaped cluster ran the import instead (2905 rows, then a 500), and a run narrowed to a one-row table wrote all 10 593. Both are one defect — an argument parser that ignores what it does not understand — so every `voltro data` subcommand now declares the flags it reads per target and refuses the rest, naming the flag and what to use instead.
69
+
70
+ **`--dry-run` and `--tables` now work on the import, on BOTH targets.** A dry run reaches every verdict a real run reaches (schema fit, cross-dialect portability, mode legality, the table selection) and stops before the first write; the api path carries them as `x-import-dry-run` / `x-import-tables` and echoes `{ dryRun: true, wrote: false }`. A `--tables` name the bundle does not carry is refused, listing what it does. `--dry-run` on an api EXPORT is refused rather than ignored — previewing a read protects nothing.
71
+
72
+ **The schema-drift pre-flight compares the INTERSECTION, not whole schemas.** A bundle's fingerprint covers its source schema regardless of export scope, and two environments never have identical whole schemas, so the check refused every cross-environment seed with a diff whose every line said the difference changes nothing — making `--force` the routine way to import and removing the protection it guards. It now reports only what would break the load: a carried table or column the target lacks, a type mismatch, or a column the target REQUIRES that the bundle carries no value for.
73
+
74
+ **A failed row says why.** `reason` was `Failed to execute statement` for every one of 2905 rows. It now names the constraint and the rule (`foreign key tasks_laneId_fkey: the referenced row does not exist [23503]`), or the driver's own message with its code, or — where there is no driver under the failure — the error from the layer that refused.
75
+
76
+ Also: `voltro data inspect` accepts a directory bundle instead of dying inside the archive reader with a JSON parse error (`--target api` always unpacks into a directory, even when the path ends in `.vbundle`).
77
+
78
+ **Three more, found by running the whole thing against live MariaDB and MySQL** rather than against sqlite:
79
+
80
+ - A re-run of a COMPLETED import wrote nothing and reported the bundle's full row count — the resume ledger lives in the bundle directory, so truncating a target and re-importing printed `import complete … 10593 rows` over an empty database. Resume is right; being quiet about it was not. It now warns, names the skipped tables, and says which ledger file to delete. - The deferred-FK recovery pass OVERWROTE the diagnosis. When a held row cannot be written, the resolver retries it with every `reference` column nulled to break a cycle — and that attempt's failure replaced the original reason, so a row whose real problem was one column reported a not-null violation on a column the framework itself had nulled. The recovery attempt no longer records a reason. - MySQL/MariaDB errno **1364** (a statement that OMITS a column which is NOT NULL with no default) is classified as a not-null violation. postgres reports 23502 for that situation and mssql 515, so the mysql family was the only one where "you did not supply a required column" came back unclassified.
81
+ - **@voltro/database** — CHECK constraints were invisible to introspection on **MySQL** — and with them every `.oneOf()` column and every `json_valid` marker.
82
+
83
+ `information_schema.check_constraints` differs between the two engines of the family: MariaDB carries `TABLE_NAME`, MySQL does not have that column at all. The introspector selected it, the query errored, and an `Effect.orElseSucceed` turned that into an empty list. A swallowed error and an empty result read identically, which is why this needed a two-engine test to surface. The query JOINs `information_schema.table_constraints` for the name now, which both engines answer.
84
+
85
+ `parseEnumCheck` also learned MySQL's rendering. The same clause is stored differently:
86
+
87
+ mariadb 11 `status` in ('draft','live','done') mysql 8.4 (`status` in (_latin1'draft',_latin1'live',_latin1'done'))
88
+
89
+ MySQL puts a charset introducer before each literal, which the pattern — written against MariaDB's form — did not read. Both are pinned in `enumCheckParity.test.ts`.
90
+
91
+ Neither fix completes the round trip on MySQL: `.oneOf()` still comes back unclassified there. That is asserted as a known gap in `oneOfCheck.mariadb.integration.test.ts` (which fails the moment it starts working) and written up in `plans/open/framework/mysql-oneof-roundtrip.md`.
92
+ - **@voltro/database** — `voltro db apply` works on MySQL. It could not create a table with an index, and could not drop a column, on that engine at all.
93
+
94
+ `IF [NOT] EXISTS` outside `CREATE`/`DROP TABLE` is a MariaDB extension — MySQL rejects it with ER_PARSE_ERROR (measured on 8.4 for `CREATE INDEX IF NOT EXISTS`, `ALTER TABLE … DROP COLUMN IF EXISTS`, and `ADD COLUMN IF NOT EXISTS`). The applier emitted the first two, because `@effect/sql-mysql2` reports the dialect `mysql` for both engines and the shared branch had only ever run against MariaDB. A `reference()` column gets an index by default, so in practice most tables were affected.
95
+
96
+ The applier now asks the SERVER which engine it is (`SELECT VERSION()`; MariaDB stamps itself into the string) and emits the plain form on MySQL. The idempotency `IF [NOT] EXISTS` provided moves into the statement runner, which tolerates exactly the errnos meaning "already in the requested state" — 1061 for a duplicate index name, 1091 for dropping something absent. The engine is read from the connection rather than from `DB_DIALECT` or `variant`, because the DDL has to be legal for the server that receives it and those are what an operator typed.
97
+
98
+ Verified against live MySQL 8.4 and MariaDB 11: a schema evolution — create, add column, add index, drop column — applied through `applyPlan` on both, converging at every step, plus a replayed plan (what a resume does) that must not error on the statements it repeats.
99
+
100
+ **sqlite had the same defect, found by the new cross-dialect scenario on its first run.** `ALTER TABLE … DROP COLUMN IF EXISTS` is accepted by postgres, mssql and MariaDB and rejected by sqlite — and the generic emitter, shaped for postgres, is what sqlite used. So `voltro db apply` could not drop a column on sqlite either. The conditional form is now emitted only where it is legal, and the "already dropped" case is tolerated per dialect (`idempotentDdl.ts`).
101
+
102
+ `runDialectParity` gained a schema-evolution scenario — create, add column, add index, drop column, applied for real with a convergence check after each step — so the migration APPLIER is now covered on all five dialects. It previously had one scenario covering one op kind, while twenty-two covered the store; that split is why four emitter defects survived.
103
+
104
+ **And a fifth, found by making one MariaDB-only suite two-sided.** `text().unique()` on an unbounded text column created a table on MariaDB and failed the CREATE outright on MySQL: `BLOB/TEXT column 'x' used in key specification without a key length`. The bring-up emitter (`migrate.ts`) wrote an inline `UNIQUE`; the declarative applier had always written a separate PREFIXED unique index. The two emitters disagreeing on one statement is the failure shape this package's own notes describe, and only one engine said so.
105
+
106
+ `migrate.ts` emits the prefixed index now, through the same `indexStmt` that already owns the per-dialect `IF NOT EXISTS` rule, and names it `<table>_<column>_key` to match the applier's — so the two paths produce the same object.
107
+
108
+ **Note the behaviour change on MariaDB.** It accepted the inline form by backing it with a HASH long-unique index, whose hidden `DB_ROW_HASH_n` column breaks the binlog CDC reader (documented in `packages/database/CLAUDE.md`). Uniqueness on such a column is now enforced on the first 191 characters rather than the whole value — which is what `voltro db apply` already did, and what MySQL can express at all. Bound the column with `text().maxLength(n)` if you need full-value uniqueness.
109
+ - **@voltro/sql-mysql** — `insertIgnore` on MySQL was a different feature from `insertIgnore` on MariaDB — and the difference could turn a conflict into an error.
110
+
111
+ The whole diagnostic apparatus — the refusal to report a REJECTED write as a conflict, and the message naming the constraint that actually fired — sat behind a `variant === 'mariadb'` branch. MySQL took an `else` that used no `INSERT IGNORE` at all: look for a row matching the conflict columns, insert if there is none. That cannot hold the one property the method exists for. A caller that looks before anyone else writes sees nothing, so the write it then makes is the one that raises the duplicate-key error `insertIgnore` promises never to raise — reproduced deterministically against both engines with an uncommitted holder (the lookup cannot see the holder's row; the insert cannot proceed until it commits).
112
+
113
+ Underneath sat the reason a straight port would still have produced nothing: **MySQL answers a PREPARED `SHOW WARNINGS` with 1295 ER_UNSUPPORTED_PS**, and the warning read is deliberately failure-tolerant (a diagnostic must never replace the caller's real problem), so it returned an empty list — indistinguishable from a statement that raised nothing. MariaDB accepts both protocols. The read goes through the text protocol now, the same spelling the binlog path already used for `SHOW MASTER STATUS`.
114
+
115
+ Both engines now run one `INSERT IGNORE` and reach one decision function. What differs is only the probe for "did it land": MariaDB has `INSERT IGNORE … RETURNING *`; MySQL has no RETURNING, so the row's own key answers instead. `SELECT ROW_COUNT()` — the obvious alternative — cannot be used: measured on both engines, it reports 1/0 correctly but CLEARS the warning list on MySQL, and run the other way round returns `-1` because `SHOW WARNINGS` is then the last statement. The count and the diagnosis cannot both be had; the diagnosis is the one worth having.
116
+
117
+ Found by converting the suite that covers this to run on both engines, which is also where every MySQL assertion in it had been reporting the driver's generic `Failed to execute statement`.
118
+ - **@voltro/database** — A `reference()` column now creates a real foreign key on **MySQL**. It did not before: MySQL/InnoDB parses a column-inline `REFERENCES` clause and discards it — no constraint, no warning, the `CREATE TABLE` succeeds — while MariaDB honours the identical clause. Both engines reach the same emitter (the driver reports the dialect `mysql` for either), and every mysql-family integration suite in the repo runs against MariaDB, so referential integrity that postgres, MariaDB, mssql and sqlite all enforced was silently absent on MySQL.
119
+
120
+ Both emitters now write a table-level `CONSTRAINT <table>_<column>_fkey FOREIGN KEY …` inside the `CREATE TABLE`, which both engines honour and which `CREATE TABLE IF NOT EXISTS` keeps idempotent. Existing MariaDB schemas are unaffected — the introspected snapshot carries no constraint name, so nothing re-plans.
121
+
122
+ Verified against live MySQL 8.4: the constraint is in the catalog, the server refuses an orphan row, introspection reads it back, and the re-plan is empty.
123
+ - **@voltro/sql-turso, @voltro/testing** — A migration on turso applied correctly and then reported itself as failed: `voltro db apply` ran an `add-column`, re-planned to prove convergence, saw the column still missing, proposed the same operation again, and the second execution died with `duplicate column name`. No fingerprint was recorded, so every subsequent boot re-proposed the same work — and the error named the migration applier, which had done nothing wrong.
124
+
125
+ The client caches one prepared statement per connection per SQL text, and a prepared statement carries the schema it was prepared against. So a cached `PRAGMA table_info(t)` keeps answering with the old columns after a DDL — it is never re-prepared, so sqlite's schema-cookie re-preparation never runs. The invalidation for this existed, on the unprepared path (`sql.unsafe`) only, and the migration path sends its DDL through the PREPARED one. The statement that changed the schema and the cache that had to be dropped were on the same connection, one function apart, with nothing connecting them.
126
+
127
+ Any schema-changing statement now drops that connection's cached statements, whichever path it arrived on.
128
+
129
+ Three hypotheses were measured and disproven before this one — an applier retry (each operation is issued once), an MVCC snapshot (two raw libsql clients both see the DDL), and a pool-wide cache problem (four connections held open together, the PRAGMA prepared on each, a DDL on one: the other three answer correctly, because SQLite bumps the schema cookie and the driver re-prepares on the connections that did not make the change).
130
+
131
+ The two `runDialectParity` scenarios that drive the migration applier were skipped for turso on the strength of that misreading. They run now, and the per-fixture opt-out that carried the skip is deleted: it was holding a defect open while reading like a documented limitation.
132
+
133
+ **`apiSurface: compatible`, and the reason is a date rather than an argument.** Removing `DialectFixture.skipApplierScenarios` moves a line in `@voltro/testing`'s golden, so the changelog's narrowing detector flags it — and it is right to, because that detector's baseline is `origin/main`. But the field never reached a RELEASE: it was added after `v0.41.0` and deleted before this one, both inside the same unreleased range. `git show v0.41.0:packages/testing/etc/testing-dialect.api.md` does not contain it. No published version ever offered it, so no consumer can have set it, and there is nothing to migrate.
134
+
135
+ Worth writing down because the first reading of this was wrong in the safe direction: it was filed `BREAKING` with a codemod on the strength of "an optional field disappeared from a published package's surface", which is the right instinct and the wrong conclusion here. **"Removed relative to main" is not "removed relative to what users have"** — a symbol that lives and dies between two tags trips the detector while breaking nobody, and the difference is only visible by asking the last TAG rather than the last commit.
136
+
137
+ ---
138
+
139
+ ## [0.41.0] — 2026-08-17
140
+
141
+ ### ⚠ BREAKING
142
+
143
+ - **@voltro/web, @voltro/cli** — `middleware.ts` exports `defineMiddleware(...)` (from `@voltro/web/middleware`) instead of a bare function, and each export carries its own `match`. Several middlewares per file are allowed; **at most one may match a given route**.
144
+
145
+ Migration: the codemod wraps the existing default export. That is behaviour-preserving — no `match` means every server-rendered route, which is what an unwrapped middleware did — and its note explains how to replace a hand-written path gate with a `match`.
146
+
147
+ **Why it was worth a break.** A hand-written `if (!req.pathname.startsWith('/app')) return` is invisible: nothing can tell you a middleware runs nowhere, or that two of them claim one route. `match` puts it where both the boot and `voltro doctor` can read it.
148
+
149
+ **The matcher speaks ROUTES, not URL patterns** — `under` / `routes` / `except`, validated against the app's own route patterns. A path matching no route refuses the boot instead of silently never firing. This is the deliberate difference from the `'/((?!api|_next/static|…).*)'` shape: our hook runs after route matching, so an app has never needed to know its own asset layout, and non-page requests are reachable only by asking (`assets: true`) — where, note, there is no render, so only `setCookies` takes effect.
150
+
151
+ An overlap refuses the boot and names both middlewares plus the route. Declaration order is not a semantic, "most specific wins" silently drops the broader hook, and merging needs a per-field rule nobody remembers — so two hooks writing one `authorization` header is a refusal, not a resolution.
152
+
153
+ **The web bundle budget moved UP, and the split is worth stating** because only one half is a cost the framework imposes:
154
+
155
+ | measured | before | after | | --- | --- | --- | | first load | 184 955 B | 185 309 B (**+354**) | | lazy route chunks | 3 502 B | 4 415 B (+913) |
156
+
157
+ The **+354 B of first load is the real price** — one `serverContext` chunk, 0.2 KB gz, which every app now carries whether or not it declares a middleware. That is the number to argue with, and it leaves 6.7 KB of headroom under the ceiling.
158
+
159
+ The +913 B is NOT a per-route regression: the fixture gained four routes (`exact`, `exact/[id]`, `mw`, `mw/skip`) to exercise the feature end to end, at 0.1–0.2 KB gz each, which accounts for the growth without remainder. Re-pinned with `--update` rather than by hand, so the `slackFloor` keeps ratcheting — a ceiling nobody lowers again silently permits re-inflating to the old number.
160
+
161
+ ### Fixed
162
+
163
+ - **@voltro/data-transfer, @voltro/cli** — `voltro data export` could not export a table whose primary key is not named `id`, and one of its two failure modes reported success.
164
+
165
+ The keyset column was `columns.find(c => c.type === 'id')?.name ?? 'id'`, and `type: 'id'` is tagged only on a column that is BOTH the single-column primary key AND literally named `id` — identically in all four dialect introspectors. So any introspected table with another PK name was ordered by a column that does not exist. It now comes from the real primary key (the synthesised `<table>_pkey` index), with the declared `id()` column still winning where there is one.
166
+
167
+ **A composite or absent primary key is now REFUSED**, not silently ordered by the first column: keyset pagination on a non-unique order splits equal values across page boundaries, so rows are dropped or duplicated into a bundle that reports success. Bounded exports are recoverable; a quietly short backup is discovered at the restore.
168
+
169
+ **A requested table missing from the schema is refused too.** `scope: { kind: 'tables' }` used to drop unknown names, so a run that explicitly named a table wrote `"tables": []` and printed `export complete` with exit 0. `kind: 'all'` over an empty database is still a legal empty export — the asymmetry is deliberate: a named table is an expectation.
170
+
171
+ **Failure reasons survive.** `String(e?.message ?? e)` produced `"write table failed: "` with nothing after the colon — `??` falls back on null/undefined, and an Effect `TaggedError` carries an empty-string `message`. Every catch site in the exporter now reports tag, message or cause.
172
+
173
+ **New: `voltro data export --exclude a,b`** — everything except these, resolved against the live table list. It is the escape hatch the refusals above require; without it a single unkeyable table would block a whole-database export. An unknown name is refused for the same reason. Direct target only (the expansion needs the live table list), and it expands to an explicit `tables` scope, so the manifest records what was actually exported.
174
+
175
+ Reported with a reduced repro, a four-way variation over PK TYPES that ruled type out, and two disproved hypotheses. The affected tables include `@effect/cluster`'s own (`cluster_locks`, `cluster_migrations`), so no app running workflows could take a whole-database export.
176
+ - **@voltro/database, @voltro/runtime, @voltro/cli** — `.encrypted()` had three writers and two encodings. The store wrote `encrypt(JSON.stringify(v))`; `encryptField` — the documented raw-SQL escape hatch — and `voltro db encrypt-column` wrote `encrypt(v)`. All three produce the same `enc:v1:` envelope and nothing distinguished them, so a value written by one and read by another either threw with the wrong diagnosis or came back subtly wrong (`decryptField` handed back the JSON encoding verbatim, quotes and all, raising nothing).
177
+
178
+ There is one encoding for every WRITE now, and every READ resolves BOTH forms — so **no data has to be rewritten and nothing is blocked**. That second half is the point: the old form is already on staging and production disks, and a fix that needs the rows rewritten before the app works is an outage with a migration attached.
179
+
180
+ Reading two forms is deterministic, not a heuristic. After decrypting, a parse failure is the raw form; a parse to a STRING is the JSON form; a parse to a non-string depends on the column's declared type (a text column cannot hold a number, so `12345` is a raw string that parsed by accident). The one case nothing can separate — a raw secret whose literal text is `"abc"`, quotes included — is stated in the code rather than hidden.
181
+
182
+ **`voltro db encrypt-column` verified itself against the wrong decoder.** It wrote the raw form and checked it with `cipher.decrypt` — a decoder nothing reads these columns with — so it reported success over columns the app could not read. It round-trips through `decodeFieldValue` now, the same function the store calls. A self-check against a decoder the runtime does not use is not a weaker check; it is a second opinion from the same mistake.
183
+
184
+ The command also NORMALISES rows in the old encoding as it goes (reported separately from the ones it encrypts), so an operator does not write a script per column. It skips anything ambiguous and anything it cannot decrypt.
185
+
186
+ **The width pre-flight measured the wrong thing after the encoding changed.** It sized the ciphertext from the PLAINTEXT's byte length while the cipher is handed the JSON encoding — two characters more at minimum, and more for every escape. Measured on a real MariaDB: a 63-byte value in a `varchar(135)` passed the check and the UPDATE answered `ER_DATA_TOO_LONG`, which is the failure that check exists to prevent, mid-column with the rest already converted. It measures the encoded length now, and the refusal says "encodes to" rather than "is" so an operator measuring their own column finds the number it names.
187
+
188
+ **Two dialect defects, both found by running the command against real servers.** SQL Server reports `-1` for `NVARCHAR(MAX)` — its spelling of unbounded — and the pre-flight read it as a one-character column, so it refused the widest column the dialect has and printed `declared as -1` at the operator. And SQLITE has no `information_schema` at all: the shared catalog query died there with `Failed to prepare statement` and no statement attached, on a dialect the command claims to support. It uses `pragma_table_info` now, reporting no length because sqlite enforces none.
189
+
190
+ Measured end to end on postgres, mysql, mariadb, mssql and sqlite: a table holding plaintext, the old encoding and the current encoding side by side converts, every row decodes back to its original value, a re-run writes nothing, and a wrong key refuses with exit 1.
191
+
192
+ **Backups and restores were never affected and now say so.** `voltro data export` reads through the raw dialect store, so ciphertext travels verbatim in either encoding — pinned by a test, because a future change that wrapped that store would put plaintext credentials in a bundle.
193
+ - **@voltro/protocol, @voltro/cli** — Three findings from one consumer round, all of the same shape: something the framework knows and does not say.
194
+
195
+ **A decode failure on a GUARDED procedure now says the guard did not run.** The payload decodes before the handler, so a guard on a procedure with a malformed payload never gets the chance to refuse. A consumer auditing a guard called one with an incomplete payload, got a decode error instead of a `ScopeError`, and concluded the guard was not applied — the wrong conclusion in the dangerous direction. The title now carries `(guarded — the guard did NOT run: the payload failed to decode first, so this says nothing about access)`. It discloses nothing new: that a procedure is guarded is already visible to anyone who sends a VALID payload. An `openAccess:` declaration is not an enforced guard and gets no such sentence — `hasEnforcedGuard` is the one predicate, read by both the label and the wire error union, because two copies of that rule would disagree invisibly.
196
+
197
+ **`middleware.ts`'s `httpOnly` default is documented at the field, and warned about.** It defaults to `HttpOnly`, which is wrong for a session cookie a browser SDK reads back: Supabase's `createBrowserClient` reads `document.cookie`, so a forgotten `httpOnly: false` gives the browser a session it cannot see — the SSR render is perfect and the user is signed out at the first client-side call. The consumer only avoided shipping it because their probes already set the flag. `voltro dev` warns once per cookie when a session-shaped name is written with no `httpOnly` decision; an explicit decision either way silences it, because warning on a decision is how a diagnostic becomes noise.
198
+
199
+ **`voltro dev` restarts when `middleware.ts` changes.** It is loaded once per boot, that is documented, and a consumer read it and still lost an afternoon: they sabotaged the middleware, saw no change, and concluded it was not wired — in an environment where everything else hot-reloads. It now restarts through the same respawn a hard-restart field in `app.config.ts` uses, extracted so there is one copy of the `execArgv` inheritance and the signal forwarding.
200
+ - **@voltro/cli** — `middleware.ts` now produces ONE view of the request that every downstream reader takes. Previously only `buildLoaderQuery` saw the hook's result, while the loader context (`ctx.headers`), the SSR request snapshot (`useServerRequest()`) and the locale resolver kept reading the raw request — four readers, two answers, within eighty lines of one function.
201
+
202
+ The consequence was worse than an inconsistency: a hook that renews purely via `setCookies` — no `headers` at all, which is the normal shape for a cookie-session IdP and the reason the response half exists — moved nothing for the render that ran it. The rpc call still sent the old `Cookie` header, because a renewed cookie only reached the browser.
203
+
204
+ `setCookies` is applied to the cookie jar before the render, the `Cookie` header is rebuilt from that jar (an explicit `cookie` in the hook's own `headers` still wins), and `maxAge <= 0` deletes, so a hook that signs someone out renders them signed out. Both SSR boot paths shadow the raw headers out of scope after the hook runs, so a new reader added below is correct without knowing any of this.
205
+ - **@voltro/cli** — `voltro start` dropped `middleware.ts`'s `Set-Cookie` on **streamed** responses — which is the arm a plain `renderMode: 'ssr'` page takes, so it was the common case. The hook renewed the session server-side, the render used the fresh value, and the browser kept the consumed one. Against an IdP that rotates refresh tokens and detects reuse, that is worse than not renewing at all.
206
+
207
+ The cause is worth stating because it read as handled: a streamed response hands the socket to `stream(res)` and the caller never looks at the returned `headers`, so the `withCookies(...)` wrapper on that arm was dead code — sitting under a comment promising the cookies were written on every arm. The cookies now travel with the headers `streamSsrResponse` itself writes, and the dead wrapper is gone.
208
+
209
+ Found by booting real `voltro dev` and `voltro start` servers against a fixture and reading the response. Every unit test was green throughout, and the render's own HTML was correct — only the wire was wrong.
210
+
211
+ ---
212
+
42
213
  ## [0.40.0] — 2026-08-16
43
214
 
44
215
  ### ⚠ BREAKING
package/dist/index.d.ts CHANGED
@@ -376,7 +376,19 @@ export declare class MysqlStore implements DataStore {
376
376
  private executeMariadbUpsert;
377
377
  private executeInsertIgnore;
378
378
  /**
379
- * The warnings MariaDB raised for the statement that just ran on `txn`.
379
+ * What a SKIPPED `INSERT IGNORE` means one decision, both engines.
380
+ *
381
+ * It is a separate method because the two engines reach it by different
382
+ * probes (RETURNING on MariaDB, a keyed re-read on MySQL) and a per-engine
383
+ * copy of THIS is what would drift: the codes, the wording, and the refusal
384
+ * to call a rejection a conflict are the same statement about the same
385
+ * feature. The warnings are passed IN rather than read here, because they
386
+ * have to be read before any other statement touches the connection and the
387
+ * caller is the only place that ordering is visible.
388
+ */
389
+ private resolveSkippedInsertIgnore;
390
+ /**
391
+ * The warnings the server raised for the statement that just ran on `txn`.
380
392
  *
381
393
  * Only meaningful inside a transaction, and that is why the parameter is not
382
394
  * optional. `SHOW WARNINGS` reports the last statement on the CONNECTION, and
package/dist/index.js CHANGED
@@ -1,18 +1,18 @@
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, hasEagerLoads as E, isTableReactive as D, makeEagerFallbackReporter as ee, observeDbOp as O, qualifyTable as te, raiseChangeListenerCeiling as ne, recordsTable as re, registerPendingAttribution as ie, requireTable as k, resolveEchoAttribution as A, runStoreTransaction as j, runWriteRecorders as ae, stampGeneratedId as M, stampGeneratedIds as oe, withCapturedAttribution as N } from "@voltro/database";
4
- import { EventEmitter as se } from "node:events";
5
- import { createLogger as P } from "@voltro/logger";
6
- import { SqlClient as F, TransactionConnection as I } from "@effect/sql/SqlClient";
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, hasEagerLoads as E, isTableReactive as D, makeEagerFallbackReporter as O, observeDbOp as k, qualifyTable as ee, raiseChangeListenerCeiling as A, recordsTable as te, registerPendingAttribution as j, requireTable as ne, resolveEchoAttribution as re, runStoreTransaction as ie, runWriteRecorders as ae, stampGeneratedId as M, stampGeneratedIds as oe, withCapturedAttribution as N } from "@voltro/database";
4
+ import { EventEmitter as P } from "node:events";
5
+ import { createLogger as F } from "@voltro/logger";
6
+ import { SqlClient as I, TransactionConnection as L } from "@effect/sql/SqlClient";
7
7
  //#region src/sqlLayer.ts
8
- var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
8
+ var se = (e) => e ? { rejectUnauthorized: !1 } : void 0, ce = (e) => {
9
9
  let t = e.acquireTimeoutMs ?? l;
10
10
  return t > 0 ? t : void 0;
11
- }, L = (e) => {
11
+ }, le = (e) => {
12
12
  let t = e.acquireQueueLimit;
13
13
  return t !== void 0 && t > 0 ? t : void 0;
14
14
  }, R = (e) => {
15
- let t = e.ssl === void 0 ? void 0 : ce(e.ssl), n = le(e), r = L(e);
15
+ let t = e.ssl === void 0 ? void 0 : se(e.ssl), n = ce(e), r = le(e);
16
16
  return {
17
17
  ...t === void 0 ? {} : { ssl: t },
18
18
  ...n === void 0 ? {} : { connectTimeout: n },
@@ -81,7 +81,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
81
81
  "updaterows",
82
82
  "deleterows"
83
83
  ]), _e = /\b(alter|rename|drop|create)\s+(table|column)?/i, K = (e) => new Promise((t) => setTimeout(t, e)), q = async (e) => {
84
- let t = P({ scope: `voltro:${e.variant}:cdc` }), n;
84
+ let t = F({ scope: `voltro:${e.variant}:cdc` }), n;
85
85
  try {
86
86
  n = (await import("@vlasky/zongji")).default;
87
87
  } catch (t) {
@@ -312,9 +312,9 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
312
312
  1062,
313
313
  1586
314
314
  ]), Q = async (e) => {
315
- let t = e.variant ?? "mysql", n = P({ scope: `voltro:${t}` }), a = e.changeStrategy ?? "inline", o = a;
315
+ let t = e.variant ?? "mysql", n = F({ scope: `voltro:${t}` }), a = e.changeStrategy ?? "inline", o = a;
316
316
  a === "cdc" && !e.cdcConfig && (n.warn("changeStrategy='cdc' requires cdcConfig (serverId + connection); falling back to 'inline'."), o = "inline");
317
- let s = e.tracerLayer ? r.mergeAll(e.sqlLayer, e.tracerLayer) : e.sqlLayer, c = i.make(s), l = new Ce(await c.runPromise(F), c, t, o);
317
+ let s = e.tracerLayer ? r.mergeAll(e.sqlLayer, e.tracerLayer) : e.sqlLayer, c = i.make(s), l = new Ce(await c.runPromise(I), c, t, o);
318
318
  return o === "cdc" && e.cdcConfig && await l.startCdcConsumer(e.cdcConfig), l;
319
319
  }, Ce = class e {
320
320
  sql;
@@ -333,13 +333,13 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
333
333
  cdcGate;
334
334
  reportEagerFallback;
335
335
  constructor(e, t, n, r = "inline", i = null, a, o) {
336
- this.sql = e, this.runtime = t, this.variant = n, this.changeStrategy = r, this.namespace = i, this.log = P({ scope: `voltro:${n}` }), this.reportEagerFallback = ee(this.log), this.emitter = a ?? new se(), ne(this.emitter), this.cdcGate = o ?? new Se(n);
336
+ this.sql = e, this.runtime = t, this.variant = n, this.changeStrategy = r, this.namespace = i, this.log = F({ scope: `voltro:${n}` }), this.reportEagerFallback = O(this.log), this.emitter = a ?? new P(), A(this.emitter), this.cdcGate = o ?? new Se(n);
337
337
  }
338
338
  withNamespace(t) {
339
339
  return t === this.namespace ? this : new e(this.sql, this.runtime, this.variant, this.changeStrategy, t, this.emitter, this.cdcGate);
340
340
  }
341
341
  nsT(e) {
342
- return te(this.namespace, e);
342
+ return ee(this.namespace, e);
343
343
  }
344
344
  get dialectId() {
345
345
  return this.variant;
@@ -351,7 +351,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
351
351
  };
352
352
  }
353
353
  async executeQuery(e, t, r) {
354
- let i = x(e, this.sql, this.namespace), a = t ? n.provideService(i, I, t) : i, o = await O(this.variant, "select", () => this.runtime.runPromise(a));
354
+ let i = x(e, this.sql, this.namespace), a = t ? n.provideService(i, L, t) : i, o = await k(this.variant, "select", () => this.runtime.runPromise(a));
355
355
  return S(o, e.table, this.variant);
356
356
  }
357
357
  get supportsInsertReturning() {
@@ -367,7 +367,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
367
367
  t = M(e, t);
368
368
  let o = this.sql;
369
369
  if (this.supportsInsertReturning) {
370
- let s = o`INSERT INTO ${o(this.nsT(e))} ${o.insert(C(t, e))} RETURNING *`, c = r ? n.provideService(s, I, r) : s, l = (await this.runtime.runPromise(c))[0];
370
+ let s = o`INSERT INTO ${o(this.nsT(e))} ${o.insert(C(t, e))} RETURNING *`, c = r ? n.provideService(s, L, r) : s, l = (await this.runtime.runPromise(c))[0];
371
371
  if (!l) throw Error(`MysqlStore.insert: no row returned for table '${e}'`);
372
372
  return await this.routeEvent({
373
373
  table: e,
@@ -386,9 +386,9 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
386
386
  new: t
387
387
  }, i, r, a), t;
388
388
  }
389
- let l = o`INSERT INTO ${o(this.nsT(e))} ${o.insert(s)}`, u = r ? n.provideService(l, I, r) : l;
389
+ let l = o`INSERT INTO ${o(this.nsT(e))} ${o.insert(s)}`, u = r ? n.provideService(l, L, r) : l;
390
390
  await this.runtime.runPromise(u);
391
- let d = o`SELECT * FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${c}`, f = r ? n.provideService(d, I, r) : d, p = (await this.runtime.runPromise(f))[0];
391
+ let d = o`SELECT * FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${c}`, f = r ? n.provideService(d, L, r) : d, p = (await this.runtime.runPromise(f))[0];
392
392
  if (!p) throw Error(`MysqlStore.insert: row not found post-insert in '${e}'`);
393
393
  return await this.routeEvent({
394
394
  table: e,
@@ -401,16 +401,16 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
401
401
  let i = this.sql;
402
402
  return this.runPinned(r, (r) => n.gen(this, function* () {
403
403
  let a = i`INSERT INTO ${i(this.nsT(e))} ${i.insert(t)}`;
404
- yield* n.provideService(a, I, r);
405
- let o = (yield* n.provideService(i`SELECT LAST_INSERT_ID() AS ${i("lastId")}`, I, r))[0]?.lastId;
406
- 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}`, I, r))[0] || (yield* n.fail(/* @__PURE__ */ Error(`MysqlStore.insert: row not found post-insert in '${e}'`)));
404
+ yield* n.provideService(a, L, r);
405
+ let o = (yield* n.provideService(i`SELECT LAST_INSERT_ID() AS ${i("lastId")}`, L, r))[0]?.lastId;
406
+ 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}`, L, r))[0] || (yield* n.fail(/* @__PURE__ */ Error(`MysqlStore.insert: row not found post-insert in '${e}'`)));
407
407
  }), "insert");
408
408
  }
409
409
  async runPinned(e, t, r) {
410
410
  if (e) return this.runtime.runPromise(t(e));
411
411
  this.inflightTxns++;
412
412
  try {
413
- let e = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(I), (e) => a.isNone(e) ? n.fail(/* @__PURE__ */ Error("MysqlStore.insert: 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.insert", { attributes: {
413
+ let e = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(L), (e) => a.isNone(e) ? n.fail(/* @__PURE__ */ Error("MysqlStore.insert: 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.insert", { attributes: {
414
414
  "db.system": this.variant,
415
415
  "db.operation": r
416
416
  } }));
@@ -425,11 +425,11 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
425
425
  if (this.supportsInsertReturning) {
426
426
  let t = (t) => o`INSERT INTO ${o(this.nsT(e))} ${o.insert(t)} RETURNING *`, s;
427
427
  if (c.length === 1) {
428
- let e = t(c[0]), i = r ? n.provideService(e, I, r) : e;
428
+ let e = t(c[0]), i = r ? n.provideService(e, L, r) : e;
429
429
  s = await this.runtime.runPromise(i);
430
430
  } else if (r) {
431
431
  let e = [];
432
- for (let i of c) e.push(...await this.runtime.runPromise(n.provideService(t(i), I, r)));
432
+ for (let i of c) e.push(...await this.runtime.runPromise(n.provideService(t(i), L, r)));
433
433
  s = e;
434
434
  } else s = await this.runtime.runPromise(o.withTransaction(n.map(n.forEach(c, t, { concurrency: 1 }), (e) => e.flat())));
435
435
  for (let t of s) await this.routeEvent({
@@ -454,16 +454,16 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
454
454
  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).");
455
455
  let u = (t) => o`INSERT INTO ${o(this.nsT(e))} ${o.insert(t)}`;
456
456
  if (c.length === 1) {
457
- let e = r ? n.provideService(u(c[0]), I, r) : u(c[0]);
457
+ let e = r ? n.provideService(u(c[0]), L, r) : u(c[0]);
458
458
  await this.runtime.runPromise(e);
459
- } else if (r) for (let e of c) await this.runtime.runPromise(n.provideService(u(e), I, r));
459
+ } else if (r) for (let e of c) await this.runtime.runPromise(n.provideService(u(e), L, r));
460
460
  else await this.runtime.runPromise(o.withTransaction(n.forEach(c, u, {
461
461
  concurrency: 1,
462
462
  discard: !0
463
463
  })));
464
464
  let d = _(l.map((e) => ({ id: e })), g(this.variant)), f = [];
465
465
  for (let t of d) {
466
- 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, I, r) : i;
466
+ 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, L, r) : i;
467
467
  f.push(...await this.runtime.runPromise(a));
468
468
  }
469
469
  let p = new Map(f.map((e) => [e.id, e])), m = l.map((e) => p.get(e)).filter((e) => e !== void 0);
@@ -481,19 +481,19 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
481
481
  let a = [];
482
482
  for (let o of t) {
483
483
  let t = i`INSERT INTO ${i(this.nsT(e))} ${i.insert(o)}`;
484
- yield* n.provideService(t, I, r);
485
- let s = (yield* n.provideService(i`SELECT LAST_INSERT_ID() AS ${i("firstId")}`, I, r))[0]?.firstId;
484
+ yield* n.provideService(t, L, r);
485
+ let s = (yield* n.provideService(i`SELECT LAST_INSERT_ID() AS ${i("firstId")}`, L, r))[0]?.firstId;
486
486
  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?`));
487
- 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`, I, r);
487
+ 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`, L, r);
488
488
  a.push(...l);
489
489
  }
490
490
  return a;
491
491
  }), "insert");
492
492
  }
493
493
  async executePatchJson(e, t, r, i, a, o, s) {
494
- 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, I, a) : m, g = await this.runtime.runPromise(h);
494
+ 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, L, a) : m, g = await this.runtime.runPromise(h);
495
495
  if (g && typeof g.affectedRows == "number" && g.affectedRows === 0) return null;
496
- let _ = c`SELECT * FROM ${c(this.nsT(e))} WHERE ${c("id")} = ${t}`, v = a ? n.provideService(_, I, a) : _, y = (await this.runtime.runPromise(v))[0];
496
+ let _ = c`SELECT * FROM ${c(this.nsT(e))} WHERE ${c("id")} = ${t}`, v = a ? n.provideService(_, L, a) : _, y = (await this.runtime.runPromise(v))[0];
497
497
  return y ? (await this.routeEvent({
498
498
  table: e,
499
499
  op: "update",
@@ -504,7 +504,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
504
504
  async executeUpdate(e, t, r, i, a, o) {
505
505
  let s = this.sql;
506
506
  if (this.supportsUpdateReturning) {
507
- let c = s`UPDATE ${s(this.nsT(e))} SET ${s.update(C(r, e))} WHERE ${s("id")} = ${t} RETURNING *`, l = i ? n.provideService(c, I, i) : c, u = (await this.runtime.runPromise(l))[0];
507
+ let c = s`UPDATE ${s(this.nsT(e))} SET ${s.update(C(r, e))} WHERE ${s("id")} = ${t} RETURNING *`, l = i ? n.provideService(c, L, i) : c, u = (await this.runtime.runPromise(l))[0];
508
508
  return u ? (await this.routeEvent({
509
509
  table: e,
510
510
  op: "update",
@@ -512,9 +512,9 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
512
512
  new: u
513
513
  }, a, i, o), u) : null;
514
514
  }
515
- let c = s`UPDATE ${s(this.nsT(e))} SET ${s.update(C(r, e))} WHERE ${s("id")} = ${t}`, l = i ? n.provideService(c, I, i) : c, u = await this.runtime.runPromise(l);
515
+ let c = s`UPDATE ${s(this.nsT(e))} SET ${s.update(C(r, e))} WHERE ${s("id")} = ${t}`, l = i ? n.provideService(c, L, i) : c, u = await this.runtime.runPromise(l);
516
516
  if (u && typeof u.affectedRows == "number" && u.affectedRows === 0) return null;
517
- let d = s`SELECT * FROM ${s(this.nsT(e))} WHERE ${s("id")} = ${t}`, f = i ? n.provideService(d, I, i) : d, p = (await this.runtime.runPromise(f))[0];
517
+ let d = s`SELECT * FROM ${s(this.nsT(e))} WHERE ${s("id")} = ${t}`, f = i ? n.provideService(d, L, i) : d, p = (await this.runtime.runPromise(f))[0];
518
518
  return p ? (await this.routeEvent({
519
519
  table: e,
520
520
  op: "update",
@@ -525,7 +525,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
525
525
  async executeDelete(e, t, r, i, a) {
526
526
  let o = this.sql;
527
527
  if (this.supportsDeleteReturning) {
528
- let s = o`DELETE FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t} RETURNING *`, c = r ? n.provideService(s, I, r) : s, l = (await this.runtime.runPromise(c))[0];
528
+ let s = o`DELETE FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t} RETURNING *`, c = r ? n.provideService(s, L, r) : s, l = (await this.runtime.runPromise(c))[0];
529
529
  return l ? (await this.routeEvent({
530
530
  table: e,
531
531
  op: "delete",
@@ -533,9 +533,9 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
533
533
  new: null
534
534
  }, i, r, a), !0) : !1;
535
535
  }
536
- let s = o`SELECT * FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t}`, c = r ? n.provideService(s, I, r) : s, l = (await this.runtime.runPromise(c))[0];
536
+ let s = o`SELECT * FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t}`, c = r ? n.provideService(s, L, r) : s, l = (await this.runtime.runPromise(c))[0];
537
537
  if (!l) return !1;
538
- let u = o`DELETE FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t}`, d = r ? n.provideService(u, I, r) : u;
538
+ let u = o`DELETE FROM ${o(this.nsT(e))} WHERE ${o("id")} = ${t}`, d = r ? n.provideService(u, L, r) : u;
539
539
  return await this.runtime.runPromise(d), await this.routeEvent({
540
540
  table: e,
541
541
  op: "delete",
@@ -545,17 +545,17 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
545
545
  }
546
546
  async appendInTxn(e, t, r) {
547
547
  let i = this.sql, a = i`INSERT INTO ${i(this.nsT(e))} ${i.insert(C(t, e))}`;
548
- await this.runtime.runPromise(r ? n.provideService(a, I, r) : a);
548
+ await this.runtime.runPromise(r ? n.provideService(a, L, r) : a);
549
549
  }
550
550
  async maxInTxn(e, t, r, i) {
551
- 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, I, i) : s))[0]?.m;
551
+ 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, L, i) : s))[0]?.m;
552
552
  return c == null ? null : Number(c);
553
553
  }
554
554
  async routeEvent(e, t, n = null, r) {
555
555
  if (e = {
556
556
  ...p(r),
557
557
  ...e
558
- }, re(e.table) && await ae({
558
+ }, te(e.table) && await ae({
559
559
  append: (e, t) => this.appendInTxn(e, t, n),
560
560
  maxOf: (e, t, r) => this.maxInTxn(e, t, r, n)
561
561
  }, {
@@ -567,7 +567,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
567
567
  subjectId: e.subjectId
568
568
  }), this.changeStrategy === "cdc") {
569
569
  let t = (e.op === "delete" ? e.old : e.new)?.id;
570
- t != null && ie(m(e.table, e.op, t), {
570
+ t != null && j(m(e.table, e.op, t), {
571
571
  ...e.traceId === void 0 ? {} : { traceId: e.traceId },
572
572
  ...e.subjectId === void 0 ? {} : { subjectId: e.subjectId }
573
573
  });
@@ -601,7 +601,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
601
601
  return N((n) => this.executeInsert(e, t, r, i, n));
602
602
  }
603
603
  async executeMariadbUpsert(e, t, r, i, a, o) {
604
- 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 = s`INSERT INTO ${s(this.nsT(e))} ${s.insert(c)} ON DUPLICATE KEY UPDATE ${d} RETURNING *`, p = i ? n.provideService(f, I, i) : f, m = (await this.runtime.runPromise(p))[0];
604
+ 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 = s`INSERT INTO ${s(this.nsT(e))} ${s.insert(c)} ON DUPLICATE KEY UPDATE ${d} RETURNING *`, p = i ? n.provideService(f, L, i) : f, m = (await this.runtime.runPromise(p))[0];
605
605
  if (!m) throw Error(`MysqlStore.upsert: no row returned for table '${e}'`);
606
606
  let h = t.id !== void 0 && t.id === m.id ? "insert" : "update";
607
607
  return await this.routeEvent({
@@ -612,22 +612,32 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
612
612
  }, a, i, o), m;
613
613
  }
614
614
  async executeInsertIgnore(e, t, r, i, a, o) {
615
- if (t = M(e, t), this.variant === "mariadb") {
616
- let s = this.sql, c = s`INSERT IGNORE INTO ${s(this.nsT(e))} ${s.insert(C(t, e))} RETURNING *`, l = i ? n.provideService(c, I, i) : c, u = (await this.runtime.runPromise(l))[0];
617
- if (u) return await this.routeEvent({
618
- table: e,
619
- op: "insert",
620
- old: null,
621
- new: u
622
- }, a, i, o), u;
623
- let d = await this.readWarnings(i), f = d.find((e) => !Z.has(e.code));
624
- if (f !== 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: [${f.code}] ${f.message}. Nothing was written and nothing conflicted — fix the cause above.`);
625
- let p = await this.findByConflict(e, t, r.conflictColumns, i);
626
- if (p) return p;
627
- let m = d[0];
628
- throw Error(`MysqlStore.insertIgnore: the insert was skipped as a conflict, but no existing row matches conflictColumns [${r.conflictColumns.join(", ")}] on '${e}'. ` + (m === void 0 ? "The warning could not be read on this connection, so the constraint that fired is unknown — it may be a second unique index, or the primary key under another name. " : `The constraint that actually fired: [${m.code}] ${m.message}. `) + "insertIgnore models ONE conflict target: name the columns of the constraint that actually collides, or handle the violation yourself.");
629
- }
630
- return await this.findByConflict(e, t, r.conflictColumns, i) || N((n) => this.executeInsert(e, t, i, a, n));
615
+ t = M(e, t);
616
+ let s = t.id;
617
+ if (s === void 0) return await this.findByConflict(e, t, r.conflictColumns, i) || N((n) => this.executeInsert(e, t, i, a, n));
618
+ let c = this.sql, l = C(t, e), u = (e) => this.runtime.runPromise(i ? n.provideService(e, L, i) : e), d;
619
+ if (this.supportsInsertReturning) return d = (await u(c`INSERT IGNORE INTO ${c(this.nsT(e))} ${c.insert(l)} RETURNING *`))[0], d ? (await this.routeEvent({
620
+ table: e,
621
+ op: "insert",
622
+ old: null,
623
+ new: d
624
+ }, a, i, o), d) : this.resolveSkippedInsertIgnore(e, t, r, await this.readWarnings(i), i);
625
+ await u(c`INSERT IGNORE INTO ${c(this.nsT(e))} ${c.insert(l)}`);
626
+ let f = await this.readWarnings(i);
627
+ return !f.some((e) => Z.has(e.code)) && (d = (await u(c`SELECT * FROM ${c(this.nsT(e))} WHERE ${c("id")} = ${s}`))[0], d) ? (await this.routeEvent({
628
+ table: e,
629
+ op: "insert",
630
+ old: null,
631
+ new: d
632
+ }, a, i, o), d) : this.resolveSkippedInsertIgnore(e, t, r, f, i);
633
+ }
634
+ async resolveSkippedInsertIgnore(e, t, n, r, i) {
635
+ let a = r.find((e) => !Z.has(e.code));
636
+ 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.`);
637
+ let o = await this.findByConflict(e, t, n.conflictColumns, i);
638
+ if (o) return o;
639
+ let s = r[0];
640
+ throw Error(`MysqlStore.insertIgnore: the insert was skipped as a conflict, but no existing row matches conflictColumns [${n.conflictColumns.join(", ")}] on '${e}'. ` + (s === void 0 ? "The warning could not be read on this connection, so the constraint that fired is unknown — it may be a second unique index, or the primary key under another name. " : `The constraint that actually fired: [${s.code}] ${s.message}. `) + "insertIgnore models ONE conflict target: name the columns of the constraint that actually collides, or handle the violation yourself.");
631
641
  }
632
642
  async findUndecodableCdcTables(e) {
633
643
  if (this.variant !== "mariadb") return [];
@@ -641,8 +651,8 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
641
651
  async readWarnings(e) {
642
652
  if (e === null) return [];
643
653
  try {
644
- let t = this.sql`SHOW WARNINGS`;
645
- return (await this.runtime.runPromise(n.provideService(t, I, e))).map((e) => ({
654
+ let t = this.sql`SHOW WARNINGS`.unprepared;
655
+ return (await this.runtime.runPromise(n.provideService(t, L, e))).map((e) => ({
646
656
  code: Number(e.Code ?? e.code ?? 0),
647
657
  message: String(e.Message ?? e.message ?? "")
648
658
  }));
@@ -652,7 +662,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
652
662
  }
653
663
  async findByConflict(e, t, r, i) {
654
664
  if (r.length === 0) return;
655
- 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, I, i) : s;
665
+ 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, L, i) : s;
656
666
  return (await this.runtime.runPromise(c))[0];
657
667
  }
658
668
  query(e) {
@@ -660,13 +670,13 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
660
670
  }
661
671
  raw(e, t) {
662
672
  let n = b(e, this.sql);
663
- return O(this.variant, "raw", () => this.runtime.runPromise(n));
673
+ return k(this.variant, "raw", () => this.runtime.runPromise(n));
664
674
  }
665
675
  async runWithEager(e, t) {
666
676
  if (!E(e)) return this.executeQuery(e, t);
667
677
  let r = this.variant === "mariadb" ? "mariadb" : "mysql", i = this.namespace === null ? v(e, this.sql, r) : null;
668
678
  if (i !== null) try {
669
- let e = t ? n.provideService(i.fragment, I, t) : i.fragment, r = await O(this.variant, "select", () => this.runtime.runPromise(e));
679
+ let e = t ? n.provideService(i.fragment, L, t) : i.fragment, r = await k(this.variant, "select", () => this.runtime.runPromise(e));
670
680
  return i.decode(r);
671
681
  } catch (t) {
672
682
  if (t instanceof u) throw t;
@@ -683,13 +693,13 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
683
693
  reason: "not-compilable"
684
694
  });
685
695
  let a = await this.executeQuery(e, t);
686
- return f(a, e.eager, e.sourceTable ?? k(e.table), (e) => this.executeQuery(e, t));
696
+ return f(a, e.eager, e.sourceTable ?? ne(e.table), (e) => this.executeQuery(e, t));
687
697
  }
688
698
  getInternalRunWithEager() {
689
699
  return this.runWithEager.bind(this);
690
700
  }
691
701
  async localWrite(e, t, n) {
692
- return O(this.variant, e, async () => {
702
+ return k(this.variant, e, async () => {
693
703
  if (this.changeStrategy !== "cdc") return N(n);
694
704
  h(t);
695
705
  try {
@@ -734,13 +744,13 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
734
744
  let i = this.sql, o = y(r.where, i, this.namespace);
735
745
  this.changeStrategy === "cdc" && h(e), this.inflightTxns++;
736
746
  try {
737
- let r = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(I), (r) => {
747
+ let r = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(L), (r) => {
738
748
  if (a.isNone(r)) return n.fail(/* @__PURE__ */ Error("MysqlStore.updateMany: TransactionConnection missing."));
739
749
  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}`;
740
- return n.flatMap(n.provideService(c, I, s), (t) => {
750
+ return n.flatMap(n.provideService(c, L, s), (t) => {
741
751
  if (t.length === 0) return n.succeed([]);
742
752
  let r = t.map((e) => e.id), a = i`SELECT * FROM ${i(this.nsT(e))} WHERE ${i("id")} IN ${i.in(r)}`;
743
- return n.flatMap(n.provideService(l, I, s), () => n.provideService(a, I, s));
753
+ return n.flatMap(n.provideService(l, L, s), () => n.provideService(a, L, s));
744
754
  });
745
755
  }))), 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: {
746
756
  "db.system": this.variant,
@@ -773,10 +783,10 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
773
783
  }
774
784
  this.changeStrategy === "cdc" && h(e), this.inflightTxns++;
775
785
  try {
776
- let t = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(I), (t) => {
786
+ let t = n.suspend(() => this.sql.withTransaction(n.flatMap(n.serviceOption(L), (t) => {
777
787
  if (a.isNone(t)) return n.fail(/* @__PURE__ */ Error("MysqlStore.deleteMany: TransactionConnection missing."));
778
788
  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}`;
779
- return n.flatMap(n.provideService(s, I, o), (e) => e.length === 0 ? n.succeed(e) : n.as(n.provideService(c, I, o), e));
789
+ return n.flatMap(n.provideService(s, L, o), (e) => e.length === 0 ? n.succeed(e) : n.as(n.provideService(c, L, o), e));
780
790
  }))), 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: {
781
791
  "db.system": this.variant,
782
792
  "db.operation": "delete"
@@ -920,7 +930,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
920
930
  async transactional(e) {
921
931
  this.inflightTxns++;
922
932
  try {
923
- return await j({
933
+ return await ie({
924
934
  ...this.txnSpec("MysqlStore.transactional"),
925
935
  work: e,
926
936
  makeView: (e, t) => new we(this, e, t)
@@ -956,7 +966,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
956
966
  injectExternalChange(e) {
957
967
  if (this.changeStrategy === "cdc" && !this.cdcGate.admit(e) || !D(e.table)) return;
958
968
  let t = (e.op === "delete" ? e.old : e.new)?.id;
959
- A(e.table, e.op, t, (t) => {
969
+ re(e.table, e.op, t, (t) => {
960
970
  this.emitter.emit("change", T(e, t));
961
971
  });
962
972
  }
@@ -1059,7 +1069,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
1059
1069
  let t = $(e);
1060
1070
  if (t === null) throw Error("mysqlReplicationAdapter: primary is not a MysqlStore (missing __mysqlReplicationFriend).");
1061
1071
  return t.runEffect(n.gen(function* () {
1062
- let e = yield* F, r = (t.variant === "mariadb" ? yield* e`SELECT @@global.gtid_current_pos AS gtid` : yield* e`SELECT @@global.gtid_executed AS gtid`)[0]?.gtid;
1072
+ let e = yield* I, r = (t.variant === "mariadb" ? yield* e`SELECT @@global.gtid_current_pos AS gtid` : yield* e`SELECT @@global.gtid_executed AS gtid`)[0]?.gtid;
1063
1073
  return typeof r == "string" ? r : yield* n.die("mysql/mariadb did not return a GTID set");
1064
1074
  }));
1065
1075
  },
@@ -1067,7 +1077,7 @@ var ce = (e) => e ? { rejectUnauthorized: !1 } : void 0, le = (e) => {
1067
1077
  let t = $(e);
1068
1078
  if (t === null) throw Error("mysqlReplicationAdapter: replica is not a MysqlStore.");
1069
1079
  return t.runEffect(n.gen(function* () {
1070
- let e = yield* F, r = (t.variant === "mariadb" ? yield* e`SELECT @@global.gtid_current_pos AS gtid` : yield* e`SELECT @@global.gtid_executed AS gtid`)[0]?.gtid;
1080
+ let e = yield* I, r = (t.variant === "mariadb" ? yield* e`SELECT @@global.gtid_current_pos AS gtid` : yield* e`SELECT @@global.gtid_executed AS gtid`)[0]?.gtid;
1071
1081
  return typeof r == "string" ? r : yield* n.die("mysql/mariadb replica did not return a GTID set");
1072
1082
  }));
1073
1083
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/sql-mysql",
3
- "version": "0.40.0",
3
+ "version": "0.42.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.40.0",
39
- "@voltro/logger": "0.40.0"
38
+ "@voltro/database": "0.42.0",
39
+ "@voltro/logger": "0.42.0"
40
40
  },
41
41
  "optionalDependencies": {
42
42
  "@vlasky/zongji": "^0.9.0"