@voltro/sql-postgres 0.20.0 → 0.20.2

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.
Files changed (3) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/dist/index.js +114 -115
  3. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -39,6 +39,165 @@ _Changes staged for the next release accumulate here (rolled up from
39
39
 
40
40
  ---
41
41
 
42
+ ## [0.20.2] — 2026-07-30
43
+
44
+ ### Fixed
45
+
46
+ - **@voltro/database, @voltro/cli, @voltro/voltro** — `voltro db drift` could never report clean. It compared the LIVE schema's fingerprint against `_voltro_migration_plans.fingerprint` — which is the **declared** snapshot's hash. The two are not comparable: introspection cannot recover everything a declaration carries (generated expressions, `maxLength`, sensitivity markers), so hashing a live snapshot never equals hashing the declaration it came from. The command was therefore RED on a provably clean database, permanently.
47
+
48
+ Fixing the postgres-only cast in the previous release is what made this visible — before that, `db drift` crashed before it could compute a wrong answer.
49
+
50
+ A consumer measured it precisely: three different fingerprints for one database (`apply` recorded `b1078b73…`, `drift` computed `8dcc9c5e…`, `plan` computed `0c376108…`), stable across runs, with `db plan` reporting 0 operations in between.
51
+
52
+ **The fix is a second, comparable baseline.** `_voltro_migration_plans` gains `liveFingerprint` — the post-apply LIVE fingerprint, taken from the convergence re-plan's `fromFingerprint` (that re-plan runs AFTER the apply, so its "pre-state" is our post-state; it is already computed, so this costs nothing). `db drift` compares against that, and hashes the live snapshot WHOLE, exactly as the applier did.
53
+
54
+ It used to strip `_voltro_*` tables before hashing, which sounds reasonable and was half the incomparability. A framework upgrade that adds a `_voltro_*` column will now show as drift until the next `db apply` records a new baseline — honest, since the live schema did change, and it self-heals on the apply an upgrade needs anyway.
55
+
56
+ Rows written before the column exists have no baseline. `db drift` says so and exits 0, instead of comparing a live hash against a declared one and calling the difference drift. `_voltro_*` table changes ride the declarative differ, so no codemod.
57
+
58
+ **The "Probable causes" list is gone.** It named out-of-band DDL and a missing ledger row, and the consumer hit it with neither being true — the row was right there in `db plans`. A diagnosis that asserts a cause it cannot know is the same defect as the `ALTER TABLE FORCE` repair line retracted in the same release, and it costs more here because it is confident: it sends the reader hunting through somebody's shell history. The command now says what it can actually see — that the schema changed, not what or who — and points at `db plan` for the real difference.
59
+
60
+ Worth recording what the pair of defects cost together, in the consumer's framing: `db drift` exists to catch a divergence between declared and live, and the one real divergence they have (`sessions.tokenHash` declared `varchar(64)`, live `longtext`) is invisible to it — while it loudly reported a divergence that did not exist. False negative on the real thing, false positive on nothing. The false negative is the still-open `maxLength`-in-the-snapshot item.
61
+
62
+ ---
63
+
64
+ ## [0.20.1] — 2026-07-30
65
+
66
+ ### Changed
67
+
68
+ - **@voltro/database, @voltro/runtime, @voltro/plugin-versioning, @voltro/plugin-presence, @voltro/voltro** — Five framework-table indexes were holding GENERIC names in a namespace that is shared with your tables. Index names are unique per SCHEMA on every supported dialect, so `_voltro_row_history.index('byTrace')` reserved `byTrace` for the whole database — and `byTrace` is the first thing anyone reaches for when indexing a `traceId`. A consumer added `traceId` to their own audit table, indexed it the obvious way, and collided with ours; the framework's own error message even suggested renaming the framework's index as the fix.
69
+
70
+ Renamed: `_voltro_row_history` `byTrace` → `byRowHistoryTrace`, `bySubject` → `byRowHistorySubject`; `_voltro_api_keys` `byTenant` → `byApiKeyTenant`; `_voltro_presence` `byChannel` → `byPresenceChannel`; `_voltro_connections` `bySubject` → `byConnectionSubject`. These are `_voltro_*` tables, so the rename rides the declarative differ on `voltro db apply` / boot — no codemod. Adopters see a one-time index rebuild.
71
+
72
+ A test now enforces the rule that most framework tables already followed: a framework index name must MENTION its own table. Mechanical, so it cannot rot the way a curated list of "generic" names would, and it does not demand the full `_voltro_<table>_<name>` form — which would force renaming ~20 already-safe indexes for no benefit. It also asserts no two framework tables claim the same index name, since installing two such plugins together would fail at migrate time for a reason neither plugin's author could see.
73
+
74
+ ### Fixed
75
+
76
+ - **@voltro/sql-mysql, @voltro/voltro** — A MariaDB table with a UNIQUE constraint on an UNBOUNDED text column can never be decoded from the binlog. The reader now says so ONCE — with the real cause and a remedy that works — and excludes the table, instead of looping on it forever.
77
+
78
+ **The mechanism.** MariaDB backs an unbounded UNIQUE with a **HASH long-unique index**, which adds a hidden `DB_ROW_HASH_n` column to the InnoDB row. That column IS in the binlog row image and is NOT in `information_schema.COLUMNS`, so the reader compares N+1 against N and throws on every write to that table:
79
+
80
+ ```text
81
+ Table app.sessions schema changed between binlog event and metadata fetch:
82
+ the event has 9 columns, fetched metadata has 8
83
+ ```
84
+
85
+ Nothing is broken; the table is shaped that way, permanently. The previous recovery (skip to the current binlog end) recovered nothing, because the end is exactly where the next failing write appears — a loop a consumer measured at roughly every 9 seconds, re-signalling resync to the whole fleet each pass.
86
+
87
+ **The cause we shipped in the previous entry was WRONG, and this retracts it.** It blamed a `DROP COLUMN` that ran as `ALGORITHM=INSTANT` leaving a phantom column, and told people to run `ALTER TABLE … FORCE`. The same consumer measured that: 9 InnoDB columns before the rebuild, 9 after, hidden column still present — the rebuild recreates the index and therefore recreates the hidden column. The repair line sent readers in a circle. They also disproved the version theory, being on the same MariaDB 11.8 we had tested on and failed to reproduce a phantom column with.
88
+
89
+ **Now:** affected tables are found at CDC start by a privilege-free probe — the direct evidence in `INNODB_SYS_COLUMNS` needs `PROCESS`, which an app DB user does not have, so the constraint SHAPE is inferred from `information_schema.STATISTICS` + `COLUMNS` instead — reported once as an error naming `text().maxLength(n)` as the remedy and `ALTER TABLE FORCE` as explicitly not one, and EXCLUDED from the reader.
90
+
91
+ Excluding is what makes it converge, and that is measured rather than assumed: an excluded table with a hidden hash column produces no reader error at all, while the same table included throws on the first write. Cross-instance change events for such a table are lost until it is bounded; own-node reactivity is unaffected (writes still emit inline).
92
+
93
+ Framework `_voltro_*` tables cannot hit this — they are filtered out of the reader's include list before it reaches the replication client, and exclusion demonstrably shields the metadata fetch.
94
+
95
+ **Caveat worth reading if you are already affected:** on a table that ALREADY exists, adding `.maxLength(n)` currently changes nothing — the schema differ does not diff text length, so it plans 0 operations and reports "up to date". That is a separate defect, reported in the same round and not yet fixed; until it is, the remedy only applies to newly created tables.
96
+ - **@voltro/cli, @voltro/voltro** — `voltro codegen` no longer writes a silently plugin-less `rpcGroup.generated.ts`, and it now reports what it merged.
97
+
98
+ `loadApiConfig` swallows every failure into `null`, and `config?.plugins ?? []` turned that into "this app has no plugins". So an `app.config.ts` that threw while importing produced a generated file with **no plugin error union and no plugin routes** — followed by `voltro codegen: wrote rpcGroup.generated.ts`. The file typechecks, so nothing downstream catches it; the only symptom is a client branching on an error tag that never arrives.
99
+
100
+ A consumer with ~140 declarative `guards:` measured that file 2781 lines shorter after a version bump, with the `ScopeError` import and the whole `__voltroPluginErrors` union gone. For the record, since they were careful to separate measurement from conclusion: the generator did NOT drop the feature — the plugin-codegen path is byte-identical between 0.19.0 and 0.20.0, and the published `@voltro/cli@0.20.0` does contain the identifier they grepped for. Their `grep` came back empty because the bundled chunk contained a literal NUL byte, which makes a file binary to most search tools (fixed separately, and it had been hiding files from our own audits too). What was real is the artefact diff, and this is the path that produces it without a word.
101
+
102
+ Now: a config that EXISTS but fails to load is a refusal with a non-zero exit and the underlying cause, not a quiet downgrade. An app with no `app.config.ts` at all still generates — absence is legitimate, failure is not. And every run prints `(plugins N, error schemas N, plugin routes N)`, because a count that drops from 7 to 0 has to be visible in the success line or the next occurrence is found the same way: by diffing artefacts during a debugging session.
103
+
104
+ `loadApiConfigDiagnosed` is the new seam (`{ config, present, error }`); `loadApiConfig` is unchanged for every existing caller.
105
+ - **@voltro/cli, @voltro/voltro** — `ssr cold-compile` log lines now carry the compile's duration, and `voltro start` emits them at all.
106
+
107
+ The lines had a `start` and an `end` and no timing, which looks readable and is not: cold compiles run concurrently up to `VOLTRO_DEV_SSR_COMPILE_CONCURRENCY`, so the pairs INTERLEAVE. Subtracting adjacent timestamps names the wrong module, and above a limit of two they cannot be paired by eye at all — which is what a user reading a pod log actually hit, with three `start` lines before their `end`s:
108
+
109
+ ```
110
+ …:59.704 ssr cold-compile start id=…/layout.tsx
111
+ …:59.704 ssr cold-compile start id=…/(main)/layout.tsx
112
+ …:03.447 ssr cold-compile end 3743ms id=…/layout.tsx
113
+ ```
114
+
115
+ The gate had the number for free and threw it away. It is measured INSIDE the concurrency permit, so it is the module's own compile cost rather than the time it spent queued behind the limit — those are different numbers and only one of them is a property of the module. A slow first paint is usually one slow module, and this is the line that names it.
116
+
117
+ A failed compile now says `FAILED` instead of `end`. Without that, a 3.7-second line for a module that threw read exactly like a slow but successful compile.
118
+
119
+ `voltro start`'s middleware fallback constructed the same gate with NO callbacks, so an on-demand compile there produced no line whatsoever; it is wired now.
120
+ - **@voltro/cli, @voltro/voltro** — `voltro db plans`, `db drift` and `db restore-snapshot` worked on postgres only. On mysql/mariadb (and mssql and sqlite) all three died with:
121
+
122
+ ```text
123
+ fatal unhandled cli error (FiberFailure) SqlError: Failed to execute statement
124
+ ```
125
+
126
+ The cause is three `${sql('col')}::text AS ${sql('col')}` casts — POSTGRES syntax, in read paths whose helper is still called `buildPgLayer`. `db apply`, which WRITES the same ledger table, has no cast and worked, which is exactly the split a consumer reported: the commands that read were broken, the one that writes was fine.
127
+
128
+ The casts existed to stop a driver handing back a `jsonb` object or a `Date`. Normalising in JS gets the same result and cannot be dialect-specific, since drivers differ in whether a json column arrives parsed and whether a timestamp arrives as a `Date`.
129
+
130
+ Worth naming what it cost: `db drift` is the command whose whole job is "alert if live diverged from declared", and the consumer who found this had live divergence at the time. The specific detector and the general one were blind together.
131
+
132
+ **And the error now names the failing statement.** Their verdict was the actionable part of the report:
133
+
134
+ > *"the error names no statement … the statement text (or even the operation name) > would turn this from a dead end into a bug report. We would have sent you the > failing SQL if the error had contained it."*
135
+
136
+ Right twice over — they could not diagnose it, and neither could we from the report; it took reading our own source. `@effect/sql`'s `SqlError` carries the driver error in `cause`, and every supported driver puts the useful part there (mysql2: `code`, `errno`, `sqlState`, `sqlMessage`, usually `sql`; pg: `code`, `detail`, `hint`, `position`). The CLI's fatal reporter printed only the wrapper. It now walks the cause chain and prints the driver message, the codes and the statement — collapsed to one line, and saying `<not attached by the driver>` when there genuinely is none, because that is information too.
137
+
138
+ Shape-based rather than `instanceof SqlError`, deliberately: the CLI catches errors that have crossed the serve/start bundle boundary, where two copies of `@effect/sql` make `instanceof` silently false — the failure mode this repo has already paid for elsewhere.
139
+ - **@voltro/cli, @voltro/voltro** — `voltro doctor`'s `plaintext-secret` rule no longer flags metadata ABOUT a credential. An audit row denormalising the public facts of an api key — `apiKeyId`, `apiKeyKeyId`, `apiKeyType`, `apiKeyOwnerId`, `apiKeyName` — had three columns already excluded by the `*Id` suffix, while `apiKeyType` and `apiKeyName` fired. Telling a team to encrypt the LABEL of a credential is how a rule earns being ignored.
140
+
141
+ The exclusion now covers final words that cannot BE the credential — `Name`, `Type`, `Kind`, `Label`, `Prefix`, `Suffix`, `Status`, `State`, `Scope(s)`, `Version`, `Count`, `Provider`, `Format`, `Note`/`Description`/`Comment`, plus the existing `Id` and the hash family. Deliberately NOT on the list: `Value`, `Secret`, `Token`, `Key`, `Password` — the words that name the thing itself. A false negative from an over-wide list is silent, so that is the failure mode the list is built against, and a test pins the words that must still fire.
142
+ - **@voltro/database, @voltro/cli, @voltro/voltro** — `voltro doctor` no longer contradicts itself about the `.serverOnly()` wire audit. The same command on the same tree reported:
143
+
144
+ ```
145
+ human: serverOnly: NOT CHECKED | json: {'checked': True, 'leaks': 0}
146
+ ```
147
+
148
+ Two causes, both fixed. `registerRelations` refused a re-registration of the IDENTICAL relation object, so a process that executes a module twice looked like two conflicting declarations — it now mirrors `registerTable`'s `existing === table` tolerance (a DIFFERENT block claiming the same name still throws). And doctor loaded the app three times per run; it now loads once, so every report sees the same outcome instead of the first one succeeding and the next failing.
149
+
150
+ The consequence was worse than the noise: the throw aborted the wire audit, so the check that a token cannot reach a client had not run since the reporting app adopted the marker — and a CI gate written exactly as we documented (`fail on serverOnly.checked === false`) reported green on an app where the audit provably had not run. That is the "reads as coverage without being coverage" failure the `serverOnly` field was added to remove, reappearing in the field added to prevent it.
151
+ - **@voltro/sql-mysql, @voltro/voltro** — `insertIgnore` on MariaDB no longer reports a cause it cannot know, and no longer turns a REJECTED write into a silent "conflict". `INSERT IGNORE` downgrades EVERY error to a warning — foreign key, NOT NULL, CHECK, truncation — so the post-check's premise ("the insert was skipped ⇒ a unique constraint fired") does not hold on this dialect. It asserted a second unique index that did not exist; the real cause was an FK (an auto-stamped `createdBy` with no matching `actors` row), and a consumer spent the diagnosis looking for a phantom index.
152
+
153
+ The message now reads the real error from `SHOW WARNINGS` on the same connection — BEFORE the existing-row lookup, since that lookup is itself a statement and resets the warning list. A non-duplicate warning is reported as a rejection and throws, because returning there is data loss presented as a normal outcome: the row is not written and the caller is told it already was. A genuine duplicate on an unnamed constraint now names the constraint that fired. Outside a transaction the warning cannot be attributed to our own statement (each statement acquires from the pool independently), so the message says the constraint is unknown rather than guessing — framework mutations are auto-transactional, so the common path has the cause.
154
+ - **@voltro/logger, @voltro/cli, @voltro/database, @voltro/voltro** — `voltro doctor --json` and `voltro capabilities --json` now emit exactly one JSON document on stdout. A `log.warn` from module discovery landed there ahead of it, so:
155
+
156
+ ```console
157
+ $ voltro doctor --json 2>/dev/null | python3 -c 'import json,sys; json.load(sys.stdin)'
158
+ JSONDecodeError: Extra data: line 2 column 1
159
+ ```
160
+
161
+ Note the `2>/dev/null` in that repro — stderr was already redirected, so there was no shell-side workaround. And it only happened when a warning fired, so a consumer's CI parsed the document correctly until one file out of 368 tripped one. That is the same failure the `serverOnly.checked` field was added to remove — an automat unable to separate the normal case from the special case — one layer out, in the surface added to fix it.
162
+
163
+ A command that owns stdout for machine output now calls `claimStdoutForJson()` before doing any work that could log, and every record goes to stderr from then on. The stream decision itself moved into ONE place (`@voltro/logger`'s `stream.ts`, exported as `routeDiagnosticsToStderr`): the Effect surface and the direct surface each carried their own copy of `level === 'error' ? stderr : stdout`, and two copies of one rule is how the rule failed to change.
164
+
165
+ **Also fixed, same report:** the warning that started it was itself wrong. A `*.relations.ts` whose `relations(...)` map is EMPTY was reported as *"no relations(...) export found"* — pointing the reader at a missing export that is right there. `isRelationsSpec` rejects an empty map (correctly — there is nothing to register), but the caller could not tell that apart from a module with no export at all. It now says the map is empty and names the export.
166
+ - **@voltro/cli, @voltro/voltro** — The SSR bundle build now externalises a bare specifier it cannot resolve instead of aborting, so an uninstalled OPTIONAL peer no longer makes `voltro build` impossible.
167
+
168
+ The SSR step runs with `ssr: { noExternal: true }` — inlining everything is what lets a production web image ship without a framework dependency tree — and that left no escape for a package that cannot be resolved at all. The commonest such package is an optional native peer reached through a library's Node entry:
169
+
170
+ ```
171
+ Rolldown failed to resolve import "canvas"
172
+ from ".../konva/lib/index-node.js"
173
+ ```
174
+
175
+ `konva`'s `main` is its Node build, which requires the optional native `canvas`; its `browser` field points at one that does not. An app that never renders to a canvas server-side has nothing to install.
176
+
177
+ A consumer measured that there was no way out from their side either, and each measurement is worth keeping: the import was ALREADY dynamic (rolldown must still resolve it to form the chunk), `renderMode: 'spa'` does not help (`.framework/app.tsx` imports every page statically for the router, so the module is in the SSR graph whatever the render mode), and an `ssr.external` passthrough in `app.config.ts` is not read. So `voltro build` — and with it the production image — was unavailable for that app.
178
+
179
+ The api serve bundle and the web start bundle already did exactly this; that plugin is esbuild's and this step is vite/rolldown, so it is the same probe behind a different interface. Framework packages (`@voltro/*`, `@effect/*`, `effect`) are never externalised, so the "needs nothing from node_modules" property still holds.
180
+
181
+ Every externalised specifier is NAMED in the `SSR bundle ready` line. Externalising is right for an uninstalled optional peer and wrong for a genuine missing dependency — it trades a loud build failure for a quiet runtime one — and only the reader can tell which, so it is reported rather than swallowed.
182
+ - **@voltro/sql-mysql, @voltro/sql-sqlite, @voltro/sql-mssql, @voltro/sql-postgres, @voltro/database, @voltro/voltro** — A typed error thrown inside a mutation now reaches the client TYPED, on every dialect. It arrived as an untagged `Die` defect on mysql/mariadb, sqlite and mssql: `transactional()` settled its program with `runPromise`, which rejects with Effect's `FiberFailure` wrapper, and the wrapper copies `message` and a decorated `name` but nothing else — no `_tag`, no payload, no prototype. So the rpc encoder could not match the failure against the mutation descriptor's `error:` union:
183
+
184
+ ```
185
+ └─ ["error"] └─ ["_tag"] └─ is missing
186
+ Expected never, actual (FiberFailure) NotFoundError: …
187
+ ```
188
+
189
+ Framework mutations are auto-transactional, so this was EVERY typed mutation error in an app. Nothing failed — `defineMutation({ error: … })` compiled, the client's type still said `NotFoundError`, and the `error._tag === 'NotFoundError'` branch was simply never taken at runtime. Actions, which are not auto-transactional, marshalled correctly the whole time, which is what made the transaction the discriminator. A hand-rolled error class lost its fields and its `instanceof` too; only `message` survived, which is why a workaround built on `error.message` looked like it worked and hid this.
190
+
191
+ Postgres already had the unwrap, with a comment describing this exact consequence, and the three sibling dialects kept the broken call — so the fix is now one shared `settleTransactionExit` in `@voltro/database` that all four import, plus a parity test that fails if any store's `transactional()` reaches `runtime.runPromise` again. Reported by a consumer on MariaDB who verified it against 0.19.0 too, so it is not a 0.20.0 regression.
192
+
193
+ ### Internal (no consumer-facing effect)
194
+
195
+ - **@voltro/runtime, @voltro/database, @voltro/protocol, @voltro/cli, @voltro/plugin-billing, @voltro/plugin-mail, @voltro/plugin-sso-saml, @voltro/plugin-storage** — Fourteen source files carried a LITERAL NUL byte — the house idiom for a composite map key, written as the raw character instead of an escape. That makes the file BINARY to every text tool: `grep` skips it entirely and reports nothing, which is indistinguishable from a clean file. It was found because a new guard test scanning for framework index names came back clean on `runtime/src/connectionVault.ts` — 1020 lines that every previous grep-based audit in this repo had also silently skipped, including the one looking for exactly the index name that file declares.
196
+
197
+ Replaced with the JavaScript escape for U+0000. Identical runtime value, files are text again. No behaviour change.
198
+
199
+ ---
200
+
42
201
  ## [0.20.0] — 2026-07-29
43
202
 
44
203
  ### ⚠ BREAKING
package/dist/index.js CHANGED
@@ -1,23 +1,23 @@
1
1
  import { PgClient as e, PgClient as t } from "@effect/sql-pg";
2
- import { Cause as n, Config as r, Effect as i, Exit as a, Fiber as o, Layer as s, ManagedRuntime as c, Option as l, Redacted as u, Schedule as d, Stream as f } from "effect";
3
- import p from "pg";
4
- import { EventEmitter as m } from "node:events";
5
- import { createLogger as h } from "@voltro/logger";
6
- import { SqlClient as g, TransactionConnection as _ } from "@effect/sql/SqlClient";
7
- import { EagerCardinalityError as v, attachEagerLoads as y, attributionFields as b, attributionKey as x, claimPendingAttribution as S, compileEagerJson as C, compilePredicate as w, compileRawFragment as T, compileSelect as E, currentWriteAttribution as D, encodeRowForSchema as O, hasEagerLoads as k, isTableReactive as A, raiseChangeListenerCeiling as j, recordsTable as M, registerPendingAttribution as N, requireTable as P, runWithWriteAttribution as ee, runWriteRecorders as te, stampGeneratedId as F, stampGeneratedIds as I } from "@voltro/database";
2
+ import { Config as n, Effect as r, Fiber as i, Layer as a, ManagedRuntime as o, Option as s, Redacted as c, Schedule as l, Stream as u } from "effect";
3
+ import d from "pg";
4
+ import { EventEmitter as f } from "node:events";
5
+ import { createLogger as p } from "@voltro/logger";
6
+ import { SqlClient as m, TransactionConnection as h } from "@effect/sql/SqlClient";
7
+ import { EagerCardinalityError as g, attachEagerLoads as _, attributionFields as v, attributionKey as y, claimPendingAttribution as b, compileEagerJson as x, compilePredicate as S, compileRawFragment as C, compileSelect as w, currentWriteAttribution as T, encodeRowForSchema as E, hasEagerLoads as D, isTableReactive as O, raiseChangeListenerCeiling as k, recordsTable as A, registerPendingAttribution as j, requireTable as M, runWithWriteAttribution as N, runWriteRecorders as P, settleTransactionExit as ee, stampGeneratedId as F, stampGeneratedIds as I } from "@voltro/database";
8
8
  //#region src/sqlLayer.ts
9
9
  var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*$/, z = (t) => {
10
10
  if (t.schema === void 0) return e.layerConfig({
11
- host: r.succeed(t.host),
12
- port: r.succeed(t.port),
13
- username: r.succeed(t.username),
14
- password: r.succeed(u.make(t.password)),
15
- database: r.succeed(t.database),
16
- ...t.maxConnections === void 0 ? {} : { maxConnections: r.succeed(t.maxConnections) },
17
- ...t.ssl === void 0 ? {} : { ssl: r.succeed(L(t.ssl)) }
11
+ host: n.succeed(t.host),
12
+ port: n.succeed(t.port),
13
+ username: n.succeed(t.username),
14
+ password: n.succeed(c.make(t.password)),
15
+ database: n.succeed(t.database),
16
+ ...t.maxConnections === void 0 ? {} : { maxConnections: n.succeed(t.maxConnections) },
17
+ ...t.ssl === void 0 ? {} : { ssl: n.succeed(L(t.ssl)) }
18
18
  });
19
19
  if (!R.test(t.schema)) throw Error(`DB_SCHEMA '${t.schema}' is not a valid postgres identifier (expected ${R}).`);
20
- let n = t.schema, a = i.acquireRelease(i.sync(() => new p.Pool({
20
+ let i = t.schema, a = r.acquireRelease(r.sync(() => new d.Pool({
21
21
  host: t.host,
22
22
  port: t.port,
23
23
  user: t.username,
@@ -25,8 +25,8 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
25
25
  database: t.database,
26
26
  ...t.maxConnections === void 0 ? {} : { max: t.maxConnections },
27
27
  ...t.ssl === void 0 ? {} : { ssl: L(t.ssl) },
28
- options: `-c search_path="${n}"`
29
- })), (e) => i.promise(() => e.end()));
28
+ options: `-c search_path="${i}"`
29
+ })), (e) => r.promise(() => e.end()));
30
30
  return e.layerFromPool({ acquire: a });
31
31
  }, B = (e) => {
32
32
  let t = e.get("sslmode");
@@ -76,39 +76,39 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
76
76
  }, G = (e) => {
77
77
  let t = W(e);
78
78
  return t !== void 0 && U.has(t);
79
- }, K = (e) => G(e) ? "retry" : "noRetry", q = ["json"], J = h({ scope: "voltro:postgres" }), Y = async (e) => {
80
- let t = e.tracerLayer ? s.mergeAll(e.sqlLayer, e.tracerLayer) : e.sqlLayer, n = c.make(t), r = await n.runPromise(g), i = e.changeStrategy ?? "inline", a = new Z(r, n, i, e.cdcChannel ?? "framework_changes");
81
- return i === "cdc" && await a.startCdcConsumer(), a;
79
+ }, K = (e) => G(e) ? "retry" : "noRetry", q = ["json"], J = p({ scope: "voltro:postgres" }), Y = async (e) => {
80
+ let t = e.tracerLayer ? a.mergeAll(e.sqlLayer, e.tracerLayer) : e.sqlLayer, n = o.make(t), r = await n.runPromise(m), i = e.changeStrategy ?? "inline", s = new Z(r, n, i, e.cdcChannel ?? "framework_changes");
81
+ return i === "cdc" && await s.startCdcConsumer(), s;
82
82
  }, X = () => {
83
- let e = D();
84
- return e === void 0 ? (e) => e() : (t) => ee(e, t);
83
+ let e = T();
84
+ return e === void 0 ? (e) => e() : (t) => N(e, t);
85
85
  }, Z = class {
86
86
  sql;
87
87
  runtime;
88
88
  changeStrategy;
89
89
  cdcChannel;
90
- emitter = new m();
90
+ emitter = new f();
91
91
  cdcFiber = null;
92
92
  inflightTxns = 0;
93
93
  constructor(e, t, n, r) {
94
- this.sql = e, this.runtime = t, this.changeStrategy = n, this.cdcChannel = r, j(this.emitter);
94
+ this.sql = e, this.runtime = t, this.changeStrategy = n, this.cdcChannel = r, k(this.emitter);
95
95
  }
96
96
  withNamespace(e) {
97
- return e === null ? this : new ne(this, e);
97
+ return e === null ? this : new te(this, e);
98
98
  }
99
99
  async runInNamespace(e, t) {
100
100
  this.inflightTxns++;
101
- let n = X(), r = this.sql, a = this.sql.withTransaction(i.flatMap(i.serviceOption(_), (a) => {
102
- if (l.isNone(a)) return i.fail(/* @__PURE__ */ Error("PostgresDataStore.runInNamespace: TransactionConnection missing."));
103
- let o = a.value, s = i.provideService(r`SET LOCAL search_path TO ${r(e)}`, _, o), c = new Q(this, o);
104
- return i.flatMap(s, () => i.tryPromise({
105
- try: () => n(() => t(c)).then((e) => ({
101
+ let n = X(), i = this.sql, a = this.sql.withTransaction(r.flatMap(r.serviceOption(h), (a) => {
102
+ if (s.isNone(a)) return r.fail(/* @__PURE__ */ Error("PostgresDataStore.runInNamespace: TransactionConnection missing."));
103
+ let o = a.value, c = r.provideService(i`SET LOCAL search_path TO ${i(e)}`, h, o), l = new Q(this, o);
104
+ return r.flatMap(c, () => r.tryPromise({
105
+ try: () => n(() => t(l)).then((e) => ({
106
106
  result: e,
107
- view: c
107
+ view: l
108
108
  })),
109
109
  catch: (e) => e
110
110
  }));
111
- })).pipe(i.withSpan("store.namespace", { attributes: {
111
+ })).pipe(r.withSpan("store.namespace", { attributes: {
112
112
  "db.system": "postgresql",
113
113
  "db.operation": "namespace.transaction"
114
114
  } }));
@@ -121,113 +121,113 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
121
121
  }
122
122
  __postgresReplicationFriend = { runEffect: (e) => this.runtime.runPromise(e) };
123
123
  async executeQuery(e, t) {
124
- let n = E(e, this.sql), r = t ? i.provideService(n, _, t) : n;
125
- return this.runtime.runPromise(r);
124
+ let n = w(e, this.sql), i = t ? r.provideService(n, h, t) : n;
125
+ return this.runtime.runPromise(i);
126
126
  }
127
- async executeInsert(e, t, n, r) {
127
+ async executeInsert(e, t, n, i) {
128
128
  t = F(e, t);
129
- let a = this.sql, o = a`INSERT INTO ${a(e)} ${a.insert(O(t, e, q))} RETURNING *`, s = n ? i.provideService(o, _, n) : o, c = (await this.runtime.runPromise(s))[0];
129
+ let a = this.sql, o = a`INSERT INTO ${a(e)} ${a.insert(E(t, e, q))} RETURNING *`, s = n ? r.provideService(o, h, n) : o, c = (await this.runtime.runPromise(s))[0];
130
130
  if (!c) throw Error(`PostgresDataStore.insert: no row returned for table '${e}'`);
131
131
  return await this.routeEvent({
132
132
  table: e,
133
133
  op: "insert",
134
134
  old: null,
135
135
  new: c
136
- }, r, n), c;
136
+ }, i, n), c;
137
137
  }
138
- async executeUpdate(e, t, n, r, a) {
139
- let o = this.sql, s = o`UPDATE ${o(e)} SET ${o.update(O(n, e, q))} WHERE ${o("id")} = ${t} RETURNING *`, c = r ? i.provideService(s, _, r) : s, l = (await this.runtime.runPromise(c))[0];
138
+ async executeUpdate(e, t, n, i, a) {
139
+ let o = this.sql, s = o`UPDATE ${o(e)} SET ${o.update(E(n, e, q))} WHERE ${o("id")} = ${t} RETURNING *`, c = i ? r.provideService(s, h, i) : s, l = (await this.runtime.runPromise(c))[0];
140
140
  return l ? (await this.routeEvent({
141
141
  table: e,
142
142
  op: "update",
143
143
  old: null,
144
144
  new: l
145
- }, a, r), l) : null;
145
+ }, a, i), l) : null;
146
146
  }
147
- async executeUpsert(e, t, n, r, a) {
147
+ async executeUpsert(e, t, n, i, a) {
148
148
  let o = this.sql;
149
149
  if (typeof n.update == "function") {
150
- let s = n.update, c = n.conflictColumns.map((e) => o`${o(e)} = ${t[e]}`), u = (n) => {
151
- let r = o`SELECT * FROM ${o(e)} WHERE ${o.and(c)} LIMIT 1 FOR UPDATE`;
152
- return this.runtime.runPromise(i.flatMap(i.provideService(r, _, n), (r) => i.promise(() => r[0] ? this.executeUpdate(e, r[0].id, s(r[0]), n, a).then((e) => e) : this.executeInsert(e, t, n, a))));
150
+ let c = n.update, u = n.conflictColumns.map((e) => o`${o(e)} = ${t[e]}`), d = (n) => {
151
+ let i = o`SELECT * FROM ${o(e)} WHERE ${o.and(u)} LIMIT 1 FOR UPDATE`;
152
+ return this.runtime.runPromise(r.flatMap(r.provideService(i, h, n), (i) => r.promise(() => i[0] ? this.executeUpdate(e, i[0].id, c(i[0]), n, a).then((e) => e) : this.executeInsert(e, t, n, a))));
153
153
  };
154
- if (r) return u(r);
154
+ if (i) return d(i);
155
155
  this.inflightTxns++;
156
156
  try {
157
- let e = i.suspend(() => this.sql.withTransaction(i.flatMap(i.serviceOption(_), (e) => l.isNone(e) ? i.fail(/* @__PURE__ */ Error("PostgresDataStore.upsert: TransactionConnection missing.")) : i.promise(() => u(e.value))))), t = d.exponential("10 millis").pipe(d.compose(d.recurs(3)), d.whileInput(G));
158
- return await this.runtime.runPromise(e.pipe(i.retry(t)));
157
+ let e = r.suspend(() => this.sql.withTransaction(r.flatMap(r.serviceOption(h), (e) => s.isNone(e) ? r.fail(/* @__PURE__ */ Error("PostgresDataStore.upsert: TransactionConnection missing.")) : r.promise(() => d(e.value))))), t = l.exponential("10 millis").pipe(l.compose(l.recurs(3)), l.whileInput(G));
158
+ return await this.runtime.runPromise(e.pipe(r.retry(t)));
159
159
  } finally {
160
160
  this.inflightTxns--;
161
161
  }
162
162
  }
163
- let s = n.conflictColumns.map((e) => o`${o(e)}`), c = Object.keys(t).filter((e) => t[e] !== void 0), u = n.update === void 0 ? c.filter((e) => e !== "id" && !n.conflictColumns.includes(e)) : n.update, f = u.length > 0 ? o.csv(u.map((e) => o`${o(e)} = EXCLUDED.${o(e)}`)) : o`${o(n.conflictColumns[0])} = EXCLUDED.${o(n.conflictColumns[0])}`, p = o`INSERT INTO ${o(e)} ${o.insert(O(t, e, q))} ON CONFLICT (${o.csv(s)}) DO UPDATE SET ${f} RETURNING *`, m = r ? i.provideService(p, _, r) : p, h = (await this.runtime.runPromise(m))[0];
164
- if (!h) throw Error(`PostgresDataStore.upsert: no row returned for table '${e}'`);
163
+ let c = n.conflictColumns.map((e) => o`${o(e)}`), u = Object.keys(t).filter((e) => t[e] !== void 0), d = n.update === void 0 ? u.filter((e) => e !== "id" && !n.conflictColumns.includes(e)) : n.update, f = d.length > 0 ? o.csv(d.map((e) => o`${o(e)} = EXCLUDED.${o(e)}`)) : o`${o(n.conflictColumns[0])} = EXCLUDED.${o(n.conflictColumns[0])}`, p = o`INSERT INTO ${o(e)} ${o.insert(E(t, e, q))} ON CONFLICT (${o.csv(c)}) DO UPDATE SET ${f} RETURNING *`, m = i ? r.provideService(p, h, i) : p, g = (await this.runtime.runPromise(m))[0];
164
+ if (!g) throw Error(`PostgresDataStore.upsert: no row returned for table '${e}'`);
165
165
  {
166
- let n = t.id !== void 0 && t.id === h.id ? "insert" : "update";
166
+ let n = t.id !== void 0 && t.id === g.id ? "insert" : "update";
167
167
  await this.routeEvent({
168
168
  table: e,
169
169
  op: n,
170
170
  old: null,
171
- new: h
172
- }, a, r);
171
+ new: g
172
+ }, a, i);
173
173
  }
174
- return h;
174
+ return g;
175
175
  }
176
- async executeInsertIgnore(e, t, n, r, a) {
176
+ async executeInsertIgnore(e, t, n, i, a) {
177
177
  t = F(e, t);
178
- let o = this.sql, s = n.conflictColumns.map((e) => o`${o(e)}`), c = o`INSERT INTO ${o(e)} ${o.insert(O(t, e, q))} ON CONFLICT (${o.csv(s)}) DO NOTHING RETURNING *`, l = r ? i.provideService(c, _, r) : c, u = (await this.runtime.runPromise(l))[0];
178
+ let o = this.sql, s = n.conflictColumns.map((e) => o`${o(e)}`), c = o`INSERT INTO ${o(e)} ${o.insert(E(t, e, q))} ON CONFLICT (${o.csv(s)}) DO NOTHING RETURNING *`, l = i ? r.provideService(c, h, i) : c, u = (await this.runtime.runPromise(l))[0];
179
179
  if (u) return await this.routeEvent({
180
180
  table: e,
181
181
  op: "insert",
182
182
  old: null,
183
183
  new: u
184
- }, a, r), u;
185
- let d = n.conflictColumns.map((e) => o`${o(e)} = ${t[e]}`), f = o`SELECT * FROM ${o(e)} WHERE ${o.and(d)} LIMIT 1`, p = r ? i.provideService(f, _, r) : f, m = await this.runtime.runPromise(p);
184
+ }, a, i), u;
185
+ let d = n.conflictColumns.map((e) => o`${o(e)} = ${t[e]}`), f = o`SELECT * FROM ${o(e)} WHERE ${o.and(d)} LIMIT 1`, p = i ? r.provideService(f, h, i) : f, m = await this.runtime.runPromise(p);
186
186
  if (!m[0]) throw Error(`PostgresDataStore.insertIgnore: the insert was skipped as a conflict, but no existing row matches conflictColumns [${n.conflictColumns.join(", ")}] on '${e}'. A DIFFERENT unique constraint fired — a second unique index, or the primary key when you named something else. insertIgnore models ONE conflict target: name the columns of the constraint that actually collides, or handle the unique violation yourself.`);
187
187
  return m[0];
188
188
  }
189
- async executeInsertMany(e, t, n, r) {
189
+ async executeInsertMany(e, t, n, i) {
190
190
  if (t = I(e, t), t.length === 0) return [];
191
- let a = this.sql, o = a`INSERT INTO ${a(e)} ${a.insert(t.map((t) => O(t, e, q)))} RETURNING *`, s = n ? i.provideService(o, _, n) : o, c = await this.runtime.runPromise(s);
191
+ let a = this.sql, o = a`INSERT INTO ${a(e)} ${a.insert(t.map((t) => E(t, e, q)))} RETURNING *`, s = n ? r.provideService(o, h, n) : o, c = await this.runtime.runPromise(s);
192
192
  for (let t of c) await this.routeEvent({
193
193
  table: e,
194
194
  op: "insert",
195
195
  old: null,
196
196
  new: t
197
- }, r, n);
197
+ }, i, n);
198
198
  return c;
199
199
  }
200
- async executePatchJson(e, t, n, r, a, o) {
201
- let s = this.sql, c = n.split("."), l = c[0], u = c.slice(1), d = JSON.stringify(r ?? null), f = u.length === 0 ? s`${s(l)} = COALESCE(${s(l)}, '{}'::jsonb) || ${d}::jsonb` : s`${s(l)} = jsonb_set(COALESCE(${s(l)}, '{}'::jsonb), ${`{${u.join(",")}}`}, ${d}::jsonb, true)`, p = s`UPDATE ${s(e)} SET ${f} WHERE ${s("id")} = ${t} RETURNING *`, m = a ? i.provideService(p, _, a) : p, h = (await this.runtime.runPromise(m))[0];
202
- return h ? (await this.routeEvent({
200
+ async executePatchJson(e, t, n, i, a, o) {
201
+ let s = this.sql, c = n.split("."), l = c[0], u = c.slice(1), d = JSON.stringify(i ?? null), f = u.length === 0 ? s`${s(l)} = COALESCE(${s(l)}, '{}'::jsonb) || ${d}::jsonb` : s`${s(l)} = jsonb_set(COALESCE(${s(l)}, '{}'::jsonb), ${`{${u.join(",")}}`}, ${d}::jsonb, true)`, p = s`UPDATE ${s(e)} SET ${f} WHERE ${s("id")} = ${t} RETURNING *`, m = a ? r.provideService(p, h, a) : p, g = (await this.runtime.runPromise(m))[0];
202
+ return g ? (await this.routeEvent({
203
203
  table: e,
204
204
  op: "update",
205
205
  old: null,
206
- new: h
207
- }, o, a), h) : null;
206
+ new: g
207
+ }, o, a), g) : null;
208
208
  }
209
- async executeDelete(e, t, n, r) {
210
- let a = this.sql, o = a`DELETE FROM ${a(e)} WHERE ${a("id")} = ${t} RETURNING *`, s = n ? i.provideService(o, _, n) : o, c = (await this.runtime.runPromise(s))[0];
209
+ async executeDelete(e, t, n, i) {
210
+ let a = this.sql, o = a`DELETE FROM ${a(e)} WHERE ${a("id")} = ${t} RETURNING *`, s = n ? r.provideService(o, h, n) : o, c = (await this.runtime.runPromise(s))[0];
211
211
  return c ? (await this.routeEvent({
212
212
  table: e,
213
213
  op: "delete",
214
214
  old: c,
215
215
  new: null
216
- }, r, n), !0) : !1;
216
+ }, i, n), !0) : !1;
217
217
  }
218
218
  async appendInTxn(e, t, n) {
219
- let r = this.sql, a = r`INSERT INTO ${r(e)} ${r.insert(O(t, e, q))}`;
220
- await this.runtime.runPromise(n ? i.provideService(a, _, n) : a);
219
+ let i = this.sql, a = i`INSERT INTO ${i(e)} ${i.insert(E(t, e, q))}`;
220
+ await this.runtime.runPromise(n ? r.provideService(a, h, n) : a);
221
221
  }
222
- async maxInTxn(e, t, n, r) {
223
- let a = this.sql, o = Object.entries(n).map(([e, t]) => a`${a(e)} = ${t}`), s = a`SELECT MAX(${a(t)}) AS ${a("m")} FROM ${a(e)} WHERE ${a.and(o)}`, c = (await this.runtime.runPromise(r ? i.provideService(s, _, r) : s))[0]?.m;
222
+ async maxInTxn(e, t, n, i) {
223
+ let a = this.sql, o = Object.entries(n).map(([e, t]) => a`${a(e)} = ${t}`), s = a`SELECT MAX(${a(t)}) AS ${a("m")} FROM ${a(e)} WHERE ${a.and(o)}`, c = (await this.runtime.runPromise(i ? r.provideService(s, h, i) : s))[0]?.m;
224
224
  return c == null ? null : Number(c);
225
225
  }
226
226
  async routeEvent(e, t, n = null) {
227
227
  if (e = {
228
- ...b(),
228
+ ...v(),
229
229
  ...e
230
- }, M(e.table) && await te({
230
+ }, A(e.table) && await P({
231
231
  append: (e, t) => this.appendInTxn(e, t, n),
232
232
  maxOf: (e, t, r) => this.maxInTxn(e, t, r, n)
233
233
  }, {
@@ -237,10 +237,10 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
237
237
  prev: e.old,
238
238
  traceId: e.traceId,
239
239
  subjectId: e.subjectId
240
- }), A(e.table)) {
240
+ }), O(e.table)) {
241
241
  if (this.changeStrategy === "cdc") {
242
242
  let t = (e.op === "delete" ? e.old : e.new)?.id;
243
- t != null && N(x(e.table, e.op, t), {
243
+ t != null && j(y(e.table, e.op, t), {
244
244
  ...e.traceId === void 0 ? {} : { traceId: e.traceId },
245
245
  ...e.subjectId === void 0 ? {} : { subjectId: e.subjectId }
246
246
  });
@@ -253,20 +253,20 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
253
253
  return this.runWithEager(e, null);
254
254
  }
255
255
  raw(e, t) {
256
- let n = T(e, this.sql);
256
+ let n = C(e, this.sql);
257
257
  return this.runtime.runPromise(n);
258
258
  }
259
259
  async runWithEager(e, t) {
260
- if (!k(e)) return this.executeQuery(e, t);
261
- let n = C(e, this.sql, "postgres");
260
+ if (!D(e)) return this.executeQuery(e, t);
261
+ let n = x(e, this.sql, "postgres");
262
262
  if (n !== null) try {
263
- let e = t ? i.provideService(n.fragment, _, t) : n.fragment, r = await this.runtime.runPromise(e);
264
- return n.decode(r);
263
+ let e = t ? r.provideService(n.fragment, h, t) : n.fragment, i = await this.runtime.runPromise(e);
264
+ return n.decode(i);
265
265
  } catch (e) {
266
- if (e instanceof v) throw e;
266
+ if (e instanceof g) throw e;
267
267
  J.warn("postgres JSON-agg eager-load failed; falling back to walker", { err: e });
268
268
  }
269
- return y(await this.executeQuery(e, t), e.eager, e.sourceTable ?? P(e.table), (e) => this.executeQuery(e, t));
269
+ return _(await this.executeQuery(e, t), e.eager, e.sourceTable ?? M(e.table), (e) => this.executeQuery(e, t));
270
270
  }
271
271
  getInternalRunWithEager() {
272
272
  return (e, t) => this.runWithEager(e, t);
@@ -292,24 +292,24 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
292
292
  async deleteMany(e, t) {
293
293
  return X()(() => this.executeDeleteMany(e, t, null, null));
294
294
  }
295
- async executeUpdateMany(e, t, n, r, a) {
296
- let o = this.sql, s = w(n.where, o), c = o`UPDATE ${o(e)} SET ${o.update(O(t, e, q))} WHERE ${s} RETURNING *`, l = r ? i.provideService(c, _, r) : c, u = await this.runtime.runPromise(l);
295
+ async executeUpdateMany(e, t, n, i, a) {
296
+ let o = this.sql, s = S(n.where, o), c = o`UPDATE ${o(e)} SET ${o.update(E(t, e, q))} WHERE ${s} RETURNING *`, l = i ? r.provideService(c, h, i) : c, u = await this.runtime.runPromise(l);
297
297
  for (let t of u) await this.routeEvent({
298
298
  table: e,
299
299
  op: "update",
300
300
  old: null,
301
301
  new: t
302
- }, a, r);
302
+ }, a, i);
303
303
  return u.length;
304
304
  }
305
- async executeDeleteMany(e, t, n, r) {
306
- let a = this.sql, o = w(t.where, a), s = a`DELETE FROM ${a(e)} WHERE ${o} RETURNING *`, c = n ? i.provideService(s, _, n) : s, l = await this.runtime.runPromise(c);
305
+ async executeDeleteMany(e, t, n, i) {
306
+ let a = this.sql, o = S(t.where, a), s = a`DELETE FROM ${a(e)} WHERE ${o} RETURNING *`, c = n ? r.provideService(s, h, n) : s, l = await this.runtime.runPromise(c);
307
307
  for (let t of l) await this.routeEvent({
308
308
  table: e,
309
309
  op: "delete",
310
310
  old: t,
311
311
  new: null
312
- }, r, n);
312
+ }, i, n);
313
313
  return l.length;
314
314
  }
315
315
  upsert(e, t, n) {
@@ -353,28 +353,27 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
353
353
  }
354
354
  async transactional(e) {
355
355
  this.inflightTxns++;
356
- let t = X(), r = 0, o = i.suspend(() => {
357
- let n = ++r;
358
- return this.sql.withTransaction(i.flatMap(i.serviceOption(_), (r) => {
359
- if (l.isNone(r)) return i.fail(/* @__PURE__ */ Error("PostgresDataStore.transactional: TransactionConnection unexpectedly missing inside withTransaction."));
360
- let a = new Q(this, r.value);
361
- return i.tryPromise({
356
+ let t = X(), n = 0, i = r.suspend(() => {
357
+ let i = ++n;
358
+ return this.sql.withTransaction(r.flatMap(r.serviceOption(h), (n) => {
359
+ if (s.isNone(n)) return r.fail(/* @__PURE__ */ Error("PostgresDataStore.transactional: TransactionConnection unexpectedly missing inside withTransaction."));
360
+ let a = new Q(this, n.value);
361
+ return r.tryPromise({
362
362
  try: () => t(() => e(a)).then((e) => ({
363
363
  result: e,
364
364
  view: a,
365
- attempt: n
365
+ attempt: i
366
366
  })),
367
367
  catch: (e) => e
368
368
  });
369
369
  }));
370
- }), s = d.exponential("10 millis").pipe(d.compose(d.recurs(3)), d.whileInput(G)), c = o.pipe(i.retry(s), i.withSpan("store.transactional", { attributes: {
370
+ }), a = l.exponential("10 millis").pipe(l.compose(l.recurs(3)), l.whileInput(G)), o = i.pipe(r.retry(a), r.withSpan("store.transactional", { attributes: {
371
371
  "db.system": "postgresql",
372
372
  "db.operation": "transaction"
373
373
  } }));
374
374
  try {
375
- let e = await this.runtime.runPromiseExit(c);
376
- if (a.isSuccess(e)) return e.value.view.commitEvents(), e.value.result;
377
- throw n.squash(e.cause);
375
+ let e = ee(await this.runtime.runPromiseExit(o));
376
+ return e.view.commitEvents(), e.result;
378
377
  } finally {
379
378
  this.inflightTxns--;
380
379
  }
@@ -388,8 +387,8 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
388
387
  return this.changeStrategy === "cdc" ? "fleet" : "local";
389
388
  }
390
389
  injectExternalChange(e) {
391
- if (!A(e.table)) return;
392
- let t = (e.op === "delete" ? e.old : e.new)?.id, n = t == null ? void 0 : S(x(e.table, e.op, t));
390
+ if (!O(e.table)) return;
391
+ let t = (e.op === "delete" ? e.old : e.new)?.id, n = t == null ? void 0 : b(y(e.table, e.op, t));
393
392
  this.emitter.emit("change", {
394
393
  ...n,
395
394
  ...e,
@@ -408,7 +407,7 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
408
407
  inflight: this.inflightTxns
409
408
  });
410
409
  }
411
- this.cdcFiber &&= (await this.runtime.runPromise(o.interrupt(this.cdcFiber)), null), await this.runtime.dispose();
410
+ this.cdcFiber &&= (await this.runtime.runPromise(i.interrupt(this.cdcFiber)), null), await this.runtime.dispose();
412
411
  }
413
412
  async ping() {
414
413
  await this.runtime.runPromise(this.sql`SELECT 1`);
@@ -422,7 +421,7 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
422
421
  J.warn("cdc: bad payload", { channel: this.cdcChannel }, e);
423
422
  }
424
423
  };
425
- this.cdcFiber = this.runtime.runFork(e.pipe(f.runForEach((e) => i.sync(() => n(e)))));
424
+ this.cdcFiber = this.runtime.runFork(e.pipe(u.runForEach((e) => r.sync(() => n(e)))));
426
425
  }
427
426
  }, Q = class {
428
427
  parent;
@@ -478,7 +477,7 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
478
477
  this.events.length = 0;
479
478
  }
480
479
  }
481
- }, ne = class {
480
+ }, te = class {
482
481
  parent;
483
482
  namespace;
484
483
  constructor(e, t) {
@@ -532,34 +531,34 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
532
531
  return r === void 0 ? Promise.reject(/* @__PURE__ */ Error("PostgresNamespaceView.raw: underlying store has no raw()")) : r(e, t);
533
532
  });
534
533
  }
535
- }, $ = (e) => e.__postgresReplicationFriend ?? null, re = (e, t) => {
534
+ }, $ = (e) => e.__postgresReplicationFriend ?? null, ne = (e, t) => {
536
535
  let [n, r] = e.split("/"), [i, a] = t.split("/");
537
536
  if (!n || !r || !i || !a) throw Error(`postgres LSN compare: invalid format (${e} vs ${t})`);
538
537
  let o = parseInt(n, 16), s = parseInt(r, 16), c = parseInt(i, 16);
539
538
  return o === c ? s - parseInt(a, 16) : o - c;
540
- }, ie = () => ({
539
+ }, re = () => ({
541
540
  async capturePrimaryPosition(e) {
542
541
  let t = $(e);
543
542
  if (t === null) throw Error("postgresReplicationAdapter: primary is not a PostgresDataStore (missing __postgresReplicationFriend). Pass the postgres store directly.");
544
- return t.runEffect(i.gen(function* () {
545
- let e = (yield* (yield* g)`SELECT pg_current_wal_lsn()::text AS lsn`)[0]?.lsn;
546
- return typeof e == "string" ? e : yield* i.die("postgres did not return a WAL LSN");
543
+ return t.runEffect(r.gen(function* () {
544
+ let e = (yield* (yield* m)`SELECT pg_current_wal_lsn()::text AS lsn`)[0]?.lsn;
545
+ return typeof e == "string" ? e : yield* r.die("postgres did not return a WAL LSN");
547
546
  }));
548
547
  },
549
548
  async probeReplicaPosition(e) {
550
549
  let t = $(e);
551
550
  if (t === null) throw Error("postgresReplicationAdapter: replica is not a PostgresDataStore.");
552
- return t.runEffect(i.gen(function* () {
553
- let e = (yield* (yield* g)`
551
+ return t.runEffect(r.gen(function* () {
552
+ let e = (yield* (yield* m)`
554
553
  SELECT COALESCE(pg_last_wal_replay_lsn()::text, pg_current_wal_lsn()::text) AS lsn
555
554
  `)[0]?.lsn;
556
- return typeof e == "string" ? e : yield* i.die("postgres did not return a replay LSN");
555
+ return typeof e == "string" ? e : yield* r.die("postgres did not return a replay LSN");
557
556
  }));
558
557
  },
559
558
  compare(e, t) {
560
- return re(t, e) >= 0 ? "caught-up" : "behind";
559
+ return ne(t, e) >= 0 ? "caught-up" : "behind";
561
560
  }
562
- }), ae = {
561
+ }), ie = {
563
562
  id: "postgres",
564
563
  makeSqlLayer: (e) => H(e),
565
564
  makeStore: (e) => Y(e),
@@ -567,4 +566,4 @@ var L = (e) => e ? { rejectUnauthorized: !1 } : !1, R = /^[A-Za-z_][A-Za-z0-9_]*
567
566
  retryFilter: K
568
567
  };
569
568
  //#endregion
570
- export { e as PgClient, V as connectionFromConfig, Y as makePostgresDataStore, z as makePostgresSqlLayer, H as makePostgresSqlLayerFromConfig, ae as postgresDialect, ie as postgresReplicationAdapter, K as postgresRetryFilter };
569
+ export { e as PgClient, V as connectionFromConfig, Y as makePostgresDataStore, z as makePostgresSqlLayer, H as makePostgresSqlLayerFromConfig, ie as postgresDialect, re as postgresReplicationAdapter, K as postgresRetryFilter };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/sql-postgres",
3
- "version": "0.20.0",
3
+ "version": "0.20.2",
4
4
  "description": "PostgreSQL dialect adapter for Voltro's cross-dialect DataStore (LISTEN/NOTIFY reactivity, logical-replication CDC).",
5
5
  "keywords": [
6
6
  "voltro",
@@ -34,8 +34,8 @@
34
34
  "dependencies": {
35
35
  "@effect/sql": "^0.51.1",
36
36
  "@effect/sql-pg": "^0.52.1",
37
- "@voltro/database": "0.20.0",
38
- "@voltro/logger": "0.20.0",
37
+ "@voltro/database": "0.20.2",
38
+ "@voltro/logger": "0.20.2",
39
39
  "pg": "^8.22.0"
40
40
  },
41
41
  "peerDependencies": {