@vibeorm/adapter-pg 5.0.1 → 5.1.1

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/dist/index.js.map CHANGED
@@ -2,21 +2,21 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/batch.ts", "../src/connection-group.ts", "../src/connection-string.ts", "../src/client-turns.ts", "../src/read-cancellation.ts", "../src/config.ts", "../src/errors.ts", "../src/params.ts", "../src/pool-config.ts", "../src/statement-cache.ts", "../src/timestamp-text.ts", "../src/transaction-sql.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * @vibeorm/adapter-pg — node-postgres (`pg`) adapter for VibeORM v2.\n *\n * Runs on Bun and Node. Owns pooling, optional named prepared statements,\n * transactions (nested → savepoints on the same client) and driver-error\n * mapping. Only `VibeError` ever escapes.\n */\n\nimport type {\n AdapterBudgetSupport,\n DatabaseAdapter,\n PipelineGroup,\n PipelineLane,\n QueryResult,\n RowChangeCount,\n StatementEffect,\n TransactionOptions,\n WireFidelity,\n} from \"@vibeorm/runtime\";\nimport {\n assertReadExecution,\n readCancelledError,\n markTransactionAborted,\n runReadExecution,\n type BudgetStage,\n abortTransactionOnServerFailure,\n createDeferredControl,\n type DeferredControl,\n observeRowChanges,\n readRowChanges,\n statementRowChanges,\n createAdapterLifecycleGate,\n runPinnedSession,\n runShutdownCleanup,\n transactionLifecycleRefusal,\n createSavepointScope,\n engineStatementBudgetMs,\n type CommitProgress,\n findRefusedSetting,\n isSavepointRollbackFailedError,\n readOnlyRequested,\n readTransactionSettings,\n renderTransactionSettings,\n type RollbackOutcome,\n transactionSettingRefusedError,\n type TransactionSettingsStatement,\n runNestedSavepoint,\n runRootScope,\n type SavepointScope,\n scopeTurn,\n settleFailedTransaction,\n startTransactionBudget,\n type TransactionBudget,\n transactionAbortedError,\n validateTransactionDeadline,\n parseExtendedDateTimeText,\n} from \"@vibeorm/runtime/adapter-kit\";\nimport { VibeError } from \"@vibeorm/schema\";\nimport type { Dialect, Provider } from \"@vibeorm/schema\";\nimport pg from \"pg\";\nimport { batchDriverAvailable, firstBatchFailure, prepareBatchValues, runBatch, supportsBatch, type BatchOutcome, type BatchStep } from \"./batch.ts\";\nimport { openConnectionGroup, type ConnectionGroupDriver, type ConnectionGroupEntry } from \"./connection-group.ts\";\nimport { honourSystemRootCert } from \"./connection-string.ts\";\nimport { createClientTurns } from \"./client-turns.ts\";\nimport { createPgReadCancellation, type PgReadCancellation } from \"./read-cancellation.ts\";\nimport { mapPgDriverError, runMapped } from \"./errors.ts\";\nimport { PgArrayParam, serializeParams, serializeParamsRaw } from \"./params.ts\";\nimport { assertIdleTimeout, assertPlanCacheMode, assertPoolMin, buildPoolConfig, type PlanCacheMode } from \"./pool-config.ts\";\nimport { createStatementNameCache, type StatementNameCache } from \"./statement-cache.ts\";\nimport { parsePlainTimestampText } from \"./timestamp-text.ts\";\nimport {\n beginStatement,\n classifyRawTransactionControl,\n isSingleStatementText,\n openTransactionStatement,\n refuseNestedTransactionOptions,\n statementTimeoutStatement,\n} from \"./transaction-sql.ts\";\n\n// ─── Minimal pg surface ───────────────────────────────────────────\n\n/** The single `pg` query form this adapter uses (config object, never overloads). */\nexport type PgQueryConfig = {\n readonly text: string;\n readonly values?: unknown[];\n readonly name?: string;\n /**\n * QUERY-LOCAL result parsers ({@link EXACT_TYPES}). node-postgres reads this\n * off the query config, so nothing outside VibeORM's own statements is\n * affected — a caller's pool keeps the driver's documented behaviour.\n */\n readonly types?: PgTypeParsers;\n};\n\n/** The `pg-types` surface a query config may carry. */\nexport type PgTypeParsers = {\n getTypeParser(oid: number, format?: \"text\" | \"binary\"): (value: string) => unknown;\n};\n\n/** The parts of a `pg` result this adapter reads. */\nexport type PgQueryResultLike = {\n readonly rows: Record<string, unknown>[];\n readonly rowCount: number | null;\n /**\n * The command tag (`INSERT`, `COMMIT`, `ROLLBACK`, …). Optional so test\n * doubles need not supply it; the adapter reads it after `COMMIT`, which\n * PostgreSQL answers with `ROLLBACK` — and no error — when the transaction\n * was aborted.\n */\n readonly command?: string;\n};\n\n/** pg returns one result per command for simple-protocol scripts. */\nexport type PgQueryResultsLike = PgQueryResultLike | PgQueryResultLike[];\n\n/** The parts of a `pg` PoolClient this adapter uses. */\nexport type PgPoolClientLike = {\n query(config: PgQueryConfig): Promise<PgQueryResultsLike>;\n /** Installed pg pipelined end waits for drain; strong cancellation refuses that lifetime. */\n readonly pipeline?: boolean;\n /** Local rejection timeouts cannot prove original statement settlement. */\n readonly connectionParameters?: { readonly query_timeout?: number };\n /**\n * Hand the client back. A TRUTHY argument tells node-postgres to DESTROY it\n * instead of pooling it — used when a rollback failed and the session state\n * can no longer be asserted (EPIC 6). Optional so existing test doubles that\n * declare `release(): void` still satisfy this type.\n */\n release(destroy?: boolean): void;\n /**\n * EventEmitter surface. A real `pg.PoolClient` has it; test doubles need not,\n * so both members are optional and the adapter feature-detects them.\n */\n on?(event: \"error\", listener: (error: unknown) => void): void;\n removeListener?(event: \"error\", listener: (error: unknown) => void): void;\n};\n\n/** The parts of a `pg` Pool this adapter uses — satisfied by a real `pg.Pool`. */\nexport type PgPoolLike = {\n connect(): Promise<PgPoolClientLike>;\n query(config: PgQueryConfig): Promise<PgQueryResultsLike>;\n end(): Promise<void>;\n /** EventEmitter surface; optional for the same reason as on {@link PgPoolClientLike}. */\n on?(event: \"error\", listener: (error: unknown, client: PgPoolClientLike) => void): void;\n};\n\n/** Anything that can run a query: the pool itself or a checked-out client. */\ntype Queryable = { query(config: PgQueryConfig): Promise<PgQueryResultsLike> };\n\ntype TransactionDispatch = (params: {\n config: PgQueryConfig;\n execution?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"execution\"];\n onReadControl?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"onReadControl\"];\n stage?: BudgetStage;\n cleanup?: boolean;\n /**\n * The text is ONE statement and may ride in a one-Sync batch behind pending\n * control (EPIC 6). False for raw text without bound values that is not\n * provably one statement ({@link isSingleStatementText}): node-postgres sends\n * it as a simple-protocol message that may hold several statements.\n */\n batchable?: boolean;\n /**\n * Called immediately before the statement is handed to node-postgres —\n * after every check that can still refuse it. COMMIT uses it to record that\n * it was sent, the fact its outcome is decided by (EPIC T).\n */\n sent?: () => void;\n /** The `$all` pipeline lane that issued the statement (see {@link PipelineControl}). */\n lane?: PipelineLaneState;\n /**\n * The transaction's LAST statement (`withCommit`, statement-count pass EPIC\n * 5): COMMIT rides right behind it when the transaction can carry it now.\n */\n commit?: true;\n /** With `commit`: nobody reads the reply's rows — a riding batch does not decode them. */\n discardRows?: true;\n}) => Promise<PgQueryResultsLike>;\n\n// ─── `$all` pipeline (DatabaseAdapter.pipeline) ─────────────────────\n\n/** One lane of a pipeline scope: the handle ONE operation issues its statements through. */\ntype PipelineLaneState = {\n open: boolean;\n /** This lane's calls that are waiting: queued in the pipeline, on the wire, or for a savepoint turn. */\n waiting: number;\n /** The lane's place in an ORDERED scope (`pipeline({ ordered: true })`); absent on `$all` lanes. */\n readonly order?: OrderedLaneState;\n /** The lane issued its transaction-final statement (`withCommit`, EPIC 5): it issues nothing after it (D2 admission). */\n final?: boolean;\n /** The group this lane opened and that is not over yet (D2): the lane counts as waiting meanwhile. */\n group?: LaneGroupState;\n /** A sub-lane of a group (D2): its place, and whether it issued its ONE statement. */\n readonly seat?: { readonly group: LaneGroupState; readonly index: number; issued: boolean };\n /** The gate of a group (D2): open and never waiting, it holds the batch until the group is sealed. */\n readonly gate?: true;\n};\n\n/**\n * An ordered group of sub-lanes one `$all` lane opened (statement-count pass\n * D2, `PipelineLane.group`): its sibling relation loads. The parent counts as\n * waiting until the group is over (sealed and every sub-lane closed); the\n * gate holds the batch until the group is sealed.\n */\ntype LaneGroupState = {\n readonly parent: PipelineLaneState;\n readonly gate: PipelineLaneState;\n /** Sub-lanes opened so far (the next one's index). */\n opened: number;\n /** Sub-lanes not closed yet. */\n live: number;\n sealed: boolean;\n /**\n * Lane A2 (`PipelineLane.group({ final: true })`): the transaction's last\n * statements, on a handle that can carry COMMIT — COMMIT may ride behind\n * the group's batch (`ridesQueued`).\n */\n readonly final: boolean;\n};\n\n/**\n * A lane of an ordered scope — the array form of `$transaction` (efficiency\n * campaign, EPIC D). Its statements leave only after every earlier lane issued\n * one, in lane order, and each send of the scope waits for the previous one.\n */\ntype OrderedLaneState = {\n readonly scope: OrderedScope;\n /** Position in the scope. */\n readonly index: number;\n /** Statements this lane issued into the pipeline (cleanup control is not counted). */\n issued: number;\n /** A later lane follows this one: it may issue ONE statement. */\n followed: boolean;\n};\n\n/** One ordered scope: its lanes, in order (closed ones included, for the prefix rule). */\ntype OrderedScope = {\n readonly lanes: PipelineLaneState[];\n /**\n * The first failure of one of the scope's sends, a failure without a server\n * answer included (a client-side `query_timeout`, a value the driver\n * refuses): nothing of the scope is sent after it.\n */\n failed?: { readonly cause: VibeError };\n};\n\n/** A lane statement waiting in the pipeline; its values are already serialized for the batch. */\ntype QueuedStatement = {\n readonly text: string;\n readonly values: unknown[];\n readonly execution?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"execution\"];\n readonly lane: PipelineLaneState;\n /**\n * Ordered scopes only: a statement that keeps its own turn (raw text without\n * bound values that may hold several statements, savepoint control, the\n * strong-cancellation queue). It is sent\n * by itself, with these dispatch parameters, once the scope's earlier sends\n * settled.\n */\n readonly alone?: Parameters<TransactionDispatch>[0];\n /** The transaction's last statement (`withCommit`): COMMIT may ride behind the batch that carries it. */\n readonly commit?: true;\n readonly resolve: (result: PgQueryResultsLike) => void;\n readonly reject: (error: unknown) => void;\n settled: boolean;\n /** The error this statement was settled with, when it failed (read by the ordered scope's barrier). */\n failure?: unknown;\n};\n\n/**\n * In-flight gathering (round-trip report V4, decision D3): ordinary statements\n * of a transaction that WAIT — behind the burst carrying the deferred opening\n * (`\"opening\"`), or for the client to finish another call (`\"turn\"`, one slot of\n * the client's turns) — and leave together, in issue order, when that wait\n * ends. No window: a statement that finds nothing to wait for is sent at once.\n * The group takes statements only while nothing else was registered after it.\n */\ntype GatheringGroup = {\n readonly phase: \"opening\" | \"turn\";\n /** `\"opening\"`: the in-flight burst the group waits for. */\n readonly behind?: Promise<void>;\n readonly members: GatheredStatement[];\n};\n\n/** One statement waiting in a {@link GatheringGroup}. */\ntype GatheredStatement = {\n readonly params: Parameters<TransactionDispatch>[0];\n /** Serialized when the statement joined: a value the driver refuses fails that statement alone. */\n readonly values: unknown[];\n readonly resolve: (result: PgQueryResultsLike) => void;\n readonly reject: (error: unknown) => void;\n};\n\n/**\n * The pipeline of ONE top-level transaction. Statements the lanes issue wait\n * here and go out TOGETHER, as one one-Sync batch with any deferred control in\n * front, once every open lane is waiting — on a queued statement, on a reply,\n * or on a savepoint turn — or closed. An explicit signal from the runtime (the\n * lanes and their `close`), never a timer.\n */\ntype PipelineControl = {\n /** Register `count` open lanes. */\n readonly open: (count: number) => PipelineLaneState[];\n /** Register `count` open lanes of a new ORDERED scope. */\n readonly openOrdered: (count: number) => PipelineLaneState[];\n /** Open the lane right after `lane`, the last lane of its ordered scope; `lane` may then issue one statement. */\n readonly follow: (lane: PipelineLaneState) => PipelineLaneState;\n /** The lane's operation settled. Idempotent. */\n readonly close: (lane: PipelineLaneState) => void;\n /** Count `lane` as waiting while `wait` is pending (a savepoint turn, an unbatched statement). */\n readonly waitAs: <T>(params: { lane: PipelineLaneState; wait: Promise<T> }) => Promise<T>;\n /** Count `lane` as waiting until the returned release runs (idempotent). */\n readonly enter: (lane: PipelineLaneState) => () => void;\n /** Send whatever is queued now, whatever the lanes are doing. */\n readonly flush: () => void;\n /**\n * D2: open a group on `lane`, or `undefined` when a group cannot keep the order now (see `PipelineLane.group`).\n * `final` (lane A2): the transaction's last statements, on a handle that can carry COMMIT.\n */\n readonly group: (lane: PipelineLaneState, final: boolean) => LaneGroupState | undefined;\n /** D2: open the group's next sub-lane (before it is sealed). */\n readonly seat: (group: LaneGroupState) => PipelineLaneState;\n /** D2: no more sub-lanes; the gate opens. Idempotent. */\n readonly seal: (group: LaneGroupState) => void;\n};\n\n/** A broken use of a lane group (D2) — a runtime defect, refused before anything is sent. */\nfunction laneGroupMisuse(params: { message: string }): VibeError {\n return new VibeError({ code: \"VIBE_INTERNAL\", message: `pipeline lane group: ${params.message}`, meta: { reason: \"pipeline-lane-group\" } });\n}\n\n/** PostgreSQL's ceiling for `statement_timeout` (an int4 of milliseconds). */\nconst MAX_STATEMENT_TIMEOUT_MS = 2_147_483_647;\n\nconst ignore = (): undefined => undefined;\n\n/** An ordered-scope statement whose earlier lane closed without issuing one: it is never sent (EPIC D). */\nfunction predecessorClosedError(): VibeError {\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message:\n \"pipeline(): an earlier lane of this ordered scope closed without issuing its statement, so this statement was not sent \" +\n \"(the operation before it failed before it reached the database)\",\n meta: { reason: \"pipeline-predecessor-closed\" },\n });\n}\n\n/** A broken use of an ordered scope's lanes — a runtime defect, refused before anything is sent. */\nfunction orderedLaneMisuse(params: { message: string }): VibeError {\n return new VibeError({ code: \"VIBE_INTERNAL\", message: `pipeline(): ${params.message}`, meta: { reason: \"pipeline-ordered-lane\" } });\n}\n\n/**\n * A COMMIT that rode with a transaction's last statement (statement-count pass\n * EPIC 5, `withCommit`). Its batch decides the transaction: `committed`;\n * `skipped` (the statement before it failed, so the server never ran it);\n * `failed` (answered with an error or a ROLLBACK tag); `lost` (no answer).\n */\ntype RiddenCommit = {\n /** Settles once the batch that carried it settled; never rejects. */\n settled: Promise<void>;\n state: \"in-flight\" | \"committed\" | \"skipped\" | \"failed\" | \"lost\";\n /** `failed`: COMMIT's mapped error; `lost`: the outcome-unknown error. */\n error?: unknown;\n};\n\n/** The COMMIT step that rides behind a transaction's last statement. */\nconst COMMIT_STEP: BatchStep = Object.freeze({ text: \"COMMIT\" });\n\n/** A statement sent after a riding COMMIT left the client (EPIC 5): it is never sent. */\nfunction commitSentRefusal(): VibeError {\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message: \"this transaction already sent its COMMIT together with its last statement, so it accepts no further statement\",\n meta: { provider: PROVIDER, reason: \"commit-sent\" },\n });\n}\n\n/** A second statement through one `withCommit` view — a runtime defect, refused before anything is sent. */\nfunction finalStatementMisuse(): VibeError {\n return new VibeError({\n code: \"VIBE_INTERNAL\",\n message: \"withCommit(): a view carries ONE statement, the transaction's last\",\n meta: { reason: \"with-commit-second-statement\" },\n });\n}\n\n/**\n * A riding batch's outcome as its statements see it: without the COMMIT step.\n * A failure only the COMMIT step saw (an error answer, or a connection lost\n * after the statements were answered) belongs to the transaction, not to them.\n */\nfunction beforeCommit(params: { outcome: BatchOutcome; commitIndex: number }): BatchOutcome {\n const { outcome, commitIndex } = params;\n const steps = outcome.steps.slice(0, commitIndex);\n return steps.length < commitIndex && outcome.transportError !== undefined ? { steps, transportError: outcome.transportError } : { steps };\n}\n\nfunction finalResult(params: { result: PgQueryResultsLike }): PgQueryResultLike {\n return Array.isArray(params.result)\n ? (params.result.at(-1) ?? { rows: [], rowCount: 0 })\n : params.result;\n}\n\n/**\n * Keep a CHECKED-OUT client's background failures from killing the process,\n * returning the detach to run before the client goes back to the pool.\n *\n * node-postgres listens for `'error'` on a pooled client only while that client\n * sits IDLE, and removes the listener the moment the client is checked out\n * (restoring it on release). A client this adapter holds — for a transaction,\n * or as a pinned raw session — therefore has NO listener, so a backend that\n * dies mid-transaction reaches `client.emit('error', …)` with none. An\n * `'error'` event without a listener is an uncaught exception: fatal under\n * Node, which turns a database failover into a dead application process.\n *\n * The listener deliberately does nothing with the error and is NOT an error\n * channel: the in-flight query already rejects on its own with the mapped\n * `VibeError`, and the pool discards the broken client. Its only job is to keep\n * the process alive. Detaching before `release()` matters just as much — a\n * listener left attached would shadow pg's own idle listener and stop the pool\n * evicting a client that fails later, while idle.\n */\n/**\n * Prepared-statement name registries, one per POOL (F16/F18) — see\n * ./statement-cache.ts for why they are shared and bounded. Weakly held, so a\n * pool that goes out of scope takes its registry with it.\n */\nconst POOL_STATEMENT_NAMES: WeakMap<PgPoolLike, StatementNameCache> = new WeakMap();\n\n/**\n * Whether a mapped driver failure means the CONNECTION is gone rather than the\n * server having answered: no SQLSTATE at all (socket-level), class 08\n * (connection exception) or an admin/crash shutdown (57P01–57P03). The same\n * rule pins a migration session as lost and decides whether a failed COMMIT's\n * outcome is unknown.\n */\nfunction isConnectionLoss(params: { error: unknown }): boolean {\n const { error } = params;\n if (!(error instanceof VibeError)) return true;\n const sqlstate = error.meta.sqlstate;\n return typeof sqlstate !== \"string\" || sqlstate.startsWith(\"08\") || [\"57P01\", \"57P02\", \"57P03\"].includes(sqlstate);\n}\n\n/**\n * A COMMIT whose acknowledgement never arrived: the write may or may not be\n * durable, and nothing on the client can tell. The mysql and bun adapters\n * report the same shape (`transaction-outcome-unknown`, stage `commit`).\n */\nfunction commitOutcomeUnknownError(params: { cause: unknown }): VibeError {\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message:\n \"the connection was lost while COMMIT was in flight, so the transaction's outcome is unknown: the write may have committed. The connection was discarded; inspect the data before retrying.\",\n meta: { provider: PROVIDER, reason: \"transaction-outcome-unknown\", outcome: \"unknown\", stage: \"commit\" },\n cause: params.cause,\n });\n}\n\n/**\n * SQLSTATE classes after which a session is never reused, whatever its\n * transaction status says: connection exception, insufficient resources,\n * operator intervention, system error, internal error.\n */\nconst NEVER_REUSE_SQLSTATE_CLASSES: ReadonlySet<string> = new Set([\"08\", \"53\", \"57\", \"58\", \"XX\"]);\n\n/**\n * SQLSTATEs after which a NAMED prepared statement can no longer be trusted on\n * the session that ran it (fix lane FX-A, RV2 MJ-1): the client's record of\n * the name and the backend's disagree. node-postgres keeps a name it once\n * parsed (`parsedStatements`) across errors, so a reused session would fail\n * the same way on every later call:\n * - `0A000` — \"cached plan must not change result type\" after a schema change;\n * - `26000` — the backend does not know the name (a transaction-mode pooler);\n * - `42P05` — the backend already holds the name, so every Parse is refused.\n * Destroying the client makes the next call prepare on a fresh session — the\n * self-healing behaviour `pool.query` gave before round-trip EPIC 3.\n */\nconst STALE_STATEMENT_SQLSTATES: ReadonlySet<string> = new Set([\"0A000\", \"26000\", \"42P05\"]);\n\n/** The node-postgres `Client` members the reuse seam needs; feature-detected, never assumed. */\ntype ReadyForQuerySurface = {\n getTransactionStatus?: () => string | null;\n on?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n removeListener?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n once?: unknown;\n pipeline?: unknown;\n};\n\n/** What the root path learns from one checked-out client while its query runs. */\ntype ReadyForQuerySeam = {\n /**\n * After a failure: may this client go back to the pool? Never true without\n * proof. `named`: the failing query was a named prepared statement.\n */\n readonly reusableAfter: (params: { error: unknown; named: boolean }) => Promise<boolean>;\n /** Remove every listener; runs before the client is released. */\n readonly detach: () => void;\n};\n\n/**\n * Round-trip EPIC 3 (A-12): prove that a root ORM statement's failure left its\n * session idle, so the client can be pooled instead of destroyed (today\n * `pool.query` destroys it on ANY error, and the next call pays a reconnect).\n *\n * Listeners for `drain` / `error` / `end` are attached BEFORE the query is\n * submitted. node-postgres sets `readyForQuery = false` when it sends a query\n * on an idle client and emits `drain` only from `_pulseQueryQueue` after\n * `_handleReadyForQuery` stored the status of THAT query's ReadyForQuery\n * (pg 8.23 `client.js` 373-396, 616-641), so the first `drain` after\n * submission carries the failing query's own status. Sampling the status at\n * rejection instead is timing-dependent (spike §3: stale in 59/200 compound\n * runs). A lost connection emits `error` / `end`, so the wait always ends.\n *\n * Reuse needs ALL of: the mapped error has a SQLSTATE outside\n * {@link NEVER_REUSE_SQLSTATE_CLASSES} (and, for a named statement, outside\n * {@link STALE_STATEMENT_SQLSTATES}); the first event was `drain`; the status\n * after it is `I`; no `error` event during the checkout. Anything else destroys\n * the client — today's behaviour. The `error` listener also keeps a background\n * failure of the checked-out client from becoming an uncaught exception (see\n * {@link guardBackgroundErrors}). Only for a client that passed\n * {@link hasReadyForQuerySeam}.\n */\nfunction observeReadyForQuery(params: { client: PgPoolClientLike }): ReadyForQuerySeam {\n const client = params.client as PgPoolClientLike & Required<Pick<ReadyForQuerySurface, \"on\" | \"removeListener\" | \"getTransactionStatus\">>;\n let backgroundFailure = false;\n let settle: (event: \"drain\" | \"error\" | \"end\") => void = () => undefined;\n const firstEvent = new Promise<\"drain\" | \"error\" | \"end\">((resolve) => { settle = resolve; });\n const onDrain = (): void => settle(\"drain\");\n const onError = (): void => { backgroundFailure = true; settle(\"error\"); };\n const onEnd = (): void => settle(\"end\");\n client.on(\"error\", onError);\n client.on(\"drain\", onDrain);\n client.on(\"end\", onEnd);\n return {\n reusableAfter: async ({ error, named }) => {\n if (!(error instanceof VibeError)) return false;\n const sqlstate = error.meta.sqlstate;\n if (typeof sqlstate !== \"string\" || NEVER_REUSE_SQLSTATE_CLASSES.has(sqlstate.slice(0, 2))) return false;\n if (named && STALE_STATEMENT_SQLSTATES.has(sqlstate)) return false;\n const event = await firstEvent;\n return event === \"drain\" && !backgroundFailure && client.getTransactionStatus() === \"I\";\n },\n detach: () => {\n client.removeListener(\"error\", onError);\n client.removeListener(\"drain\", onDrain);\n client.removeListener(\"end\", onEnd);\n },\n };\n}\n\n/**\n * Whether a checked-out client exposes node-postgres' events and status the\n * reuse seam needs (`on`, `removeListener`, `once`, `getTransactionStatus`) and\n * is not a `pipeline: true` client. A client without them (an injected pool's\n * wrapper) cannot even carry the `error` listener that keeps a socket failure\n * from becoming an uncaught exception, so the root path never runs a\n * statement on it (fix lane FX-A, RV2 MJ-3).\n */\nfunction hasReadyForQuerySeam(params: { client: PgPoolClientLike }): boolean {\n const client = params.client as PgPoolClientLike & ReadyForQuerySurface;\n return typeof client.on === \"function\" &&\n typeof client.removeListener === \"function\" &&\n typeof client.once === \"function\" &&\n typeof client.getTransactionStatus === \"function\" &&\n client.pipeline !== true;\n}\n\nfunction guardBackgroundErrors(params: { client: PgPoolClientLike; onError?: (error: unknown) => void }): () => void {\n const { client, onError } = params;\n if (typeof client.on !== \"function\") return (): void => undefined;\n const swallow = (error: unknown): void => {\n /* the failing call rejects with a mapped VibeError; nothing to report here */\n onError?.(error);\n };\n client.on(\"error\", swallow);\n return (): void => {\n client.removeListener?.(\"error\", swallow);\n };\n}\n\n// ─── Options ──────────────────────────────────────────────────────\n\n/**\n * Every {@link pgAdapter} option. {@link PgAdapterOptions} adds the rule that\n * one of `connectionString` and `pool` is present.\n */\nexport type PgAdapterSettings = {\n /**\n * PostgreSQL connection URL. The adapter never reads `DATABASE_URL` (or any\n * other environment variable) itself: pass the URL you mean. Give a complete\n * URL — node-postgres fills parts the URL omits (host, user, database, …)\n * from the `PG*` environment variables.\n *\n * libpq's `sslrootcert=system` (as in PlanetScale's URLs) is accepted:\n * the adapter verifies the server certificate's chain and host name against\n * the runtime's default trust store (`sslmode=verify-full`), and refuses a\n * weaker `sslmode` next to it with `VIBE_CONFIG`, as libpq does.\n */\n readonly connectionString?: string;\n /**\n * An existing `pg.Pool` to use instead of creating one. The adapter never\n * ends a pool it did not create: `disconnect()` only ends this adapter (and\n * rolls back and releases its own raw session); the pool stays usable.\n * Wins over `connectionString` when both are given.\n *\n * `connect()` must return a distinct client object for each physical\n * connection and never hand the same object out for another one (node-postgres\n * `pg.Pool` does: a `Client` never reconnects). The returned object is the\n * transaction's `connectionIdentity`, which native-RLS per-connection\n * verdicts and the operator login check are keyed on.\n */\n readonly pool?: PgPoolLike;\n /** Maximum pooled connections (default 10). Ignored when `pool` is given. */\n readonly max?: number;\n /**\n * Connections the pool keeps open however long they sit idle (pg-pool's\n * `min`; default 0). `adapter.connect()` (`db.$connect()`) opens this many\n * at once, so a burst of parallel queries finds them warm instead of paying\n * TCP + startup + authentication per connection — about three round trips\n * each, more with TLS. Must be an integer from 0 through `max`, else the\n * factory throws `VIBE_CONFIG`. Refused next to `pool` (`VIBE_CONFIG`): the\n * adapter cannot change a caller's pool — set `min` on that pool instead.\n */\n readonly min?: number;\n /**\n * Pool-wide `statement_timeout` in milliseconds. Every connection inherits\n * it; a per-transaction `timeout` overrides it for that transaction.\n */\n readonly statementTimeout?: number;\n /** Milliseconds to wait for a pool checkout before failing (pg's `connectionTimeoutMillis`). */\n readonly connectionTimeout?: number;\n /**\n * Milliseconds a pooled connection may sit idle before the pool closes it\n * (pg-pool's `idleTimeoutMillis`). Unset keeps pg-pool's default of 10 000:\n * the next query after a quiet spell then opens a new connection (TCP,\n * startup, authentication — ≈ 2.4 ms locally, more over TLS). `0` keeps idle\n * connections open until the server or network closes them; a longer value\n * trades held server connections for fewer reconnects. Must be integer\n * milliseconds from 0 through 2,147,483,647, else the factory throws\n * `VIBE_CONFIG`. Ignored when\n * `pool` is given: set `idleTimeoutMillis` on that pool.\n */\n readonly idleTimeout?: number;\n /** Separate direct/session-pinned PostgreSQL control endpoint for running reads.\n * Required with an injected pool; never inferred from that pool or ambient env.\n * The same role must be allowed to signal its target. Server support needs live acceptance.\n */\n readonly cancellationConnectionString?: string;\n /**\n * Send ORM-path queries as named prepared statements (default false).\n *\n * Measured on this repo's benchmark (postgres 16, interleaved rounds):\n * −17…−25 % on reads, −6 % on a by-key update — the server skips the\n * parse/analyze and the protocol Parse/Describe round on every repeat. The\n * gain survives {@link PgAdapterOptions.planCacheMode} `force_custom_plan`,\n * which removes the classic downside (a generic plan after ~5 executions\n * picking worse indexes for range/LIKE/skewed filters).\n *\n * Off by default because named statements live on the BACKEND connection:\n * behind a transaction-mode pooler (PgBouncer before 1.21 or with\n * `max_prepared_statements = 0`, Supavisor, Neon's pooler) a client that\n * remembers a name from an earlier transaction is handed another backend\n * later. Names are collision-resistant (`vibeorm_` + the SHA-256 of the exact\n * text, see `statementNameFor`), so a name can only ever stand for its own\n * text: the remaining failure is a typed `VIBE_ADAPTER` error (SQLSTATE 26000\n * or 42P05), never another statement's rows. Turn it on for direct\n * connections, session pooling, or PgBouncer 1.21+ with\n * `max_prepared_statements > 0`.\n *\n * Schema changes can invalidate a retained result descriptor (SQLSTATE\n * 0A000). No statement or transaction callback is retried. Drain traffic and\n * recycle backend connections across incompatible schema deployments. For\n * an injected pool its owner must replace the pool; adapter.disconnect()\n * does not end it. force_custom_plan does not remove this requirement.\n */\n readonly preparedStatements?: boolean;\n /**\n * Budget of prepared-statement NAMES per pool (default 1000). Names never\n * evict — a name evicted here would stay prepared on every backend that saw\n * it — so this is a bound on the server's retention per connection, and a\n * text arriving after the budget is spent runs unnamed (it still binds its\n * parameters; only the server-side plan cache is skipped). A name is\n * allocated on a text's SECOND sighting, so one-off texts — offset pagination\n * emits one per page — never spend the budget.\n */\n readonly stmtCacheMax?: number;\n /**\n * PostgreSQL `plan_cache_mode` for every connection of the pool this adapter\n * builds (default `\"auto\"`, the server default — nothing is sent). Pair\n * `\"force_custom_plan\"` with {@link PgAdapterOptions.preparedStatements}: the\n * statement is still prepared once, but planned with the real parameter\n * values on every execution. Rides the `options` startup parameter, merged\n * with whatever the connection string already carries (a URL that sets\n * `plan_cache_mode` itself wins). Refused with `VIBE_CONFIG` together with\n * a caller-supplied `pool` — the adapter never reconfigures a pool it does\n * not own; set it on that pool's own `options` instead.\n */\n readonly planCacheMode?: PlanCacheMode;\n};\n\n/**\n * Options for {@link pgAdapter}: an explicit address is required. Either point\n * it at a connection string (the adapter then owns the pool it creates) or hand\n * it a pool you already own. Without either, the factory throws `VIBE_CONFIG`\n * before any pool or connection exists.\n */\nexport type PgAdapterOptions = PgAdapterSettings &\n ({ readonly connectionString: string } | { readonly pool: PgPoolLike });\n\n// ─── Adapter ──────────────────────────────────────────────────────\n\nconst DIALECT: Dialect = \"postgres\";\nconst PROVIDER: Provider = \"postgresql\";\n\n/**\n * node-postgres wire (board #30, live-verified on both execute paths):\n * timestamptz → `Date`, json/jsonb → parsed values, int4/float8 → numbers,\n * bytea (and bytea[] elements) → `Buffer` (5.0: the join strategy's relation\n * children follow it, so both strategies return the same class).\n * (int8 stays a string — BigInt decoding is real work and never pruned.)\n */\nconst WIRE: WireFidelity = Object.freeze({ dateTime: \"native\", json: \"parsed\", numbers: \"native\", bytes: \"buffer\" } as const);\n\n/**\n * A PostgreSQL server: every round trip crosses a network (a local socket\n * included), so the runtime's one-statement folds apply. The transaction\n * facades carry the same declaration.\n */\nconst ROUND_TRIPS: NonNullable<DatabaseAdapter[\"roundTrips\"]> = \"network\";\n\n/**\n * `$all`'s snapshot: a read-only REPEATABLE READ transaction reads ONE snapshot\n * and never fails with a serialization error.\n */\nconst READ_SNAPSHOT: NonNullable<DatabaseAdapter[\"readSnapshot\"]> = Object.freeze({ isolationLevel: \"RepeatableRead\", accessMode: \"readOnly\" } as const);\n\n/**\n * Statements issued together on a transaction handle share one round trip: the\n * handle offers `pipeline()` and sends lane statements as one one-Sync batch.\n * A checked-out client that cannot batch (a wrapper, a test double) declares\n * `\"ordered\"` on its handles and offers no lanes.\n */\nconst PIPELINING: NonNullable<DatabaseAdapter[\"pipelining\"]> = \"batched\";\n\n/**\n * Timing budgets this adapter genuinely enforces (EPIC 6).\n *\n * - `acquireTimeout: true` — {@link PgAdapterOptions.connectionTimeout} maps to\n * node-postgres' `connectionTimeoutMillis`, which bounds the checkout wait\n * and rejects when the pool stays exhausted. The capability is declared here;\n * it is OFF until the option is set (pg's own default is \"wait forever\").\n * - `statementTimeout: \"all-statements\"` — PostgreSQL's `statement_timeout`\n * cancels ANY over-long statement, writes included (SQLSTATE 57014).\n * - `transactionDeadline: \"cancel-running-statements\"` — the strongest level:\n * the remaining budget is handed to the SERVER before each statement, so the\n * database itself stops work that would outlive the deadline. Nothing here is\n * a `Promise.race` over a statement that keeps running.\n */\nconst BUDGETS: AdapterBudgetSupport = Object.freeze({\n acquireTimeout: true,\n statementTimeout: \"all-statements\",\n transactionDeadline: \"cancel-running-statements\",\n accessModes: Object.freeze([\"readOnly\"] as const),\n} as const);\n\n// ─── Exact numeric arrays (F12) ───────────────────────────────\n\n/** `_numeric`: the array form of `numeric`/`DECIMAL`. */\nconst NUMERIC_ARRAY_OID = 1231;\n/** `_text`: its parser splits a postgres array literal into RAW element strings. */\nconst TEXT_ARRAY_OID = 1009;\n/** `timestamp without time zone` and `date` — the zone-less types — and their array forms. */\nconst TIMESTAMP_OID = 1114;\nconst TIMESTAMP_ARRAY_OID = 1115;\nconst DATE_OID = 1082;\nconst DATE_ARRAY_OID = 1182;\n/** `timestamp with time zone` and its array form (AW-03). */\nconst TIMESTAMPTZ_OID = 1184;\nconst TIMESTAMPTZ_ARRAY_OID = 1185;\n\n/**\n * `pg.types.getTypeParser` behind a plain numeric-OID signature. `@types/pg`\n * narrows the two-argument overload to its own `TypeId` union of well-known\n * OIDs, which does not include every array OID this function must look up.\n */\nconst driverTypeParser: (oid: number, format?: \"text\" | \"binary\") => (value: string) => unknown =\n pg.types.getTypeParser as unknown as (oid: number, format?: \"text\" | \"binary\") => (value: string) => unknown;\n\n/** postgres' text output for the zone-less types: `2026-03-08 19:38:08.538` or `2026-03-08`. */\nconst ZONE_LESS_TEXT = /^\\d{4}-\\d{2}-\\d{2}(?: \\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,6})?)?$/;\n\n/**\n * Zone-less date/timestamp text read as **UTC** — the same rule as the codec\n * table's `parseDateTimeText` (@vibeorm/sql), applied at the driver level\n * because node-postgres hands these columns to the ORM as `Date` objects\n * already (`wire.dateTime: \"native\"` prunes the codec decode). pg-types reads\n * them as host-LOCAL time, so one stored row decoded to a different instant\n * on every host TZ, and to a different instant than bun:sql, PGlite's ORM\n * path and Prisma (all UTC) return. A year of five or more digits and a BC\n * era take the codec table's extended reading (`parseExtendedDateTimeText`,\n * UTC too — 5.0: the join strategy reads the same text that way);\n * `infinity` and anything else outside those forms keep the driver's own parser.\n */\nfunction parseZoneLessAsUtc(value: string): unknown {\n // AW-03: the plain `YYYY-MM-DD HH:MM:SS[.f]` form by char codes; everything else below, as before.\n const plain = parsePlainTimestampText({ text: value, zoned: false });\n if (plain !== undefined) return plain;\n if (ZONE_LESS_TEXT.test(value)) {\n const iso = value.includes(\" \") ? `${value.replace(\" \", \"T\").replace(/(\\.\\d{3})\\d+$/, \"$1\")}Z` : value;\n const parsed = new Date(iso);\n if (!Number.isNaN(parsed.getTime())) return parsed;\n }\n return parseExtendedDateTimeText({ text: value }) ?? driverTypeParser(TIMESTAMP_OID, \"text\")(value);\n}\n\n/** The array forms: the driver's `_text` parser splits the literal, elements go through {@link parseZoneLessAsUtc}. */\nfunction parseZoneLessArrayAsUtc(value: string): unknown {\n const mapElements = (element: unknown): unknown => {\n if (element === null) return null;\n if (Array.isArray(element)) return element.map(mapElements);\n return parseZoneLessAsUtc(String(element));\n };\n return mapElements(driverTypeParser(TEXT_ARRAY_OID, \"text\")(value));\n}\n\n/** pg-types' array splitter (`arrayParser.create(source, transform).parse()`); `@types/pg` types it as a plain function. */\ntype PgTypesArrayParser = {\n readonly create: (source: string, transform: (entry: string | null) => unknown) => { readonly parse: () => unknown };\n};\n\nconst pgTypesArrayParser: PgTypesArrayParser | undefined = (() => {\n const candidate = (pg.types as unknown as { readonly arrayParser?: Partial<PgTypesArrayParser> }).arrayParser;\n return typeof candidate?.create === \"function\" ? (candidate as PgTypesArrayParser) : undefined;\n})();\n\n/**\n * pg-types' OWN text parser for `oid`, recognised once at load: pg-types\n * registers one function (`name`) for the oid and its date-typed `peers`. An\n * application that registered its own global parser for the oid keeps it —\n * {@link EXACT_TYPES} hands out the char-code parser only while the driver's\n * registered parser is still this built-in one. `undefined` when it cannot be\n * recognised (an override before load, a renamed build): today's path then.\n */\nfunction recogniseBuiltinParser(params: { oid: number; peers: readonly number[]; name: string }): ((value: string) => unknown) | undefined {\n const parser = driverTypeParser(params.oid, \"text\");\n return parser.name === params.name && params.peers.every((peer) => driverTypeParser(peer, \"text\") === parser) ? parser : undefined;\n}\n\nconst BUILTIN_TIMESTAMPTZ_PARSER: ((value: string) => unknown) | undefined = recogniseBuiltinParser({\n oid: TIMESTAMPTZ_OID,\n peers: [TIMESTAMP_OID, DATE_OID],\n name: \"parseDate\",\n});\nconst BUILTIN_TIMESTAMPTZ_ARRAY_PARSER: ((value: string) => unknown) | undefined =\n pgTypesArrayParser === undefined || BUILTIN_TIMESTAMPTZ_PARSER === undefined\n ? undefined\n : recogniseBuiltinParser({ oid: TIMESTAMPTZ_ARRAY_OID, peers: [TIMESTAMP_ARRAY_OID, DATE_ARRAY_OID], name: \"parseDateArray\" });\n\n/**\n * `timestamptz` (AW-03): the plain wire form by char codes, anything else\n * (infinity, BC, years before 1000, seconds offsets) through pg-types' own\n * parser — the one this replaces, so every instant is unchanged.\n */\nfunction parseTimestamptzText(value: string): unknown {\n return parsePlainTimestampText({ text: value, zoned: true }) ?? (BUILTIN_TIMESTAMPTZ_PARSER as (value: string) => unknown)(value);\n}\n\n/** `timestamptz[]`: pg-types' `parseDateArray` with {@link parseTimestamptzText} per element. */\nfunction parseTimestamptzArrayText(value: string): unknown {\n if (!value) return null;\n return (pgTypesArrayParser as PgTypesArrayParser).create(value, (entry) => (entry !== null ? parseTimestamptzText(entry) : entry)).parse();\n}\n\n/**\n * Query-local type parsers that keep `numeric[]` EXACT and read zone-less\n * timestamps as UTC.\n *\n * pg-types decodes `_numeric` with `parseFloat` per element, so\n * `9007199254740993` comes back as `9007199254740992` and `12.340` as the\n * number `12.34` — while the SCALAR `numeric` correctly stays a string and\n * VibeORM's Decimal contract is \"string in, string out\" on every dialect. The\n * array is the anomaly, and the loss happens inside the driver, before any\n * codec can see the value.\n *\n * The fix reuses the driver's OWN array-literal parser (`_text`), so array\n * syntax, quoting and NULL elements stay node-postgres' business; only the\n * per-element float conversion is dropped. It is attached PER QUERY (F12's\n * acceptance criterion), never by mutating `pg.types` globally: an injected\n * pool is shared property, and a global override would silently change every\n * other consumer in the process. The zone-less parsers ride the same hook for\n * the same reason.\n */\nconst EXACT_TYPES: PgTypeParsers = {\n getTypeParser(oid: number, format?: \"text\" | \"binary\"): (value: string) => unknown {\n if (format === undefined || format === \"text\") {\n if (oid === NUMERIC_ARRAY_OID) return driverTypeParser(TEXT_ARRAY_OID, \"text\");\n if (oid === TIMESTAMP_OID || oid === DATE_OID) return parseZoneLessAsUtc;\n if (oid === TIMESTAMP_ARRAY_OID || oid === DATE_ARRAY_OID) return parseZoneLessArrayAsUtc;\n if (oid === TIMESTAMPTZ_OID) {\n const driver = driverTypeParser(oid, \"text\");\n return driver === BUILTIN_TIMESTAMPTZ_PARSER ? parseTimestamptzText : driver;\n }\n if (oid === TIMESTAMPTZ_ARRAY_OID) {\n const driver = driverTypeParser(oid, \"text\");\n return driver === BUILTIN_TIMESTAMPTZ_ARRAY_PARSER ? parseTimestamptzArrayText : driver;\n }\n }\n return driverTypeParser(oid, format);\n },\n};\n\n/**\n * The one address this adapter will ever use, taken at construction: an\n * injected pool (it wins, as documented) or a non-empty connection string,\n * with libpq's `sslrootcert=system` rewritten for node-postgres\n * ({@link honourSystemRootCert}). Nothing is read from the environment, and\n * nothing is re-read later.\n *\n * @throws VibeError `VIBE_CONFIG` (`meta.reason: \"missing-address\"`) when\n * neither is present, or `\"sslrootcert-system-weak-sslmode\"`. The message\n * never echoes the URL.\n */\nfunction takeAddress(params: { options: PgAdapterOptions | undefined }): { pool: PgPoolLike } | { connectionString: string } {\n const options: PgAdapterSettings | undefined = params.options;\n if (options?.pool !== undefined && options.pool !== null) return { pool: options.pool };\n const connectionString = options?.connectionString;\n if (typeof connectionString === \"string\" && connectionString.trim() !== \"\") {\n return { connectionString: honourSystemRootCert({ connectionString, option: \"connectionString\" }) };\n }\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message:\n \"pgAdapter needs an explicit address: pass `connectionString` (a PostgreSQL URL) or an existing `pool`. \" +\n \"The adapter does not read DATABASE_URL or the PG* environment variables.\",\n meta: { adapter: \"pg\", reason: \"missing-address\" },\n });\n}\n\n/**\n * Round-trip follow-up lane E (`DatabaseAdapter.oneRoundTripTransactions`):\n * whether every client `address` hands out can run a transaction opened without\n * options in one round trip — BEGIN deferred, `orderedPipeline`, `withCommit`.\n * Per client that holds when it batches (`supportsBatch`) and has no local\n * `query_timeout` (see the transaction's `ordered` / `commits`). Read here from\n * the same sources node-postgres' `ConnectionParameters` reads, at\n * construction: the driver exports `prepareValue`; the pool config is not in\n * pipeline mode; `query_timeout` from the connection string's query parameters\n * (they override the config), else from the config, else `pg.defaults`. A\n * connection string that is no URL, or a client changed later (a `connect`\n * listener, `pg.defaults` set afterwards), is not seen: the declaration is\n * performance-only and the runtime still checks every transaction handle.\n */\nfunction transactionsTakeOneRoundTrip(params: { address: { pool: PgPoolLike } | { connectionString: string } }): boolean {\n const { address } = params;\n if (!batchDriverAvailable()) return false;\n const config: Record<string, unknown> = \"pool\" in address\n ? ((address.pool as { readonly options?: Record<string, unknown> }).options ?? {})\n : { connectionString: address.connectionString };\n if (config.pipeline === true) return false;\n let timeout: unknown = config.query_timeout;\n const connectionString = config.connectionString;\n if (typeof connectionString === \"string\") {\n if (!URL.canParse(connectionString)) return false;\n const fromUrl = new URL(connectionString).searchParams.get(\"query_timeout\");\n if (fromUrl !== null) timeout = fromUrl;\n }\n // node-postgres: `config[key] || defaults[key]`.\n timeout ||= (pg.defaults as { readonly query_timeout?: unknown }).query_timeout;\n return !(Number(timeout ?? 0) > 0);\n}\n\n/**\n * Create a VibeORM adapter backed by node-postgres.\n *\n * Requires an explicit address (`connectionString` or `pool`); see\n * {@link PgAdapterOptions}. Construction opens nothing — the pool is created\n * on first use.\n *\n * @example\n * ```ts\n * const adapter = pgAdapter({ connectionString: \"postgresql://app:secret@db.internal:5432/app\", max: 20 });\n * await adapter.connect();\n * const rows = await adapter.execute({ text: 'SELECT * FROM \"User\" WHERE \"id\" = $1', values: [1] });\n * ```\n *\n * @example Reusing a pool you already own\n * ```ts\n * import pg from \"pg\";\n * const pool = new pg.Pool({ connectionString });\n * const adapter = pgAdapter({ pool });\n * ```\n */\nexport function pgAdapter(options: PgAdapterOptions): DatabaseAdapter {\n const address = takeAddress({ options });\n const cancellationAddress = options.cancellationConnectionString !== undefined\n ? honourSystemRootCert({ connectionString: options.cancellationConnectionString, option: \"cancellationConnectionString\" })\n : (\"connectionString\" in address ? address.connectionString : undefined);\n const readCancellation: NonNullable<DatabaseAdapter[\"readCancellation\"]> = cancellationAddress === undefined ? \"before-dispatch\" : \"running\";\n const usePrepared = options?.preparedStatements ?? false;\n const stmtCacheMax = options?.stmtCacheMax ?? 1000;\n const planCacheMode = options?.planCacheMode === undefined ? \"auto\" : assertPlanCacheMode({ value: options.planCacheMode });\n // AW-04: only an owned pool consumes this setting; an injected pool keeps its own configuration.\n const idleTimeout = \"pool\" in address || options?.idleTimeout === undefined ? undefined : assertIdleTimeout({ value: options.idleTimeout });\n // V7: refused next to an injected pool, unlike `idleTimeout` — ignoring it\n // would leave the caller with the cold pool `min` exists to avoid.\n if (options?.min !== undefined && \"pool\" in address) {\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message: \"pgAdapter `min` configures the pool the adapter builds — it cannot be applied to a caller-supplied `pool`; set `min` (and `idleTimeoutMillis`) on that pool instead\",\n meta: { adapter: \"pg\", reason: \"pool-min-with-injected-pool\", option: \"min\" },\n });\n }\n const poolMin = options?.min === undefined ? undefined : assertPoolMin({ value: options.min, max: options.max ?? 10 });\n if (planCacheMode !== \"auto\" && \"pool\" in address) {\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message:\n \"planCacheMode configures the pool the adapter builds — it cannot be applied to a caller-supplied `pool`; \" +\n \"set `options: \\\"-c plan_cache_mode=…\\\"` on that pool instead\",\n meta: { planCacheMode },\n });\n }\n\n let pool: PgPoolLike | null = null;\n let ownsPool = false;\n\n /**\n * The checked-out client of an OPEN raw transaction — session affinity for\n * the raw path. @vibeorm/migrate wraps transactional DDL in literal `BEGIN`\n * / `COMMIT` / `ROLLBACK` sent through `executeUnsafe`; without pinning,\n * `pool.query(\"BEGIN\")` sequences stay on one client only by LIFO checkout\n * luck, and any concurrent traffic silently splits the transaction across\n * connections. A pure `BEGIN` checks a client out, every raw statement until\n * the matching `COMMIT`/`ROLLBACK` rides it, and the close releases it. The\n * ORM path (`execute`) and `transaction()` stay on the pool. Concurrent raw\n * transactions on one adapter are unsupported.\n */\n let rawSession: PgPoolClientLike | null = null;\n /** Detach for {@link rawSession}'s background-error guard; runs before its release. */\n let rawSessionUnguard: (() => void) | null = null;\n /**\n * Set once a checked-out client lacked {@link hasReadyForQuerySeam}: the\n * pool hands out wrappers, so root ORM statements keep running through the\n * pool's own `query()` — the path (and the guard) they had before round-trip\n * EPIC 3 (fix lane FX-A, RV2 MJ-3 / MN-6c).\n */\n let rootViaPoolQuery = false;\n\n function getPool(): PgPoolLike {\n if (pool !== null) return pool;\n\n if (\"pool\" in address) {\n pool = address.pool;\n ownsPool = false;\n return pool;\n }\n\n const config = buildPoolConfig({\n connectionString: address.connectionString,\n max: options?.max ?? 10,\n ...(poolMin === undefined ? {} : { min: poolMin }),\n ...(options?.statementTimeout === undefined ? {} : { statementTimeout: options.statementTimeout }),\n ...(options?.connectionTimeout === undefined ? {} : { connectionTimeout: options.connectionTimeout }),\n ...(idleTimeout === undefined ? {} : { idleTimeout }),\n planCacheMode,\n });\n\n const PoolCtor = pg.Pool as unknown as new (poolConfig: Record<string, unknown>) => PgPoolLike;\n pool = new PoolCtor(config);\n /**\n * The IDLE half of the same hazard {@link guardBackgroundErrors} covers: a\n * pooled client that loses its socket while idle makes pg re-emit on the\n * POOL, and an unhandled `'error'` there is equally fatal. The pool already\n * evicts that client, so this listener only keeps the process alive.\n *\n * Attached ONLY to a pool this adapter constructed. A caller-supplied pool\n * (the `pool` option) has its own owner: the adapter never ends it either,\n * node-postgres documents attaching an `'error'` listener as that owner's\n * job, and registering one here that is never removed would stack up a\n * listener per adapter sharing that pool. The dangerous case — a client\n * checked out for a transaction or a raw session, which pg leaves\n * unlistened by construction — is guarded in BOTH modes.\n */\n pool.on?.(\"error\", () => {\n /* the pool has already discarded the failed client */\n });\n ownsPool = true;\n return pool;\n }\n\n /**\n * Prepared-statement names for the pool this adapter runs on (F18): the\n * registry is keyed by the POOL, so two adapters sharing one pool share one\n * name budget and do not prepare the same text twice (names themselves are\n * content hashes of the text, equal in every registry — `statementNameFor`).\n * It also bounds how many names that pool can ever put on a backend (F16) no\n * matter how many adapters come and go over it.\n */\n function statementNamesFor(params: { pool: PgPoolLike }): StatementNameCache {\n const existing = POOL_STATEMENT_NAMES.get(params.pool);\n if (existing !== undefined) return existing;\n const created = createStatementNameCache({ max: stmtCacheMax });\n POOL_STATEMENT_NAMES.set(params.pool, created);\n return created;\n }\n\n /** Build the config for one ORM-path query (statement name only when enabled). */\n function buildQueryConfig(params: { text: string; values: unknown[] }): PgQueryConfig {\n const values = serializeParams({ values: params.values });\n if (!usePrepared) return { text: params.text, values, types: EXACT_TYPES };\n // `undefined` on a text's first sighting and once the pool's name budget is\n // spent: the statement runs unnamed rather than growing the server's\n // prepared-statement retention.\n const name = statementNamesFor({ pool: getPool() }).getName({ text: params.text });\n return name === undefined\n ? { text: params.text, values, types: EXACT_TYPES }\n : { name, text: params.text, values, types: EXACT_TYPES };\n }\n\n function observeResult(params: { scope?: SavepointScope; effect?: StatementEffect; result: PgQueryResultsLike }): void {\n if (params.scope === undefined) return;\n const results = Array.isArray(params.result) ? params.result : [params.result];\n if (results.length === 0) observeRowChanges({ scope: params.scope, count: statementRowChanges({ effect: params.effect }) });\n for (const result of results) observeRowChanges({ scope: params.scope, count: statementRowChanges({ effect: params.effect, count: result.rowCount, rows: result.rows?.length, resultRows: result.rows }) });\n }\n\n async function runExecute(params: {\n queryable: Queryable;\n text: string;\n values: unknown[];\n scope?: SavepointScope;\n effect?: StatementEffect;\n }): Promise<Record<string, unknown>[]> {\n const config = buildQueryConfig({ text: params.text, values: params.values });\n const result = await runMapped(() => params.queryable.query(config));\n observeResult({ scope: params.scope, effect: params.effect, result });\n return finalResult({ result }).rows;\n }\n\n async function runExecuteUnsafe(params: {\n queryable: Queryable;\n text: string;\n values?: unknown[];\n scope?: SavepointScope;\n effect?: StatementEffect;\n }): Promise<QueryResult> {\n const values = params.values === undefined ? undefined : serializeParamsRaw({ values: params.values });\n const result = await runMapped(() => params.queryable.query({ text: params.text, values, types: EXACT_TYPES }));\n observeResult({ scope: params.scope, effect: params.effect, result });\n const final = finalResult({ result });\n return { rows: final.rows, affectedRows: final.rowCount ?? 0 };\n }\n\n /**\n * Adapter bound to one checked-out client that is already inside a\n * transaction. Nested `transaction()` calls open savepoints on that same\n * client, and their LIFETIMES are serialized by the savepoint gate (F14):\n * overlapping siblings share one savepoint stack, so the earlier one's\n * rollback would erase the later one's already released work.\n */\n function createClientAdapter(params: {\n dispatch: TransactionDispatch;\n scope: SavepointScope;\n budget: TransactionBudget;\n /** Pending control of this transaction; `null` when the client cannot batch (nothing is deferred). */\n deferred: DeferredControl | null;\n cancellation: PgReadCancellation;\n /** This transaction's `$all` pipeline; `null` when the client cannot batch (no lanes are offered). */\n pipelines: PipelineControl | null;\n /** The pipeline lane this handle belongs to; nested handles inherit it. */\n lane?: PipelineLaneState;\n /**\n * This handle offers ordered scopes (`orderedPipeline`, EPIC D): the\n * top-level handle of a transaction without a `deadline` (a `timeout` is\n * fine, V2), and the savepoint handles it opens outside a pipeline lane (a\n * nested array `$transaction`, performance audit round 2, C-03).\n */\n ordered?: boolean;\n /** The checked-out `PoolClient`: this transaction's `connectionIdentity` (statement-count pass EPIC 1). */\n connection: object;\n /** The top-level handle: it alone offers `deferStatement` (EPIC 2). */\n topLevel?: boolean;\n /**\n * This transaction can ride COMMIT behind its last statement (EPIC 5): the\n * handle offers `withCommit` when it sits at savepoint depth 0 (the\n * top-level handle and its pipeline lanes, never a savepoint handle).\n */\n commits?: boolean;\n /** This handle is a `withCommit` view: its first statement carries COMMIT, a second is refused. */\n final?: { used: boolean; readonly discardRows?: boolean };\n }): DatabaseAdapter {\n const { dispatch, scope, budget, deferred, cancellation, pipelines, lane, connection, final } = params;\n const laneOf = lane === undefined ? {} : { lane };\n /** EPIC 5: the COMMIT flag of a view's ONE statement; checked when the statement is dispatched, before anything is sent. */\n const finalOf = (): { commit?: true; discardRows?: true } => {\n if (final === undefined) return {};\n if (final.used) throw finalStatementMisuse();\n final.used = true;\n return { commit: true, ...(final.discardRows === true ? { discardRows: true as const } : {}) };\n };\n // A wait a lane spends inside the adapter counts as waiting, so the\n // pipeline never holds its siblings' statements for it.\n const waitAsLane = <T>(wait: Promise<T>): Promise<T> =>\n lane === undefined || pipelines === null ? wait : pipelines.waitAs({ lane, wait });\n // ORM statements are always ONE statement; raw text is one when it binds\n // values (node-postgres then uses the extended protocol itself) or when it\n // provably is one (C-01: a framework's `SELECT set_config(…)` rides with BEGIN).\n const rawClient: Queryable = {\n query: (config) => dispatch({ config, batchable: (config.values?.length ?? 0) > 0 || isSingleStatementText({ text: config.text }), ...laneOf, ...finalOf() }),\n };\n // EPIC 6: SAVEPOINT rides with the body's first statement; a body that\n // sent nothing sends neither its RELEASE nor its ROLLBACK TO.\n const savepointControl = (statement: string, cleanup: boolean): Promise<unknown> | undefined => {\n if (deferred !== null && deferred.routeSavepoint({ text: statement, cleanup }) !== \"send\") return undefined;\n return runMapped(() => dispatch({\n config: { text: statement },\n stage: \"nested\",\n batchable: true,\n ...(cleanup ? { cleanup: true } : {}),\n ...laneOf,\n }));\n };\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n budgets: BUDGETS,\n readCancellation: cancellation.support,\n roundTrips: ROUND_TRIPS,\n readSnapshot: READ_SNAPSHOT,\n pipelining: pipelines === null ? \"ordered\" : PIPELINING,\n connectionIdentity: connection,\n // EPIC 2: a bound statement nobody reads (the native-RLS claims) waits with\n // the deferred opening and rides with the next statement. Serialized now:\n // a value the driver refuses throws here and nothing is queued.\n ...(params.topLevel !== true || deferred === null ? {} : {\n deferStatement: (statement: { readonly text: string; readonly values: readonly unknown[] }): void => {\n budget.assertUsable({ stage: \"statement\" });\n deferred.defer({ text: statement.text, values: prepareBatchValues({ values: statement.values }) });\n },\n }),\n // EPIC 5: a view for the transaction's last statement — COMMIT rides behind it.\n ...(params.commits !== true || deferred === null || scope.depth !== 0 || final !== undefined ? {} : {\n withCommit: (options?: { readonly rows?: \"discard\" }): DatabaseAdapter => createClientAdapter({\n dispatch, scope, budget, deferred, cancellation, pipelines, ...laneOf, connection,\n final: { used: false, ...(options?.rows === \"discard\" ? { discardRows: true } : {}) },\n }),\n }),\n ...(pipelines === null ? {} : {\n ...(params.ordered === true ? { orderedPipeline: true as const } : {}),\n pipeline: ({ lanes: count, ordered }: { lanes: number; ordered?: true }): readonly PipelineLane[] => {\n budget.assertUsable({ stage: \"statement\" });\n // D2 (review D2-05): a sub-lane, or a lane whose group is open, opens no lanes — a nested lane in\n // the flat lane set would hold the group's batch while its owner awaits it (OP-11).\n if (lane?.seat !== undefined) throw laneGroupMisuse({ message: \"a sub-lane opens no pipeline scope\" });\n if (lane?.group !== undefined) throw laneGroupMisuse({ message: \"a lane opens no pipeline scope while its group is open\" });\n if (!Number.isSafeInteger(count) || count < 1) {\n throw new VibeError({ code: \"VIBE_VALIDATION\", message: \"pipeline() needs a positive whole number of lanes\", meta: { lanes: count } });\n }\n if (ordered === true && params.ordered !== true) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: \"pipeline({ ordered: true }) is offered only on a handle that declares orderedPipeline (the top-level or a savepoint handle of a transaction without a deadline, outside a pipeline lane)\",\n meta: { ordered: true, reason: \"ordered-pipeline-undeclared\" },\n });\n }\n const laneHandle = (opened: PipelineLaneState): PipelineLane => ({\n adapter: createClientAdapter({ dispatch, scope, budget, deferred, cancellation, pipelines, lane: opened, connection, ...(params.commits === true && opened.seat === undefined ? { commits: true } : {}) }),\n close: (): void => { pipelines.close(opened); },\n ...(opened.order === undefined ? {} : {\n follow: (): PipelineLane => {\n budget.assertUsable({ stage: \"statement\" });\n return laneHandle(pipelines.follow(opened));\n },\n }),\n // D2: a lane of an unordered scope opened on a handle that is no lane itself.\n ...(opened.order !== undefined || opened.seat !== undefined || lane !== undefined ? {} : {\n group: (options?: { readonly final?: true }): PipelineGroup | undefined => {\n // No budget check here: a handle that refuses statements refuses no group —\n // the caller's next statement raises today's refusal.\n // Lane A2: `final` counts only where this handle's lanes can carry COMMIT (`commits`).\n const opening = pipelines.group(opened, options?.final === true && params.commits === true);\n if (opening === undefined) return undefined;\n return {\n lane: (): PipelineLane => laneHandle(pipelines.seat(opening)),\n seal: (): void => { pipelines.seal(opening); },\n };\n },\n }),\n });\n return (ordered === true ? pipelines.openOrdered(count) : pipelines.open(count)).map(laneHandle);\n },\n }),\n rowChanges: (): RowChangeCount => { budget.assertUsable({ stage: \"statement\" }); return readRowChanges({ scope }); },\n\n async execute(execParams) {\n return runReadExecution({ ...execParams, support: cancellation.support, provider: PROVIDER, run: async () => {\n const turn = scopeTurn({ scope });\n if (turn !== undefined) await waitAsLane(turn);\n // After the turn, not before: waiting for a sibling savepoint spends\n // the same budget the statement is about to run against.\n budget.assertUsable({ stage: \"statement\" });\n assertReadExecution({ ...execParams, support: cancellation.support, provider: PROVIDER, stage: \"waiting-for-connection\" });\n // A server-reported failure aborts a postgres transaction: record it so\n // a callback that swallows it cannot commit nothing.\n const queryable: Queryable = { query: (config) => dispatch({ config, batchable: execParams.execution?.cancellation !== \"running\", execution: execParams.execution, onReadControl: execParams.onReadControl, ...laneOf, ...finalOf() }) };\n return runExecute({ queryable, scope, ...execParams })\n .catch((error: unknown) => abortTransactionOnServerFailure({ scope, error }));\n } });\n },\n\n async executeUnsafe(execParams) {\n const turn = scopeTurn({ scope });\n if (turn !== undefined) await waitAsLane(turn);\n budget.assertUsable({ stage: \"statement\" });\n return runExecuteUnsafe({ queryable: rawClient, scope, ...execParams })\n .catch((error: unknown) => abortTransactionOnServerFailure({ scope, error }));\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n nestedOptions?: TransactionOptions,\n ): Promise<T> {\n refuseNestedTransactionOptions({ options: nestedOptions, provider: PROVIDER });\n budget.assertUsable({ stage: \"nested\" });\n // D2: a lane whose group is open issues nothing — not even a SAVEPOINT (checked before the flush below).\n if (lane?.group !== undefined) throw laneGroupMisuse({ message: \"a lane opens no savepoint while its group is open\" });\n // Review D2-05: nor a sub-lane — the flush below would send its group's statements before the group is sealed.\n if (lane?.seat !== undefined) throw laneGroupMisuse({ message: \"a sub-lane opens no savepoint\" });\n // Lane statements queued before this savepoint go out in front of it,\n // as they would have without the pipeline.\n pipelines?.flush();\n // A lane waiting for its savepoint turn counts as waiting until its body starts.\n const leave = lane === undefined || pipelines === null ? ignore : pipelines.enter(lane);\n return runNestedSavepoint({\n scope,\n execute: (statement) => savepointControl(statement, false),\n cleanup: (statement: string) => savepointControl(statement, true),\n // The child shares the ROOT budget by reference: a savepoint never\n // gets an independent clock or session setting.\n body: (child) => {\n leave();\n // C-03: a savepoint handle outside a lane offers ordered scopes too,\n // so a nested array `$transaction` bursts like a top-level one.\n const ordered = lane === undefined && params.ordered === true ? { ordered: true } : {};\n return fn(createClientAdapter({ dispatch, scope: child, budget, deferred, cancellation, pipelines, connection, ...laneOf, ...ordered }));\n },\n }).finally(leave);\n },\n\n // The open transaction owns this connection: neither call may act on it.\n // An expired handle keeps its own refusal (the budget check comes first).\n async connect(): Promise<void> {\n budget.assertUsable({ stage: \"statement\" });\n throw transactionLifecycleRefusal({ method: \"connect\" });\n },\n\n async disconnect(): Promise<void> {\n budget.assertUsable({ stage: \"statement\" });\n throw transactionLifecycleRefusal({ method: \"disconnect\" });\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return new PgArrayParam(values);\n },\n };\n }\n\n /**\n * Final cleanup, run ONCE by the lifecycle gate after every admitted\n * operation settled — so a raw BEGIN that was still pending at the\n * `disconnect()` call has published its session by now. Rolls back and\n * releases an abandoned raw session (destroyed when the rollback failed),\n * then ends the pool the adapter created. An injected pool is never ended.\n */\n function closeOwnedResources(): Promise<void> {\n return runShutdownCleanup({\n steps: [\n async (): Promise<void> => {\n if (rawSession === null) return;\n const session = rawSession;\n const unguard = rawSessionUnguard;\n rawSession = null;\n rawSessionUnguard = null;\n // An abandoned raw checkout is reusable only after a successful rollback.\n await runMapped(() => session.query({ text: \"ROLLBACK\" })).then(\n () => { unguard?.(); session.release(); },\n (error: unknown) => { unguard?.(); session.release(true); throw error; },\n );\n },\n async (): Promise<void> => {\n if (pool === null || !ownsPool) return;\n const closing = pool;\n await runMapped(() => closing.end());\n },\n ],\n });\n }\n\n const lifecycle = createAdapterLifecycleGate({ driver: \"pg\", cleanup: closeOwnedResources });\n\n /** The root operations; the adapter below admits each one through {@link lifecycle}. */\n const root: Pick<Required<DatabaseAdapter>, \"withSession\" | \"execute\" | \"executeUnsafe\" | \"transaction\" | \"connect\"> = {\n async withSession({ run }) {\n const client = await runMapped(() => getPool().connect());\n let backgroundFailure: unknown;\n const onError = (error: unknown): void => { backgroundFailure = error; };\n client.on?.(\"error\", onError);\n return runPinnedSession({\n run,\n execute: async (query) => {\n if (backgroundFailure !== undefined) throw mapPgDriverError({ error: backgroundFailure });\n return (await runExecuteUnsafe({ queryable: client, ...query })).rows;\n },\n isLost: (error) => backgroundFailure !== undefined || isConnectionLoss({ error }),\n release: async () => {\n client.removeListener?.(\"error\", onError);\n // Migration SQL may change arbitrary session state. Never pool it.\n client.release(true);\n },\n });\n },\n\n async execute(params) {\n assertReadExecution({ ...params, support: readCancellation, provider: PROVIDER });\n if (params.execution?.cancellation === \"running\") {\n // READ ONLY pins a backend even behind a transaction-mode pooler.\n // Transaction lifecycle stays outside the individual read receipt.\n const options = { accessMode: \"readOnly\" as const };\n return root.transaction((tx) => tx.execute(params), options);\n }\n // Round-trip EPIC 3 (A-12): own checkout instead of `pool.query`, so an\n // ordinary error can keep a session proven idle (see observeReadyForQuery).\n const config = buildQueryConfig({ text: params.text, values: params.values });\n const rootPool = getPool();\n if (!rootViaPoolQuery) {\n const client = await runMapped(() => rootPool.connect());\n if (hasReadyForQuerySeam({ client }) || params.execution !== undefined) {\n const seam = hasReadyForQuerySeam({ client }) ? observeReadyForQuery({ client }) : undefined;\n let reuse = false;\n try {\n assertReadExecution({ ...params, provider: PROVIDER, stage: \"waiting-for-connection\" });\n const result = await runMapped(() => client.query(config));\n reuse = true;\n return finalResult({ result }).rows;\n } catch (error) {\n reuse = await seam?.reusableAfter({ error, named: config.name !== undefined }) ?? false;\n throw error;\n } finally {\n seam?.detach();\n client.release(!reuse);\n }\n }\n // A client without the seam: hand it back unused and keep today's path.\n client.release();\n rootViaPoolQuery = true;\n }\n assertReadExecution({ ...params, provider: PROVIDER, stage: \"waiting-for-connection\" });\n return finalResult({ result: await runMapped(() => rootPool.query(config)) }).rows;\n },\n\n async executeUnsafe(params) {\n const control = classifyRawTransactionControl({ text: params.text });\n if (rawSession !== null) {\n if (control === \"close\") {\n const session = rawSession;\n const unguard = rawSessionUnguard;\n rawSession = null;\n rawSessionUnguard = null;\n try {\n return await runExecuteUnsafe({ queryable: session, ...params });\n } finally {\n unguard?.();\n session.release();\n }\n }\n // A nested raw BEGIN lands here too — postgres treats it as a warning\n // no-op on the open session, exactly like a single connection would.\n return runExecuteUnsafe({ queryable: rawSession, ...params });\n }\n if (control === \"open\") {\n const client = await runMapped(() => getPool().connect());\n const unguard = guardBackgroundErrors({ client });\n try {\n const result = await runExecuteUnsafe({ queryable: client, ...params });\n rawSession = client;\n rawSessionUnguard = unguard;\n return result;\n } catch (error) {\n unguard();\n client.release();\n throw error;\n }\n }\n return runExecuteUnsafe({ queryable: getPool(), ...params });\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n // Refuse an unsupportable budget BEFORE checking a connection out, so a\n // bad option never costs a checkout and never leaves a transaction open.\n validateTransactionDeadline({\n options: transactionOptions,\n support: BUDGETS.transactionDeadline,\n provider: PROVIDER,\n settings: \"transaction-local\",\n });\n // Round-trip EPIC 3 (A-02): BEGIN [… READ ONLY] and the timeout's SET as\n // ONE message. Built (and the timeout validated) before the checkout.\n const openingOptions = {\n isolationLevel: transactionOptions?.isolationLevel,\n readOnly: readOnlyRequested({ options: transactionOptions, provider: PROVIDER }),\n timeout: transactionOptions?.timeout,\n };\n const openText = openTransactionStatement(openingOptions);\n // TU-02: transaction settings, validated and rendered before the checkout\n // (an invalid name or value never costs a connection). None = today's path.\n const settings = readTransactionSettings({ settings: transactionOptions?.settings, provider: PROVIDER });\n const settingsStatement = settings.length === 0 ? undefined : renderTransactionSettings({ settings });\n const client = await runMapped(() => getPool().connect());\n /**\n * pg@9 (./client-turns.ts): every query this transaction sends on\n * `client` — statements, batches, control, the read-cancellation\n * preflight — takes a turn, so node-postgres never receives a query while\n * it still runs one. Same order as the driver's own queue gave.\n */\n const turns = createClientTurns();\n /** V4: the gathering group that still takes statements, or `null` (see {@link GatheringGroup}). */\n let gathering: GatheringGroup | null = null;\n /** V4: gathering groups not sent yet; while one waits, a server failure is recorded the moment a reply shows it. */\n let gatheringsPending = 0;\n /** Every call of this transaction takes its turn here: a call queued behind an open gathering group closes it. */\n const runTurn = <T>(send: () => Promise<T>): Promise<T> => {\n gathering = null;\n return turns.run(send);\n };\n const onClient: Pick<PgPoolClientLike, \"query\" | \"pipeline\" | \"connectionParameters\"> = {\n query: (config) => runTurn(() => client.query(config)),\n get pipeline() { return client.pipeline; },\n get connectionParameters() { return client.connectionParameters; },\n };\n /**\n * The connection failure node-postgres reported on this client while the\n * transaction held it (EPIC T review, finding 1). node-postgres marks the\n * client unqueryable in the same handler that emits `error`, and from\n * then on refuses every query locally, without writing it: a COMMIT\n * after this point never leaves the client.\n */\n let connectionFailure: { readonly cause: unknown } | undefined;\n const unguard = guardBackgroundErrors({\n client,\n onError: (cause) => {\n if (connectionFailure === undefined) connectionFailure = { cause };\n },\n });\n const scope = createSavepointScope();\n // The deadline clock starts HERE: the connection is already in hand, so\n // acquisition (bounded separately by `connectionTimeout`) is not charged\n // against the caller's transaction budget.\n const budget = startTransactionBudget({ options: transactionOptions, provider: PROVIDER });\n // Round-trip EPIC 6 (pipelining): on a client that can run a one-Sync\n // batch, the opening, every SAVEPOINT and the deadline's SET LOCAL wait\n // here and ride IN FRONT OF the next statement — one wait for all of\n // them. A transaction whose callback sends nothing sends nothing. The\n // opening is sent eagerly (EPIC 3's one message) only when a `timeout`\n // beyond PostgreSQL's int4 ceiling could make its SET fail: that error\n // keeps surfacing before the callback runs, as today.\n const capable = supportsBatch({ client });\n // With settings (TU-02) the opening is never deferred: it must be confirmed\n // before the callback runs (see `openWithSettings`) — unless the caller\n // opted in to `deferSettings` (lane Y): then the bound settings statement\n // waits with the opening and rides in front of the first statement.\n const deferOpening = (settingsStatement === undefined || transactionOptions?.deferSettings === true) && capable && (openingOptions.timeout === undefined || openingOptions.timeout <= MAX_STATEMENT_TIMEOUT_MS);\n const opening: readonly string[] = deferOpening\n ? [beginStatement(openingOptions), ...(openingOptions.timeout === undefined ? [] : [statementTimeoutStatement({ timeout: openingOptions.timeout })])]\n : [];\n // EPIC 5: without a deadline a nested call's success-path RELEASE waits\n // here too and rides with the next statement (dropped when COMMIT is\n // next); a deadline keeps refusing at the nested call's own RELEASE.\n const deferred = createDeferredControl({ opening, ...(budget.totalMs === null ? { deferReleases: true as const } : {}) });\n /**\n * Lane Y (`deferSettings`): the settings statement queued right behind the\n * opening texts, so it is opening step `opening.length` of the burst that\n * carries the opening — ahead of the native-RLS claims, which the runtime\n * defers later. Values serialized now (validated strings).\n */\n const settingsDeferred = deferOpening && settingsStatement !== undefined;\n if (settingsDeferred) deferred.defer({ text: settingsStatement.text, values: prepareBatchValues({ values: settingsStatement.values }) });\n /** Steps of the opening in the burst that carries it: the opening texts, then the deferred settings statement. */\n const openingLength = opening.length + (settingsDeferred ? 1 : 0);\n /**\n * The mapped failure of opening step `index`: a server refusal of the\n * deferred settings statement becomes TU-02's `setting-refused` error\n * (`meta.deferred: true`), naming the setting from the diagnostic; any\n * other step (or no server answer) its mapped driver error, as today.\n */\n const openingStepError = (index: number, error: unknown): VibeError => {\n const mapped = mapPgDriverError({ error });\n if (!settingsDeferred || index !== opening.length || typeof mapped.meta.sqlstate !== \"string\") return mapped;\n return transactionSettingRefusedError({ provider: PROVIDER, settings, setting: findRefusedSetting({ settings, cause: mapped }), cause: mapped, deferred: true });\n };\n /** The deferred opening failed (mapped): the server holds no transaction, so nothing more may be sent. */\n let openingFailure: VibeError | undefined;\n /** A burst carrying deferred control that has not settled yet (no deadline); later statements wait for it. */\n let inFlight: Promise<void> | null = null;\n /**\n * EPIC 5 (`withCommit`): COMMIT may ride behind the transaction's last\n * statement on a client that batches, without a deadline (the COMMIT must\n * stay refusable after the last statement), and without a local\n * `query_timeout` (it fails a statement without stopping the COMMIT behind it).\n */\n const commits = capable && budget.totalMs === null && !((client.connectionParameters?.query_timeout ?? 0) > 0);\n /** The COMMIT that rode with the last statement, once its batch was handed to the driver. */\n let ridden: RiddenCommit | undefined;\n /**\n * Ordinary dispatches of this transaction not settled yet (the one being\n * sent included). COMMIT rides only when the last statement is the only\n * one: a statement still waiting to be sent would otherwise follow COMMIT.\n */\n let ordinaryOpen = 0;\n /** Whether a riding COMMIT may leave with the statement being sent now. */\n const ridesNow = (): boolean =>\n commits && ridden === undefined && !cancellationQueue && !cancellationAttempted && connectionFailure === undefined &&\n openingFailure === undefined && scope.state.open === null && scope.state.aborted === null && scope.state.poisoned === null;\n /**\n * Record how far the riding COMMIT got, with the lone COMMIT's rules\n * (EPIC T): no answer, or an error answer of the connection classes\n * (`isConnectionLoss`: SQLSTATE class 08, 57P01-57P03) = unanswered\n * (unknown, discarded); skipped by the server behind a failed statement =\n * never sent; any other error answer or a ROLLBACK tag = answered.\n */\n const settleRidden = (entry: RiddenCommit, outcome: BatchOutcome, commitIndex: number): void => {\n const step = outcome.steps[commitIndex];\n const answeredError = step?.status === \"failed\" ? mapPgDriverError({ error: step.error }) : undefined;\n if (step === undefined || (answeredError !== undefined && isConnectionLoss({ error: answeredError }))) {\n commitProgress = \"unanswered\";\n discard = true;\n budget.close({ outcome: \"unknown\" });\n entry.state = \"lost\";\n entry.error = commitOutcomeUnknownError({ cause: answeredError ?? outcome.transportError ?? firstBatchFailure({ outcome })?.error });\n } else if (step.status === \"skipped\") {\n commitProgress = \"not-sent\";\n entry.state = \"skipped\";\n } else if (step.status === \"failed\" || step.result.command === \"ROLLBACK\") {\n commitProgress = \"answered\";\n entry.state = \"failed\";\n entry.error = answeredError ?? transactionAbortedError({ cause: scope.state.aborted?.cause });\n } else {\n entry.state = \"committed\";\n }\n };\n /** COMMIT rides in `batch` at `commitIndex`: it is sent now (the lone COMMIT's `sent` moment). */\n const trackRidden = (batch: Promise<BatchOutcome>, commitIndex: number): void => {\n commitProgress = \"sent\";\n const entry: RiddenCommit = { settled: Promise.resolve(), state: \"in-flight\" };\n // Registered before the statements' own continuations: the outcome is known when they resume.\n entry.settled = batch.then(\n (outcome) => { settleRidden(entry, outcome, commitIndex); },\n (error: unknown) => { settleRidden(entry, { steps: [], transportError: error }, commitIndex); },\n );\n ridden = entry;\n };\n\n const sendWithControl = (dispatchParams: Parameters<TransactionDispatch>[0]): Promise<PgQueryResultsLike> => {\n const { config, cleanup } = dispatchParams;\n const handOver = (): Promise<PgQueryResultsLike> => {\n assertReadExecution({ execution: dispatchParams.execution, effect: \"read\", support: readCancellation, provider: PROVIDER, stage: \"waiting-for-connection\" });\n dispatchParams.sent?.();\n return cancellation.run({ config, execution: dispatchParams.execution, onReadControl: dispatchParams.onReadControl, send: () => onClient.query(config) });\n };\n if (cleanup !== true && cancellationAttempted) throw transactionAbortedError({ cause: readCancelledError({ stage: \"running\" }) });\n if (cleanup !== true && openingFailure !== undefined) throw transactionAbortedError({ cause: openingFailure });\n if (cleanup !== true && ridden !== undefined) throw commitSentRefusal();\n let bound: string | undefined;\n if (cleanup !== true && budget.totalMs !== null) {\n if (scope.state.poisoned !== null) throw scope.state.poisoned;\n budget.assertUsable({ stage: dispatchParams.stage ?? \"statement\" });\n const ms = engineStatementBudgetMs({ budget });\n if (ms !== null) bound = statementTimeoutStatement({ timeout: ms });\n }\n if (!capable) {\n // Nothing is deferred on this client: today's awaited SET, re-check, statement.\n if (bound === undefined) return handOver();\n const stage = dispatchParams.stage ?? \"statement\";\n return runMapped(() => onClient.query({ text: bound })).then(() => {\n // SET LOCAL itself costs time. Refuse if its round trip exhausted\n // the deadline; no user query may enter pg's queue afterwards.\n budget.assertUsable({ stage });\n return handOver();\n });\n }\n // Nothing to carry: node-postgres sends the statement and serializes\n // its values itself (fix lane FX-A, RV5 MI-7: never twice).\n const pendingControl = cleanup !== true && deferred.hasPending();\n // EPIC 5: the transaction's last statement, ONE statement, and COMMIT can leave with it now.\n const rides = dispatchParams.commit === true && cleanup !== true && dispatchParams.batchable === true && bound === undefined && ordinaryOpen === 1 && ridesNow();\n if (!pendingControl && bound === undefined && !rides) {\n // V4: the client is busy (or a turn group still takes statements) — wait in\n // that group and leave with every statement waiting with it.\n if ((gathering?.phase === \"turn\" || turns.outstanding() > 0) && gathers(dispatchParams) && deferred.opened()) return gatherInTurn(dispatchParams);\n return handOver();\n }\n // Serialize the statement's values BEFORE taking the pending control:\n // a value the driver refuses must leave the control pending, unsent.\n const statement: BatchStep[] = dispatchParams.batchable === true\n ? [{ text: config.text, values: prepareBatchValues({ values: config.values ?? [] }), ...(rides && dispatchParams.discardRows === true ? { discardRows: true as const } : {}) }]\n : [];\n // A read cancelled while it waited refuses BEFORE the pending control is\n // taken, so that control stays pending and leaves with the next statement\n // (review RLS-03: a taken-and-dropped SAVEPOINT, RELEASE or bound step\n // would never be sent).\n assertReadExecution({ execution: dispatchParams.execution, effect: \"read\", support: readCancellation, provider: PROVIDER, stage: \"waiting-for-connection\" });\n const carriesOpening = !deferred.opened();\n // Steps, not texts: a deferred bound statement (EPIC 2 claims) keeps its values.\n const control: BatchStep[] = pendingControl ? [...deferred.takeSteps()] : [];\n if (bound !== undefined) control.push({ text: bound });\n const openingSteps = carriesOpening ? openingLength : 0;\n // A statement that cannot ride (raw text without values that may hold\n // several statements) goes alone, AFTER its control was confirmed:\n // never behind a BEGIN that may fail.\n if (statement.length > 0) dispatchParams.sent?.();\n const commitIndex = control.length + statement.length;\n const batch = runTurn(() => runBatch({ client, steps: [...control, ...statement, ...(rides ? [COMMIT_STEP] : [])], types: EXACT_TYPES }));\n if (rides) trackRidden(batch, commitIndex);\n const burst = batch\n .then((received): PgQueryResultsLike | Promise<PgQueryResultsLike> => {\n const outcome = rides ? beforeCommit({ outcome: received, commitIndex }) : received;\n const failure = firstBatchFailure({ outcome });\n if (failure !== undefined) {\n // A failed control step rejects the statement it rode with — the\n // error today's awaited control step raised before the statement.\n const openingFailed = failure.index < openingSteps || (outcome.transportError !== undefined && openingSteps > 0);\n if (openingFailed) {\n // Mapped, so the refusals it causes carry its code and SQLSTATE.\n openingFailure = openingStepError(failure.index, failure.error);\n }\n if (gatheringsPending > 0) {\n // V4: statements gathered behind this burst read the failure before\n // they are sent — refused, never answered 25P02 by the server.\n const mapped = openingFailed && openingFailure !== undefined ? openingFailure : mapPgDriverError({ error: failure.error });\n if (typeof mapped.meta.sqlstate === \"string\") markTransactionAborted({ scope, cause: mapped });\n }\n // Lane Y: a refused deferred setting rejects the carrying statement with the setting-refused error.\n throw openingFailed && settingsDeferred && failure.index === opening.length && openingFailure !== undefined ? openingFailure : failure.error;\n }\n if (statement.length === 0) return handOver();\n const last = outcome.steps.at(-1);\n return last?.status === \"ok\" ? last.result : { rows: [], rowCount: 0 };\n });\n if (budget.totalMs === null && carriesOpening) {\n // Without a deadline, statements are not serialized here: a statement\n // dispatched while the opening is unconfirmed must wait for it, or a\n // failed BEGIN would let it run in autocommit.\n const settled: Promise<void> = burst.then(ignore, ignore).then(() => {\n if (inFlight === settled) inFlight = null;\n });\n inFlight = settled;\n }\n return burst;\n };\n /** A synchronous refusal becomes the statement's rejection. */\n const guarded = (run: () => Promise<PgQueryResultsLike>): Promise<PgQueryResultsLike> => {\n try {\n return run();\n } catch (error) {\n return Promise.reject(error);\n }\n };\n const send = (dispatchParams: Parameters<TransactionDispatch>[0]): Promise<PgQueryResultsLike> =>\n guarded(() => sendWithControl(dispatchParams));\n // With a deadline, one turn for SET LOCAL + dispatch + completion, shared\n // by every nested handle. Never queue merely the timeout update: pg queues\n // queries itself, which would let concurrent statements spend the same\n // stale budget.\n let tail: Promise<unknown> = Promise.resolve();\n const activeDispatches = new Set<Promise<PgQueryResultsLike>>();\n let cancellationQueue = false;\n\n // ─── `$all` pipeline (see PipelineControl) ───\n // Lane statements wait in `queued` and go out together as ONE one-Sync\n // batch — behind any deferred control, exactly like a statement riding\n // alone — once every open lane is waiting or closed. Only on a client that\n // can batch, without a deadline, outside the strong-cancellation queue,\n // and without a local `query_timeout`: there every statement keeps its own\n // turn (a deadline re-checks the budget and sends a fresh SET LOCAL before\n // EACH statement; a running cancellation must name one statement as its\n // target; node-postgres arms ONE read timer per `client.query()` call, so a\n // batch would share one timer, where `turns` gives each statement its own).\n const lanes = new Set<PipelineLaneState>();\n let queued: QueuedStatement[] = [];\n const settleQueued = (entry: QueuedStatement, outcome: { readonly result: PgQueryResultsLike } | { readonly error: unknown }): void => {\n if (entry.settled) return;\n entry.settled = true;\n // Synchronously, before any continuation runs: the lane is running again.\n entry.lane.waiting -= 1;\n if (\"result\" in outcome) {\n entry.resolve(outcome.result);\n } else {\n entry.failure = outcome.error;\n entry.reject(outcome.error);\n }\n };\n /**\n * Hand each queued statement the outcome sequential dispatch in this\n * transaction would have given it: the first failing statement its mapped\n * error, statements the server skipped after a failure the aborted refusal\n * naming it, statements behind a failed control step (BEGIN, its SET, a\n * SAVEPOINT) that step's error for the first and the refusal for the rest.\n */\n const distributeBurst = (burst: { outcome: BatchOutcome; live: readonly QueuedStatement[]; controlSteps: number; openingSteps: number }): void => {\n const { outcome, live, controlSteps, openingSteps } = burst;\n const failure = firstBatchFailure({ outcome });\n if (failure === undefined) {\n live.forEach((entry, index) => {\n const step = outcome.steps[controlSteps + index];\n settleQueued(entry, { result: step?.status === \"ok\" ? step.result : { rows: [], rowCount: 0 } });\n });\n return;\n }\n const mapped = failure.index < openingSteps ? openingStepError(failure.index, failure.error) : mapPgDriverError({ error: failure.error });\n if (failure.index < openingSteps || (outcome.transportError !== undefined && openingSteps > 0)) openingFailure = mapped;\n // A server failure aborts the transaction: record it NOW (first kept), naming\n // the very error its statement's caller receives, before any sibling resumes.\n if (typeof mapped.meta.sqlstate === \"string\") markTransactionAborted({ scope, cause: mapped });\n const answered = outcome.transportError === undefined;\n if (failure.index < controlSteps) {\n const later = answered || openingFailure !== undefined ? transactionAbortedError({ cause: openingFailure ?? mapped }) : mapped;\n live.forEach((entry, index) => { settleQueued(entry, { error: index === 0 ? mapped : later }); });\n return;\n }\n let abortCause: VibeError = mapped;\n live.forEach((entry, index) => {\n const position = controlSteps + index;\n const step = outcome.steps[position];\n if (step === undefined) {\n // No answer (the connection failed): what the server did is unknown.\n settleQueued(entry, { error: position === failure.index || openingFailure === undefined ? mapped : transactionAbortedError({ cause: openingFailure }) });\n } else if (step.status === \"ok\") {\n settleQueued(entry, { result: step.result });\n } else if (step.status === \"failed\") {\n const error = position === failure.index ? mapped : mapPgDriverError({ error: step.error });\n if (typeof error.meta.sqlstate === \"string\") abortCause = error;\n settleQueued(entry, { error });\n } else {\n settleQueued(entry, { error: transactionAbortedError({ cause: abortCause }) });\n }\n });\n };\n /** The refusal sequential dispatch raises before a statement is sent now, or `undefined`. */\n const sendRefusal = (): unknown => ridden !== undefined\n ? commitSentRefusal()\n : cancellationAttempted\n ? transactionAbortedError({ cause: readCancelledError({ stage: \"running\" }) })\n : openingFailure !== undefined\n ? transactionAbortedError({ cause: openingFailure })\n : scope.state.poisoned ?? (scope.state.aborted === null ? undefined : transactionAbortedError({ cause: scope.state.aborted.cause }));\n /**\n * EPIC 5: whether COMMIT may ride behind these queued statements — the\n * last one is the transaction's last (`withCommit`), each is the last of\n * its lane (a final statement, or the one statement of a followed lane),\n * nothing else is queued or opening, and every open lane waits on these\n * statements and nothing else.\n */\n const ridesQueued = (live: readonly QueuedStatement[]): boolean => {\n const last = live.at(-1);\n if (last === undefined || (last.commit !== true && last.lane.seat?.group.final !== true) || queued.length > 0 || inFlight !== null || ordinaryOpen > 0 || !ridesNow()) return false;\n const counts = new Map<PipelineLaneState, number>();\n for (const entry of live) {\n // Lane A2: a sub-lane statement of a final group is a transaction-final statement too.\n if (entry.commit !== true && entry.lane.order?.followed !== true && entry.lane.seat?.group.final !== true) return false;\n counts.set(entry.lane, (counts.get(entry.lane) ?? 0) + 1);\n }\n // An open lane that is not waiting on these statements may still issue one.\n for (const open of lanes) {\n const count = counts.get(open) ?? 0;\n if (count > 0 && open.waiting === count) continue;\n // Lane A2: the parent of a sealed final group whose statements are in this batch waits on that group alone.\n const group = open.group;\n if (count === 0 && group?.final === true && group.sealed && open.waiting === 1 && live.some((entry) => entry.lane.seat?.group === group)) continue;\n // Lane A2: a lane that issued its transaction-final statement and waits on nothing is done (the D2 group rule).\n if (count === 0 && open.final === true && open.waiting === 0) continue;\n return false;\n }\n return true;\n };\n /**\n * One burst for the queued statements: [pending control…, statements… (, COMMIT)]. Settles once every entry is settled.\n * `inTurn` (V4, a turn gathering group): sent inside the group's own turn — no pending control (it belongs to a\n * later statement), no opening, no riding COMMIT.\n */\n const sendQueued = (entries: readonly QueuedStatement[], options?: { readonly inTurn?: true }): Promise<void> => {\n const inTurn = options?.inTurn === true;\n // The refusals sequential dispatch raises before sending.\n const refusal = sendRefusal();\n const live: QueuedStatement[] = [];\n for (const entry of entries) {\n if (refusal !== undefined) settleQueued(entry, { error: refusal });\n else if (entry.execution?.signal?.aborted === true) settleQueued(entry, { error: readCancelledError({ stage: \"waiting-for-connection\" }) });\n else live.push(entry);\n }\n if (live.length === 0) return Promise.resolve();\n const carriesOpening = !inTurn && !deferred.opened();\n // EPIC 5: decided before the pending control is taken (it reads the queue's state).\n const rides = !inTurn && live.length === entries.length && ridesQueued(live);\n const control = inTurn ? [] : deferred.takeSteps();\n const openingSteps = carriesOpening ? openingLength : 0;\n const commitIndex = control.length + live.length;\n const sendBatch = (): Promise<BatchOutcome> => runBatch({ client, steps: [...control, ...live.map((entry) => ({ text: entry.text, values: entry.values })), ...(rides ? [COMMIT_STEP] : [])], types: EXACT_TYPES });\n // Inside its own turn the batch goes now (a synchronous throw becomes its rejection, as in a turn).\n const batch = inTurn ? new Promise<BatchOutcome>((resolve) => { resolve(sendBatch()); }) : runTurn(sendBatch);\n if (rides) trackRidden(batch, commitIndex);\n const burst = batch\n .then((received) => { distributeBurst({ outcome: rides ? beforeCommit({ outcome: received, commitIndex }) : received, live, controlSteps: control.length, openingSteps }); })\n .then(undefined, (error: unknown) => {\n // Never handed over (or a defect above): nothing may stay pending.\n if (openingSteps > 0) openingFailure ??= mapPgDriverError({ error });\n for (const entry of live) settleQueued(entry, { error });\n });\n if (carriesOpening) {\n // Ordinary statements dispatched meanwhile wait for the opening's\n // answer, as behind any burst that carries it.\n const settled: Promise<void> = burst.then(() => {\n if (inFlight === settled) inFlight = null;\n });\n inFlight = settled;\n }\n return burst;\n };\n\n // ─── In-flight gathering (round-trip report V4, decision D3) ───\n // An ordinary statement that would WAIT — behind the in-flight burst that\n // carries the opening, or for the client to finish another call — waits in\n // ONE group with every statement issued while that wait lasts, and they\n // leave together, in issue order, when it ends: one batch, `sendQueued`'s\n // distribution (the first failure its mapped error, the statements the\n // server skipped the aborted refusal naming it, a failed control step its\n // error first). A statement that finds nothing to wait for is sent at once,\n // and a group of ONE takes today's path. Any other registration (a call\n // queued in the client's turns, a statement or lane batch waiting for the\n // in-flight burst) closes the open group, so issue order on the connection\n // never changes.\n /**\n * Whether an ordinary statement may wait in a gathering group: the `$all`\n * lane rule ({@link coalescable}: a client that batches, no deadline, no\n * running-cancellation queue, no local `query_timeout`, ONE statement that\n * is no control) — and not the transaction's last statement (`withCommit`\n * keeps its own place, last).\n */\n const gathers = (dispatchParams: Parameters<TransactionDispatch>[0]): boolean =>\n dispatchParams.commit !== true && coalescable(dispatchParams);\n /** A registration that is no gathering join: the open group takes no more statements. */\n const closeGathering = (): void => {\n gathering = null;\n };\n /** The stand-in lane of gathered statements in `sendQueued`: never open, never in `lanes`. */\n const gatheredLane: PipelineLaneState = { open: false, waiting: 0 };\n /** Wait in `group`; `values` were serialized before (a value the driver refuses failed that statement alone). */\n const joinGathering = (group: GatheringGroup, dispatchParams: Parameters<TransactionDispatch>[0], values: unknown[]): Promise<PgQueryResultsLike> =>\n new Promise<PgQueryResultsLike>((resolve, reject) => {\n group.members.push({ params: dispatchParams, values, resolve, reject });\n });\n /**\n * The members of a group of two or more, as ONE burst. A turn group's\n * members passed their signal check when they joined — where today's\n * hand-over checks it — so it is not repeated when the slot comes.\n */\n const sendGathered = (members: readonly GatheredStatement[], options?: { readonly inTurn?: true }): Promise<void> =>\n sendQueued(members.map((member): QueuedStatement => {\n gatheredLane.waiting += 1;\n return {\n text: member.params.config.text,\n values: member.values,\n ...(member.params.execution === undefined || options?.inTurn === true ? {} : { execution: member.params.execution }),\n lane: gatheredLane,\n resolve: member.resolve,\n reject: member.reject,\n settled: false,\n };\n }), options);\n /**\n * Wait behind `behind` — the in-flight burst carrying the opening — in the\n * open opening group, or open one. When `behind` settles, ONE member takes\n * today's path (`send`, which takes any pending control in front, as\n * before); two or more leave as one burst with that control in front.\n */\n const gatherBehind = (dispatchParams: Parameters<TransactionDispatch>[0], behind: Promise<void>): Promise<PgQueryResultsLike> => {\n const values = prepareBatchValues({ values: dispatchParams.config.values ?? [] });\n const open = gathering;\n if (open !== null && open.phase === \"opening\" && open.behind === behind) return joinGathering(open, dispatchParams, values);\n const group: GatheringGroup = { phase: \"opening\", behind, members: [] };\n gathering = group;\n gatheringsPending += 1;\n const joined = joinGathering(group, dispatchParams, values);\n void behind.then(() => {\n if (gathering === group) gathering = null;\n gatheringsPending -= 1;\n const [only, ...more] = group.members;\n if (only !== undefined && more.length === 0) {\n void send(only.params).then(only.resolve, only.reject);\n return;\n }\n void sendGathered(group.members);\n });\n return joined;\n };\n /**\n * Wait for the client in the open turn group, or open one: ONE slot of the\n * client's turns. The checks today's hand-over makes before a statement\n * waits run now. When the slot comes, ONE member is handed to node-postgres\n * exactly as before; two or more leave as one burst — without pending\n * control (control deferred after a member joined belongs to a later\n * statement, which carries it) and never with the opening.\n */\n const gatherInTurn = (dispatchParams: Parameters<TransactionDispatch>[0]): Promise<PgQueryResultsLike> => {\n assertReadExecution({ execution: dispatchParams.execution, effect: \"read\", support: readCancellation, provider: PROVIDER, stage: \"waiting-for-connection\" });\n const values = prepareBatchValues({ values: dispatchParams.config.values ?? [] });\n const open = gathering;\n if (open !== null && open.phase === \"turn\") return joinGathering(open, dispatchParams, values);\n const group: GatheringGroup = { phase: \"turn\", members: [] };\n gatheringsPending += 1;\n const joined = joinGathering(group, dispatchParams, values);\n // Its own slot: `turns.run`, not `runTurn` (which closes the open group).\n void turns.run(() => sendTurnGroup(group));\n gathering = group;\n return joined;\n };\n /** A turn group's slot has come: nothing joins any more. Settles with the slot's outcome. */\n const sendTurnGroup = (group: GatheringGroup): Promise<unknown> => {\n if (gathering === group) gathering = null;\n gatheringsPending -= 1;\n const [only, ...more] = group.members;\n if (only !== undefined && more.length === 0) {\n // The slot's outcome is the statement's own: the turn keeper records its failure for the next group.\n const query = new Promise<PgQueryResultsLike>((resolve) => { resolve(client.query(only.params.config)); });\n void query.then(only.resolve, only.reject);\n return query;\n }\n // A server failure answered right before this slot (a statement handed to\n // node-postgres by itself) is recorded first: the group is refused, never\n // answered 25P02.\n const prior = turns.lastFailure();\n if (prior !== undefined) {\n const mapped = mapPgDriverError({ error: prior.error });\n if (typeof mapped.meta.sqlstate === \"string\") markTransactionAborted({ scope, cause: mapped });\n }\n return sendGathered(group.members, { inTurn: true });\n };\n /**\n * An ordered-scope statement that keeps its own turn, sent by itself once\n * the scope's earlier sends settled — and refused, never sent, when one of\n * them failed. A server failure is recorded before the scope's next send\n * looks (its caller records it again; the first record is kept).\n */\n const sendAlone = (entry: QueuedStatement, alone: Parameters<TransactionDispatch>[0]): Promise<void> => {\n const refusal = sendRefusal();\n if (refusal !== undefined) {\n settleQueued(entry, { error: refusal });\n return Promise.resolve();\n }\n return dispatchOrdinary(alone).then(\n (result) => { settleQueued(entry, { result }); },\n (error: unknown) => {\n const mapped = mapPgDriverError({ error });\n if (typeof mapped.meta.sqlstate === \"string\") markTransactionAborted({ scope, cause: mapped });\n settleQueued(entry, { error });\n },\n );\n };\n /** Whether every earlier lane of `lane`'s ordered scope issued a statement (\"issued\"), one has not yet (\"open\"), or one closed without issuing (\"closed\"). */\n const prefixOf = (lane: PipelineLaneState): \"issued\" | \"open\" | \"closed\" => {\n const order = lane.order;\n if (order === undefined) return \"issued\";\n let state: \"issued\" | \"open\" = \"issued\";\n for (let index = 0; index < order.index; index++) {\n const earlier = order.scope.lanes[index] as PipelineLaneState;\n if ((earlier.order as OrderedLaneState).issued > 0) continue;\n if (!earlier.open) return \"closed\";\n state = \"open\";\n }\n return state;\n };\n /** Refuse the queued ordered-scope statements whose earlier lane closed without issuing one: they are never sent. */\n const refuseOrphaned = (): void => {\n if (!queued.some((entry) => prefixOf(entry.lane) === \"closed\")) return;\n const kept: QueuedStatement[] = [];\n for (const entry of queued) {\n if (prefixOf(entry.lane) === \"closed\") settleQueued(entry, { error: predecessorClosedError() });\n else kept.push(entry);\n }\n queued = kept;\n };\n /**\n * One send of an ordered scope. Behind a failed send of the same scope its\n * statements are refused and never sent — also when that failure had no\n * server answer, which leaves PostgreSQL's transaction open (a client-side\n * `query_timeout`, a value the driver refuses): the refusal sequential\n * dispatch would have raised is then the aborted-transaction refusal naming\n * it. A failure of its own fails the scope.\n */\n const orderedSend = (entries: readonly QueuedStatement[], send: (live: readonly QueuedStatement[]) => Promise<void>): (() => Promise<void>) => () => {\n const live: QueuedStatement[] = [];\n for (const entry of entries) {\n const failed = entry.lane.order?.scope.failed;\n if (failed === undefined) live.push(entry);\n else settleQueued(entry, { error: sendRefusal() ?? transactionAbortedError({ cause: failed.cause }) });\n }\n if (live.length === 0) return Promise.resolve();\n return send(live).then(() => {\n for (const entry of live) {\n const order = entry.lane.order;\n if (order !== undefined && entry.failure !== undefined) order.scope.failed ??= { cause: mapPgDriverError({ error: entry.failure }) };\n }\n });\n };\n /** The last send of an ordered scope, settled once its outcome is distributed; the next one waits for it. */\n let orderedTail: Promise<void> | null = null;\n /**\n * Ordered scopes (array `$transaction` bursts, EPIC D). The queued\n * statements whose earlier lanes all issued theirs go out in LANE order —\n * the others stay queued, or are refused when such a lane closed without\n * issuing — as consecutive sends: one batch per run of batchable\n * statements, a statement that keeps its own turn by itself. Every send\n * waits for the previous send of the scope (and for an opening in flight),\n * so a failure refuses what is behind it before it is sent: no lane ever\n * sees 25P02.\n */\n const flushOrdered = (): void => {\n refuseOrphaned();\n const ready: QueuedStatement[] = [];\n const held: QueuedStatement[] = [];\n for (const entry of queued) (prefixOf(entry.lane) === \"issued\" ? ready : held).push(entry);\n queued = held;\n if (ready.length === 0) return;\n // A stable sort: one lane's statements keep their own order.\n ready.sort((first, second) => (first.lane.order?.index ?? 0) - (second.lane.order?.index ?? 0));\n const sends: (() => Promise<void>)[] = [];\n let run: QueuedStatement[] = [];\n for (const entry of ready) {\n const alone = entry.alone;\n if (alone === undefined) {\n run.push(entry);\n continue;\n }\n if (run.length > 0) {\n sends.push(orderedSend(run, sendQueued));\n run = [];\n }\n sends.push(orderedSend([entry], () => sendAlone(entry, alone)));\n }\n if (run.length > 0) sends.push(orderedSend(run, sendQueued));\n const before = [orderedTail, inFlight].filter((wait): wait is Promise<void> => wait !== null);\n let chain: Promise<void> = before.length === 0\n ? (sends.shift() as () => Promise<void>)()\n : Promise.all(before).then(ignore);\n for (const next of sends) chain = chain.then(next);\n const tail = chain;\n orderedTail = tail;\n void tail.then(() => {\n if (orderedTail === tail) orderedTail = null;\n });\n };\n const flushQueue = (): void => {\n if (queued.length === 0) return;\n // V4: a statement issued after these lane statements must not join a group sent before them.\n closeGathering();\n if (queued.some((entry) => entry.lane.order !== undefined)) {\n flushOrdered();\n return;\n }\n const entries = queued.some((entry) => entry.lane.seat !== undefined) ? seatOrder(queued) : queued;\n queued = [];\n if (inFlight === null) sendQueued(entries);\n else void inFlight.then(() => { sendQueued(entries); });\n };\n const flushIfReady = (): void => {\n if (queued.length === 0) return;\n for (const open of lanes) if (open.waiting === 0) return;\n flushQueue();\n };\n /**\n * D2: a group's statements leave in SUB-LANE order, whatever order they\n * arrived in, behind every other statement of the batch (a stable sort).\n */\n const seatOrder = (entries: readonly QueuedStatement[]): QueuedStatement[] =>\n [...entries].sort((first, second) => (first.lane.seat?.index ?? -1) - (second.lane.seat?.index ?? -1));\n /** D2: a sealed group whose sub-lanes all closed is over — its parent no longer counts as waiting. */\n const endGroupIfOver = (opening: LaneGroupState): void => {\n if (!opening.sealed || opening.live > 0 || opening.parent.group !== opening) return;\n opening.parent.group = undefined;\n opening.parent.waiting -= 1;\n };\n const closeLane = (lane: PipelineLaneState): void => {\n if (!lane.open) return;\n lane.open = false;\n lanes.delete(lane);\n // A later lane's statements behind a lane that never issued must not wait for anything.\n if (lane.order !== undefined) refuseOrphaned();\n if (lane.seat !== undefined) {\n lane.seat.group.live -= 1;\n endGroupIfOver(lane.seat.group);\n }\n flushIfReady();\n };\n const pipelines: PipelineControl = {\n open: (count) => Array.from({ length: count }, (): PipelineLaneState => {\n const opened: PipelineLaneState = { open: true, waiting: 0 };\n lanes.add(opened);\n return opened;\n }),\n openOrdered: (count) => {\n const ordered: OrderedScope = { lanes: [] };\n for (let index = 0; index < count; index++) {\n const opened: PipelineLaneState = { open: true, waiting: 0, order: { scope: ordered, index, issued: 0, followed: false } };\n ordered.lanes.push(opened);\n lanes.add(opened);\n }\n return [...ordered.lanes];\n },\n follow: (lane) => {\n const order = lane.order;\n if (order === undefined) throw orderedLaneMisuse({ message: \"follow() exists only on the lanes of an ordered scope\" });\n if (!lane.open) throw orderedLaneMisuse({ message: \"follow() on a closed lane\" });\n if (order.followed || order.scope.lanes.at(-1) !== lane) throw orderedLaneMisuse({ message: \"follow() opens one lane after the LAST lane of its scope\" });\n if (order.issued > 0) throw orderedLaneMisuse({ message: \"follow() must come before the lane issues its statement\" });\n order.followed = true;\n // Open and not waiting: it holds the batch until it issues or closes.\n const next: PipelineLaneState = { open: true, waiting: 0, order: { scope: order.scope, index: order.scope.lanes.length, issued: 0, followed: false } };\n order.scope.lanes.push(next);\n lanes.add(next);\n return next;\n },\n close: closeLane,\n waitAs: ({ lane, wait }) => {\n if (!lane.open) return wait;\n lane.waiting += 1;\n flushIfReady();\n return wait.then(\n (value) => { lane.waiting -= 1; return value; },\n (error: unknown) => { lane.waiting -= 1; throw error; },\n );\n },\n enter: (lane) => {\n if (!lane.open) return ignore;\n lane.waiting += 1;\n flushIfReady();\n let left = false;\n return (): void => {\n if (left) return;\n left = true;\n lane.waiting -= 1;\n };\n },\n flush: flushQueue,\n /**\n * D2 (`PipelineLane.group`). Admitted only where the group cannot move\n * a statement ahead of one sequential dispatch would send first: the\n * statements combine now, the transaction accepts statements, and\n * every OTHER open lane is done (issued its transaction-final statement\n * and has nothing waiting) — an ordinary lane still loading, or another\n * group, could issue a statement after the group's batch that sequential\n * dispatch would have sent before some of its statements.\n */\n group: (lane, final) => {\n if (!lane.open || lane.order !== undefined || lane.seat !== undefined || lane.gate === true || lane.group !== undefined || lane.final === true) return undefined;\n if (!capable || budget.totalMs !== null || cancellationQueue || sendRefusal() !== undefined) return undefined;\n // Review D2-01: a local `query_timeout` arms ONE timer per batch — the group's statements would share\n // it, where one after another each has its own (as ordered scopes and COMMIT riding, above).\n if ((client.connectionParameters?.query_timeout ?? 0) > 0) return undefined;\n for (const other of lanes) {\n if (other !== lane && (other.final !== true || other.waiting > 0)) return undefined;\n }\n // The gate is open and never waiting: it holds the batch until the group is sealed.\n const gate: PipelineLaneState = { open: true, waiting: 0, gate: true };\n const opening: LaneGroupState = { parent: lane, gate, opened: 0, live: 0, sealed: false, final };\n lanes.add(gate);\n lane.group = opening;\n // OP-11: the parent awaits its sub-lanes, so it counts as waiting until the group is over.\n lane.waiting += 1;\n return opening;\n },\n seat: (opening) => {\n if (opening.sealed) throw laneGroupMisuse({ message: \"a sub-lane is opened only before the group is sealed\" });\n if (!opening.parent.open) throw laneGroupMisuse({ message: \"a sub-lane of a closed lane\" });\n // Open and not waiting: it holds the batch until it issued its statement or closed.\n const seat: PipelineLaneState = { open: true, waiting: 0, seat: { group: opening, index: opening.opened, issued: false } };\n opening.opened += 1;\n opening.live += 1;\n lanes.add(seat);\n return seat;\n },\n seal: (opening) => {\n if (opening.sealed) return;\n opening.sealed = true;\n endGroupIfOver(opening);\n closeLane(opening.gate);\n },\n };\n /**\n * The transaction is ending: every lane closes, and a statement still\n * queued goes out now — ahead of COMMIT/ROLLBACK, exactly where an\n * un-awaited statement sits in node-postgres' own queue.\n */\n const endPipeline = (): void => {\n for (const open of lanes) open.open = false;\n lanes.clear();\n flushQueue();\n };\n const enqueue = (dispatchParams: Parameters<TransactionDispatch>[0], lane: PipelineLaneState, alone?: true): Promise<PgQueryResultsLike> => {\n // The refusals sequential dispatch raises, then the values serialized\n // NOW: a value the driver refuses fails this statement alone. A statement\n // that keeps its own turn (ordered scopes) is serialized when it is sent.\n if (cancellationAttempted) throw transactionAbortedError({ cause: readCancelledError({ stage: \"running\" }) });\n if (openingFailure !== undefined) throw transactionAbortedError({ cause: openingFailure });\n if (ridden !== undefined) throw commitSentRefusal();\n assertReadExecution({ execution: dispatchParams.execution, effect: \"read\", support: readCancellation, provider: PROVIDER, stage: \"waiting-for-connection\" });\n const values = alone === true ? [] : prepareBatchValues({ values: dispatchParams.config.values ?? [] });\n const pending = new Promise<PgQueryResultsLike>((resolve, reject) => {\n lane.waiting += 1;\n queued.push({\n text: dispatchParams.config.text,\n values,\n ...(dispatchParams.execution === undefined ? {} : { execution: dispatchParams.execution }),\n ...(alone === true ? { alone: dispatchParams } : {}),\n ...(dispatchParams.commit === true ? { commit: true as const } : {}),\n lane,\n resolve,\n reject,\n settled: false,\n });\n });\n if (lane.order !== undefined) lane.order.issued += 1;\n // A later strong read drains it like any ordinary statement.\n activeDispatches.add(pending);\n void pending.then(() => activeDispatches.delete(pending), () => activeDispatches.delete(pending));\n flushIfReady();\n return pending;\n };\n /** Whether a lane statement may wait in the pipeline (see the block comment above). */\n const coalescable = (dispatchParams: Parameters<TransactionDispatch>[0]): boolean =>\n capable && budget.totalMs === null && !cancellationQueue &&\n // 5.0 lane F: a local `query_timeout` (as `pipelines.group`, review D2-01) — `$all` members one per flight.\n !((client.connectionParameters?.query_timeout ?? 0) > 0) &&\n dispatchParams.batchable === true && dispatchParams.cleanup !== true && dispatchParams.stage === undefined &&\n dispatchParams.sent === undefined && dispatchParams.execution?.cancellation !== \"running\";\n\n const dispatch: TransactionDispatch = (dispatchParams) => {\n const lane = dispatchParams.lane?.open === true ? dispatchParams.lane : undefined;\n if (lane !== undefined && dispatchParams.cleanup !== true) {\n // D2: the lane-group rules, checked before anything is queued or sent.\n if (lane.group !== undefined) return Promise.reject(laneGroupMisuse({ message: \"a lane issues nothing while its group is open\" }));\n const seat = lane.seat;\n if (seat !== undefined) {\n if (seat.issued) return Promise.reject(laneGroupMisuse({ message: \"a sub-lane issues ONE statement\" }));\n if (!coalescable(dispatchParams)) return Promise.reject(laneGroupMisuse({ message: \"a sub-lane statement must be able to join a batch\" }));\n seat.issued = true;\n }\n // EPIC 5: the lane's transaction-final statement — it issues nothing after it.\n if (dispatchParams.commit === true) lane.final = true;\n }\n const order = lane?.order;\n if (lane !== undefined && order !== undefined && dispatchParams.cleanup !== true) {\n // Ordered scope: every statement waits in the pipeline, one that keeps\n // its own turn included, so lane order and the prefix rule hold for all.\n return guarded(() => {\n if (order.followed && order.issued > 0) throw orderedLaneMisuse({ message: \"a lane that has a follower may issue ONE statement\" });\n return coalescable(dispatchParams) ? enqueue(dispatchParams, lane) : enqueue(dispatchParams, lane, true);\n });\n }\n if (lane !== undefined && coalescable(dispatchParams)) return guarded(() => enqueue(dispatchParams, lane));\n if (lane === undefined) return dispatchOrdinary(dispatchParams);\n // A lane statement that keeps its own turn: the lane counts as waiting\n // while it runs, and whatever the lanes already queued goes out FIRST —\n // call order on the connection, as sequential dispatch (a RELEASE or a\n // raw statement never overtakes a statement issued before it).\n const leave = pipelines.enter(lane);\n flushQueue();\n return dispatchOrdinary(dispatchParams).then(\n (result) => { leave(); return result; },\n (error: unknown) => { leave(); throw error; },\n );\n };\n const dispatchOrdinary: TransactionDispatch = (dispatchParams) => {\n if (dispatchParams.execution?.cancellation === \"running\" && !cancellationQueue) {\n // Drain earlier ordinary statements before naming a target. All later\n // work (including siblings/cleanup) waits for BOTH query and control.\n // Lane statements still queued go out first, so the drain includes them.\n flushQueue();\n cancellationQueue = true;\n closeGathering();\n tail = Promise.allSettled([...activeDispatches]);\n }\n if (budget.totalMs === null && !cancellationQueue) {\n // Register this arrival before waiting for the deferred opening. A\n // later strong read must drain it, not recursively move it behind\n // the cancellation queue when that opening finally settles.\n // EPIC 5: counted before it is sent (a riding COMMIT needs it to be the only one).\n ordinaryOpen += 1;\n // V4: an open opening group is waited for too — nothing overtakes the statements in it.\n const behind = gathering?.phase === \"opening\" ? (gathering.behind ?? null) : inFlight;\n let pending: Promise<PgQueryResultsLike>;\n if (behind === null) pending = send(dispatchParams);\n else if (gathers(dispatchParams)) pending = guarded(() => gatherBehind(dispatchParams, behind));\n else {\n closeGathering();\n pending = behind.then(() => send(dispatchParams));\n }\n activeDispatches.add(pending);\n const settle = (): void => { activeDispatches.delete(pending); ordinaryOpen -= 1; };\n void pending.then(settle, settle);\n return pending;\n }\n const pending = tail.then(() => send(dispatchParams));\n // A failed statement must not strand ROLLBACK behind a rejected tail.\n tail = pending.then(ignore, ignore);\n closeGathering();\n return pending;\n };\n /** Set when the session's state can no longer be asserted (see below). */\n let discard = false;\n let released = false;\n let cancellationAttempted = false;\n const cancellation = createPgReadCancellation({ connectionString: cancellationAddress, target: onClient, terminate: () => {\n if (!released) { released = true; client.release(true); }\n }, discard: () => {\n discard = true;\n cancellationAttempted = true;\n // Even a successful read can race an asynchronous backend signal. No\n // later user statement/commit may enter this target transaction.\n markTransactionAborted({ scope, cause: readCancelledError({ stage: \"running\" }) });\n } });\n /** How far COMMIT got — the only input of the commit outcome (EPIC T). */\n let commitProgress: CommitProgress = \"not-sent\";\n /** Set when `openWithSettings` already rolled the transaction back: the cleanup sends no second ROLLBACK. */\n let openingRollback: RollbackOutcome | undefined;\n /**\n * TU-02: a transaction with `settings` opens EAGERLY and waits for the\n * answer, so a refused setting fails the opening and the callback never\n * runs. On a client that batches, `BEGIN …` (+ the timeout's SET) and the\n * ONE bound settings statement travel in ONE flight (one Sync): a failed\n * `BEGIN` leaves the settings unrun. Otherwise the opening text, then the\n * settings statement. A refused setting (a server answer): ROLLBACK, name\n * the refused setting (`findRefusedSetting`, failure path only), reject\n * with `VIBE_TRANSACTION` `meta.reason: \"setting-refused\"`. A failed\n * opening or a lost answer keeps today's opening failure.\n */\n const openWithSettings = async (statement: TransactionSettingsStatement): Promise<void> => {\n let failed: { readonly error: unknown } | undefined;\n if (capable) {\n const control = [beginStatement(openingOptions), ...(openingOptions.timeout === undefined ? [] : [statementTimeoutStatement({ timeout: openingOptions.timeout })])];\n const outcome = await turns.run(() => runBatch({\n client,\n steps: [...control.map((text) => ({ text })), { text: statement.text, values: prepareBatchValues({ values: statement.values }) }],\n types: EXACT_TYPES,\n }));\n const failure = firstBatchFailure({ outcome });\n if (failure === undefined) return;\n if (failure.index < control.length || outcome.transportError !== undefined) throw mapPgDriverError({ error: failure.error });\n failed = { error: failure.error };\n } else {\n await runMapped(() => onClient.query({ text: openText }));\n failed = await onClient.query({ text: statement.text, values: [...statement.values] }).then(\n () => undefined,\n (error: unknown) => ({ error }),\n );\n if (failed === undefined) return;\n }\n const cause = mapPgDriverError({ error: failed.error });\n // No server answer: what ran is unknown — today's opening failure and cleanup.\n if (typeof cause.meta.sqlstate !== \"string\") throw cause;\n openingRollback = await onClient.query({ text: \"ROLLBACK\" }).then((): RollbackOutcome => \"acknowledged\", (): RollbackOutcome => \"failed\");\n if (openingRollback === \"failed\") discard = true;\n const setting = findRefusedSetting({ settings, cause });\n throw transactionSettingRefusedError({ provider: PROVIDER, settings, setting, cause });\n };\n try {\n if (settingsStatement !== undefined && !settingsDeferred) await openWithSettings(settingsStatement);\n else if (!deferOpening) await runMapped(() => onClient.query({ text: openText }));\n const result = await runRootScope({\n scope,\n // Ordered scopes (array `$transaction` bursts) only without a deadline:\n // there every statement keeps its own turn and its own bound. A `timeout`\n // does not exclude them (V2): it is only the server's `statement_timeout`,\n // which PostgreSQL arms anew for every statement of a batch.\n // And not on a client with a local `query_timeout`: it fails a statement\n // without stopping it, so it could not stop a statement already sent\n // behind it in the same batch (read cancellation refuses it too).\n body: () => fn(createClientAdapter({\n dispatch, scope, budget, deferred: capable ? deferred : null, cancellation, pipelines: capable ? pipelines : null,\n connection: client, topLevel: true,\n ordered: capable && budget.totalMs === null && !((client.connectionParameters?.query_timeout ?? 0) > 0),\n commits,\n })),\n });\n endPipeline();\n const riding = ridden;\n if (riding !== undefined) {\n // EPIC 5: COMMIT rode with the last statement; that batch decided the transaction.\n await riding.settled;\n if (riding.state === \"committed\") {\n budget.close({ outcome: \"committed\" });\n return result;\n }\n throw riding.state === \"skipped\" ? transactionAbortedError({ cause: scope.state.aborted?.cause }) : riding.error;\n }\n // An expired budget must never commit, however the callback ended.\n budget.assertUsable({ stage: \"commit\" });\n if (!deferred.opened()) {\n // The callback sent nothing: no BEGIN left the client, so there is\n // nothing to commit (EPIC 6, empty transaction: 2 waits → 0).\n budget.close({ outcome: \"committed\" });\n return result;\n }\n // The deferred opening failed and the callback swallowed it: there is\n // no transaction to commit. Refuse here, so the ordinary cleanup below\n // runs — not the COMMIT branch, which would report a COMMIT that was\n // never sent as lost in flight (fix lane FX-A, RV5 MI-2).\n if (openingFailure !== undefined) throw transactionAbortedError({ cause: openingFailure });\n // EPIC 5: COMMIT releases every savepoint — a RELEASE still pending never leaves.\n deferred.dropReleases();\n const commit = await runMapped(() => dispatch({\n config: { text: \"COMMIT\" },\n stage: \"commit\",\n batchable: true,\n sent: () => {\n // A client whose connection already failed refuses COMMIT locally:\n // raise that failure here, with COMMIT still unsent.\n if (connectionFailure !== undefined) throw mapPgDriverError({ error: connectionFailure.cause });\n commitProgress = \"sent\";\n },\n }))\n .catch((cause: unknown) => {\n // Refused before it reached node-postgres (the deadline re-check in\n // the dispatch turn, a poisoned scope, a connection that had\n // already failed): COMMIT was never sent, so the outcome is known\n // and the refusal is rethrown as it is.\n if (commitProgress === \"not-sent\") throw cause;\n // The server answered (a serialization failure at commit is a\n // definite rollback) — or the acknowledgement was LOST, in which\n // case a later successful ROLLBACK disproves nothing: the write may\n // have committed. Close unknown BEFORE cleanup, like mysql and bun.\n if (!isConnectionLoss({ error: cause })) {\n commitProgress = \"answered\";\n throw cause;\n }\n commitProgress = \"unanswered\";\n discard = true;\n budget.close({ outcome: \"unknown\" });\n throw commitOutcomeUnknownError({ cause });\n });\n // Belt and braces over the gate's tracking: an aborted transaction's\n // COMMIT is answered with a ROLLBACK tag and no error.\n if (finalResult({ result: commit }).command === \"ROLLBACK\") {\n commitProgress = \"answered\";\n throw transactionAbortedError({ cause: scope.state.aborted?.cause });\n }\n budget.close({ outcome: \"committed\" });\n return result;\n } catch (caught) {\n endPipeline();\n const riding = ridden;\n if (riding !== undefined) await riding.settled;\n if (riding?.state === \"committed\") {\n // EPIC 5 (named exception E-T1): the transaction committed with its\n // last statement and the callback failed afterwards (a read's verdict).\n // Nothing is open to roll back, and nothing failed to report.\n budget.close({ outcome: \"committed\" });\n throw caught;\n }\n // A riding COMMIT without an answer: the outcome is unknown, whatever the callback threw.\n const error = riding?.state === \"lost\" ? riding.error : caught;\n if (isSavepointRollbackFailedError(error) || scope.state.poisoned !== null) {\n // A successful outer ROLLBACK cannot establish what happened when the\n // savepoint stack was lost. Keep the shared poison's unknown outcome.\n discard = true;\n budget.close({ outcome: \"unknown\" });\n }\n let rollback: RollbackOutcome = \"not-needed\";\n try {\n // Settings refused at the opening (TU-02): already rolled back there.\n if (openingRollback !== undefined) rollback = openingRollback;\n // A deferred opening that never left the client left nothing to undo.\n else if (deferred.opened()) {\n await dispatch({ config: { text: \"ROLLBACK\" }, cleanup: true });\n rollback = \"acknowledged\";\n }\n } catch {\n // The rollback that should have cleaned up failed: this connection may\n // still be inside a transaction with `SET LOCAL` settings that were\n // never reverted, so it is DESTROYED rather than pooled. The commit\n // outcome does not change: it follows from how far COMMIT got, and\n // the server ends an open transaction when the connection closes.\n discard = true;\n rollback = \"failed\";\n }\n // EPIC T: the same error, with the facts recorded beside it.\n throw settleFailedTransaction({\n error,\n provider: PROVIDER,\n budget,\n scope,\n commit: commitProgress,\n rollback,\n connection: discard ? \"discarded\" : \"returned\",\n });\n } finally {\n unguard();\n if (!released) client.release(discard);\n }\n },\n\n async connect(): Promise<void> {\n // V7: open `min` connections AT ONCE (at least one), then release them\n // to the pool, so a warm pool exists before the first burst. Every\n // opened connection is released before a failure is reported.\n const opened = await Promise.allSettled(Array.from({ length: Math.max(1, poolMin ?? 0) }, () => runMapped(() => getPool().connect())));\n for (const outcome of opened) {\n if (outcome.status === \"fulfilled\") outcome.value.release();\n }\n const failed = opened.find((outcome) => outcome.status === \"rejected\");\n if (failed !== undefined) throw failed.reason;\n },\n };\n\n /**\n * Round-trip follow-up, lane A2 (`DatabaseAdapter.connectionGroup`): send a\n * read's sibling relation statements on ONE checked-out client as one\n * one-Sync batch — one round trip, one implicit transaction of the server\n * (under READ COMMITTED each statement still reads its own snapshot). The\n * client is re-checked here: one that cannot batch, carries a local\n * `query_timeout` (its one timer would cover every statement) or lacks the\n * ready-for-query seam is handed back unused, and the statements go through\n * `root.execute` one after another — today's path — the ones after the first\n * failure reported as skipped. After a server failure the client is pooled\n * only with the root path's proof (`observeReadyForQuery`).\n */\n const sendConnectionGroup = async (entries: readonly ConnectionGroupEntry[]): Promise<BatchOutcome> => {\n const rootPool = getPool();\n const client = rootViaPoolQuery ? undefined : await runMapped(() => rootPool.connect());\n if (client === undefined || !hasReadyForQuerySeam({ client }) || !supportsBatch({ client }) || (client.connectionParameters?.query_timeout ?? 0) > 0) {\n client?.release();\n const steps: BatchOutcome[\"steps\"][number][] = [];\n for (const entry of entries) {\n if (steps.some((step) => step.status === \"failed\")) {\n steps.push({ status: \"skipped\" });\n continue;\n }\n steps.push(await root.execute(entry.call).then(\n (rows) => ({ status: \"ok\" as const, result: { rows, rowCount: rows.length } }),\n (error: unknown) => ({ status: \"failed\" as const, error }),\n ));\n }\n return { steps };\n }\n const seam = observeReadyForQuery({ client });\n let reuse = false;\n const outcome = await runBatch({ client, steps: entries.map((entry) => entry.step), types: EXACT_TYPES }).then(\n (settled) => settled,\n (error: unknown): BatchOutcome => ({ steps: [], transportError: error }),\n );\n const failure = firstBatchFailure({ outcome });\n if (failure === undefined) reuse = true;\n else if (outcome.transportError === undefined) reuse = await seam.reusableAfter({ error: mapPgDriverError({ error: failure.error }), named: false });\n seam.detach();\n client.release(!reuse);\n return outcome;\n };\n /** The fields every connection-group sub-lane carries (the root's declarations). */\n const connectionGroupBase: ConnectionGroupDriver[\"base\"] = {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n budgets: BUDGETS,\n roundTrips: ROUND_TRIPS,\n formatArrayParam: (values: unknown[]): unknown => new PgArrayParam(values),\n };\n const connectionGroupDriver: ConnectionGroupDriver = {\n base: connectionGroupBase,\n prepare: (call) => ({ text: call.text, values: prepareBatchValues({ values: serializeParams({ values: call.values }) }) }),\n send: (entries) => lifecycle.admit({ run: () => sendConnectionGroup(entries) }),\n mapError: (error) => mapPgDriverError({ error }),\n };\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n budgets: BUDGETS,\n readCancellation,\n roundTrips: ROUND_TRIPS,\n readSnapshot: READ_SNAPSHOT,\n pipelining: PIPELINING,\n transactionOutcome: \"reported\",\n transactionSettings: \"transaction-local\",\n // Round-trip follow-up lane E: see `transactionsTakeOneRoundTrip`.\n ...(transactionsTakeOneRoundTrip({ address }) ? {\n oneRoundTripTransactions: true as const,\n // Lane A2: the same per-client conditions (a driver that batches, no local `query_timeout`).\n // Opening one sends nothing; after `disconnect()` it is refused like every root call (lane BN).\n connectionGroup: (): PipelineGroup | undefined => {\n const closed = lifecycle.refusal();\n if (closed !== undefined) throw closed;\n return rootViaPoolQuery ? undefined : openConnectionGroup({ driver: connectionGroupDriver });\n },\n } : {}),\n\n withSession({ run }) {\n return lifecycle.admit({ run: () => root.withSession({ run: (executor) => lifecycle.inCallback({ run: () => run(executor) }) }) });\n },\n\n execute(params) {\n return lifecycle.admit({ run: () => params.execution === undefined ? root.execute(params) : runReadExecution({ ...params, support: readCancellation, provider: PROVIDER, run: () => root.execute(params) }) });\n },\n\n executeUnsafe(params) {\n return lifecycle.admit({ run: () => root.executeUnsafe(params) });\n },\n\n transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n return lifecycle.admit({ run: () => root.transaction((txAdapter) => lifecycle.inCallback({ run: () => fn(txAdapter) }), transactionOptions) });\n },\n\n connect(): Promise<void> {\n return lifecycle.admit({ run: () => root.connect() });\n },\n\n /**\n * Terminal (EPIC A2): refuses new work at once, waits for admitted work —\n * whole transaction and session callbacks included — then closes what the\n * adapter owns, once. Repeated calls share that completion. A new adapter\n * is the only way to connect again.\n */\n disconnect(): Promise<void> {\n return lifecycle.disconnect();\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return new PgArrayParam(values);\n },\n };\n}\n\n// ─── Re-exports (driver-error table, markers, helpers) ────────────\n\nexport { PG_SQLSTATE_ERROR_CODES, PG_SQLSTATE_REASONS, mapPgDriverError, pgErrorSqlstate } from \"./errors.ts\";\nexport { PgArrayParam, serializeParams, serializeParamsRaw } from \"./params.ts\";\nexport { createSavepointCounter, nextSavepointName } from \"@vibeorm/runtime/adapter-kit\";\nexport type { SavepointCounter } from \"@vibeorm/runtime/adapter-kit\";\nexport { createStatementNameCache } from \"./statement-cache.ts\";\nexport type { StatementNameCache } from \"./statement-cache.ts\";\nexport { buildPoolConfig, placePlanCacheMode } from \"./pool-config.ts\";\nexport type { PlanCacheMode, StartupOptionsPlacement } from \"./pool-config.ts\";\nexport {\n ISOLATION_LEVEL_SQL,\n beginStatement,\n classifyRawTransactionControl,\n refuseNestedTransactionOptions,\n statementTimeoutStatement,\n} from \"./transaction-sql.ts\";\nexport type { RawTransactionControl } from \"./transaction-sql.ts\";\n// ─── EPIC 6: transaction budgets (shared, @vibeorm/runtime/adapter-kit) ───\nexport {\n DEFAULT_DEADLINE_CLOCK,\n engineStatementBudgetMs,\n isTransactionDeadlineError,\n startTransactionBudget,\n transactionClosedError,\n transactionDeadlineError,\n transactionOutcomeUnknownError,\n validateTransactionDeadline,\n} from \"@vibeorm/runtime/adapter-kit\";\nexport type { BudgetStage, DeadlineClock, TransactionBudget, TransactionOutcome } from \"@vibeorm/runtime/adapter-kit\";\n",
6
- "/**\n * One-Sync batch for node-postgres (round-trip EPIC 6, pipelining).\n *\n * Several statements go to the server as Parse / Bind / Describe / Execute\n * each, followed by ONE Sync — one wait instead of one per statement. It is a\n * `Submittable` (the extension point `client.query(object)` documents and\n * pg-cursor uses) running on an ordinary, NON-pipeline client: the batch is one\n * query object, so the client's own queue, ReadyForQuery handling and status\n * bookkeeping stay node-postgres'.\n *\n * PostgreSQL's extended protocol skips every message after an error until the\n * Sync (as libpq pipeline mode does), so a failing step leaves every later step\n * UNRUN — a failed `BEGIN` can never let a later write run in autocommit, and\n * no later step answers 25P02 (spike-report §1.3, \"pg one-Sync batch\").\n *\n * Only API that node-postgres exposes is used: `connection.parse / bind /\n * describe / execute / sync` (declared on `Connection` in @types/pg), the\n * message handlers of the Submittable contract, and the driver's own\n * `utils.prepareValue` (a property of the `pg` module object, feature-detected)\n * so parameters serialize exactly as `client.query` serializes them. Rows are\n * decoded HERE, with the adapter's query-local type parsers — never through\n * node-postgres' internal `lib/result.js`.\n */\n\nimport pg from \"pg\";\n\n// ─── Types ────────────────────────────────────────────────────────\n\n/** One statement of a batch. Values are the adapter's already-serialized params. */\nexport type BatchStep = {\n readonly text: string;\n readonly values?: readonly unknown[];\n /**\n * Nobody reads this step's rows (statement-count pass EPIC 5: the final\n * statement that rides with COMMIT): they are not decoded, so no type parser\n * can fail on them; the step reports no rows and its command tag's count.\n */\n readonly discardRows?: true;\n};\n\n/** A step's decoded result, shaped like the node-postgres result the adapter reads. */\nexport type BatchStepResult = {\n readonly rows: Record<string, unknown>[];\n readonly rowCount: number | null;\n readonly command?: string;\n};\n\n/** Per-step outcome after the batch's ReadyForQuery. */\nexport type BatchStepOutcome =\n | { readonly status: \"ok\"; readonly result: BatchStepResult }\n | { readonly status: \"failed\"; readonly error: unknown }\n | { readonly status: \"skipped\" };\n\n/** What a batch reports once it settled. */\nexport type BatchOutcome = {\n /** One entry per step, in order. */\n readonly steps: readonly BatchStepOutcome[];\n /**\n * A failure WITHOUT a server answer — the socket broke, or the client's\n * `query_timeout` fired while the batch was still on the wire. What the\n * server did with the batch is unknown; `steps` lists only what was seen.\n */\n readonly transportError?: unknown;\n};\n\n/** The query-local type parser surface (the adapter's `EXACT_TYPES`). */\nexport type BatchTypeParsers = {\n getTypeParser(oid: number, format?: \"text\" | \"binary\"): (value: string) => unknown;\n};\n\n/** The protocol writer surface of node-postgres' `Connection`. */\ntype BatchConnection = {\n readonly stream?: { cork?: () => void; uncork?: () => void };\n parse(params: { text: string; name?: string; types?: readonly number[] }): void;\n bind(params: { portal?: string; statement?: string; values: readonly unknown[] }): void;\n describe(params: { type: \"P\"; name: string }): void;\n execute(params: { portal: string; rows: number }): void;\n sync(): void;\n sendCopyFail?(message: string): void;\n};\n\n/** The client surface a batch needs; feature-detected, never assumed. */\ntype BatchClient = {\n readonly connection?: unknown;\n readonly pipeline?: unknown;\n};\n\ntype RowDescriptionField = { readonly name: string; readonly dataTypeID: number; readonly format?: \"text\" | \"binary\" };\n\n// ─── Feature detection ────────────────────────────────────────────\n\n/** node-postgres' own parameter serializer, when the installed driver exposes it. */\nconst prepareValue: ((value: unknown) => unknown) | undefined = (() => {\n const utils = (pg as unknown as { utils?: { prepareValue?: unknown } }).utils;\n return typeof utils?.prepareValue === \"function\"\n ? (utils.prepareValue as (value: unknown) => unknown)\n : undefined;\n})();\n\n/** Whether this `pg` build exports what a one-Sync batch needs (`utils.prepareValue`); per-client checks stay in {@link supportsBatch}. */\nexport function batchDriverAvailable(): boolean {\n return prepareValue !== undefined;\n}\n\n/**\n * Whether `client` can run a one-Sync batch: a node-postgres client whose\n * connection exposes the protocol writers, NOT in pipeline mode (pipeline mode\n * sends a Sync per query and was rejected by the spike), with the driver's\n * value serializer available. Test doubles and foreign clients answer false\n * and keep today's one-statement-per-wait path.\n */\nexport function supportsBatch(params: { client: unknown }): boolean {\n if (prepareValue === undefined) return false;\n const client = params.client as BatchClient | null;\n if (client === null || typeof client !== \"object\" || client.pipeline === true) return false;\n const connection = client.connection as Partial<Record<keyof BatchConnection, unknown>> | null | undefined;\n return connection !== null && typeof connection === \"object\" &&\n typeof connection.parse === \"function\" &&\n typeof connection.bind === \"function\" &&\n typeof connection.describe === \"function\" &&\n typeof connection.execute === \"function\" &&\n typeof connection.sync === \"function\";\n}\n\n/**\n * Serialize a step's parameters with the driver's own `prepareValue`. Runs\n * BEFORE anything is written, so a value the driver cannot serialize refuses\n * the whole batch with nothing sent (node-postgres' own path closes and syncs\n * instead; the caller-visible error is the same driver error).\n */\nexport function prepareBatchValues(params: { values: readonly unknown[] }): unknown[] {\n const prepare = prepareValue as (value: unknown) => unknown;\n return params.values.map((value) => prepare(value));\n}\n\n// ─── The batch ────────────────────────────────────────────────────\n\n/** `INSERT 0 3` → command `INSERT`, rows 3 (the CommandComplete tag grammar). */\nconst COMMAND_TAG = /^([A-Za-z]+)(?: (\\d+))?(?: (\\d+))?/;\n\n/** A server ErrorResponse (pg-protocol `DatabaseError`), as opposed to a client/socket failure. */\nfunction isServerError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const candidate = error as { code?: unknown; severity?: unknown };\n return typeof candidate.code === \"string\" && /^[0-9A-Z]{5}$/.test(candidate.code) && typeof candidate.severity === \"string\";\n}\n\n/**\n * The Submittable. Construct with steps whose values are already prepared\n * ({@link prepareBatchValues}); pass to `client.query(batch)`; await\n * {@link PgBatch.done}.\n */\nexport class PgBatch {\n /** Settles once: at the batch's ReadyForQuery, at its first server error, or at a transport failure. */\n readonly done: Promise<BatchOutcome>;\n /**\n * Set by node-postgres when the client has a `query_timeout`: its wrapper\n * clears the read-timeout timer. Called once when the batch settles, so a\n * timer never outlives the batch (fix lane FX-A, RV5 MI-6).\n */\n callback: ((error: unknown, result?: unknown) => void) | undefined = undefined;\n\n private readonly steps: readonly BatchStep[];\n private readonly types: BatchTypeParsers;\n private readonly outcomes: BatchStepOutcome[] = [];\n private parsers: ((value: string) => unknown)[] = [];\n private fields: readonly RowDescriptionField[] = [];\n private rows: Record<string, unknown>[] = [];\n /** The first type-parser failure of the current step; its remaining rows are skipped. */\n private rowError: { readonly error: unknown } | undefined = undefined;\n private settled = false;\n private resolve: (outcome: BatchOutcome) => void = () => undefined;\n\n constructor(params: { steps: readonly BatchStep[]; types: BatchTypeParsers }) {\n this.steps = params.steps;\n this.types = params.types;\n this.done = new Promise<BatchOutcome>((resolve) => {\n this.resolve = resolve;\n });\n }\n\n /** Called by node-postgres when the batch reaches the head of the client's queue. */\n submit(connection: unknown): void {\n const writer = connection as BatchConnection;\n writer.stream?.cork?.();\n try {\n for (const step of this.steps) {\n writer.parse({ text: step.text, types: [] });\n writer.bind({ values: step.values ?? [] });\n writer.describe({ type: \"P\", name: \"\" });\n writer.execute({ portal: \"\", rows: 0 });\n }\n writer.sync();\n } finally {\n writer.stream?.uncork?.();\n }\n }\n\n handleRowDescription(message: { fields: readonly RowDescriptionField[] }): void {\n this.rows = [];\n if (this.steps[this.outcomes.length]?.discardRows === true) {\n this.fields = [];\n this.parsers = [];\n return;\n }\n this.fields = message.fields;\n this.parsers = message.fields.map((field) => this.types.getTypeParser(field.dataTypeID, field.format ?? \"text\"));\n }\n\n handleDataRow(message: { fields: readonly (string | null)[] }): void {\n if (this.settled || this.rowError !== undefined) return;\n if (this.steps[this.outcomes.length]?.discardRows === true) return;\n // Same object shape as node-postgres' default row mode: one property per\n // column in RowDescription order; a repeated name keeps its first position\n // and its last value.\n const row: Record<string, unknown> = {};\n try {\n for (let index = 0; index < this.fields.length; index++) {\n const raw = message.fields[index] ?? null;\n row[(this.fields[index] as RowDescriptionField).name] = raw === null ? null : (this.parsers[index] as (value: string) => unknown)(raw);\n }\n } catch (error) {\n // APPROVED driver boundary (plan §3 \"Final-review decisions\", RV5 MJ-2):\n // a type parser (the application's global `pg.types` reach it through\n // EXACT_TYPES) may throw. Escaping here would leave node-postgres'\n // socket `data` handler mid-buffer — the batch never settles and the\n // error becomes an uncaught exception. node-postgres' own Query keeps\n // the first parser error, skips the remaining rows and rejects with it\n // (`_canceledDueToError`); the batch reports it as this step's failure.\n this.rowError = { error };\n return;\n }\n this.rows.push(row);\n }\n\n handleCommandComplete(message: { text?: string; command?: string }): void {\n if (this.settled) return;\n if (this.rowError !== undefined) {\n // The server ran the step; its rows could not be decoded.\n this.outcomes.push({ status: \"failed\", error: this.rowError.error });\n this.rowError = undefined;\n this.rows = [];\n this.fields = [];\n this.parsers = [];\n return;\n }\n const match = COMMAND_TAG.exec(message.text ?? message.command ?? \"\");\n const command = match?.[1];\n const rowCount = match?.[3] !== undefined\n ? Number.parseInt(match[3], 10)\n : match?.[2] !== undefined ? Number.parseInt(match[2], 10) : null;\n this.outcomes.push({ status: \"ok\", result: { rows: this.rows, rowCount, ...(command === undefined ? {} : { command }) } });\n this.rows = [];\n this.fields = [];\n this.parsers = [];\n }\n\n handleEmptyQuery(): void {\n if (this.settled) return;\n this.outcomes.push({ status: \"ok\", result: { rows: [], rowCount: null } });\n }\n\n handleError(error: unknown): void {\n if (this.settled) return;\n if (!isServerError(error)) {\n // No server answer: the socket broke, or `query_timeout` fired with the\n // batch still on the wire (node-postgres keeps the query running there).\n this.finish({ transportError: error });\n return;\n }\n // The server skips everything up to the Sync: the remaining steps never\n // ran. Settle NOW: node-postgres drops the active query before routing an\n // ErrorResponse (pg 8.23 `client.js` `_handleErrorMessage`), so this\n // batch never sees its ReadyForQuery. The client queues the next query\n // until that ReadyForQuery arrives, so a ROLLBACK sent after this still\n // runs after the Sync. A parser failure of this step wins, as in\n // node-postgres' Query.\n this.outcomes.push({ status: \"failed\", error: this.rowError === undefined ? error : this.rowError.error });\n while (this.outcomes.length < this.steps.length) this.outcomes.push({ status: \"skipped\" });\n this.finish({});\n }\n\n handleReadyForQuery(): void {\n this.finish({});\n }\n\n handlePortalSuspended(): void {\n // Never requested: every Execute asks for all rows.\n }\n\n handleCopyInResponse(connection: unknown): void {\n (connection as BatchConnection).sendCopyFail?.(\"COPY FROM STDIN is not supported inside a batch\");\n }\n\n handleCopyData(): void {\n // COPY TO STDOUT data is not collected (node-postgres' Query ignores it too).\n }\n\n private finish(params: { transportError?: unknown }): void {\n if (this.settled) return;\n this.settled = true;\n this.callback?.(params.transportError ?? null);\n this.resolve({\n steps: this.outcomes,\n ...(params.transportError === undefined ? {} : { transportError: params.transportError }),\n });\n }\n}\n\n/** Run `steps` as one batch on `client` and wait for it to settle. */\nexport async function runBatch(params: {\n /** A checked-out client that passed {@link supportsBatch}. */\n client: { query: (...args: never[]) => unknown };\n steps: readonly BatchStep[];\n types: BatchTypeParsers;\n}): Promise<BatchOutcome> {\n const batch = new PgBatch({ steps: params.steps, types: params.types });\n (params.client.query as (submittable: PgBatch) => unknown).call(params.client, batch);\n return batch.done;\n}\n\n/**\n * The first failure of a settled batch: the transport error, or the first\n * failed step with its index. `undefined` when every step succeeded.\n */\nexport function firstBatchFailure(params: { outcome: BatchOutcome }): { readonly index: number; readonly error: unknown } | undefined {\n const { outcome } = params;\n const index = outcome.steps.findIndex((step) => step.status === \"failed\");\n if (index !== -1) return { index, error: (outcome.steps[index] as { error: unknown }).error };\n if (outcome.transportError !== undefined) return { index: outcome.steps.length, error: outcome.transportError };\n return undefined;\n}\n",
5
+ "/**\n * @vibeorm/adapter-pg — node-postgres (`pg`) adapter for VibeORM v2.\n *\n * Runs on Bun and Node. Owns pooling, optional named prepared statements,\n * transactions (nested → savepoints on the same client) and driver-error\n * mapping. Only `VibeError` ever escapes.\n */\n\nimport type {\n AdapterBudgetSupport,\n DatabaseAdapter,\n PipelineGroup,\n PipelineLane,\n QueryResult,\n RowChangeCount,\n StatementEffect,\n TransactionOptions,\n WireFidelity,\n} from \"@vibeorm/runtime\";\nimport {\n assertReadExecution,\n readCancelledError,\n markTransactionAborted,\n runReadExecution,\n type BudgetStage,\n abortTransactionOnServerFailure,\n createDeferredControl,\n type DeferredControl,\n observeRowChanges,\n readRowChanges,\n statementRowChanges,\n createAdapterLifecycleGate,\n runPinnedSession,\n runShutdownCleanup,\n transactionLifecycleRefusal,\n createSavepointScope,\n engineStatementBudgetMs,\n type CommitProgress,\n findRefusedSetting,\n isSavepointRollbackFailedError,\n readOnlyRequested,\n readTransactionSettings,\n renderTransactionSettings,\n type RollbackOutcome,\n transactionSettingRefusedError,\n type TransactionSettingsStatement,\n runNestedSavepoint,\n runRootScope,\n type SavepointScope,\n scopeTurn,\n settleFailedTransaction,\n startTransactionBudget,\n type TransactionBudget,\n transactionAbortedError,\n validateTransactionDeadline,\n parseExtendedDateTimeText,\n assertStatementName,\n} from \"@vibeorm/runtime/adapter-kit\";\nimport { VibeError } from \"@vibeorm/schema\";\nimport type { Dialect, Provider } from \"@vibeorm/schema\";\nimport pg from \"pg\";\nimport { batchDriverAvailable, firstBatchFailure, prepareBatchValues, runBatch, supportsBatch, type BatchOutcome, type BatchStep } from \"./batch.ts\";\nimport { openConnectionGroup, type ConnectionGroupDriver, type ConnectionGroupEntry } from \"./connection-group.ts\";\nimport { honourSystemRootCert } from \"./connection-string.ts\";\nimport { createClientTurns } from \"./client-turns.ts\";\nimport { createPgReadCancellation, type PgReadCancellation } from \"./read-cancellation.ts\";\nimport { mapPgDriverError, runMapped } from \"./errors.ts\";\nimport { PgArrayParam, serializeParams, serializeParamsRaw } from \"./params.ts\";\nimport { assertIdleTimeout, assertPlanCacheMode, assertPoolMin, buildPoolConfig, type PlanCacheMode } from \"./pool-config.ts\";\nimport { createRawStatementNames, createStatementNameCache, type RawStatementNames, type StatementNameCache } from \"./statement-cache.ts\";\nimport { parsePlainTimestampText } from \"./timestamp-text.ts\";\nimport {\n beginStatement,\n classifyRawTransactionControl,\n isSingleStatementText,\n openTransactionStatement,\n refuseNestedTransactionOptions,\n statementTimeoutStatement,\n} from \"./transaction-sql.ts\";\n\n// ─── Minimal pg surface ───────────────────────────────────────────\n\n/** The single `pg` query form this adapter uses (config object, never overloads). */\nexport type PgQueryConfig = {\n readonly text: string;\n readonly values?: unknown[];\n readonly name?: string;\n /**\n * QUERY-LOCAL result parsers ({@link EXACT_TYPES}). node-postgres reads this\n * off the query config, so nothing outside VibeORM's own statements is\n * affected — a caller's pool keeps the driver's documented behaviour.\n */\n readonly types?: PgTypeParsers;\n};\n\n/** The `pg-types` surface a query config may carry. */\nexport type PgTypeParsers = {\n getTypeParser(oid: number, format?: \"text\" | \"binary\"): (value: string) => unknown;\n};\n\n/** The parts of a `pg` result this adapter reads. */\nexport type PgQueryResultLike = {\n readonly rows: Record<string, unknown>[];\n readonly rowCount: number | null;\n /**\n * The command tag (`INSERT`, `COMMIT`, `ROLLBACK`, …). Optional so test\n * doubles need not supply it; the adapter reads it after `COMMIT`, which\n * PostgreSQL answers with `ROLLBACK` — and no error — when the transaction\n * was aborted.\n */\n readonly command?: string;\n};\n\n/** pg returns one result per command for simple-protocol scripts. */\nexport type PgQueryResultsLike = PgQueryResultLike | PgQueryResultLike[];\n\n/** The parts of a `pg` PoolClient this adapter uses. */\nexport type PgPoolClientLike = {\n query(config: PgQueryConfig): Promise<PgQueryResultsLike>;\n /** Installed pg pipelined end waits for drain; strong cancellation refuses that lifetime. */\n readonly pipeline?: boolean;\n /** Local rejection timeouts cannot prove original statement settlement. */\n readonly connectionParameters?: { readonly query_timeout?: number };\n /**\n * Hand the client back. A TRUTHY argument tells node-postgres to DESTROY it\n * instead of pooling it — used when a rollback failed and the session state\n * can no longer be asserted (EPIC 6). Optional so existing test doubles that\n * declare `release(): void` still satisfy this type.\n */\n release(destroy?: boolean): void;\n /**\n * EventEmitter surface. A real `pg.PoolClient` has it; test doubles need not,\n * so both members are optional and the adapter feature-detects them.\n */\n on?(event: \"error\", listener: (error: unknown) => void): void;\n removeListener?(event: \"error\", listener: (error: unknown) => void): void;\n};\n\n/** The parts of a `pg` Pool this adapter uses — satisfied by a real `pg.Pool`. */\nexport type PgPoolLike = {\n connect(): Promise<PgPoolClientLike>;\n query(config: PgQueryConfig): Promise<PgQueryResultsLike>;\n end(): Promise<void>;\n /** EventEmitter surface; optional for the same reason as on {@link PgPoolClientLike}. */\n on?(event: \"error\", listener: (error: unknown, client: PgPoolClientLike) => void): void;\n};\n\n/** Anything that can run a query: the pool itself or a checked-out client. */\ntype Queryable = { query(config: PgQueryConfig): Promise<PgQueryResultsLike> };\n\ntype TransactionDispatch = (params: {\n config: PgQueryConfig;\n execution?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"execution\"];\n onReadControl?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"onReadControl\"];\n stage?: BudgetStage;\n cleanup?: boolean;\n /**\n * The text is ONE statement and may ride in a one-Sync batch behind pending\n * control (EPIC 6). False for raw text without bound values that is not\n * provably one statement ({@link isSingleStatementText}): node-postgres sends\n * it as a simple-protocol message that may hold several statements.\n */\n batchable?: boolean;\n /**\n * Called immediately before the statement is handed to node-postgres —\n * after every check that can still refuse it. COMMIT uses it to record that\n * it was sent, the fact its outcome is decided by (EPIC T).\n */\n sent?: () => void;\n /** The `$all` pipeline lane that issued the statement (see {@link PipelineControl}). */\n lane?: PipelineLaneState;\n /**\n * The transaction's LAST statement (`withCommit`, statement-count pass EPIC\n * 5): COMMIT rides right behind it when the transaction can carry it now.\n */\n commit?: true;\n /** With `commit`: nobody reads the reply's rows — a riding batch does not decode them. */\n discardRows?: true;\n /**\n * A RAW statement's caller-chosen name (`executeUnsafe({ name })`, equal to\n * `config.name`): its batch step is named too, so a batch or the COMMIT ride\n * parses it once per connection. The ORM path's content-addressed names\n * (`preparedStatements`) never set it: in a batch they stay unnamed, as before.\n */\n name?: string;\n}) => Promise<PgQueryResultsLike>;\n\n// ─── `$all` pipeline (DatabaseAdapter.pipeline) ─────────────────────\n\n/** One lane of a pipeline scope: the handle ONE operation issues its statements through. */\ntype PipelineLaneState = {\n open: boolean;\n /** This lane's calls that are waiting: queued in the pipeline, on the wire, or for a savepoint turn. */\n waiting: number;\n /** The lane's place in an ORDERED scope (`pipeline({ ordered: true })`); absent on `$all` lanes. */\n readonly order?: OrderedLaneState;\n /** The lane issued its transaction-final statement (`withCommit`, EPIC 5): it issues nothing after it (D2 admission). */\n final?: boolean;\n /** The group this lane opened and that is not over yet (D2): the lane counts as waiting meanwhile. */\n group?: LaneGroupState;\n /** A sub-lane of a group (D2): its place, and whether it issued its ONE statement. */\n readonly seat?: { readonly group: LaneGroupState; readonly index: number; issued: boolean };\n /** The gate of a group (D2): open and never waiting, it holds the batch until the group is sealed. */\n readonly gate?: true;\n};\n\n/**\n * An ordered group of sub-lanes one `$all` lane opened (statement-count pass\n * D2, `PipelineLane.group`): its sibling relation loads. The parent counts as\n * waiting until the group is over (sealed and every sub-lane closed); the\n * gate holds the batch until the group is sealed.\n */\ntype LaneGroupState = {\n readonly parent: PipelineLaneState;\n readonly gate: PipelineLaneState;\n /** Sub-lanes opened so far (the next one's index). */\n opened: number;\n /** Sub-lanes not closed yet. */\n live: number;\n sealed: boolean;\n /**\n * Lane A2 (`PipelineLane.group({ final: true })`): the transaction's last\n * statements, on a handle that can carry COMMIT — COMMIT may ride behind\n * the group's batch (`ridesQueued`).\n */\n readonly final: boolean;\n};\n\n/**\n * A lane of an ordered scope — the array form of `$transaction` (efficiency\n * campaign, EPIC D). Its statements leave only after every earlier lane issued\n * one, in lane order, and each send of the scope waits for the previous one.\n */\ntype OrderedLaneState = {\n readonly scope: OrderedScope;\n /** Position in the scope. */\n readonly index: number;\n /** Statements this lane issued into the pipeline (cleanup control is not counted). */\n issued: number;\n /** A later lane follows this one: it may issue ONE statement. */\n followed: boolean;\n};\n\n/** One ordered scope: its lanes, in order (closed ones included, for the prefix rule). */\ntype OrderedScope = {\n readonly lanes: PipelineLaneState[];\n /**\n * The first failure of one of the scope's sends, a failure without a server\n * answer included (a client-side `query_timeout`, a value the driver\n * refuses): nothing of the scope is sent after it.\n */\n failed?: { readonly cause: VibeError };\n};\n\n/** A lane statement waiting in the pipeline; its values are already serialized for the batch. */\ntype QueuedStatement = {\n readonly text: string;\n readonly values: unknown[];\n /** A raw statement's caller-chosen name (`TransactionDispatch` `name`): its step is named. */\n readonly name?: string;\n readonly execution?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"execution\"];\n readonly lane: PipelineLaneState;\n /**\n * Ordered scopes only: a statement that keeps its own turn (raw text without\n * bound values that may hold several statements, savepoint control, the\n * strong-cancellation queue). It is sent\n * by itself, with these dispatch parameters, once the scope's earlier sends\n * settled.\n */\n readonly alone?: Parameters<TransactionDispatch>[0];\n /** The transaction's last statement (`withCommit`): COMMIT may ride behind the batch that carries it. */\n readonly commit?: true;\n readonly resolve: (result: PgQueryResultsLike) => void;\n readonly reject: (error: unknown) => void;\n settled: boolean;\n /** The error this statement was settled with, when it failed (read by the ordered scope's barrier). */\n failure?: unknown;\n};\n\n/**\n * In-flight gathering (round-trip report V4, decision D3): ordinary statements\n * of a transaction that WAIT — behind the burst carrying the deferred opening\n * (`\"opening\"`), or for the client to finish another call (`\"turn\"`, one slot of\n * the client's turns) — and leave together, in issue order, when that wait\n * ends. No window: a statement that finds nothing to wait for is sent at once.\n * The group takes statements only while nothing else was registered after it.\n */\ntype GatheringGroup = {\n readonly phase: \"opening\" | \"turn\";\n /** `\"opening\"`: the in-flight burst the group waits for. */\n readonly behind?: Promise<void>;\n readonly members: GatheredStatement[];\n};\n\n/** One statement waiting in a {@link GatheringGroup}. */\ntype GatheredStatement = {\n readonly params: Parameters<TransactionDispatch>[0];\n /** Serialized when the statement joined: a value the driver refuses fails that statement alone. */\n readonly values: unknown[];\n readonly resolve: (result: PgQueryResultsLike) => void;\n readonly reject: (error: unknown) => void;\n};\n\n/**\n * The pipeline of ONE top-level transaction. Statements the lanes issue wait\n * here and go out TOGETHER, as one one-Sync batch with any deferred control in\n * front, once every open lane is waiting — on a queued statement, on a reply,\n * or on a savepoint turn — or closed. An explicit signal from the runtime (the\n * lanes and their `close`), never a timer.\n */\ntype PipelineControl = {\n /** Register `count` open lanes. */\n readonly open: (count: number) => PipelineLaneState[];\n /** Register `count` open lanes of a new ORDERED scope. */\n readonly openOrdered: (count: number) => PipelineLaneState[];\n /** Open the lane right after `lane`, the last lane of its ordered scope; `lane` may then issue one statement. */\n readonly follow: (lane: PipelineLaneState) => PipelineLaneState;\n /** The lane's operation settled. Idempotent. */\n readonly close: (lane: PipelineLaneState) => void;\n /** Count `lane` as waiting while `wait` is pending (a savepoint turn, an unbatched statement). */\n readonly waitAs: <T>(params: { lane: PipelineLaneState; wait: Promise<T> }) => Promise<T>;\n /** Count `lane` as waiting until the returned release runs (idempotent). */\n readonly enter: (lane: PipelineLaneState) => () => void;\n /** Send whatever is queued now, whatever the lanes are doing. */\n readonly flush: () => void;\n /**\n * D2: open a group on `lane`, or `undefined` when a group cannot keep the order now (see `PipelineLane.group`).\n * `final` (lane A2): the transaction's last statements, on a handle that can carry COMMIT.\n */\n readonly group: (lane: PipelineLaneState, final: boolean) => LaneGroupState | undefined;\n /** D2: open the group's next sub-lane (before it is sealed). */\n readonly seat: (group: LaneGroupState) => PipelineLaneState;\n /** D2: no more sub-lanes; the gate opens. Idempotent. */\n readonly seal: (group: LaneGroupState) => void;\n};\n\n/** A broken use of a lane group (D2) — a runtime defect, refused before anything is sent. */\nfunction laneGroupMisuse(params: { message: string }): VibeError {\n return new VibeError({ code: \"VIBE_INTERNAL\", message: `pipeline lane group: ${params.message}`, meta: { reason: \"pipeline-lane-group\" } });\n}\n\n/** PostgreSQL's ceiling for `statement_timeout` (an int4 of milliseconds). */\nconst MAX_STATEMENT_TIMEOUT_MS = 2_147_483_647;\n\nconst ignore = (): undefined => undefined;\n\n/** An ordered-scope statement whose earlier lane closed without issuing one: it is never sent (EPIC D). */\nfunction predecessorClosedError(): VibeError {\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message:\n \"pipeline(): an earlier lane of this ordered scope closed without issuing its statement, so this statement was not sent \" +\n \"(the operation before it failed before it reached the database)\",\n meta: { reason: \"pipeline-predecessor-closed\" },\n });\n}\n\n/** A broken use of an ordered scope's lanes — a runtime defect, refused before anything is sent. */\nfunction orderedLaneMisuse(params: { message: string }): VibeError {\n return new VibeError({ code: \"VIBE_INTERNAL\", message: `pipeline(): ${params.message}`, meta: { reason: \"pipeline-ordered-lane\" } });\n}\n\n/**\n * A COMMIT that rode with a transaction's last statement (statement-count pass\n * EPIC 5, `withCommit`). Its batch decides the transaction: `committed`;\n * `skipped` (the statement before it failed, so the server never ran it);\n * `failed` (answered with an error or a ROLLBACK tag); `lost` (no answer).\n */\ntype RiddenCommit = {\n /** Settles once the batch that carried it settled; never rejects. */\n settled: Promise<void>;\n state: \"in-flight\" | \"committed\" | \"skipped\" | \"failed\" | \"lost\";\n /** `failed`: COMMIT's mapped error; `lost`: the outcome-unknown error. */\n error?: unknown;\n};\n\n/** The COMMIT step that rides behind a transaction's last statement. */\nconst COMMIT_STEP: BatchStep = Object.freeze({ text: \"COMMIT\" });\n\n/** A statement sent after a riding COMMIT left the client (EPIC 5): it is never sent. */\nfunction commitSentRefusal(): VibeError {\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message: \"this transaction already sent its COMMIT together with its last statement, so it accepts no further statement\",\n meta: { provider: PROVIDER, reason: \"commit-sent\" },\n });\n}\n\n/** A second statement through one `withCommit` view — a runtime defect, refused before anything is sent. */\nfunction finalStatementMisuse(): VibeError {\n return new VibeError({\n code: \"VIBE_INTERNAL\",\n message: \"withCommit(): a view carries ONE statement, the transaction's last\",\n meta: { reason: \"with-commit-second-statement\" },\n });\n}\n\n/**\n * A riding batch's outcome as its statements see it: without the COMMIT step.\n * A failure only the COMMIT step saw (an error answer, or a connection lost\n * after the statements were answered) belongs to the transaction, not to them.\n */\nfunction beforeCommit(params: { outcome: BatchOutcome; commitIndex: number }): BatchOutcome {\n const { outcome, commitIndex } = params;\n const steps = outcome.steps.slice(0, commitIndex);\n return steps.length < commitIndex && outcome.transportError !== undefined ? { steps, transportError: outcome.transportError } : { steps };\n}\n\nfunction finalResult(params: { result: PgQueryResultsLike }): PgQueryResultLike {\n return Array.isArray(params.result)\n ? (params.result.at(-1) ?? { rows: [], rowCount: 0 })\n : params.result;\n}\n\n/**\n * Keep a CHECKED-OUT client's background failures from killing the process,\n * returning the detach to run before the client goes back to the pool.\n *\n * node-postgres listens for `'error'` on a pooled client only while that client\n * sits IDLE, and removes the listener the moment the client is checked out\n * (restoring it on release). A client this adapter holds — for a transaction,\n * or as a pinned raw session — therefore has NO listener, so a backend that\n * dies mid-transaction reaches `client.emit('error', …)` with none. An\n * `'error'` event without a listener is an uncaught exception: fatal under\n * Node, which turns a database failover into a dead application process.\n *\n * The listener deliberately does nothing with the error and is NOT an error\n * channel: the in-flight query already rejects on its own with the mapped\n * `VibeError`, and the pool discards the broken client. Its only job is to keep\n * the process alive. Detaching before `release()` matters just as much — a\n * listener left attached would shadow pg's own idle listener and stop the pool\n * evicting a client that fails later, while idle.\n */\n/**\n * Prepared-statement name registries, one per POOL (F16/F18) — see\n * ./statement-cache.ts for why they are shared and bounded. Weakly held, so a\n * pool that goes out of scope takes its registry with it.\n */\nconst POOL_STATEMENT_NAMES: WeakMap<PgPoolLike, StatementNameCache> = new WeakMap();\n\n/** The caller-chosen raw names' texts, one registry per POOL (one name = one text on every connection). */\nconst POOL_RAW_STATEMENT_NAMES: WeakMap<PgPoolLike, RawStatementNames> = new WeakMap();\n\n/**\n * Whether a mapped driver failure means the CONNECTION is gone rather than the\n * server having answered: no SQLSTATE at all (socket-level), class 08\n * (connection exception) or an admin/crash shutdown (57P01–57P03). The same\n * rule pins a migration session as lost and decides whether a failed COMMIT's\n * outcome is unknown.\n */\nfunction isConnectionLoss(params: { error: unknown }): boolean {\n const { error } = params;\n if (!(error instanceof VibeError)) return true;\n const sqlstate = error.meta.sqlstate;\n return typeof sqlstate !== \"string\" || sqlstate.startsWith(\"08\") || [\"57P01\", \"57P02\", \"57P03\"].includes(sqlstate);\n}\n\n/**\n * A COMMIT whose acknowledgement never arrived: the write may or may not be\n * durable, and nothing on the client can tell. The mysql and bun adapters\n * report the same shape (`transaction-outcome-unknown`, stage `commit`).\n */\nfunction commitOutcomeUnknownError(params: { cause: unknown }): VibeError {\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message:\n \"the connection was lost while COMMIT was in flight, so the transaction's outcome is unknown: the write may have committed. The connection was discarded; inspect the data before retrying.\",\n meta: { provider: PROVIDER, reason: \"transaction-outcome-unknown\", outcome: \"unknown\", stage: \"commit\" },\n cause: params.cause,\n });\n}\n\n/**\n * SQLSTATE classes after which a session is never reused, whatever its\n * transaction status says: connection exception, insufficient resources,\n * operator intervention, system error, internal error.\n */\nconst NEVER_REUSE_SQLSTATE_CLASSES: ReadonlySet<string> = new Set([\"08\", \"53\", \"57\", \"58\", \"XX\"]);\n\n/**\n * SQLSTATEs after which a NAMED prepared statement can no longer be trusted on\n * the session that ran it (fix lane FX-A, RV2 MJ-1): the client's record of\n * the name and the backend's disagree. node-postgres keeps a name it once\n * parsed (`parsedStatements`) across errors, so a reused session would fail\n * the same way on every later call:\n * - `0A000` — \"cached plan must not change result type\" after a schema change;\n * - `26000` — the backend does not know the name (a transaction-mode pooler);\n * - `42P05` — the backend already holds the name, so every Parse is refused.\n * Destroying the client makes the next call prepare on a fresh session — the\n * self-healing behaviour `pool.query` gave before round-trip EPIC 3.\n */\nconst STALE_STATEMENT_SQLSTATES: ReadonlySet<string> = new Set([\"0A000\", \"26000\", \"42P05\"]);\n\n/**\n * Whether a NAMED statement's failure leaves its session untrustworthy\n * ({@link STALE_STATEMENT_SQLSTATES}). The transaction path discards such a\n * connection at release, as the root path does (`reusableAfter`).\n */\nfunction isStaleStatementFailure(params: { error: unknown }): boolean {\n const sqlstate = mapPgDriverError({ error: params.error }).meta.sqlstate;\n return typeof sqlstate === \"string\" && STALE_STATEMENT_SQLSTATES.has(sqlstate);\n}\n\n/** The node-postgres `Client` members the reuse seam needs; feature-detected, never assumed. */\ntype ReadyForQuerySurface = {\n getTransactionStatus?: () => string | null;\n on?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n removeListener?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n once?: unknown;\n pipeline?: unknown;\n};\n\n/** What the root path learns from one checked-out client while its query runs. */\ntype ReadyForQuerySeam = {\n /**\n * After a failure: may this client go back to the pool? Never true without\n * proof. `named`: the failing query was a named prepared statement.\n */\n readonly reusableAfter: (params: { error: unknown; named: boolean }) => Promise<boolean>;\n /** Remove every listener; runs before the client is released. */\n readonly detach: () => void;\n};\n\n/**\n * Round-trip EPIC 3 (A-12): prove that a root ORM statement's failure left its\n * session idle, so the client can be pooled instead of destroyed (today\n * `pool.query` destroys it on ANY error, and the next call pays a reconnect).\n *\n * Listeners for `drain` / `error` / `end` are attached BEFORE the query is\n * submitted. node-postgres sets `readyForQuery = false` when it sends a query\n * on an idle client and emits `drain` only from `_pulseQueryQueue` after\n * `_handleReadyForQuery` stored the status of THAT query's ReadyForQuery\n * (pg 8.23 `client.js` 373-396, 616-641), so the first `drain` after\n * submission carries the failing query's own status. Sampling the status at\n * rejection instead is timing-dependent (spike §3: stale in 59/200 compound\n * runs). A lost connection emits `error` / `end`, so the wait always ends.\n *\n * Reuse needs ALL of: the mapped error has a SQLSTATE outside\n * {@link NEVER_REUSE_SQLSTATE_CLASSES} (and, for a named statement, outside\n * {@link STALE_STATEMENT_SQLSTATES}); the first event was `drain`; the status\n * after it is `I`; no `error` event during the checkout. Anything else destroys\n * the client — today's behaviour. The `error` listener also keeps a background\n * failure of the checked-out client from becoming an uncaught exception (see\n * {@link guardBackgroundErrors}). Only for a client that passed\n * {@link hasReadyForQuerySeam}.\n */\nfunction observeReadyForQuery(params: { client: PgPoolClientLike }): ReadyForQuerySeam {\n const client = params.client as PgPoolClientLike & Required<Pick<ReadyForQuerySurface, \"on\" | \"removeListener\" | \"getTransactionStatus\">>;\n let backgroundFailure = false;\n let settle: (event: \"drain\" | \"error\" | \"end\") => void = () => undefined;\n const firstEvent = new Promise<\"drain\" | \"error\" | \"end\">((resolve) => { settle = resolve; });\n const onDrain = (): void => settle(\"drain\");\n const onError = (): void => { backgroundFailure = true; settle(\"error\"); };\n const onEnd = (): void => settle(\"end\");\n client.on(\"error\", onError);\n client.on(\"drain\", onDrain);\n client.on(\"end\", onEnd);\n return {\n reusableAfter: async ({ error, named }) => {\n if (!(error instanceof VibeError)) return false;\n const sqlstate = error.meta.sqlstate;\n if (typeof sqlstate !== \"string\" || NEVER_REUSE_SQLSTATE_CLASSES.has(sqlstate.slice(0, 2))) return false;\n if (named && STALE_STATEMENT_SQLSTATES.has(sqlstate)) return false;\n const event = await firstEvent;\n return event === \"drain\" && !backgroundFailure && client.getTransactionStatus() === \"I\";\n },\n detach: () => {\n client.removeListener(\"error\", onError);\n client.removeListener(\"drain\", onDrain);\n client.removeListener(\"end\", onEnd);\n },\n };\n}\n\n/**\n * Whether a checked-out client exposes node-postgres' events and status the\n * reuse seam needs (`on`, `removeListener`, `once`, `getTransactionStatus`) and\n * is not a `pipeline: true` client. A client without them (an injected pool's\n * wrapper) cannot even carry the `error` listener that keeps a socket failure\n * from becoming an uncaught exception, so the root path never runs a\n * statement on it (fix lane FX-A, RV2 MJ-3).\n */\nfunction hasReadyForQuerySeam(params: { client: PgPoolClientLike }): boolean {\n const client = params.client as PgPoolClientLike & ReadyForQuerySurface;\n return typeof client.on === \"function\" &&\n typeof client.removeListener === \"function\" &&\n typeof client.once === \"function\" &&\n typeof client.getTransactionStatus === \"function\" &&\n client.pipeline !== true;\n}\n\nfunction guardBackgroundErrors(params: { client: PgPoolClientLike; onError?: (error: unknown) => void }): () => void {\n const { client, onError } = params;\n if (typeof client.on !== \"function\") return (): void => undefined;\n const swallow = (error: unknown): void => {\n /* the failing call rejects with a mapped VibeError; nothing to report here */\n onError?.(error);\n };\n client.on(\"error\", swallow);\n return (): void => {\n client.removeListener?.(\"error\", swallow);\n };\n}\n\n// ─── Options ──────────────────────────────────────────────────────\n\n/**\n * Every {@link pgAdapter} option. {@link PgAdapterOptions} adds the rule that\n * one of `connectionString` and `pool` is present.\n */\nexport type PgAdapterSettings = {\n /**\n * PostgreSQL connection URL. The adapter never reads `DATABASE_URL` (or any\n * other environment variable) itself: pass the URL you mean. Give a complete\n * URL — node-postgres fills parts the URL omits (host, user, database, …)\n * from the `PG*` environment variables.\n *\n * libpq's `sslrootcert=system` (as in PlanetScale's URLs) is accepted:\n * the adapter verifies the server certificate's chain and host name against\n * the runtime's default trust store (`sslmode=verify-full`), and refuses a\n * weaker `sslmode` next to it with `VIBE_CONFIG`, as libpq does.\n */\n readonly connectionString?: string;\n /**\n * An existing `pg.Pool` to use instead of creating one. The adapter never\n * ends a pool it did not create: `disconnect()` only ends this adapter (and\n * rolls back and releases its own raw session); the pool stays usable.\n * Wins over `connectionString` when both are given.\n *\n * `connect()` must return a distinct client object for each physical\n * connection and never hand the same object out for another one (node-postgres\n * `pg.Pool` does: a `Client` never reconnects). The returned object is the\n * transaction's `connectionIdentity`, which native-RLS per-connection\n * verdicts and the operator login check are keyed on.\n */\n readonly pool?: PgPoolLike;\n /** Maximum pooled connections (default 10). Ignored when `pool` is given. */\n readonly max?: number;\n /**\n * Connections the pool keeps open however long they sit idle (pg-pool's\n * `min`; default 0). `adapter.connect()` (`db.$connect()`) opens this many\n * at once, so a burst of parallel queries finds them warm instead of paying\n * TCP + startup + authentication per connection — about three round trips\n * each, more with TLS. Must be an integer from 0 through `max`, else the\n * factory throws `VIBE_CONFIG`. Refused next to `pool` (`VIBE_CONFIG`): the\n * adapter cannot change a caller's pool — set `min` on that pool instead.\n */\n readonly min?: number;\n /**\n * Pool-wide `statement_timeout` in milliseconds. Every connection inherits\n * it; a per-transaction `timeout` overrides it for that transaction.\n */\n readonly statementTimeout?: number;\n /** Milliseconds to wait for a pool checkout before failing (pg's `connectionTimeoutMillis`). */\n readonly connectionTimeout?: number;\n /**\n * Milliseconds a pooled connection may sit idle before the pool closes it\n * (pg-pool's `idleTimeoutMillis`). Unset keeps pg-pool's default of 10 000:\n * the next query after a quiet spell then opens a new connection (TCP,\n * startup, authentication — ≈ 2.4 ms locally, more over TLS). `0` keeps idle\n * connections open until the server or network closes them; a longer value\n * trades held server connections for fewer reconnects. Must be integer\n * milliseconds from 0 through 2,147,483,647, else the factory throws\n * `VIBE_CONFIG`. Ignored when\n * `pool` is given: set `idleTimeoutMillis` on that pool.\n */\n readonly idleTimeout?: number;\n /** Separate direct/session-pinned PostgreSQL control endpoint for running reads.\n * Required with an injected pool; never inferred from that pool or ambient env.\n * The same role must be allowed to signal its target. Server support needs live acceptance.\n */\n readonly cancellationConnectionString?: string;\n /**\n * Send ORM-path queries as named prepared statements (default false).\n *\n * Measured on this repo's benchmark (postgres 16, interleaved rounds):\n * −17…−25 % on reads, −6 % on a by-key update — the server skips the\n * parse/analyze and the protocol Parse/Describe round on every repeat. The\n * gain survives {@link PgAdapterOptions.planCacheMode} `force_custom_plan`,\n * which removes the classic downside (a generic plan after ~5 executions\n * picking worse indexes for range/LIKE/skewed filters).\n *\n * Off by default because named statements live on the BACKEND connection:\n * behind a transaction-mode pooler (PgBouncer before 1.21 or with\n * `max_prepared_statements = 0`, Supavisor, Neon's pooler) a client that\n * remembers a name from an earlier transaction is handed another backend\n * later. Names are collision-resistant (`vibeorm_` + the SHA-256 of the exact\n * text, see `statementNameFor`), so a name can only ever stand for its own\n * text: the remaining failure is a typed `VIBE_ADAPTER` error (SQLSTATE 26000\n * or 42P05), never another statement's rows. Turn it on for direct\n * connections, session pooling, or PgBouncer 1.21+ with\n * `max_prepared_statements > 0`.\n *\n * Schema changes can invalidate a retained result descriptor (SQLSTATE\n * 0A000). No statement or transaction callback is retried. Drain traffic and\n * recycle backend connections across incompatible schema deployments. For\n * an injected pool its owner must replace the pool; adapter.disconnect()\n * does not end it. force_custom_plan does not remove this requirement.\n */\n readonly preparedStatements?: boolean;\n /**\n * Budget of prepared-statement NAMES per pool (default 1000). Names never\n * evict — a name evicted here would stay prepared on every backend that saw\n * it — so this is a bound on the server's retention per connection, and a\n * text arriving after the budget is spent runs unnamed (it still binds its\n * parameters; only the server-side plan cache is skipped). A name is\n * allocated on a text's SECOND sighting, so one-off texts — offset pagination\n * emits one per page — never spend the budget.\n */\n readonly stmtCacheMax?: number;\n /**\n * PostgreSQL `plan_cache_mode` for every connection of the pool this adapter\n * builds (default `\"auto\"`, the server default — nothing is sent). Pair\n * `\"force_custom_plan\"` with {@link PgAdapterOptions.preparedStatements}: the\n * statement is still prepared once, but planned with the real parameter\n * values on every execution. Rides the `options` startup parameter, merged\n * with whatever the connection string already carries (a URL that sets\n * `plan_cache_mode` itself wins). Refused with `VIBE_CONFIG` together with\n * a caller-supplied `pool` — the adapter never reconfigures a pool it does\n * not own; set it on that pool's own `options` instead.\n */\n readonly planCacheMode?: PlanCacheMode;\n};\n\n/**\n * Options for {@link pgAdapter}: an explicit address is required. Either point\n * it at a connection string (the adapter then owns the pool it creates) or hand\n * it a pool you already own. Without either, the factory throws `VIBE_CONFIG`\n * before any pool or connection exists.\n */\nexport type PgAdapterOptions = PgAdapterSettings &\n ({ readonly connectionString: string } | { readonly pool: PgPoolLike });\n\n// ─── Adapter ──────────────────────────────────────────────────────\n\nconst DIALECT: Dialect = \"postgres\";\nconst PROVIDER: Provider = \"postgresql\";\n\n/**\n * node-postgres wire (board #30, live-verified on both execute paths):\n * timestamptz → `Date`, json/jsonb → parsed values, int4/float8 → numbers,\n * bytea (and bytea[] elements) → `Buffer` (5.0: the join strategy's relation\n * children follow it, so both strategies return the same class).\n * (int8 stays a string — BigInt decoding is real work and never pruned.)\n */\nconst WIRE: WireFidelity = Object.freeze({ dateTime: \"native\", json: \"parsed\", numbers: \"native\", bytes: \"buffer\" } as const);\n\n/**\n * A PostgreSQL server: every round trip crosses a network (a local socket\n * included), so the runtime's one-statement folds apply. The transaction\n * facades carry the same declaration.\n */\nconst ROUND_TRIPS: NonNullable<DatabaseAdapter[\"roundTrips\"]> = \"network\";\n\n/**\n * `$all`'s snapshot: a read-only REPEATABLE READ transaction reads ONE snapshot\n * and never fails with a serialization error.\n */\nconst READ_SNAPSHOT: NonNullable<DatabaseAdapter[\"readSnapshot\"]> = Object.freeze({ isolationLevel: \"RepeatableRead\", accessMode: \"readOnly\" } as const);\n\n/**\n * Statements issued together on a transaction handle share one round trip: the\n * handle offers `pipeline()` and sends lane statements as one one-Sync batch.\n * A checked-out client that cannot batch (a wrapper, a test double) declares\n * `\"ordered\"` on its handles and offers no lanes.\n */\nconst PIPELINING: NonNullable<DatabaseAdapter[\"pipelining\"]> = \"batched\";\n\n/**\n * Timing budgets this adapter genuinely enforces (EPIC 6).\n *\n * - `acquireTimeout: true` — {@link PgAdapterOptions.connectionTimeout} maps to\n * node-postgres' `connectionTimeoutMillis`, which bounds the checkout wait\n * and rejects when the pool stays exhausted. The capability is declared here;\n * it is OFF until the option is set (pg's own default is \"wait forever\").\n * - `statementTimeout: \"all-statements\"` — PostgreSQL's `statement_timeout`\n * cancels ANY over-long statement, writes included (SQLSTATE 57014).\n * - `transactionDeadline: \"cancel-running-statements\"` — the strongest level:\n * the remaining budget is handed to the SERVER before each statement, so the\n * database itself stops work that would outlive the deadline. Nothing here is\n * a `Promise.race` over a statement that keeps running.\n */\nconst BUDGETS: AdapterBudgetSupport = Object.freeze({\n acquireTimeout: true,\n statementTimeout: \"all-statements\",\n transactionDeadline: \"cancel-running-statements\",\n accessModes: Object.freeze([\"readOnly\"] as const),\n} as const);\n\n// ─── Exact numeric arrays (F12) ───────────────────────────────\n\n/** `_numeric`: the array form of `numeric`/`DECIMAL`. */\nconst NUMERIC_ARRAY_OID = 1231;\n/** `_text`: its parser splits a postgres array literal into RAW element strings. */\nconst TEXT_ARRAY_OID = 1009;\n/** `timestamp without time zone` and `date` — the zone-less types — and their array forms. */\nconst TIMESTAMP_OID = 1114;\nconst TIMESTAMP_ARRAY_OID = 1115;\nconst DATE_OID = 1082;\nconst DATE_ARRAY_OID = 1182;\n/** `timestamp with time zone` and its array form (AW-03). */\nconst TIMESTAMPTZ_OID = 1184;\nconst TIMESTAMPTZ_ARRAY_OID = 1185;\n\n/**\n * `pg.types.getTypeParser` behind a plain numeric-OID signature. `@types/pg`\n * narrows the two-argument overload to its own `TypeId` union of well-known\n * OIDs, which does not include every array OID this function must look up.\n */\nconst driverTypeParser: (oid: number, format?: \"text\" | \"binary\") => (value: string) => unknown =\n pg.types.getTypeParser as unknown as (oid: number, format?: \"text\" | \"binary\") => (value: string) => unknown;\n\n/** postgres' text output for the zone-less types: `2026-03-08 19:38:08.538` or `2026-03-08`. */\nconst ZONE_LESS_TEXT = /^\\d{4}-\\d{2}-\\d{2}(?: \\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,6})?)?$/;\n\n/**\n * Zone-less date/timestamp text read as **UTC** — the same rule as the codec\n * table's `parseDateTimeText` (@vibeorm/sql), applied at the driver level\n * because node-postgres hands these columns to the ORM as `Date` objects\n * already (`wire.dateTime: \"native\"` prunes the codec decode). pg-types reads\n * them as host-LOCAL time, so one stored row decoded to a different instant\n * on every host TZ, and to a different instant than bun:sql, PGlite's ORM\n * path and Prisma (all UTC) return. A year of five or more digits and a BC\n * era take the codec table's extended reading (`parseExtendedDateTimeText`,\n * UTC too — 5.0: the join strategy reads the same text that way);\n * `infinity` and anything else outside those forms keep the driver's own parser.\n */\nfunction parseZoneLessAsUtc(value: string): unknown {\n // AW-03: the plain `YYYY-MM-DD HH:MM:SS[.f]` form by char codes; everything else below, as before.\n const plain = parsePlainTimestampText({ text: value, zoned: false });\n if (plain !== undefined) return plain;\n if (ZONE_LESS_TEXT.test(value)) {\n const iso = value.includes(\" \") ? `${value.replace(\" \", \"T\").replace(/(\\.\\d{3})\\d+$/, \"$1\")}Z` : value;\n const parsed = new Date(iso);\n if (!Number.isNaN(parsed.getTime())) return parsed;\n }\n return parseExtendedDateTimeText({ text: value }) ?? driverTypeParser(TIMESTAMP_OID, \"text\")(value);\n}\n\n/** The array forms: the driver's `_text` parser splits the literal, elements go through {@link parseZoneLessAsUtc}. */\nfunction parseZoneLessArrayAsUtc(value: string): unknown {\n const mapElements = (element: unknown): unknown => {\n if (element === null) return null;\n if (Array.isArray(element)) return element.map(mapElements);\n return parseZoneLessAsUtc(String(element));\n };\n return mapElements(driverTypeParser(TEXT_ARRAY_OID, \"text\")(value));\n}\n\n/** pg-types' array splitter (`arrayParser.create(source, transform).parse()`); `@types/pg` types it as a plain function. */\ntype PgTypesArrayParser = {\n readonly create: (source: string, transform: (entry: string | null) => unknown) => { readonly parse: () => unknown };\n};\n\nconst pgTypesArrayParser: PgTypesArrayParser | undefined = (() => {\n const candidate = (pg.types as unknown as { readonly arrayParser?: Partial<PgTypesArrayParser> }).arrayParser;\n return typeof candidate?.create === \"function\" ? (candidate as PgTypesArrayParser) : undefined;\n})();\n\n/**\n * pg-types' OWN text parser for `oid`, recognised once at load: pg-types\n * registers one function (`name`) for the oid and its date-typed `peers`. An\n * application that registered its own global parser for the oid keeps it —\n * {@link EXACT_TYPES} hands out the char-code parser only while the driver's\n * registered parser is still this built-in one. `undefined` when it cannot be\n * recognised (an override before load, a renamed build): today's path then.\n */\nfunction recogniseBuiltinParser(params: { oid: number; peers: readonly number[]; name: string }): ((value: string) => unknown) | undefined {\n const parser = driverTypeParser(params.oid, \"text\");\n return parser.name === params.name && params.peers.every((peer) => driverTypeParser(peer, \"text\") === parser) ? parser : undefined;\n}\n\nconst BUILTIN_TIMESTAMPTZ_PARSER: ((value: string) => unknown) | undefined = recogniseBuiltinParser({\n oid: TIMESTAMPTZ_OID,\n peers: [TIMESTAMP_OID, DATE_OID],\n name: \"parseDate\",\n});\nconst BUILTIN_TIMESTAMPTZ_ARRAY_PARSER: ((value: string) => unknown) | undefined =\n pgTypesArrayParser === undefined || BUILTIN_TIMESTAMPTZ_PARSER === undefined\n ? undefined\n : recogniseBuiltinParser({ oid: TIMESTAMPTZ_ARRAY_OID, peers: [TIMESTAMP_ARRAY_OID, DATE_ARRAY_OID], name: \"parseDateArray\" });\n\n/**\n * `timestamptz` (AW-03): the plain wire form by char codes, anything else\n * (infinity, BC, years before 1000, seconds offsets) through pg-types' own\n * parser — the one this replaces, so every instant is unchanged.\n */\nfunction parseTimestamptzText(value: string): unknown {\n return parsePlainTimestampText({ text: value, zoned: true }) ?? (BUILTIN_TIMESTAMPTZ_PARSER as (value: string) => unknown)(value);\n}\n\n/** `timestamptz[]`: pg-types' `parseDateArray` with {@link parseTimestamptzText} per element. */\nfunction parseTimestamptzArrayText(value: string): unknown {\n if (!value) return null;\n return (pgTypesArrayParser as PgTypesArrayParser).create(value, (entry) => (entry !== null ? parseTimestamptzText(entry) : entry)).parse();\n}\n\n/**\n * Query-local type parsers that keep `numeric[]` EXACT and read zone-less\n * timestamps as UTC.\n *\n * pg-types decodes `_numeric` with `parseFloat` per element, so\n * `9007199254740993` comes back as `9007199254740992` and `12.340` as the\n * number `12.34` — while the SCALAR `numeric` correctly stays a string and\n * VibeORM's Decimal contract is \"string in, string out\" on every dialect. The\n * array is the anomaly, and the loss happens inside the driver, before any\n * codec can see the value.\n *\n * The fix reuses the driver's OWN array-literal parser (`_text`), so array\n * syntax, quoting and NULL elements stay node-postgres' business; only the\n * per-element float conversion is dropped. It is attached PER QUERY (F12's\n * acceptance criterion), never by mutating `pg.types` globally: an injected\n * pool is shared property, and a global override would silently change every\n * other consumer in the process. The zone-less parsers ride the same hook for\n * the same reason.\n */\nconst EXACT_TYPES: PgTypeParsers = {\n getTypeParser(oid: number, format?: \"text\" | \"binary\"): (value: string) => unknown {\n if (format === undefined || format === \"text\") {\n if (oid === NUMERIC_ARRAY_OID) return driverTypeParser(TEXT_ARRAY_OID, \"text\");\n if (oid === TIMESTAMP_OID || oid === DATE_OID) return parseZoneLessAsUtc;\n if (oid === TIMESTAMP_ARRAY_OID || oid === DATE_ARRAY_OID) return parseZoneLessArrayAsUtc;\n if (oid === TIMESTAMPTZ_OID) {\n const driver = driverTypeParser(oid, \"text\");\n return driver === BUILTIN_TIMESTAMPTZ_PARSER ? parseTimestamptzText : driver;\n }\n if (oid === TIMESTAMPTZ_ARRAY_OID) {\n const driver = driverTypeParser(oid, \"text\");\n return driver === BUILTIN_TIMESTAMPTZ_ARRAY_PARSER ? parseTimestamptzArrayText : driver;\n }\n }\n return driverTypeParser(oid, format);\n },\n};\n\n/**\n * The one address this adapter will ever use, taken at construction: an\n * injected pool (it wins, as documented) or a non-empty connection string,\n * with libpq's `sslrootcert=system` rewritten for node-postgres\n * ({@link honourSystemRootCert}). Nothing is read from the environment, and\n * nothing is re-read later.\n *\n * @throws VibeError `VIBE_CONFIG` (`meta.reason: \"missing-address\"`) when\n * neither is present, or `\"sslrootcert-system-weak-sslmode\"`. The message\n * never echoes the URL.\n */\nfunction takeAddress(params: { options: PgAdapterOptions | undefined }): { pool: PgPoolLike } | { connectionString: string } {\n const options: PgAdapterSettings | undefined = params.options;\n if (options?.pool !== undefined && options.pool !== null) return { pool: options.pool };\n const connectionString = options?.connectionString;\n if (typeof connectionString === \"string\" && connectionString.trim() !== \"\") {\n return { connectionString: honourSystemRootCert({ connectionString, option: \"connectionString\" }) };\n }\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message:\n \"pgAdapter needs an explicit address: pass `connectionString` (a PostgreSQL URL) or an existing `pool`. \" +\n \"The adapter does not read DATABASE_URL or the PG* environment variables.\",\n meta: { adapter: \"pg\", reason: \"missing-address\" },\n });\n}\n\n/**\n * Round-trip follow-up lane E (`DatabaseAdapter.oneRoundTripTransactions`):\n * whether every client `address` hands out can run a transaction opened without\n * options in one round trip — BEGIN deferred, `orderedPipeline`, `withCommit`.\n * Per client that holds when it batches (`supportsBatch`) and has no local\n * `query_timeout` (see the transaction's `ordered` / `commits`). Read here from\n * the same sources node-postgres' `ConnectionParameters` reads, at\n * construction: the driver exports `prepareValue`; the pool config is not in\n * pipeline mode; `query_timeout` from the connection string's query parameters\n * (they override the config), else from the config, else `pg.defaults`. A\n * connection string that is no URL, or a client changed later (a `connect`\n * listener, `pg.defaults` set afterwards), is not seen: the declaration is\n * performance-only and the runtime still checks every transaction handle.\n */\nfunction transactionsTakeOneRoundTrip(params: { address: { pool: PgPoolLike } | { connectionString: string } }): boolean {\n const { address } = params;\n if (!batchDriverAvailable()) return false;\n const config: Record<string, unknown> = \"pool\" in address\n ? ((address.pool as { readonly options?: Record<string, unknown> }).options ?? {})\n : { connectionString: address.connectionString };\n if (config.pipeline === true) return false;\n let timeout: unknown = config.query_timeout;\n const connectionString = config.connectionString;\n if (typeof connectionString === \"string\") {\n if (!URL.canParse(connectionString)) return false;\n const fromUrl = new URL(connectionString).searchParams.get(\"query_timeout\");\n if (fromUrl !== null) timeout = fromUrl;\n }\n // node-postgres: `config[key] || defaults[key]`.\n timeout ||= (pg.defaults as { readonly query_timeout?: unknown }).query_timeout;\n return !(Number(timeout ?? 0) > 0);\n}\n\n/**\n * Create a VibeORM adapter backed by node-postgres.\n *\n * Requires an explicit address (`connectionString` or `pool`); see\n * {@link PgAdapterOptions}. Construction opens nothing — the pool is created\n * on first use.\n *\n * @example\n * ```ts\n * const adapter = pgAdapter({ connectionString: \"postgresql://app:secret@db.internal:5432/app\", max: 20 });\n * await adapter.connect();\n * const rows = await adapter.execute({ text: 'SELECT * FROM \"User\" WHERE \"id\" = $1', values: [1] });\n * ```\n *\n * @example Reusing a pool you already own\n * ```ts\n * import pg from \"pg\";\n * const pool = new pg.Pool({ connectionString });\n * const adapter = pgAdapter({ pool });\n * ```\n */\nexport function pgAdapter(options: PgAdapterOptions): DatabaseAdapter {\n const address = takeAddress({ options });\n const cancellationAddress = options.cancellationConnectionString !== undefined\n ? honourSystemRootCert({ connectionString: options.cancellationConnectionString, option: \"cancellationConnectionString\" })\n : (\"connectionString\" in address ? address.connectionString : undefined);\n const readCancellation: NonNullable<DatabaseAdapter[\"readCancellation\"]> = cancellationAddress === undefined ? \"before-dispatch\" : \"running\";\n const usePrepared = options?.preparedStatements ?? false;\n const stmtCacheMax = options?.stmtCacheMax ?? 1000;\n const planCacheMode = options?.planCacheMode === undefined ? \"auto\" : assertPlanCacheMode({ value: options.planCacheMode });\n // AW-04: only an owned pool consumes this setting; an injected pool keeps its own configuration.\n const idleTimeout = \"pool\" in address || options?.idleTimeout === undefined ? undefined : assertIdleTimeout({ value: options.idleTimeout });\n // V7: refused next to an injected pool, unlike `idleTimeout` — ignoring it\n // would leave the caller with the cold pool `min` exists to avoid.\n if (options?.min !== undefined && \"pool\" in address) {\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message: \"pgAdapter `min` configures the pool the adapter builds — it cannot be applied to a caller-supplied `pool`; set `min` (and `idleTimeoutMillis`) on that pool instead\",\n meta: { adapter: \"pg\", reason: \"pool-min-with-injected-pool\", option: \"min\" },\n });\n }\n const poolMin = options?.min === undefined ? undefined : assertPoolMin({ value: options.min, max: options.max ?? 10 });\n if (planCacheMode !== \"auto\" && \"pool\" in address) {\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message:\n \"planCacheMode configures the pool the adapter builds — it cannot be applied to a caller-supplied `pool`; \" +\n \"set `options: \\\"-c plan_cache_mode=…\\\"` on that pool instead\",\n meta: { planCacheMode },\n });\n }\n\n let pool: PgPoolLike | null = null;\n let ownsPool = false;\n\n /**\n * The checked-out client of an OPEN raw transaction — session affinity for\n * the raw path. @vibeorm/migrate wraps transactional DDL in literal `BEGIN`\n * / `COMMIT` / `ROLLBACK` sent through `executeUnsafe`; without pinning,\n * `pool.query(\"BEGIN\")` sequences stay on one client only by LIFO checkout\n * luck, and any concurrent traffic silently splits the transaction across\n * connections. A pure `BEGIN` checks a client out, every raw statement until\n * the matching `COMMIT`/`ROLLBACK` rides it, and the close releases it. The\n * ORM path (`execute`) and `transaction()` stay on the pool. Concurrent raw\n * transactions on one adapter are unsupported.\n */\n let rawSession: PgPoolClientLike | null = null;\n /** Detach for {@link rawSession}'s background-error guard; runs before its release. */\n let rawSessionUnguard: (() => void) | null = null;\n /**\n * Set once a checked-out client lacked {@link hasReadyForQuerySeam}: the\n * pool hands out wrappers, so root ORM statements keep running through the\n * pool's own `query()` — the path (and the guard) they had before round-trip\n * EPIC 3 (fix lane FX-A, RV2 MJ-3 / MN-6c).\n */\n let rootViaPoolQuery = false;\n\n function getPool(): PgPoolLike {\n if (pool !== null) return pool;\n\n if (\"pool\" in address) {\n pool = address.pool;\n ownsPool = false;\n return pool;\n }\n\n const config = buildPoolConfig({\n connectionString: address.connectionString,\n max: options?.max ?? 10,\n ...(poolMin === undefined ? {} : { min: poolMin }),\n ...(options?.statementTimeout === undefined ? {} : { statementTimeout: options.statementTimeout }),\n ...(options?.connectionTimeout === undefined ? {} : { connectionTimeout: options.connectionTimeout }),\n ...(idleTimeout === undefined ? {} : { idleTimeout }),\n planCacheMode,\n });\n\n const PoolCtor = pg.Pool as unknown as new (poolConfig: Record<string, unknown>) => PgPoolLike;\n pool = new PoolCtor(config);\n /**\n * The IDLE half of the same hazard {@link guardBackgroundErrors} covers: a\n * pooled client that loses its socket while idle makes pg re-emit on the\n * POOL, and an unhandled `'error'` there is equally fatal. The pool already\n * evicts that client, so this listener only keeps the process alive.\n *\n * Attached ONLY to a pool this adapter constructed. A caller-supplied pool\n * (the `pool` option) has its own owner: the adapter never ends it either,\n * node-postgres documents attaching an `'error'` listener as that owner's\n * job, and registering one here that is never removed would stack up a\n * listener per adapter sharing that pool. The dangerous case — a client\n * checked out for a transaction or a raw session, which pg leaves\n * unlistened by construction — is guarded in BOTH modes.\n */\n pool.on?.(\"error\", () => {\n /* the pool has already discarded the failed client */\n });\n ownsPool = true;\n return pool;\n }\n\n /**\n * Prepared-statement names for the pool this adapter runs on (F18): the\n * registry is keyed by the POOL, so two adapters sharing one pool share one\n * name budget and do not prepare the same text twice (names themselves are\n * content hashes of the text, equal in every registry — `statementNameFor`).\n * It also bounds how many names that pool can ever put on a backend (F16) no\n * matter how many adapters come and go over it.\n */\n function statementNamesFor(params: { pool: PgPoolLike }): StatementNameCache {\n const existing = POOL_STATEMENT_NAMES.get(params.pool);\n if (existing !== undefined) return existing;\n const created = createStatementNameCache({ max: stmtCacheMax });\n POOL_STATEMENT_NAMES.set(params.pool, created);\n return created;\n }\n\n /** The caller-chosen raw names of the pool this adapter runs on, shared like {@link statementNamesFor}. */\n function rawStatementNamesFor(params: { pool: PgPoolLike }): RawStatementNames {\n const existing = POOL_RAW_STATEMENT_NAMES.get(params.pool);\n if (existing !== undefined) return existing;\n const created = createRawStatementNames();\n POOL_RAW_STATEMENT_NAMES.set(params.pool, created);\n return created;\n }\n\n /** Build the config for one ORM-path query (statement name only when enabled). */\n function buildQueryConfig(params: { text: string; values: unknown[] }): PgQueryConfig {\n const values = serializeParams({ values: params.values });\n if (!usePrepared) return { text: params.text, values, types: EXACT_TYPES };\n // `undefined` on a text's first sighting and once the pool's name budget is\n // spent: the statement runs unnamed rather than growing the server's\n // prepared-statement retention.\n const name = statementNamesFor({ pool: getPool() }).getName({ text: params.text });\n return name === undefined\n ? { text: params.text, values, types: EXACT_TYPES }\n : { name, text: params.text, values, types: EXACT_TYPES };\n }\n\n function observeResult(params: { scope?: SavepointScope; effect?: StatementEffect; result: PgQueryResultsLike }): void {\n if (params.scope === undefined) return;\n const results = Array.isArray(params.result) ? params.result : [params.result];\n if (results.length === 0) observeRowChanges({ scope: params.scope, count: statementRowChanges({ effect: params.effect }) });\n for (const result of results) observeRowChanges({ scope: params.scope, count: statementRowChanges({ effect: params.effect, count: result.rowCount, rows: result.rows?.length, resultRows: result.rows }) });\n }\n\n async function runExecute(params: {\n queryable: Queryable;\n text: string;\n values: unknown[];\n scope?: SavepointScope;\n effect?: StatementEffect;\n }): Promise<Record<string, unknown>[]> {\n const config = buildQueryConfig({ text: params.text, values: params.values });\n const result = await runMapped(() => params.queryable.query(config));\n observeResult({ scope: params.scope, effect: params.effect, result });\n return finalResult({ result }).rows;\n }\n\n async function runExecuteUnsafe(params: {\n queryable: Queryable;\n text: string;\n values?: unknown[];\n scope?: SavepointScope;\n effect?: StatementEffect;\n /** A caller-chosen statement name: node-postgres parses it once per connection. */\n name?: string;\n }): Promise<QueryResult> {\n // Admitted before anything is sent: the shared name rule, then one text per name on this pool.\n const name = params.name === undefined ? undefined : assertStatementName({ name: params.name, method: \"executeUnsafe\" });\n if (name !== undefined) rawStatementNamesFor({ pool: getPool() }).admit({ name, text: params.text });\n const values = params.values === undefined ? undefined : serializeParamsRaw({ values: params.values });\n const config: PgQueryConfig = name === undefined ? { text: params.text, values, types: EXACT_TYPES } : { name, text: params.text, values, types: EXACT_TYPES };\n const result = await runMapped(() => params.queryable.query(config));\n observeResult({ scope: params.scope, effect: params.effect, result });\n const final = finalResult({ result });\n return { rows: final.rows, affectedRows: final.rowCount ?? 0 };\n }\n\n /**\n * Adapter bound to one checked-out client that is already inside a\n * transaction. Nested `transaction()` calls open savepoints on that same\n * client, and their LIFETIMES are serialized by the savepoint gate (F14):\n * overlapping siblings share one savepoint stack, so the earlier one's\n * rollback would erase the later one's already released work.\n */\n function createClientAdapter(params: {\n dispatch: TransactionDispatch;\n scope: SavepointScope;\n budget: TransactionBudget;\n /** Pending control of this transaction; `null` when the client cannot batch (nothing is deferred). */\n deferred: DeferredControl | null;\n cancellation: PgReadCancellation;\n /** This transaction's `$all` pipeline; `null` when the client cannot batch (no lanes are offered). */\n pipelines: PipelineControl | null;\n /** The pipeline lane this handle belongs to; nested handles inherit it. */\n lane?: PipelineLaneState;\n /**\n * This handle offers ordered scopes (`orderedPipeline`, EPIC D): the\n * top-level handle of a transaction without a `deadline` (a `timeout` is\n * fine, V2), and the savepoint handles it opens outside a pipeline lane (a\n * nested array `$transaction`, performance audit round 2, C-03).\n */\n ordered?: boolean;\n /** The checked-out `PoolClient`: this transaction's `connectionIdentity` (statement-count pass EPIC 1). */\n connection: object;\n /** The top-level handle: it alone offers `deferStatement` (EPIC 2). */\n topLevel?: boolean;\n /**\n * This transaction can ride COMMIT behind its last statement (EPIC 5): the\n * handle offers `withCommit` when it sits at savepoint depth 0 (the\n * top-level handle and its pipeline lanes, never a savepoint handle).\n */\n commits?: boolean;\n /** This handle is a `withCommit` view: its first statement carries COMMIT, a second is refused. */\n final?: { used: boolean; readonly discardRows?: boolean };\n }): DatabaseAdapter {\n const { dispatch, scope, budget, deferred, cancellation, pipelines, lane, connection, final } = params;\n const laneOf = lane === undefined ? {} : { lane };\n /** EPIC 5: the COMMIT flag of a view's ONE statement; checked when the statement is dispatched, before anything is sent. */\n const finalOf = (): { commit?: true; discardRows?: true } => {\n if (final === undefined) return {};\n if (final.used) throw finalStatementMisuse();\n final.used = true;\n return { commit: true, ...(final.discardRows === true ? { discardRows: true as const } : {}) };\n };\n // A wait a lane spends inside the adapter counts as waiting, so the\n // pipeline never holds its siblings' statements for it.\n const waitAsLane = <T>(wait: Promise<T>): Promise<T> =>\n lane === undefined || pipelines === null ? wait : pipelines.waitAs({ lane, wait });\n // ORM statements are always ONE statement; raw text is one when it binds\n // values (node-postgres then uses the extended protocol itself), when it is\n // named (a named statement is always extended protocol), or when it\n // provably is one (C-01: a framework's `SELECT set_config(…)` rides with BEGIN).\n const rawClient: Queryable = {\n query: (config) => dispatch({\n config,\n batchable: (config.values?.length ?? 0) > 0 || config.name !== undefined || isSingleStatementText({ text: config.text }),\n ...(config.name === undefined ? {} : { name: config.name }),\n ...laneOf,\n ...finalOf(),\n }),\n };\n // EPIC 6: SAVEPOINT rides with the body's first statement; a body that\n // sent nothing sends neither its RELEASE nor its ROLLBACK TO.\n const savepointControl = (statement: string, cleanup: boolean): Promise<unknown> | undefined => {\n if (deferred !== null && deferred.routeSavepoint({ text: statement, cleanup }) !== \"send\") return undefined;\n return runMapped(() => dispatch({\n config: { text: statement },\n stage: \"nested\",\n batchable: true,\n ...(cleanup ? { cleanup: true } : {}),\n ...laneOf,\n }));\n };\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n budgets: BUDGETS,\n readCancellation: cancellation.support,\n roundTrips: ROUND_TRIPS,\n readSnapshot: READ_SNAPSHOT,\n pipelining: pipelines === null ? \"ordered\" : PIPELINING,\n connectionIdentity: connection,\n // EPIC 2: a bound statement nobody reads (the native-RLS claims) waits with\n // the deferred opening and rides with the next statement. Serialized now:\n // a value the driver refuses throws here and nothing is queued.\n ...(params.topLevel !== true || deferred === null ? {} : {\n deferStatement: (statement: { readonly text: string; readonly values: readonly unknown[] }): void => {\n budget.assertUsable({ stage: \"statement\" });\n deferred.defer({ text: statement.text, values: prepareBatchValues({ values: statement.values }) });\n },\n }),\n // EPIC 5: a view for the transaction's last statement — COMMIT rides behind it.\n ...(params.commits !== true || deferred === null || scope.depth !== 0 || final !== undefined ? {} : {\n withCommit: (options?: { readonly rows?: \"discard\" }): DatabaseAdapter => createClientAdapter({\n dispatch, scope, budget, deferred, cancellation, pipelines, ...laneOf, connection,\n final: { used: false, ...(options?.rows === \"discard\" ? { discardRows: true } : {}) },\n }),\n }),\n ...(pipelines === null ? {} : {\n ...(params.ordered === true ? { orderedPipeline: true as const } : {}),\n pipeline: ({ lanes: count, ordered }: { lanes: number; ordered?: true }): readonly PipelineLane[] => {\n budget.assertUsable({ stage: \"statement\" });\n // D2 (review D2-05): a sub-lane, or a lane whose group is open, opens no lanes — a nested lane in\n // the flat lane set would hold the group's batch while its owner awaits it (OP-11).\n if (lane?.seat !== undefined) throw laneGroupMisuse({ message: \"a sub-lane opens no pipeline scope\" });\n if (lane?.group !== undefined) throw laneGroupMisuse({ message: \"a lane opens no pipeline scope while its group is open\" });\n if (!Number.isSafeInteger(count) || count < 1) {\n throw new VibeError({ code: \"VIBE_VALIDATION\", message: \"pipeline() needs a positive whole number of lanes\", meta: { lanes: count } });\n }\n if (ordered === true && params.ordered !== true) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: \"pipeline({ ordered: true }) is offered only on a handle that declares orderedPipeline (the top-level or a savepoint handle of a transaction without a deadline, outside a pipeline lane)\",\n meta: { ordered: true, reason: \"ordered-pipeline-undeclared\" },\n });\n }\n const laneHandle = (opened: PipelineLaneState): PipelineLane => ({\n adapter: createClientAdapter({ dispatch, scope, budget, deferred, cancellation, pipelines, lane: opened, connection, ...(params.commits === true && opened.seat === undefined ? { commits: true } : {}) }),\n close: (): void => { pipelines.close(opened); },\n ...(opened.order === undefined ? {} : {\n follow: (): PipelineLane => {\n budget.assertUsable({ stage: \"statement\" });\n return laneHandle(pipelines.follow(opened));\n },\n }),\n // D2: a lane of an unordered scope opened on a handle that is no lane itself.\n ...(opened.order !== undefined || opened.seat !== undefined || lane !== undefined ? {} : {\n group: (options?: { readonly final?: true }): PipelineGroup | undefined => {\n // No budget check here: a handle that refuses statements refuses no group —\n // the caller's next statement raises today's refusal.\n // Lane A2: `final` counts only where this handle's lanes can carry COMMIT (`commits`).\n const opening = pipelines.group(opened, options?.final === true && params.commits === true);\n if (opening === undefined) return undefined;\n return {\n lane: (): PipelineLane => laneHandle(pipelines.seat(opening)),\n seal: (): void => { pipelines.seal(opening); },\n };\n },\n }),\n });\n return (ordered === true ? pipelines.openOrdered(count) : pipelines.open(count)).map(laneHandle);\n },\n }),\n rowChanges: (): RowChangeCount => { budget.assertUsable({ stage: \"statement\" }); return readRowChanges({ scope }); },\n\n async execute(execParams) {\n return runReadExecution({ ...execParams, support: cancellation.support, provider: PROVIDER, run: async () => {\n const turn = scopeTurn({ scope });\n if (turn !== undefined) await waitAsLane(turn);\n // After the turn, not before: waiting for a sibling savepoint spends\n // the same budget the statement is about to run against.\n budget.assertUsable({ stage: \"statement\" });\n assertReadExecution({ ...execParams, support: cancellation.support, provider: PROVIDER, stage: \"waiting-for-connection\" });\n // A server-reported failure aborts a postgres transaction: record it so\n // a callback that swallows it cannot commit nothing.\n const queryable: Queryable = { query: (config) => dispatch({ config, batchable: execParams.execution?.cancellation !== \"running\", execution: execParams.execution, onReadControl: execParams.onReadControl, ...laneOf, ...finalOf() }) };\n return runExecute({ queryable, scope, ...execParams })\n .catch((error: unknown) => abortTransactionOnServerFailure({ scope, error }));\n } });\n },\n\n async executeUnsafe(execParams) {\n const turn = scopeTurn({ scope });\n if (turn !== undefined) await waitAsLane(turn);\n budget.assertUsable({ stage: \"statement\" });\n return runExecuteUnsafe({ queryable: rawClient, scope, ...execParams })\n .catch((error: unknown) => abortTransactionOnServerFailure({ scope, error }));\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n nestedOptions?: TransactionOptions,\n ): Promise<T> {\n refuseNestedTransactionOptions({ options: nestedOptions, provider: PROVIDER });\n budget.assertUsable({ stage: \"nested\" });\n // D2: a lane whose group is open issues nothing — not even a SAVEPOINT (checked before the flush below).\n if (lane?.group !== undefined) throw laneGroupMisuse({ message: \"a lane opens no savepoint while its group is open\" });\n // Review D2-05: nor a sub-lane — the flush below would send its group's statements before the group is sealed.\n if (lane?.seat !== undefined) throw laneGroupMisuse({ message: \"a sub-lane opens no savepoint\" });\n // Lane statements queued before this savepoint go out in front of it,\n // as they would have without the pipeline.\n pipelines?.flush();\n // A lane waiting for its savepoint turn counts as waiting until its body starts.\n const leave = lane === undefined || pipelines === null ? ignore : pipelines.enter(lane);\n return runNestedSavepoint({\n scope,\n execute: (statement) => savepointControl(statement, false),\n cleanup: (statement: string) => savepointControl(statement, true),\n // The child shares the ROOT budget by reference: a savepoint never\n // gets an independent clock or session setting.\n body: (child) => {\n leave();\n // C-03: a savepoint handle outside a lane offers ordered scopes too,\n // so a nested array `$transaction` bursts like a top-level one.\n const ordered = lane === undefined && params.ordered === true ? { ordered: true } : {};\n return fn(createClientAdapter({ dispatch, scope: child, budget, deferred, cancellation, pipelines, connection, ...laneOf, ...ordered }));\n },\n }).finally(leave);\n },\n\n // The open transaction owns this connection: neither call may act on it.\n // An expired handle keeps its own refusal (the budget check comes first).\n async connect(): Promise<void> {\n budget.assertUsable({ stage: \"statement\" });\n throw transactionLifecycleRefusal({ method: \"connect\" });\n },\n\n async disconnect(): Promise<void> {\n budget.assertUsable({ stage: \"statement\" });\n throw transactionLifecycleRefusal({ method: \"disconnect\" });\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return new PgArrayParam(values);\n },\n };\n }\n\n /**\n * Final cleanup, run ONCE by the lifecycle gate after every admitted\n * operation settled — so a raw BEGIN that was still pending at the\n * `disconnect()` call has published its session by now. Rolls back and\n * releases an abandoned raw session (destroyed when the rollback failed),\n * then ends the pool the adapter created. An injected pool is never ended.\n */\n function closeOwnedResources(): Promise<void> {\n return runShutdownCleanup({\n steps: [\n async (): Promise<void> => {\n if (rawSession === null) return;\n const session = rawSession;\n const unguard = rawSessionUnguard;\n rawSession = null;\n rawSessionUnguard = null;\n // An abandoned raw checkout is reusable only after a successful rollback.\n await runMapped(() => session.query({ text: \"ROLLBACK\" })).then(\n () => { unguard?.(); session.release(); },\n (error: unknown) => { unguard?.(); session.release(true); throw error; },\n );\n },\n async (): Promise<void> => {\n if (pool === null || !ownsPool) return;\n const closing = pool;\n await runMapped(() => closing.end());\n },\n ],\n });\n }\n\n const lifecycle = createAdapterLifecycleGate({ driver: \"pg\", cleanup: closeOwnedResources });\n\n /** The root operations; the adapter below admits each one through {@link lifecycle}. */\n const root: Pick<Required<DatabaseAdapter>, \"withSession\" | \"execute\" | \"executeUnsafe\" | \"transaction\" | \"connect\"> = {\n async withSession({ run }) {\n const client = await runMapped(() => getPool().connect());\n let backgroundFailure: unknown;\n const onError = (error: unknown): void => { backgroundFailure = error; };\n client.on?.(\"error\", onError);\n return runPinnedSession({\n run,\n execute: async (query) => {\n if (backgroundFailure !== undefined) throw mapPgDriverError({ error: backgroundFailure });\n return (await runExecuteUnsafe({ queryable: client, ...query })).rows;\n },\n isLost: (error) => backgroundFailure !== undefined || isConnectionLoss({ error }),\n release: async () => {\n client.removeListener?.(\"error\", onError);\n // Migration SQL may change arbitrary session state. Never pool it.\n client.release(true);\n },\n });\n },\n\n async execute(params) {\n assertReadExecution({ ...params, support: readCancellation, provider: PROVIDER });\n if (params.execution?.cancellation === \"running\") {\n // READ ONLY pins a backend even behind a transaction-mode pooler.\n // Transaction lifecycle stays outside the individual read receipt.\n const options = { accessMode: \"readOnly\" as const };\n return root.transaction((tx) => tx.execute(params), options);\n }\n // Round-trip EPIC 3 (A-12): own checkout instead of `pool.query`, so an\n // ordinary error can keep a session proven idle (see observeReadyForQuery).\n const config = buildQueryConfig({ text: params.text, values: params.values });\n const rootPool = getPool();\n if (!rootViaPoolQuery) {\n const client = await runMapped(() => rootPool.connect());\n if (hasReadyForQuerySeam({ client }) || params.execution !== undefined) {\n const seam = hasReadyForQuerySeam({ client }) ? observeReadyForQuery({ client }) : undefined;\n let reuse = false;\n try {\n assertReadExecution({ ...params, provider: PROVIDER, stage: \"waiting-for-connection\" });\n const result = await runMapped(() => client.query(config));\n reuse = true;\n return finalResult({ result }).rows;\n } catch (error) {\n reuse = await seam?.reusableAfter({ error, named: config.name !== undefined }) ?? false;\n throw error;\n } finally {\n seam?.detach();\n client.release(!reuse);\n }\n }\n // A client without the seam: hand it back unused and keep today's path.\n client.release();\n rootViaPoolQuery = true;\n }\n assertReadExecution({ ...params, provider: PROVIDER, stage: \"waiting-for-connection\" });\n return finalResult({ result: await runMapped(() => rootPool.query(config)) }).rows;\n },\n\n async executeUnsafe(params) {\n const control = classifyRawTransactionControl({ text: params.text });\n if (rawSession !== null) {\n if (control === \"close\") {\n const session = rawSession;\n const unguard = rawSessionUnguard;\n rawSession = null;\n rawSessionUnguard = null;\n try {\n return await runExecuteUnsafe({ queryable: session, ...params });\n } finally {\n unguard?.();\n session.release();\n }\n }\n // A nested raw BEGIN lands here too — postgres treats it as a warning\n // no-op on the open session, exactly like a single connection would.\n return runExecuteUnsafe({ queryable: rawSession, ...params });\n }\n if (control === \"open\") {\n const client = await runMapped(() => getPool().connect());\n const unguard = guardBackgroundErrors({ client });\n try {\n const result = await runExecuteUnsafe({ queryable: client, ...params });\n rawSession = client;\n rawSessionUnguard = unguard;\n return result;\n } catch (error) {\n unguard();\n client.release();\n throw error;\n }\n }\n return runExecuteUnsafe({ queryable: getPool(), ...params });\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n // Refuse an unsupportable budget BEFORE checking a connection out, so a\n // bad option never costs a checkout and never leaves a transaction open.\n validateTransactionDeadline({\n options: transactionOptions,\n support: BUDGETS.transactionDeadline,\n provider: PROVIDER,\n settings: \"transaction-local\",\n });\n // Round-trip EPIC 3 (A-02): BEGIN [… READ ONLY] and the timeout's SET as\n // ONE message. Built (and the timeout validated) before the checkout.\n const openingOptions = {\n isolationLevel: transactionOptions?.isolationLevel,\n readOnly: readOnlyRequested({ options: transactionOptions, provider: PROVIDER }),\n timeout: transactionOptions?.timeout,\n };\n const openText = openTransactionStatement(openingOptions);\n // TU-02: transaction settings, validated and rendered before the checkout\n // (an invalid name or value never costs a connection). None = today's path.\n const settings = readTransactionSettings({ settings: transactionOptions?.settings, provider: PROVIDER });\n const settingsStatement = settings.length === 0 ? undefined : renderTransactionSettings({ settings });\n const client = await runMapped(() => getPool().connect());\n /**\n * pg@9 (./client-turns.ts): every query this transaction sends on\n * `client` — statements, batches, control, the read-cancellation\n * preflight — takes a turn, so node-postgres never receives a query while\n * it still runs one. Same order as the driver's own queue gave.\n */\n const turns = createClientTurns();\n /** V4: the gathering group that still takes statements, or `null` (see {@link GatheringGroup}). */\n let gathering: GatheringGroup | null = null;\n /** V4: gathering groups not sent yet; while one waits, a server failure is recorded the moment a reply shows it. */\n let gatheringsPending = 0;\n /** Every call of this transaction takes its turn here: a call queued behind an open gathering group closes it. */\n const runTurn = <T>(send: () => Promise<T>): Promise<T> => {\n gathering = null;\n return turns.run(send);\n };\n const onClient: Pick<PgPoolClientLike, \"query\" | \"pipeline\" | \"connectionParameters\"> = {\n query: (config) => runTurn(() => client.query(config)),\n get pipeline() { return client.pipeline; },\n get connectionParameters() { return client.connectionParameters; },\n };\n /**\n * The connection failure node-postgres reported on this client while the\n * transaction held it (EPIC T review, finding 1). node-postgres marks the\n * client unqueryable in the same handler that emits `error`, and from\n * then on refuses every query locally, without writing it: a COMMIT\n * after this point never leaves the client.\n */\n let connectionFailure: { readonly cause: unknown } | undefined;\n const unguard = guardBackgroundErrors({\n client,\n onError: (cause) => {\n if (connectionFailure === undefined) connectionFailure = { cause };\n },\n });\n const scope = createSavepointScope();\n // The deadline clock starts HERE: the connection is already in hand, so\n // acquisition (bounded separately by `connectionTimeout`) is not charged\n // against the caller's transaction budget.\n const budget = startTransactionBudget({ options: transactionOptions, provider: PROVIDER });\n // Round-trip EPIC 6 (pipelining): on a client that can run a one-Sync\n // batch, the opening, every SAVEPOINT and the deadline's SET LOCAL wait\n // here and ride IN FRONT OF the next statement — one wait for all of\n // them. A transaction whose callback sends nothing sends nothing. The\n // opening is sent eagerly (EPIC 3's one message) only when a `timeout`\n // beyond PostgreSQL's int4 ceiling could make its SET fail: that error\n // keeps surfacing before the callback runs, as today.\n const capable = supportsBatch({ client });\n // With settings (TU-02) the opening is never deferred: it must be confirmed\n // before the callback runs (see `openWithSettings`) — unless the caller\n // opted in to `deferSettings` (lane Y): then the bound settings statement\n // waits with the opening and rides in front of the first statement.\n const deferOpening = (settingsStatement === undefined || transactionOptions?.deferSettings === true) && capable && (openingOptions.timeout === undefined || openingOptions.timeout <= MAX_STATEMENT_TIMEOUT_MS);\n const opening: readonly string[] = deferOpening\n ? [beginStatement(openingOptions), ...(openingOptions.timeout === undefined ? [] : [statementTimeoutStatement({ timeout: openingOptions.timeout })])]\n : [];\n // EPIC 5: without a deadline a nested call's success-path RELEASE waits\n // here too and rides with the next statement (dropped when COMMIT is\n // next); a deadline keeps refusing at the nested call's own RELEASE.\n const deferred = createDeferredControl({ opening, ...(budget.totalMs === null ? { deferReleases: true as const } : {}) });\n /**\n * Lane Y (`deferSettings`): the settings statement queued right behind the\n * opening texts, so it is opening step `opening.length` of the burst that\n * carries the opening — ahead of the native-RLS claims, which the runtime\n * defers later. Values serialized now (validated strings).\n */\n const settingsDeferred = deferOpening && settingsStatement !== undefined;\n if (settingsDeferred) deferred.defer({ text: settingsStatement.text, values: prepareBatchValues({ values: settingsStatement.values }) });\n /** Steps of the opening in the burst that carries it: the opening texts, then the deferred settings statement. */\n const openingLength = opening.length + (settingsDeferred ? 1 : 0);\n /**\n * The mapped failure of opening step `index`: a server refusal of the\n * deferred settings statement becomes TU-02's `setting-refused` error\n * (`meta.deferred: true`), naming the setting from the diagnostic; any\n * other step (or no server answer) its mapped driver error, as today.\n */\n const openingStepError = (index: number, error: unknown): VibeError => {\n const mapped = mapPgDriverError({ error });\n if (!settingsDeferred || index !== opening.length || typeof mapped.meta.sqlstate !== \"string\") return mapped;\n return transactionSettingRefusedError({ provider: PROVIDER, settings, setting: findRefusedSetting({ settings, cause: mapped }), cause: mapped, deferred: true });\n };\n /** The deferred opening failed (mapped): the server holds no transaction, so nothing more may be sent. */\n let openingFailure: VibeError | undefined;\n /** A burst carrying deferred control that has not settled yet (no deadline); later statements wait for it. */\n let inFlight: Promise<void> | null = null;\n /**\n * EPIC 5 (`withCommit`): COMMIT may ride behind the transaction's last\n * statement on a client that batches, without a deadline (the COMMIT must\n * stay refusable after the last statement), and without a local\n * `query_timeout` (it fails a statement without stopping the COMMIT behind it).\n */\n const commits = capable && budget.totalMs === null && !((client.connectionParameters?.query_timeout ?? 0) > 0);\n /** The COMMIT that rode with the last statement, once its batch was handed to the driver. */\n let ridden: RiddenCommit | undefined;\n /**\n * Ordinary dispatches of this transaction not settled yet (the one being\n * sent included). COMMIT rides only when the last statement is the only\n * one: a statement still waiting to be sent would otherwise follow COMMIT.\n */\n let ordinaryOpen = 0;\n /** Whether a riding COMMIT may leave with the statement being sent now. */\n const ridesNow = (): boolean =>\n commits && ridden === undefined && !cancellationQueue && !cancellationAttempted && connectionFailure === undefined &&\n openingFailure === undefined && scope.state.open === null && scope.state.aborted === null && scope.state.poisoned === null;\n /**\n * Record how far the riding COMMIT got, with the lone COMMIT's rules\n * (EPIC T): no answer, or an error answer of the connection classes\n * (`isConnectionLoss`: SQLSTATE class 08, 57P01-57P03) = unanswered\n * (unknown, discarded); skipped by the server behind a failed statement =\n * never sent; any other error answer or a ROLLBACK tag = answered.\n */\n const settleRidden = (entry: RiddenCommit, outcome: BatchOutcome, commitIndex: number): void => {\n const step = outcome.steps[commitIndex];\n const answeredError = step?.status === \"failed\" ? mapPgDriverError({ error: step.error }) : undefined;\n if (step === undefined && outcome.unsent === true) {\n // Provably nothing of the batch reached the socket (`BatchOutcome.unsent`):\n // COMMIT never left, so the server cannot have committed — a lone COMMIT that was never sent.\n commitProgress = \"not-sent\";\n entry.state = \"skipped\";\n } else if (step === undefined || (answeredError !== undefined && isConnectionLoss({ error: answeredError }))) {\n commitProgress = \"unanswered\";\n discard = true;\n budget.close({ outcome: \"unknown\" });\n entry.state = \"lost\";\n entry.error = commitOutcomeUnknownError({ cause: answeredError ?? outcome.transportError ?? firstBatchFailure({ outcome })?.error });\n } else if (step.status === \"skipped\") {\n commitProgress = \"not-sent\";\n entry.state = \"skipped\";\n } else if (step.status === \"failed\" || step.result.command === \"ROLLBACK\") {\n commitProgress = \"answered\";\n entry.state = \"failed\";\n entry.error = answeredError ?? transactionAbortedError({ cause: scope.state.aborted?.cause });\n } else {\n entry.state = \"committed\";\n }\n };\n /** COMMIT rides in `batch` at `commitIndex`: it is sent now (the lone COMMIT's `sent` moment). */\n const trackRidden = (batch: Promise<BatchOutcome>, commitIndex: number): void => {\n commitProgress = \"sent\";\n const entry: RiddenCommit = { settled: Promise.resolve(), state: \"in-flight\" };\n // Registered before the statements' own continuations: the outcome is known when they resume.\n entry.settled = batch.then(\n (outcome) => { settleRidden(entry, outcome, commitIndex); },\n (error: unknown) => { settleRidden(entry, { steps: [], transportError: error }, commitIndex); },\n );\n ridden = entry;\n };\n\n const sendWithControl = (dispatchParams: Parameters<TransactionDispatch>[0]): Promise<PgQueryResultsLike> => {\n const { config, cleanup } = dispatchParams;\n const handOver = (): Promise<PgQueryResultsLike> => {\n assertReadExecution({ execution: dispatchParams.execution, effect: \"read\", support: readCancellation, provider: PROVIDER, stage: \"waiting-for-connection\" });\n dispatchParams.sent?.();\n return cancellation.run({ config, execution: dispatchParams.execution, onReadControl: dispatchParams.onReadControl, send: () => onClient.query(config) });\n };\n if (cleanup !== true && cancellationAttempted) throw transactionAbortedError({ cause: readCancelledError({ stage: \"running\" }) });\n if (cleanup !== true && openingFailure !== undefined) throw transactionAbortedError({ cause: openingFailure });\n if (cleanup !== true && ridden !== undefined) throw commitSentRefusal();\n let bound: string | undefined;\n if (cleanup !== true && budget.totalMs !== null) {\n if (scope.state.poisoned !== null) throw scope.state.poisoned;\n budget.assertUsable({ stage: dispatchParams.stage ?? \"statement\" });\n const ms = engineStatementBudgetMs({ budget });\n if (ms !== null) bound = statementTimeoutStatement({ timeout: ms });\n }\n if (!capable) {\n // Nothing is deferred on this client: today's awaited SET, re-check, statement.\n if (bound === undefined) return handOver();\n const stage = dispatchParams.stage ?? \"statement\";\n return runMapped(() => onClient.query({ text: bound })).then(() => {\n // SET LOCAL itself costs time. Refuse if its round trip exhausted\n // the deadline; no user query may enter pg's queue afterwards.\n budget.assertUsable({ stage });\n return handOver();\n });\n }\n // Nothing to carry: node-postgres sends the statement and serializes\n // its values itself (fix lane FX-A, RV5 MI-7: never twice).\n const pendingControl = cleanup !== true && deferred.hasPending();\n // EPIC 5: the transaction's last statement, ONE statement, and COMMIT can leave with it now.\n const rides = dispatchParams.commit === true && cleanup !== true && dispatchParams.batchable === true && bound === undefined && ordinaryOpen === 1 && ridesNow();\n if (!pendingControl && bound === undefined && !rides) {\n // V4: the client is busy (or a turn group still takes statements) — wait in\n // that group and leave with every statement waiting with it.\n if ((gathering?.phase === \"turn\" || turns.outstanding() > 0) && gathers(dispatchParams) && deferred.opened()) return gatherInTurn(dispatchParams);\n return handOver();\n }\n // Serialize the statement's values BEFORE taking the pending control:\n // a value the driver refuses must leave the control pending, unsent.\n const statement: BatchStep[] = dispatchParams.batchable === true\n ? [{\n text: config.text,\n values: prepareBatchValues({ values: config.values ?? [] }),\n ...(dispatchParams.name === undefined ? {} : { name: dispatchParams.name }),\n ...(rides && dispatchParams.discardRows === true ? { discardRows: true as const } : {}),\n }]\n : [];\n // A read cancelled while it waited refuses BEFORE the pending control is\n // taken, so that control stays pending and leaves with the next statement\n // (review RLS-03: a taken-and-dropped SAVEPOINT, RELEASE or bound step\n // would never be sent).\n assertReadExecution({ execution: dispatchParams.execution, effect: \"read\", support: readCancellation, provider: PROVIDER, stage: \"waiting-for-connection\" });\n const carriesOpening = !deferred.opened();\n // Steps, not texts: a deferred bound statement (EPIC 2 claims) keeps its values.\n const control: BatchStep[] = pendingControl ? [...deferred.takeSteps()] : [];\n if (bound !== undefined) control.push({ text: bound });\n const openingSteps = carriesOpening ? openingLength : 0;\n // A statement that cannot ride (raw text without values that may hold\n // several statements) goes alone, AFTER its control was confirmed:\n // never behind a BEGIN that may fail.\n if (statement.length > 0) dispatchParams.sent?.();\n const commitIndex = control.length + statement.length;\n const batch = runTurn(() => runBatch({ client, steps: [...control, ...statement, ...(rides ? [COMMIT_STEP] : [])], types: EXACT_TYPES }));\n if (rides) trackRidden(batch, commitIndex);\n const burst = batch\n .then((received): PgQueryResultsLike | Promise<PgQueryResultsLike> => {\n const outcome = rides ? beforeCommit({ outcome: received, commitIndex }) : received;\n const failure = firstBatchFailure({ outcome });\n if (failure !== undefined) {\n // A failed control step rejects the statement it rode with — the\n // error today's awaited control step raised before the statement.\n const openingFailed = failure.index < openingSteps || (outcome.transportError !== undefined && openingSteps > 0);\n if (openingFailed) {\n // Mapped, so the refusals it causes carry its code and SQLSTATE.\n openingFailure = openingStepError(failure.index, failure.error);\n }\n if (gatheringsPending > 0) {\n // V4: statements gathered behind this burst read the failure before\n // they are sent — refused, never answered 25P02 by the server.\n const mapped = openingFailed && openingFailure !== undefined ? openingFailure : mapPgDriverError({ error: failure.error });\n if (typeof mapped.meta.sqlstate === \"string\") markTransactionAborted({ scope, cause: mapped });\n }\n // Lane Y: a refused deferred setting rejects the carrying statement with the setting-refused error.\n throw openingFailed && settingsDeferred && failure.index === opening.length && openingFailure !== undefined ? openingFailure : failure.error;\n }\n if (statement.length === 0) return handOver();\n const last = outcome.steps.at(-1);\n return last?.status === \"ok\" ? last.result : { rows: [], rowCount: 0 };\n });\n if (budget.totalMs === null && carriesOpening) {\n // Without a deadline, statements are not serialized here: a statement\n // dispatched while the opening is unconfirmed must wait for it, or a\n // failed BEGIN would let it run in autocommit.\n const settled: Promise<void> = burst.then(ignore, ignore).then(() => {\n if (inFlight === settled) inFlight = null;\n });\n inFlight = settled;\n }\n return burst;\n };\n /** A synchronous refusal becomes the statement's rejection. */\n const guarded = (run: () => Promise<PgQueryResultsLike>): Promise<PgQueryResultsLike> => {\n try {\n return run();\n } catch (error) {\n return Promise.reject(error);\n }\n };\n const send = (dispatchParams: Parameters<TransactionDispatch>[0]): Promise<PgQueryResultsLike> =>\n guarded(() => sendWithControl(dispatchParams));\n // With a deadline, one turn for SET LOCAL + dispatch + completion, shared\n // by every nested handle. Never queue merely the timeout update: pg queues\n // queries itself, which would let concurrent statements spend the same\n // stale budget.\n let tail: Promise<unknown> = Promise.resolve();\n const activeDispatches = new Set<Promise<PgQueryResultsLike>>();\n let cancellationQueue = false;\n\n // ─── `$all` pipeline (see PipelineControl) ───\n // Lane statements wait in `queued` and go out together as ONE one-Sync\n // batch — behind any deferred control, exactly like a statement riding\n // alone — once every open lane is waiting or closed. Only on a client that\n // can batch, without a deadline, outside the strong-cancellation queue,\n // and without a local `query_timeout`: there every statement keeps its own\n // turn (a deadline re-checks the budget and sends a fresh SET LOCAL before\n // EACH statement; a running cancellation must name one statement as its\n // target; node-postgres arms ONE read timer per `client.query()` call, so a\n // batch would share one timer, where `turns` gives each statement its own).\n const lanes = new Set<PipelineLaneState>();\n let queued: QueuedStatement[] = [];\n const settleQueued = (entry: QueuedStatement, outcome: { readonly result: PgQueryResultsLike } | { readonly error: unknown }): void => {\n if (entry.settled) return;\n entry.settled = true;\n // Synchronously, before any continuation runs: the lane is running again.\n entry.lane.waiting -= 1;\n if (\"result\" in outcome) {\n entry.resolve(outcome.result);\n } else {\n entry.failure = outcome.error;\n entry.reject(outcome.error);\n }\n };\n /**\n * Hand each queued statement the outcome sequential dispatch in this\n * transaction would have given it: the first failing statement its mapped\n * error, statements the server skipped after a failure the aborted refusal\n * naming it, statements behind a failed control step (BEGIN, its SET, a\n * SAVEPOINT) that step's error for the first and the refusal for the rest.\n */\n const distributeBurst = (burst: { outcome: BatchOutcome; live: readonly QueuedStatement[]; controlSteps: number; openingSteps: number }): void => {\n const { outcome, live, controlSteps, openingSteps } = burst;\n const failure = firstBatchFailure({ outcome });\n if (failure === undefined) {\n live.forEach((entry, index) => {\n const step = outcome.steps[controlSteps + index];\n settleQueued(entry, { result: step?.status === \"ok\" ? step.result : { rows: [], rowCount: 0 } });\n });\n return;\n }\n const mapped = failure.index < openingSteps ? openingStepError(failure.index, failure.error) : mapPgDriverError({ error: failure.error });\n if (failure.index < openingSteps || (outcome.transportError !== undefined && openingSteps > 0)) openingFailure = mapped;\n // A server failure aborts the transaction: record it NOW (first kept), naming\n // the very error its statement's caller receives, before any sibling resumes.\n if (typeof mapped.meta.sqlstate === \"string\") markTransactionAborted({ scope, cause: mapped });\n const answered = outcome.transportError === undefined;\n if (failure.index < controlSteps) {\n const later = answered || openingFailure !== undefined ? transactionAbortedError({ cause: openingFailure ?? mapped }) : mapped;\n live.forEach((entry, index) => { settleQueued(entry, { error: index === 0 ? mapped : later }); });\n return;\n }\n let abortCause: VibeError = mapped;\n live.forEach((entry, index) => {\n const position = controlSteps + index;\n const step = outcome.steps[position];\n if (step === undefined) {\n // No answer (the connection failed): what the server did is unknown.\n settleQueued(entry, { error: position === failure.index || openingFailure === undefined ? mapped : transactionAbortedError({ cause: openingFailure }) });\n } else if (step.status === \"ok\") {\n settleQueued(entry, { result: step.result });\n } else if (step.status === \"failed\") {\n const error = position === failure.index ? mapped : mapPgDriverError({ error: step.error });\n if (typeof error.meta.sqlstate === \"string\") abortCause = error;\n settleQueued(entry, { error });\n } else {\n settleQueued(entry, { error: transactionAbortedError({ cause: abortCause }) });\n }\n });\n };\n /** The refusal sequential dispatch raises before a statement is sent now, or `undefined`. */\n const sendRefusal = (): unknown => ridden !== undefined\n ? commitSentRefusal()\n : cancellationAttempted\n ? transactionAbortedError({ cause: readCancelledError({ stage: \"running\" }) })\n : openingFailure !== undefined\n ? transactionAbortedError({ cause: openingFailure })\n : scope.state.poisoned ?? (scope.state.aborted === null ? undefined : transactionAbortedError({ cause: scope.state.aborted.cause }));\n /**\n * EPIC 5: whether COMMIT may ride behind these queued statements — the\n * last one is the transaction's last (`withCommit`), each is the last of\n * its lane (a final statement, or the one statement of a followed lane),\n * nothing else is queued or opening, and every open lane waits on these\n * statements and nothing else.\n */\n const ridesQueued = (live: readonly QueuedStatement[]): boolean => {\n const last = live.at(-1);\n if (last === undefined || (last.commit !== true && last.lane.seat?.group.final !== true) || queued.length > 0 || inFlight !== null || ordinaryOpen > 0 || !ridesNow()) return false;\n const counts = new Map<PipelineLaneState, number>();\n for (const entry of live) {\n // Lane A2: a sub-lane statement of a final group is a transaction-final statement too.\n if (entry.commit !== true && entry.lane.order?.followed !== true && entry.lane.seat?.group.final !== true) return false;\n counts.set(entry.lane, (counts.get(entry.lane) ?? 0) + 1);\n }\n // An open lane that is not waiting on these statements may still issue one.\n for (const open of lanes) {\n const count = counts.get(open) ?? 0;\n if (count > 0 && open.waiting === count) continue;\n // Lane A2: the parent of a sealed final group whose statements are in this batch waits on that group alone.\n const group = open.group;\n if (count === 0 && group?.final === true && group.sealed && open.waiting === 1 && live.some((entry) => entry.lane.seat?.group === group)) continue;\n // Lane A2: a lane that issued its transaction-final statement and waits on nothing is done (the D2 group rule).\n if (count === 0 && open.final === true && open.waiting === 0) continue;\n return false;\n }\n return true;\n };\n /**\n * One burst for the queued statements: [pending control…, statements… (, COMMIT)]. Settles once every entry is settled.\n * `inTurn` (V4, a turn gathering group): sent inside the group's own turn — no pending control (it belongs to a\n * later statement), no opening, no riding COMMIT.\n */\n const sendQueued = (entries: readonly QueuedStatement[], options?: { readonly inTurn?: true }): Promise<void> => {\n const inTurn = options?.inTurn === true;\n // The refusals sequential dispatch raises before sending.\n const refusal = sendRefusal();\n const live: QueuedStatement[] = [];\n for (const entry of entries) {\n if (refusal !== undefined) settleQueued(entry, { error: refusal });\n else if (entry.execution?.signal?.aborted === true) settleQueued(entry, { error: readCancelledError({ stage: \"waiting-for-connection\" }) });\n else live.push(entry);\n }\n if (live.length === 0) return Promise.resolve();\n const carriesOpening = !inTurn && !deferred.opened();\n // EPIC 5: decided before the pending control is taken (it reads the queue's state).\n const rides = !inTurn && live.length === entries.length && ridesQueued(live);\n const control = inTurn ? [] : deferred.takeSteps();\n const openingSteps = carriesOpening ? openingLength : 0;\n const commitIndex = control.length + live.length;\n const sendBatch = (): Promise<BatchOutcome> => runBatch({\n client,\n steps: [...control, ...live.map((entry): BatchStep => (entry.name === undefined ? { text: entry.text, values: entry.values } : { text: entry.text, values: entry.values, name: entry.name })), ...(rides ? [COMMIT_STEP] : [])],\n types: EXACT_TYPES,\n });\n // Inside its own turn the batch goes now (a synchronous throw becomes its rejection, as in a turn).\n const batch = inTurn ? new Promise<BatchOutcome>((resolve) => { resolve(sendBatch()); }) : runTurn(sendBatch);\n if (rides) trackRidden(batch, commitIndex);\n const burst = batch\n .then((received) => { distributeBurst({ outcome: rides ? beforeCommit({ outcome: received, commitIndex }) : received, live, controlSteps: control.length, openingSteps }); })\n .then(undefined, (error: unknown) => {\n // Never handed over (or a defect above): nothing may stay pending.\n if (openingSteps > 0) openingFailure ??= mapPgDriverError({ error });\n for (const entry of live) settleQueued(entry, { error });\n });\n if (carriesOpening) {\n // Ordinary statements dispatched meanwhile wait for the opening's\n // answer, as behind any burst that carries it.\n const settled: Promise<void> = burst.then(() => {\n if (inFlight === settled) inFlight = null;\n });\n inFlight = settled;\n }\n return burst;\n };\n\n // ─── In-flight gathering (round-trip report V4, decision D3) ───\n // An ordinary statement that would WAIT — behind the in-flight burst that\n // carries the opening, or for the client to finish another call — waits in\n // ONE group with every statement issued while that wait lasts, and they\n // leave together, in issue order, when it ends: one batch, `sendQueued`'s\n // distribution (the first failure its mapped error, the statements the\n // server skipped the aborted refusal naming it, a failed control step its\n // error first). A statement that finds nothing to wait for is sent at once,\n // and a group of ONE takes today's path. Any other registration (a call\n // queued in the client's turns, a statement or lane batch waiting for the\n // in-flight burst) closes the open group, so issue order on the connection\n // never changes.\n /**\n * Whether an ordinary statement may wait in a gathering group: the `$all`\n * lane rule ({@link coalescable}: a client that batches, no deadline, no\n * running-cancellation queue, no local `query_timeout`, ONE statement that\n * is no control) — and not the transaction's last statement (`withCommit`\n * keeps its own place, last).\n */\n const gathers = (dispatchParams: Parameters<TransactionDispatch>[0]): boolean =>\n dispatchParams.commit !== true && coalescable(dispatchParams);\n /** A registration that is no gathering join: the open group takes no more statements. */\n const closeGathering = (): void => {\n gathering = null;\n };\n /** The stand-in lane of gathered statements in `sendQueued`: never open, never in `lanes`. */\n const gatheredLane: PipelineLaneState = { open: false, waiting: 0 };\n /** Wait in `group`; `values` were serialized before (a value the driver refuses failed that statement alone). */\n const joinGathering = (group: GatheringGroup, dispatchParams: Parameters<TransactionDispatch>[0], values: unknown[]): Promise<PgQueryResultsLike> =>\n new Promise<PgQueryResultsLike>((resolve, reject) => {\n group.members.push({ params: dispatchParams, values, resolve, reject });\n });\n /**\n * The members of a group of two or more, as ONE burst. A turn group's\n * members passed their signal check when they joined — where today's\n * hand-over checks it — so it is not repeated when the slot comes.\n */\n const sendGathered = (members: readonly GatheredStatement[], options?: { readonly inTurn?: true }): Promise<void> =>\n sendQueued(members.map((member): QueuedStatement => {\n gatheredLane.waiting += 1;\n return {\n text: member.params.config.text,\n values: member.values,\n ...(member.params.name === undefined ? {} : { name: member.params.name }),\n ...(member.params.execution === undefined || options?.inTurn === true ? {} : { execution: member.params.execution }),\n lane: gatheredLane,\n resolve: member.resolve,\n reject: member.reject,\n settled: false,\n };\n }), options);\n /**\n * Wait behind `behind` — the in-flight burst carrying the opening — in the\n * open opening group, or open one. When `behind` settles, ONE member takes\n * today's path (`send`, which takes any pending control in front, as\n * before); two or more leave as one burst with that control in front.\n */\n const gatherBehind = (dispatchParams: Parameters<TransactionDispatch>[0], behind: Promise<void>): Promise<PgQueryResultsLike> => {\n const values = prepareBatchValues({ values: dispatchParams.config.values ?? [] });\n const open = gathering;\n if (open !== null && open.phase === \"opening\" && open.behind === behind) return joinGathering(open, dispatchParams, values);\n const group: GatheringGroup = { phase: \"opening\", behind, members: [] };\n gathering = group;\n gatheringsPending += 1;\n const joined = joinGathering(group, dispatchParams, values);\n void behind.then(() => {\n if (gathering === group) gathering = null;\n gatheringsPending -= 1;\n const [only, ...more] = group.members;\n if (only !== undefined && more.length === 0) {\n void send(only.params).then(only.resolve, only.reject);\n return;\n }\n void sendGathered(group.members);\n });\n return joined;\n };\n /**\n * Wait for the client in the open turn group, or open one: ONE slot of the\n * client's turns. The checks today's hand-over makes before a statement\n * waits run now. When the slot comes, ONE member is handed to node-postgres\n * exactly as before; two or more leave as one burst — without pending\n * control (control deferred after a member joined belongs to a later\n * statement, which carries it) and never with the opening.\n */\n const gatherInTurn = (dispatchParams: Parameters<TransactionDispatch>[0]): Promise<PgQueryResultsLike> => {\n assertReadExecution({ execution: dispatchParams.execution, effect: \"read\", support: readCancellation, provider: PROVIDER, stage: \"waiting-for-connection\" });\n const values = prepareBatchValues({ values: dispatchParams.config.values ?? [] });\n const open = gathering;\n if (open !== null && open.phase === \"turn\") return joinGathering(open, dispatchParams, values);\n const group: GatheringGroup = { phase: \"turn\", members: [] };\n gatheringsPending += 1;\n const joined = joinGathering(group, dispatchParams, values);\n // Its own slot: `turns.run`, not `runTurn` (which closes the open group).\n void turns.run(() => sendTurnGroup(group));\n gathering = group;\n return joined;\n };\n /** A turn group's slot has come: nothing joins any more. Settles with the slot's outcome. */\n const sendTurnGroup = (group: GatheringGroup): Promise<unknown> => {\n if (gathering === group) gathering = null;\n gatheringsPending -= 1;\n const [only, ...more] = group.members;\n if (only !== undefined && more.length === 0) {\n // The slot's outcome is the statement's own: the turn keeper records its failure for the next group.\n const query = new Promise<PgQueryResultsLike>((resolve) => { resolve(client.query(only.params.config)); });\n void query.then(only.resolve, only.reject);\n return query;\n }\n // A server failure answered right before this slot (a statement handed to\n // node-postgres by itself) is recorded first: the group is refused, never\n // answered 25P02.\n const prior = turns.lastFailure();\n if (prior !== undefined) {\n const mapped = mapPgDriverError({ error: prior.error });\n if (typeof mapped.meta.sqlstate === \"string\") markTransactionAborted({ scope, cause: mapped });\n }\n return sendGathered(group.members, { inTurn: true });\n };\n /**\n * An ordered-scope statement that keeps its own turn, sent by itself once\n * the scope's earlier sends settled — and refused, never sent, when one of\n * them failed. A server failure is recorded before the scope's next send\n * looks (its caller records it again; the first record is kept).\n */\n const sendAlone = (entry: QueuedStatement, alone: Parameters<TransactionDispatch>[0]): Promise<void> => {\n const refusal = sendRefusal();\n if (refusal !== undefined) {\n settleQueued(entry, { error: refusal });\n return Promise.resolve();\n }\n return dispatchOrdinary(alone).then(\n (result) => { settleQueued(entry, { result }); },\n (error: unknown) => {\n const mapped = mapPgDriverError({ error });\n if (typeof mapped.meta.sqlstate === \"string\") markTransactionAborted({ scope, cause: mapped });\n settleQueued(entry, { error });\n },\n );\n };\n /** Whether every earlier lane of `lane`'s ordered scope issued a statement (\"issued\"), one has not yet (\"open\"), or one closed without issuing (\"closed\"). */\n const prefixOf = (lane: PipelineLaneState): \"issued\" | \"open\" | \"closed\" => {\n const order = lane.order;\n if (order === undefined) return \"issued\";\n let state: \"issued\" | \"open\" = \"issued\";\n for (let index = 0; index < order.index; index++) {\n const earlier = order.scope.lanes[index] as PipelineLaneState;\n if ((earlier.order as OrderedLaneState).issued > 0) continue;\n if (!earlier.open) return \"closed\";\n state = \"open\";\n }\n return state;\n };\n /** Refuse the queued ordered-scope statements whose earlier lane closed without issuing one: they are never sent. */\n const refuseOrphaned = (): void => {\n if (!queued.some((entry) => prefixOf(entry.lane) === \"closed\")) return;\n const kept: QueuedStatement[] = [];\n for (const entry of queued) {\n if (prefixOf(entry.lane) === \"closed\") settleQueued(entry, { error: predecessorClosedError() });\n else kept.push(entry);\n }\n queued = kept;\n };\n /**\n * One send of an ordered scope. Behind a failed send of the same scope its\n * statements are refused and never sent — also when that failure had no\n * server answer, which leaves PostgreSQL's transaction open (a client-side\n * `query_timeout`, a value the driver refuses): the refusal sequential\n * dispatch would have raised is then the aborted-transaction refusal naming\n * it. A failure of its own fails the scope.\n */\n const orderedSend = (entries: readonly QueuedStatement[], send: (live: readonly QueuedStatement[]) => Promise<void>): (() => Promise<void>) => () => {\n const live: QueuedStatement[] = [];\n for (const entry of entries) {\n const failed = entry.lane.order?.scope.failed;\n if (failed === undefined) live.push(entry);\n else settleQueued(entry, { error: sendRefusal() ?? transactionAbortedError({ cause: failed.cause }) });\n }\n if (live.length === 0) return Promise.resolve();\n return send(live).then(() => {\n for (const entry of live) {\n const order = entry.lane.order;\n if (order !== undefined && entry.failure !== undefined) order.scope.failed ??= { cause: mapPgDriverError({ error: entry.failure }) };\n }\n });\n };\n /** The last send of an ordered scope, settled once its outcome is distributed; the next one waits for it. */\n let orderedTail: Promise<void> | null = null;\n /**\n * Ordered scopes (array `$transaction` bursts, EPIC D). The queued\n * statements whose earlier lanes all issued theirs go out in LANE order —\n * the others stay queued, or are refused when such a lane closed without\n * issuing — as consecutive sends: one batch per run of batchable\n * statements, a statement that keeps its own turn by itself. Every send\n * waits for the previous send of the scope (and for an opening in flight),\n * so a failure refuses what is behind it before it is sent: no lane ever\n * sees 25P02.\n */\n const flushOrdered = (): void => {\n refuseOrphaned();\n const ready: QueuedStatement[] = [];\n const held: QueuedStatement[] = [];\n for (const entry of queued) (prefixOf(entry.lane) === \"issued\" ? ready : held).push(entry);\n queued = held;\n if (ready.length === 0) return;\n // A stable sort: one lane's statements keep their own order.\n ready.sort((first, second) => (first.lane.order?.index ?? 0) - (second.lane.order?.index ?? 0));\n const sends: (() => Promise<void>)[] = [];\n let run: QueuedStatement[] = [];\n for (const entry of ready) {\n const alone = entry.alone;\n if (alone === undefined) {\n run.push(entry);\n continue;\n }\n if (run.length > 0) {\n sends.push(orderedSend(run, sendQueued));\n run = [];\n }\n sends.push(orderedSend([entry], () => sendAlone(entry, alone)));\n }\n if (run.length > 0) sends.push(orderedSend(run, sendQueued));\n const before = [orderedTail, inFlight].filter((wait): wait is Promise<void> => wait !== null);\n let chain: Promise<void> = before.length === 0\n ? (sends.shift() as () => Promise<void>)()\n : Promise.all(before).then(ignore);\n for (const next of sends) chain = chain.then(next);\n const tail = chain;\n orderedTail = tail;\n void tail.then(() => {\n if (orderedTail === tail) orderedTail = null;\n });\n };\n const flushQueue = (): void => {\n if (queued.length === 0) return;\n // V4: a statement issued after these lane statements must not join a group sent before them.\n closeGathering();\n if (queued.some((entry) => entry.lane.order !== undefined)) {\n flushOrdered();\n return;\n }\n const entries = queued.some((entry) => entry.lane.seat !== undefined) ? seatOrder(queued) : queued;\n queued = [];\n if (inFlight === null) sendQueued(entries);\n else void inFlight.then(() => { sendQueued(entries); });\n };\n const flushIfReady = (): void => {\n if (queued.length === 0) return;\n for (const open of lanes) if (open.waiting === 0) return;\n flushQueue();\n };\n /**\n * D2: a group's statements leave in SUB-LANE order, whatever order they\n * arrived in, behind every other statement of the batch (a stable sort).\n */\n const seatOrder = (entries: readonly QueuedStatement[]): QueuedStatement[] =>\n [...entries].sort((first, second) => (first.lane.seat?.index ?? -1) - (second.lane.seat?.index ?? -1));\n /** D2: a sealed group whose sub-lanes all closed is over — its parent no longer counts as waiting. */\n const endGroupIfOver = (opening: LaneGroupState): void => {\n if (!opening.sealed || opening.live > 0 || opening.parent.group !== opening) return;\n opening.parent.group = undefined;\n opening.parent.waiting -= 1;\n };\n const closeLane = (lane: PipelineLaneState): void => {\n if (!lane.open) return;\n lane.open = false;\n lanes.delete(lane);\n // A later lane's statements behind a lane that never issued must not wait for anything.\n if (lane.order !== undefined) refuseOrphaned();\n if (lane.seat !== undefined) {\n lane.seat.group.live -= 1;\n endGroupIfOver(lane.seat.group);\n }\n flushIfReady();\n };\n const pipelines: PipelineControl = {\n open: (count) => Array.from({ length: count }, (): PipelineLaneState => {\n const opened: PipelineLaneState = { open: true, waiting: 0 };\n lanes.add(opened);\n return opened;\n }),\n openOrdered: (count) => {\n const ordered: OrderedScope = { lanes: [] };\n for (let index = 0; index < count; index++) {\n const opened: PipelineLaneState = { open: true, waiting: 0, order: { scope: ordered, index, issued: 0, followed: false } };\n ordered.lanes.push(opened);\n lanes.add(opened);\n }\n return [...ordered.lanes];\n },\n follow: (lane) => {\n const order = lane.order;\n if (order === undefined) throw orderedLaneMisuse({ message: \"follow() exists only on the lanes of an ordered scope\" });\n if (!lane.open) throw orderedLaneMisuse({ message: \"follow() on a closed lane\" });\n if (order.followed || order.scope.lanes.at(-1) !== lane) throw orderedLaneMisuse({ message: \"follow() opens one lane after the LAST lane of its scope\" });\n if (order.issued > 0) throw orderedLaneMisuse({ message: \"follow() must come before the lane issues its statement\" });\n order.followed = true;\n // Open and not waiting: it holds the batch until it issues or closes.\n const next: PipelineLaneState = { open: true, waiting: 0, order: { scope: order.scope, index: order.scope.lanes.length, issued: 0, followed: false } };\n order.scope.lanes.push(next);\n lanes.add(next);\n return next;\n },\n close: closeLane,\n waitAs: ({ lane, wait }) => {\n if (!lane.open) return wait;\n lane.waiting += 1;\n flushIfReady();\n return wait.then(\n (value) => { lane.waiting -= 1; return value; },\n (error: unknown) => { lane.waiting -= 1; throw error; },\n );\n },\n enter: (lane) => {\n if (!lane.open) return ignore;\n lane.waiting += 1;\n flushIfReady();\n let left = false;\n return (): void => {\n if (left) return;\n left = true;\n lane.waiting -= 1;\n };\n },\n flush: flushQueue,\n /**\n * D2 (`PipelineLane.group`). Admitted only where the group cannot move\n * a statement ahead of one sequential dispatch would send first: the\n * statements combine now, the transaction accepts statements, and\n * every OTHER open lane is done (issued its transaction-final statement\n * and has nothing waiting) — an ordinary lane still loading, or another\n * group, could issue a statement after the group's batch that sequential\n * dispatch would have sent before some of its statements.\n */\n group: (lane, final) => {\n if (!lane.open || lane.order !== undefined || lane.seat !== undefined || lane.gate === true || lane.group !== undefined || lane.final === true) return undefined;\n if (!capable || budget.totalMs !== null || cancellationQueue || sendRefusal() !== undefined) return undefined;\n // Review D2-01: a local `query_timeout` arms ONE timer per batch — the group's statements would share\n // it, where one after another each has its own (as ordered scopes and COMMIT riding, above).\n if ((client.connectionParameters?.query_timeout ?? 0) > 0) return undefined;\n for (const other of lanes) {\n if (other !== lane && (other.final !== true || other.waiting > 0)) return undefined;\n }\n // The gate is open and never waiting: it holds the batch until the group is sealed.\n const gate: PipelineLaneState = { open: true, waiting: 0, gate: true };\n const opening: LaneGroupState = { parent: lane, gate, opened: 0, live: 0, sealed: false, final };\n lanes.add(gate);\n lane.group = opening;\n // OP-11: the parent awaits its sub-lanes, so it counts as waiting until the group is over.\n lane.waiting += 1;\n return opening;\n },\n seat: (opening) => {\n if (opening.sealed) throw laneGroupMisuse({ message: \"a sub-lane is opened only before the group is sealed\" });\n if (!opening.parent.open) throw laneGroupMisuse({ message: \"a sub-lane of a closed lane\" });\n // Open and not waiting: it holds the batch until it issued its statement or closed.\n const seat: PipelineLaneState = { open: true, waiting: 0, seat: { group: opening, index: opening.opened, issued: false } };\n opening.opened += 1;\n opening.live += 1;\n lanes.add(seat);\n return seat;\n },\n seal: (opening) => {\n if (opening.sealed) return;\n opening.sealed = true;\n endGroupIfOver(opening);\n closeLane(opening.gate);\n },\n };\n /**\n * The transaction is ending: every lane closes, and a statement still\n * queued goes out now — ahead of COMMIT/ROLLBACK, exactly where an\n * un-awaited statement sits in node-postgres' own queue.\n */\n const endPipeline = (): void => {\n for (const open of lanes) open.open = false;\n lanes.clear();\n flushQueue();\n };\n const enqueue = (dispatchParams: Parameters<TransactionDispatch>[0], lane: PipelineLaneState, alone?: true): Promise<PgQueryResultsLike> => {\n // The refusals sequential dispatch raises, then the values serialized\n // NOW: a value the driver refuses fails this statement alone. A statement\n // that keeps its own turn (ordered scopes) is serialized when it is sent.\n if (cancellationAttempted) throw transactionAbortedError({ cause: readCancelledError({ stage: \"running\" }) });\n if (openingFailure !== undefined) throw transactionAbortedError({ cause: openingFailure });\n if (ridden !== undefined) throw commitSentRefusal();\n assertReadExecution({ execution: dispatchParams.execution, effect: \"read\", support: readCancellation, provider: PROVIDER, stage: \"waiting-for-connection\" });\n const values = alone === true ? [] : prepareBatchValues({ values: dispatchParams.config.values ?? [] });\n const pending = new Promise<PgQueryResultsLike>((resolve, reject) => {\n lane.waiting += 1;\n queued.push({\n text: dispatchParams.config.text,\n values,\n ...(dispatchParams.name === undefined ? {} : { name: dispatchParams.name }),\n ...(dispatchParams.execution === undefined ? {} : { execution: dispatchParams.execution }),\n ...(alone === true ? { alone: dispatchParams } : {}),\n ...(dispatchParams.commit === true ? { commit: true as const } : {}),\n lane,\n resolve,\n reject,\n settled: false,\n });\n });\n if (lane.order !== undefined) lane.order.issued += 1;\n // A later strong read drains it like any ordinary statement.\n activeDispatches.add(pending);\n void pending.then(() => activeDispatches.delete(pending), () => activeDispatches.delete(pending));\n flushIfReady();\n return pending;\n };\n /** Whether a lane statement may wait in the pipeline (see the block comment above). */\n const coalescable = (dispatchParams: Parameters<TransactionDispatch>[0]): boolean =>\n capable && budget.totalMs === null && !cancellationQueue &&\n // 5.0 lane F: a local `query_timeout` (as `pipelines.group`, review D2-01) — `$all` members one per flight.\n !((client.connectionParameters?.query_timeout ?? 0) > 0) &&\n dispatchParams.batchable === true && dispatchParams.cleanup !== true && dispatchParams.stage === undefined &&\n dispatchParams.sent === undefined && dispatchParams.execution?.cancellation !== \"running\";\n\n /**\n * A NAMED statement of this transaction (a raw caller name or an ORM\n * auto-name) failed with 0A000 / 26000 / 42P05: node-postgres keeps its\n * record of the name across errors, so the connection would fail the same\n * way on every later call. It is discarded at release, whatever the\n * transaction's outcome (the callback may catch the error and commit).\n */\n let staleNamedStatement = false;\n const dispatch: TransactionDispatch = (dispatchParams) => {\n const dispatched = route(dispatchParams);\n if (dispatchParams.config.name === undefined) return dispatched;\n return dispatched.then(undefined, (error: unknown) => {\n if (isStaleStatementFailure({ error })) staleNamedStatement = true;\n throw error;\n });\n };\n const route: TransactionDispatch = (dispatchParams) => {\n const lane = dispatchParams.lane?.open === true ? dispatchParams.lane : undefined;\n if (lane !== undefined && dispatchParams.cleanup !== true) {\n // D2: the lane-group rules, checked before anything is queued or sent.\n if (lane.group !== undefined) return Promise.reject(laneGroupMisuse({ message: \"a lane issues nothing while its group is open\" }));\n const seat = lane.seat;\n if (seat !== undefined) {\n if (seat.issued) return Promise.reject(laneGroupMisuse({ message: \"a sub-lane issues ONE statement\" }));\n if (!coalescable(dispatchParams)) return Promise.reject(laneGroupMisuse({ message: \"a sub-lane statement must be able to join a batch\" }));\n seat.issued = true;\n }\n // EPIC 5: the lane's transaction-final statement — it issues nothing after it.\n if (dispatchParams.commit === true) lane.final = true;\n }\n const order = lane?.order;\n if (lane !== undefined && order !== undefined && dispatchParams.cleanup !== true) {\n // Ordered scope: every statement waits in the pipeline, one that keeps\n // its own turn included, so lane order and the prefix rule hold for all.\n return guarded(() => {\n if (order.followed && order.issued > 0) throw orderedLaneMisuse({ message: \"a lane that has a follower may issue ONE statement\" });\n return coalescable(dispatchParams) ? enqueue(dispatchParams, lane) : enqueue(dispatchParams, lane, true);\n });\n }\n if (lane !== undefined && coalescable(dispatchParams)) return guarded(() => enqueue(dispatchParams, lane));\n if (lane === undefined) return dispatchOrdinary(dispatchParams);\n // A lane statement that keeps its own turn: the lane counts as waiting\n // while it runs, and whatever the lanes already queued goes out FIRST —\n // call order on the connection, as sequential dispatch (a RELEASE or a\n // raw statement never overtakes a statement issued before it).\n const leave = pipelines.enter(lane);\n flushQueue();\n return dispatchOrdinary(dispatchParams).then(\n (result) => { leave(); return result; },\n (error: unknown) => { leave(); throw error; },\n );\n };\n const dispatchOrdinary: TransactionDispatch = (dispatchParams) => {\n if (dispatchParams.execution?.cancellation === \"running\" && !cancellationQueue) {\n // Drain earlier ordinary statements before naming a target. All later\n // work (including siblings/cleanup) waits for BOTH query and control.\n // Lane statements still queued go out first, so the drain includes them.\n flushQueue();\n cancellationQueue = true;\n closeGathering();\n tail = Promise.allSettled([...activeDispatches]);\n }\n if (budget.totalMs === null && !cancellationQueue) {\n // Register this arrival before waiting for the deferred opening. A\n // later strong read must drain it, not recursively move it behind\n // the cancellation queue when that opening finally settles.\n // EPIC 5: counted before it is sent (a riding COMMIT needs it to be the only one).\n ordinaryOpen += 1;\n // V4: an open opening group is waited for too — nothing overtakes the statements in it.\n const behind = gathering?.phase === \"opening\" ? (gathering.behind ?? null) : inFlight;\n let pending: Promise<PgQueryResultsLike>;\n if (behind === null) pending = send(dispatchParams);\n else if (gathers(dispatchParams)) pending = guarded(() => gatherBehind(dispatchParams, behind));\n else {\n closeGathering();\n pending = behind.then(() => send(dispatchParams));\n }\n activeDispatches.add(pending);\n const settle = (): void => { activeDispatches.delete(pending); ordinaryOpen -= 1; };\n void pending.then(settle, settle);\n return pending;\n }\n const pending = tail.then(() => send(dispatchParams));\n // A failed statement must not strand ROLLBACK behind a rejected tail.\n tail = pending.then(ignore, ignore);\n closeGathering();\n return pending;\n };\n /** Set when the session's state can no longer be asserted (see below). */\n let discard = false;\n let released = false;\n let cancellationAttempted = false;\n const cancellation = createPgReadCancellation({ connectionString: cancellationAddress, target: onClient, terminate: () => {\n if (!released) { released = true; client.release(true); }\n }, discard: () => {\n discard = true;\n cancellationAttempted = true;\n // Even a successful read can race an asynchronous backend signal. No\n // later user statement/commit may enter this target transaction.\n markTransactionAborted({ scope, cause: readCancelledError({ stage: \"running\" }) });\n } });\n /** How far COMMIT got — the only input of the commit outcome (EPIC T). */\n let commitProgress: CommitProgress = \"not-sent\";\n /** Set when `openWithSettings` already rolled the transaction back: the cleanup sends no second ROLLBACK. */\n let openingRollback: RollbackOutcome | undefined;\n /**\n * TU-02: a transaction with `settings` opens EAGERLY and waits for the\n * answer, so a refused setting fails the opening and the callback never\n * runs. On a client that batches, `BEGIN …` (+ the timeout's SET) and the\n * ONE bound settings statement travel in ONE flight (one Sync): a failed\n * `BEGIN` leaves the settings unrun. Otherwise the opening text, then the\n * settings statement. A refused setting (a server answer): ROLLBACK, name\n * the refused setting (`findRefusedSetting`, failure path only), reject\n * with `VIBE_TRANSACTION` `meta.reason: \"setting-refused\"`. A failed\n * opening or a lost answer keeps today's opening failure.\n */\n const openWithSettings = async (statement: TransactionSettingsStatement): Promise<void> => {\n let failed: { readonly error: unknown } | undefined;\n if (capable) {\n const control = [beginStatement(openingOptions), ...(openingOptions.timeout === undefined ? [] : [statementTimeoutStatement({ timeout: openingOptions.timeout })])];\n const outcome = await turns.run(() => runBatch({\n client,\n steps: [...control.map((text) => ({ text })), { text: statement.text, values: prepareBatchValues({ values: statement.values }) }],\n types: EXACT_TYPES,\n }));\n const failure = firstBatchFailure({ outcome });\n if (failure === undefined) return;\n if (failure.index < control.length || outcome.transportError !== undefined) throw mapPgDriverError({ error: failure.error });\n failed = { error: failure.error };\n } else {\n await runMapped(() => onClient.query({ text: openText }));\n failed = await onClient.query({ text: statement.text, values: [...statement.values] }).then(\n () => undefined,\n (error: unknown) => ({ error }),\n );\n if (failed === undefined) return;\n }\n const cause = mapPgDriverError({ error: failed.error });\n // No server answer: what ran is unknown — today's opening failure and cleanup.\n if (typeof cause.meta.sqlstate !== \"string\") throw cause;\n openingRollback = await onClient.query({ text: \"ROLLBACK\" }).then((): RollbackOutcome => \"acknowledged\", (): RollbackOutcome => \"failed\");\n if (openingRollback === \"failed\") discard = true;\n const setting = findRefusedSetting({ settings, cause });\n throw transactionSettingRefusedError({ provider: PROVIDER, settings, setting, cause });\n };\n try {\n if (settingsStatement !== undefined && !settingsDeferred) await openWithSettings(settingsStatement);\n else if (!deferOpening) await runMapped(() => onClient.query({ text: openText }));\n const result = await runRootScope({\n scope,\n // Ordered scopes (array `$transaction` bursts) only without a deadline:\n // there every statement keeps its own turn and its own bound. A `timeout`\n // does not exclude them (V2): it is only the server's `statement_timeout`,\n // which PostgreSQL arms anew for every statement of a batch.\n // And not on a client with a local `query_timeout`: it fails a statement\n // without stopping it, so it could not stop a statement already sent\n // behind it in the same batch (read cancellation refuses it too).\n body: () => fn(createClientAdapter({\n dispatch, scope, budget, deferred: capable ? deferred : null, cancellation, pipelines: capable ? pipelines : null,\n connection: client, topLevel: true,\n ordered: capable && budget.totalMs === null && !((client.connectionParameters?.query_timeout ?? 0) > 0),\n commits,\n })),\n });\n endPipeline();\n const riding = ridden;\n if (riding !== undefined) {\n // EPIC 5: COMMIT rode with the last statement; that batch decided the transaction.\n await riding.settled;\n if (riding.state === \"committed\") {\n budget.close({ outcome: \"committed\" });\n return result;\n }\n throw riding.state === \"skipped\" ? transactionAbortedError({ cause: scope.state.aborted?.cause }) : riding.error;\n }\n // An expired budget must never commit, however the callback ended.\n budget.assertUsable({ stage: \"commit\" });\n if (!deferred.opened()) {\n // The callback sent nothing: no BEGIN left the client, so there is\n // nothing to commit (EPIC 6, empty transaction: 2 waits → 0).\n budget.close({ outcome: \"committed\" });\n return result;\n }\n // The deferred opening failed and the callback swallowed it: there is\n // no transaction to commit. Refuse here, so the ordinary cleanup below\n // runs — not the COMMIT branch, which would report a COMMIT that was\n // never sent as lost in flight (fix lane FX-A, RV5 MI-2).\n if (openingFailure !== undefined) throw transactionAbortedError({ cause: openingFailure });\n // EPIC 5: COMMIT releases every savepoint — a RELEASE still pending never leaves.\n deferred.dropReleases();\n const commit = await runMapped(() => dispatch({\n config: { text: \"COMMIT\" },\n stage: \"commit\",\n batchable: true,\n sent: () => {\n // A client whose connection already failed refuses COMMIT locally:\n // raise that failure here, with COMMIT still unsent.\n if (connectionFailure !== undefined) throw mapPgDriverError({ error: connectionFailure.cause });\n commitProgress = \"sent\";\n },\n }))\n .catch((cause: unknown) => {\n // Refused before it reached node-postgres (the deadline re-check in\n // the dispatch turn, a poisoned scope, a connection that had\n // already failed): COMMIT was never sent, so the outcome is known\n // and the refusal is rethrown as it is.\n if (commitProgress === \"not-sent\") throw cause;\n // The server answered (a serialization failure at commit is a\n // definite rollback) — or the acknowledgement was LOST, in which\n // case a later successful ROLLBACK disproves nothing: the write may\n // have committed. Close unknown BEFORE cleanup, like mysql and bun.\n if (!isConnectionLoss({ error: cause })) {\n commitProgress = \"answered\";\n throw cause;\n }\n commitProgress = \"unanswered\";\n discard = true;\n budget.close({ outcome: \"unknown\" });\n throw commitOutcomeUnknownError({ cause });\n });\n // Belt and braces over the gate's tracking: an aborted transaction's\n // COMMIT is answered with a ROLLBACK tag and no error.\n if (finalResult({ result: commit }).command === \"ROLLBACK\") {\n commitProgress = \"answered\";\n throw transactionAbortedError({ cause: scope.state.aborted?.cause });\n }\n budget.close({ outcome: \"committed\" });\n return result;\n } catch (caught) {\n endPipeline();\n const riding = ridden;\n if (riding !== undefined) await riding.settled;\n if (riding?.state === \"committed\") {\n // EPIC 5 (named exception E-T1): the transaction committed with its\n // last statement and the callback failed afterwards (a read's verdict).\n // Nothing is open to roll back, and nothing failed to report.\n budget.close({ outcome: \"committed\" });\n throw caught;\n }\n // A riding COMMIT without an answer: the outcome is unknown, whatever the callback threw.\n const error = riding?.state === \"lost\" ? riding.error : caught;\n if (isSavepointRollbackFailedError(error) || scope.state.poisoned !== null) {\n // A successful outer ROLLBACK cannot establish what happened when the\n // savepoint stack was lost. Keep the shared poison's unknown outcome.\n discard = true;\n budget.close({ outcome: \"unknown\" });\n }\n let rollback: RollbackOutcome = \"not-needed\";\n try {\n // Settings refused at the opening (TU-02): already rolled back there.\n if (openingRollback !== undefined) rollback = openingRollback;\n // A deferred opening that never left the client left nothing to undo.\n else if (deferred.opened()) {\n await dispatch({ config: { text: \"ROLLBACK\" }, cleanup: true });\n rollback = \"acknowledged\";\n }\n } catch {\n // The rollback that should have cleaned up failed: this connection may\n // still be inside a transaction with `SET LOCAL` settings that were\n // never reverted, so it is DESTROYED rather than pooled. The commit\n // outcome does not change: it follows from how far COMMIT got, and\n // the server ends an open transaction when the connection closes.\n discard = true;\n rollback = \"failed\";\n }\n // EPIC T: the same error, with the facts recorded beside it.\n throw settleFailedTransaction({\n error,\n provider: PROVIDER,\n budget,\n scope,\n commit: commitProgress,\n rollback,\n connection: discard || staleNamedStatement ? \"discarded\" : \"returned\",\n });\n } finally {\n unguard();\n if (!released) client.release(discard || staleNamedStatement);\n }\n },\n\n async connect(): Promise<void> {\n // V7: open `min` connections AT ONCE (at least one), then release them\n // to the pool, so a warm pool exists before the first burst. Every\n // opened connection is released before a failure is reported.\n const opened = await Promise.allSettled(Array.from({ length: Math.max(1, poolMin ?? 0) }, () => runMapped(() => getPool().connect())));\n for (const outcome of opened) {\n if (outcome.status === \"fulfilled\") outcome.value.release();\n }\n const failed = opened.find((outcome) => outcome.status === \"rejected\");\n if (failed !== undefined) throw failed.reason;\n },\n };\n\n /**\n * Round-trip follow-up, lane A2 (`DatabaseAdapter.connectionGroup`): send a\n * read's sibling relation statements on ONE checked-out client as one\n * one-Sync batch — one round trip, one implicit transaction of the server\n * (under READ COMMITTED each statement still reads its own snapshot). The\n * client is re-checked here: one that cannot batch, carries a local\n * `query_timeout` (its one timer would cover every statement) or lacks the\n * ready-for-query seam is handed back unused, and the statements go through\n * `root.execute` one after another — today's path — the ones after the first\n * failure reported as skipped. After a server failure the client is pooled\n * only with the root path's proof (`observeReadyForQuery`).\n */\n const sendConnectionGroup = async (entries: readonly ConnectionGroupEntry[]): Promise<BatchOutcome> => {\n const rootPool = getPool();\n const client = rootViaPoolQuery ? undefined : await runMapped(() => rootPool.connect());\n if (client === undefined || !hasReadyForQuerySeam({ client }) || !supportsBatch({ client }) || (client.connectionParameters?.query_timeout ?? 0) > 0) {\n client?.release();\n const steps: BatchOutcome[\"steps\"][number][] = [];\n for (const entry of entries) {\n if (steps.some((step) => step.status === \"failed\")) {\n steps.push({ status: \"skipped\" });\n continue;\n }\n steps.push(await root.execute(entry.call).then(\n (rows) => ({ status: \"ok\" as const, result: { rows, rowCount: rows.length } }),\n (error: unknown) => ({ status: \"failed\" as const, error }),\n ));\n }\n return { steps };\n }\n const seam = observeReadyForQuery({ client });\n let reuse = false;\n const outcome = await runBatch({ client, steps: entries.map((entry) => entry.step), types: EXACT_TYPES }).then(\n (settled) => settled,\n (error: unknown): BatchOutcome => ({ steps: [], transportError: error }),\n );\n const failure = firstBatchFailure({ outcome });\n if (failure === undefined) reuse = true;\n else if (outcome.transportError === undefined) reuse = await seam.reusableAfter({ error: mapPgDriverError({ error: failure.error }), named: false });\n seam.detach();\n client.release(!reuse);\n return outcome;\n };\n /** The fields every connection-group sub-lane carries (the root's declarations). */\n const connectionGroupBase: ConnectionGroupDriver[\"base\"] = {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n budgets: BUDGETS,\n roundTrips: ROUND_TRIPS,\n formatArrayParam: (values: unknown[]): unknown => new PgArrayParam(values),\n };\n const connectionGroupDriver: ConnectionGroupDriver = {\n base: connectionGroupBase,\n prepare: (call) => ({ text: call.text, values: prepareBatchValues({ values: serializeParams({ values: call.values }) }) }),\n send: (entries) => lifecycle.admit({ run: () => sendConnectionGroup(entries) }),\n mapError: (error) => mapPgDriverError({ error }),\n };\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n budgets: BUDGETS,\n readCancellation,\n roundTrips: ROUND_TRIPS,\n readSnapshot: READ_SNAPSHOT,\n pipelining: PIPELINING,\n transactionOutcome: \"reported\",\n transactionSettings: \"transaction-local\",\n // Round-trip follow-up lane E: see `transactionsTakeOneRoundTrip`.\n ...(transactionsTakeOneRoundTrip({ address }) ? {\n oneRoundTripTransactions: true as const,\n // Lane A2: the same per-client conditions (a driver that batches, no local `query_timeout`).\n // Opening one sends nothing; after `disconnect()` it is refused like every root call (lane BN).\n connectionGroup: (): PipelineGroup | undefined => {\n const closed = lifecycle.refusal();\n if (closed !== undefined) throw closed;\n return rootViaPoolQuery ? undefined : openConnectionGroup({ driver: connectionGroupDriver });\n },\n } : {}),\n\n withSession({ run }) {\n return lifecycle.admit({ run: () => root.withSession({ run: (executor) => lifecycle.inCallback({ run: () => run(executor) }) }) });\n },\n\n execute(params) {\n return lifecycle.admit({ run: () => params.execution === undefined ? root.execute(params) : runReadExecution({ ...params, support: readCancellation, provider: PROVIDER, run: () => root.execute(params) }) });\n },\n\n executeUnsafe(params) {\n return lifecycle.admit({ run: () => root.executeUnsafe(params) });\n },\n\n transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n return lifecycle.admit({ run: () => root.transaction((txAdapter) => lifecycle.inCallback({ run: () => fn(txAdapter) }), transactionOptions) });\n },\n\n connect(): Promise<void> {\n return lifecycle.admit({ run: () => root.connect() });\n },\n\n /**\n * Terminal (EPIC A2): refuses new work at once, waits for admitted work —\n * whole transaction and session callbacks included — then closes what the\n * adapter owns, once. Repeated calls share that completion. A new adapter\n * is the only way to connect again.\n */\n disconnect(): Promise<void> {\n return lifecycle.disconnect();\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return new PgArrayParam(values);\n },\n };\n}\n\n// ─── Re-exports (driver-error table, markers, helpers) ────────────\n\nexport { PG_SQLSTATE_ERROR_CODES, PG_SQLSTATE_REASONS, mapPgDriverError, pgErrorSqlstate } from \"./errors.ts\";\nexport { PgArrayParam, serializeParams, serializeParamsRaw } from \"./params.ts\";\nexport { createSavepointCounter, nextSavepointName } from \"@vibeorm/runtime/adapter-kit\";\nexport type { SavepointCounter } from \"@vibeorm/runtime/adapter-kit\";\nexport { createStatementNameCache } from \"./statement-cache.ts\";\nexport type { StatementNameCache } from \"./statement-cache.ts\";\nexport { buildPoolConfig, placePlanCacheMode } from \"./pool-config.ts\";\nexport type { PlanCacheMode, StartupOptionsPlacement } from \"./pool-config.ts\";\nexport {\n ISOLATION_LEVEL_SQL,\n beginStatement,\n classifyRawTransactionControl,\n refuseNestedTransactionOptions,\n statementTimeoutStatement,\n} from \"./transaction-sql.ts\";\nexport type { RawTransactionControl } from \"./transaction-sql.ts\";\n// ─── EPIC 6: transaction budgets (shared, @vibeorm/runtime/adapter-kit) ───\nexport {\n DEFAULT_DEADLINE_CLOCK,\n engineStatementBudgetMs,\n isTransactionDeadlineError,\n startTransactionBudget,\n transactionClosedError,\n transactionDeadlineError,\n transactionOutcomeUnknownError,\n validateTransactionDeadline,\n} from \"@vibeorm/runtime/adapter-kit\";\nexport type { BudgetStage, DeadlineClock, TransactionBudget, TransactionOutcome } from \"@vibeorm/runtime/adapter-kit\";\n",
6
+ "/**\n * One-Sync batch for node-postgres (round-trip EPIC 6, pipelining).\n *\n * Several statements go to the server as Parse / Bind / Describe / Execute\n * each, followed by ONE Sync — one wait instead of one per statement. It is a\n * `Submittable` (the extension point `client.query(object)` documents and\n * pg-cursor uses) running on an ordinary, NON-pipeline client: the batch is one\n * query object, so the client's own queue, ReadyForQuery handling and status\n * bookkeeping stay node-postgres'.\n *\n * PostgreSQL's extended protocol skips every message after an error until the\n * Sync (as libpq pipeline mode does), so a failing step leaves every later step\n * UNRUN — a failed `BEGIN` can never let a later write run in autocommit, and\n * no later step answers 25P02 (spike-report §1.3, \"pg one-Sync batch\").\n *\n * Only API that node-postgres exposes is used: `connection.parse / bind /\n * describe / execute / sync` (declared on `Connection` in @types/pg), the\n * message handlers of the Submittable contract, and the driver's own\n * `utils.prepareValue` (a property of the `pg` module object, feature-detected)\n * so parameters serialize exactly as `client.query` serializes them. Rows are\n * decoded HERE, with the adapter's query-local type parsers — never through\n * node-postgres' internal `lib/result.js`.\n *\n * Named steps (throughput request 1): a step with a `name` is parsed under\n * that name only when this connection has not prepared it yet, and bound to\n * the name either way. The record of prepared names is node-postgres' OWN\n * (`connection.parsedStatements` / `submittedNamedStatements`, the objects its\n * `Query` reads), kept exactly as `Query` keeps it: a name is \"submitted\" when\n * its Parse is written, \"parsed\" only when its ParseComplete arrives (the\n * connection's `parseComplete` event, counted per Parse this batch wrote), and\n * forgotten when the server refused or skipped its Parse. So a name a plain\n * query prepared is never parsed again here, and the other way round.\n */\n\nimport { VibeError } from \"@vibeorm/schema\";\nimport pg from \"pg\";\n\n// ─── Types ────────────────────────────────────────────────────────\n\n/** One statement of a batch. Values are the adapter's already-serialized params. */\nexport type BatchStep = {\n readonly text: string;\n readonly values?: readonly unknown[];\n /**\n * A caller-chosen prepared-statement name (raw path, throughput request 1):\n * parsed under it once per connection, bound to it every time. A text that\n * differs from the one this connection already holds is refused before any\n * step or bookkeeping change.\n */\n readonly name?: string;\n /**\n * Nobody reads this step's rows (statement-count pass EPIC 5: the final\n * statement that rides with COMMIT): they are not decoded, so no type parser\n * can fail on them; the step reports no rows and its command tag's count.\n */\n readonly discardRows?: true;\n};\n\n/** A step's decoded result, shaped like the node-postgres result the adapter reads. */\nexport type BatchStepResult = {\n readonly rows: Record<string, unknown>[];\n readonly rowCount: number | null;\n readonly command?: string;\n};\n\n/** Per-step outcome after the batch's ReadyForQuery. */\nexport type BatchStepOutcome =\n | { readonly status: \"ok\"; readonly result: BatchStepResult }\n | { readonly status: \"failed\"; readonly error: unknown }\n | { readonly status: \"skipped\" };\n\n/** What a batch reports once it settled. */\nexport type BatchOutcome = {\n /** One entry per step, in order. */\n readonly steps: readonly BatchStepOutcome[];\n /**\n * A failure WITHOUT a server answer — the socket broke, or the client's\n * `query_timeout` fired while the batch was still on the wire. What the\n * server did with the batch is unknown; `steps` lists only what was seen.\n */\n readonly transportError?: unknown;\n /**\n * With `transportError`: PROVABLY no byte of this batch reached the socket,\n * so the server received none of its statements. Either node-postgres never\n * submitted the batch (a client already not queryable or ending answers\n * `query()` with `handleError` and never calls `submit`; a client that fails\n * errors its queued queries the same way), or its stream was no longer\n * writable when it was (node-postgres' `Connection._send` writes nothing to a\n * stream that is not writable, and a socket never becomes writable again).\n */\n readonly unsent?: true;\n};\n\n/** The query-local type parser surface (the adapter's `EXACT_TYPES`). */\nexport type BatchTypeParsers = {\n getTypeParser(oid: number, format?: \"text\" | \"binary\"): (value: string) => unknown;\n};\n\n/** The protocol writer surface of node-postgres' `Connection`. */\ntype BatchConnection = {\n readonly stream?: { cork?: () => void; uncork?: () => void };\n parse(params: { text: string; name?: string; types?: readonly number[] }): void;\n bind(params: { portal?: string; statement?: string; values: readonly unknown[] }): void;\n describe(params: { type: \"P\"; name: string }): void;\n execute(params: { portal: string; rows: number }): void;\n sync(): void;\n sendCopyFail?(message: string): void;\n};\n\n/**\n * node-postgres' per-connection record of named statements — the very\n * objects its `Query` reads and writes (`pg/lib/query.js` `hasBeenParsed`,\n * `prepare`; `client.js` `_handleParseComplete`, `_handleErrorMessage`).\n */\ntype StatementBook = {\n /** Name → text the server confirmed (ParseComplete). */\n readonly parsed: Record<string, string>;\n /** Name → text whose Parse is on the wire, not confirmed yet. */\n readonly submitted: Record<string, string>;\n /** Subscribe to the connection's ParseComplete messages; returns the unsubscribe. */\n readonly onParseComplete: (listener: () => void) => () => void;\n};\n\n/** A Parse this batch wrote: the name it prepares and its text, or `null` for an unnamed Parse. */\ntype WrittenParse = { readonly name: string; readonly text: string } | null;\n\n/**\n * The connection's statement record, when the driver exposes it (pg 8.x:\n * plain objects on `Connection`, which is an EventEmitter). `undefined` on a\n * test double or a foreign driver: named steps then run unnamed.\n */\nfunction statementBookOf(params: { connection: unknown }): StatementBook | undefined {\n const connection = params.connection as {\n parsedStatements?: unknown;\n submittedNamedStatements?: unknown;\n on?: unknown;\n removeListener?: unknown;\n } | null;\n if (connection === null || typeof connection !== \"object\") return undefined;\n const { parsedStatements, submittedNamedStatements, on, removeListener } = connection;\n if (typeof parsedStatements !== \"object\" || parsedStatements === null) return undefined;\n if (typeof submittedNamedStatements !== \"object\" || submittedNamedStatements === null) return undefined;\n if (typeof on !== \"function\" || typeof removeListener !== \"function\") return undefined;\n return {\n parsed: parsedStatements as Record<string, string>,\n submitted: submittedNamedStatements as Record<string, string>,\n onParseComplete: (listener) => {\n (on as (event: string, listener: () => void) => unknown).call(connection, \"parseComplete\", listener);\n return () => { (removeListener as (event: string, listener: () => void) => unknown).call(connection, \"parseComplete\", listener); };\n },\n };\n}\n\n/** The client surface a batch needs; feature-detected, never assumed. */\ntype BatchClient = {\n readonly connection?: unknown;\n readonly pipeline?: unknown;\n};\n\ntype RowDescriptionField = { readonly name: string; readonly dataTypeID: number; readonly format?: \"text\" | \"binary\" };\n\n// ─── Feature detection ────────────────────────────────────────────\n\n/** node-postgres' own parameter serializer, when the installed driver exposes it. */\nconst prepareValue: ((value: unknown) => unknown) | undefined = (() => {\n const utils = (pg as unknown as { utils?: { prepareValue?: unknown } }).utils;\n return typeof utils?.prepareValue === \"function\"\n ? (utils.prepareValue as (value: unknown) => unknown)\n : undefined;\n})();\n\n/** Whether this `pg` build exports what a one-Sync batch needs (`utils.prepareValue`); per-client checks stay in {@link supportsBatch}. */\nexport function batchDriverAvailable(): boolean {\n return prepareValue !== undefined;\n}\n\n/**\n * Whether `client` can run a one-Sync batch: a node-postgres client whose\n * connection exposes the protocol writers, NOT in pipeline mode (pipeline mode\n * sends a Sync per query and was rejected by the spike), with the driver's\n * value serializer available. Test doubles and foreign clients answer false\n * and keep today's one-statement-per-wait path.\n */\nexport function supportsBatch(params: { client: unknown }): boolean {\n if (prepareValue === undefined) return false;\n const client = params.client as BatchClient | null;\n if (client === null || typeof client !== \"object\" || client.pipeline === true) return false;\n const connection = client.connection as Partial<Record<keyof BatchConnection, unknown>> | null | undefined;\n return connection !== null && typeof connection === \"object\" &&\n typeof connection.parse === \"function\" &&\n typeof connection.bind === \"function\" &&\n typeof connection.describe === \"function\" &&\n typeof connection.execute === \"function\" &&\n typeof connection.sync === \"function\";\n}\n\n/**\n * Serialize a step's parameters with the driver's own `prepareValue`. Runs\n * BEFORE anything is written, so a value the driver cannot serialize refuses\n * the whole batch with nothing sent (node-postgres' own path closes and syncs\n * instead; the caller-visible error is the same driver error).\n */\nexport function prepareBatchValues(params: { values: readonly unknown[] }): unknown[] {\n const prepare = prepareValue as (value: unknown) => unknown;\n return params.values.map((value) => prepare(value));\n}\n\n// ─── The batch ────────────────────────────────────────────────────\n\n/** `INSERT 0 3` → command `INSERT`, rows 3 (the CommandComplete tag grammar). */\nconst COMMAND_TAG = /^([A-Za-z]+)(?: (\\d+))?(?: (\\d+))?/;\n\n/** A server ErrorResponse (pg-protocol `DatabaseError`), as opposed to a client/socket failure. */\nfunction isServerError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const candidate = error as { code?: unknown; severity?: unknown };\n return typeof candidate.code === \"string\" && /^[0-9A-Z]{5}$/.test(candidate.code) && typeof candidate.severity === \"string\";\n}\n\n/**\n * The Submittable. Construct with steps whose values are already prepared\n * ({@link prepareBatchValues}); pass to `client.query(batch)`; await\n * {@link PgBatch.done}.\n *\n * It has NO `name` property on purpose: node-postgres' own ParseComplete and\n * ErrorResponse handlers record `activeQuery.name`, and a batch's names are\n * recorded per step here instead.\n */\nexport class PgBatch {\n /** Settles once: at the batch's ReadyForQuery, at its first server error, or at a transport failure. */\n readonly done: Promise<BatchOutcome>;\n /**\n * Set by node-postgres when the client has a `query_timeout`: its wrapper\n * clears the read-timeout timer. Called once when the batch settles, so a\n * timer never outlives the batch (fix lane FX-A, RV5 MI-6).\n */\n callback: ((error: unknown, result?: unknown) => void) | undefined = undefined;\n\n private readonly steps: readonly BatchStep[];\n private readonly types: BatchTypeParsers;\n private readonly outcomes: BatchStepOutcome[] = [];\n private parsers: ((value: string) => unknown)[] = [];\n private fields: readonly RowDescriptionField[] = [];\n private rows: Record<string, unknown>[] = [];\n /** The first type-parser failure of the current step; its remaining rows are skipped. */\n private rowError: { readonly error: unknown } | undefined = undefined;\n private settled = false;\n private resolve: (outcome: BatchOutcome) => void = () => undefined;\n /** The connection's statement record while a named Parse of this batch may still be answered. */\n private book: StatementBook | undefined = undefined;\n /** Every Parse this batch wrote, in order: the k-th ParseComplete answers the k-th entry. */\n private parses: WrittenParse[] = [];\n private parsesAnswered = 0;\n private stopParseTracking: (() => void) | undefined = undefined;\n /** Whether `submit` wrote this batch's messages to a writable stream ({@link BatchOutcome.unsent} otherwise). */\n private written = false;\n\n constructor(params: { steps: readonly BatchStep[]; types: BatchTypeParsers }) {\n this.steps = params.steps;\n this.types = params.types;\n this.done = new Promise<BatchOutcome>((resolve) => {\n this.resolve = resolve;\n });\n }\n\n /**\n * Called by node-postgres when the batch reaches the head of the client's\n * queue. Returns an error, with nothing written, when a statement name\n * conflicts or the stream is no longer writable. node-postgres then calls\n * `handleError`, as for its own `Query.submit` refusals; `null` once written.\n */\n submit(connection: unknown): Error | null {\n const writer = connection as BatchConnection;\n if ((writer.stream as { writable?: unknown } | undefined)?.writable === false) {\n return new VibeError({\n code: \"VIBE_ADAPTER\",\n message: \"the connection's socket is no longer writable: the batch was not sent\",\n meta: { adapter: \"pg\", reason: \"connection-not-writable\" },\n });\n }\n const book = this.steps.some((step) => step.name !== undefined) ? statementBookOf({ connection }) : undefined;\n // Preflight the WHOLE batch before changing the connection's records. This\n // includes names submitted by another caller and names introduced by an\n // earlier step here. A refusal must leave every step unsent.\n const pending = new Map<string, string>();\n const names: { readonly parse: boolean; readonly name?: string }[] = [];\n for (const step of this.steps) {\n const name = step.name;\n if (name === undefined || book === undefined) {\n names.push({ parse: true });\n continue;\n }\n const known = book.parsed[name] ?? book.submitted[name] ?? pending.get(name);\n if (known !== undefined && known !== step.text) {\n return new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `statement name \"${name}\" already names another SQL text on this connection: one name means one text`,\n meta: { adapter: \"pg\", reason: \"statement-name-reused\", name },\n });\n }\n if (known === undefined) pending.set(name, step.text);\n names.push({ parse: known === undefined, name });\n }\n if (book !== undefined) for (const [name, text] of pending) book.submitted[name] = text;\n this.written = true;\n if (names.some((entry) => entry.parse && entry.name !== undefined) && book !== undefined) {\n this.book = book;\n this.stopParseTracking = book.onParseComplete(() => { this.answerParse(); });\n }\n writer.stream?.cork?.();\n try {\n this.steps.forEach((step, index) => {\n const entry = names[index] as { readonly parse: boolean; readonly name?: string };\n if (entry.parse) {\n writer.parse(entry.name === undefined ? { text: step.text, types: [] } : { text: step.text, name: entry.name, types: [] });\n this.parses.push(entry.name === undefined ? null : { name: entry.name, text: step.text });\n }\n writer.bind(entry.name === undefined ? { values: step.values ?? [] } : { statement: entry.name, values: step.values ?? [] });\n writer.describe({ type: \"P\", name: \"\" });\n writer.execute({ portal: \"\", rows: 0 });\n });\n writer.sync();\n } finally {\n writer.stream?.uncork?.();\n }\n return null;\n }\n\n /** One ParseComplete: the oldest unanswered Parse of this batch succeeded — its name is prepared now. */\n private answerParse(): void {\n const book = this.book;\n if (book === undefined || this.parsesAnswered >= this.parses.length) return;\n const parse = this.parses[this.parsesAnswered];\n this.parsesAnswered += 1;\n if (parse === null || parse === undefined) return;\n book.parsed[parse.name] = parse.text;\n delete book.submitted[parse.name];\n }\n\n /**\n * No more ParseComplete can come for this batch (its ReadyForQuery, or a\n * server error: the server skips every message up to the Sync). A Parse\n * still unanswered was refused or skipped, so its name is NOT prepared:\n * forget it, as node-postgres' `_handleErrorMessage` forgets a query's\n * submitted name. Recording it would answer 26000 on its next use.\n */\n private endParseTracking(): void {\n const book = this.book;\n if (book === undefined) return;\n for (const parse of this.parses.slice(this.parsesAnswered)) {\n if (parse !== null && book.submitted[parse.name] === parse.text) delete book.submitted[parse.name];\n }\n this.parsesAnswered = this.parses.length;\n this.book = undefined;\n this.stopParseTracking?.();\n this.stopParseTracking = undefined;\n }\n\n handleRowDescription(message: { fields: readonly RowDescriptionField[] }): void {\n this.rows = [];\n if (this.steps[this.outcomes.length]?.discardRows === true) {\n this.fields = [];\n this.parsers = [];\n return;\n }\n this.fields = message.fields;\n this.parsers = message.fields.map((field) => this.types.getTypeParser(field.dataTypeID, field.format ?? \"text\"));\n }\n\n handleDataRow(message: { fields: readonly (string | null)[] }): void {\n if (this.settled || this.rowError !== undefined) return;\n if (this.steps[this.outcomes.length]?.discardRows === true) return;\n // Same object shape as node-postgres' default row mode: one property per\n // column in RowDescription order; a repeated name keeps its first position\n // and its last value.\n const row: Record<string, unknown> = {};\n try {\n for (let index = 0; index < this.fields.length; index++) {\n const raw = message.fields[index] ?? null;\n row[(this.fields[index] as RowDescriptionField).name] = raw === null ? null : (this.parsers[index] as (value: string) => unknown)(raw);\n }\n } catch (error) {\n // APPROVED driver boundary (plan §3 \"Final-review decisions\", RV5 MJ-2):\n // a type parser (the application's global `pg.types` reach it through\n // EXACT_TYPES) may throw. Escaping here would leave node-postgres'\n // socket `data` handler mid-buffer — the batch never settles and the\n // error becomes an uncaught exception. node-postgres' own Query keeps\n // the first parser error, skips the remaining rows and rejects with it\n // (`_canceledDueToError`); the batch reports it as this step's failure.\n this.rowError = { error };\n return;\n }\n this.rows.push(row);\n }\n\n handleCommandComplete(message: { text?: string; command?: string }): void {\n if (this.settled) return;\n if (this.rowError !== undefined) {\n // The server ran the step; its rows could not be decoded.\n this.outcomes.push({ status: \"failed\", error: this.rowError.error });\n this.rowError = undefined;\n this.rows = [];\n this.fields = [];\n this.parsers = [];\n return;\n }\n const match = COMMAND_TAG.exec(message.text ?? message.command ?? \"\");\n const command = match?.[1];\n const rowCount = match?.[3] !== undefined\n ? Number.parseInt(match[3], 10)\n : match?.[2] !== undefined ? Number.parseInt(match[2], 10) : null;\n this.outcomes.push({ status: \"ok\", result: { rows: this.rows, rowCount, ...(command === undefined ? {} : { command }) } });\n this.rows = [];\n this.fields = [];\n this.parsers = [];\n }\n\n handleEmptyQuery(): void {\n if (this.settled) return;\n this.outcomes.push({ status: \"ok\", result: { rows: [], rowCount: null } });\n }\n\n handleError(error: unknown): void {\n // Before the settled check: a server error that follows a transport\n // settle (`query_timeout`) still ends what this batch may have prepared.\n if (isServerError(error)) this.endParseTracking();\n if (this.settled) return;\n if (!isServerError(error)) {\n // No server answer: the socket broke, or `query_timeout` fired with the\n // batch still on the wire (node-postgres keeps the query running there,\n // so ParseComplete is still tracked until its ReadyForQuery or error).\n this.finish({ transportError: error });\n return;\n }\n // The server skips everything up to the Sync: the remaining steps never\n // ran. Settle NOW: node-postgres drops the active query before routing an\n // ErrorResponse (pg 8.23 `client.js` `_handleErrorMessage`), so this\n // batch never sees its ReadyForQuery. The client queues the next query\n // until that ReadyForQuery arrives, so a ROLLBACK sent after this still\n // runs after the Sync. A parser failure of this step wins, as in\n // node-postgres' Query.\n this.outcomes.push({ status: \"failed\", error: this.rowError === undefined ? error : this.rowError.error });\n while (this.outcomes.length < this.steps.length) this.outcomes.push({ status: \"skipped\" });\n this.finish({});\n }\n\n handleReadyForQuery(): void {\n this.endParseTracking();\n this.finish({});\n }\n\n handlePortalSuspended(): void {\n // Never requested: every Execute asks for all rows.\n }\n\n handleCopyInResponse(connection: unknown): void {\n (connection as BatchConnection).sendCopyFail?.(\"COPY FROM STDIN is not supported inside a batch\");\n }\n\n handleCopyData(): void {\n // COPY TO STDOUT data is not collected (node-postgres' Query ignores it too).\n }\n\n private finish(params: { transportError?: unknown }): void {\n if (this.settled) return;\n this.settled = true;\n this.callback?.(params.transportError ?? null);\n this.resolve({\n steps: this.outcomes,\n ...(params.transportError === undefined ? {} : { transportError: params.transportError, ...(this.written ? {} : { unsent: true as const }) }),\n });\n }\n}\n\n/** Run `steps` as one batch on `client` and wait for it to settle. */\nexport async function runBatch(params: {\n /** A checked-out client that passed {@link supportsBatch}. */\n client: { query: (...args: never[]) => unknown };\n steps: readonly BatchStep[];\n types: BatchTypeParsers;\n}): Promise<BatchOutcome> {\n const batch = new PgBatch({ steps: params.steps, types: params.types });\n (params.client.query as (submittable: PgBatch) => unknown).call(params.client, batch);\n return batch.done;\n}\n\n/**\n * The first failure of a settled batch: the transport error, or the first\n * failed step with its index. `undefined` when every step succeeded.\n */\nexport function firstBatchFailure(params: { outcome: BatchOutcome }): { readonly index: number; readonly error: unknown } | undefined {\n const { outcome } = params;\n const index = outcome.steps.findIndex((step) => step.status === \"failed\");\n if (index !== -1) return { index, error: (outcome.steps[index] as { error: unknown }).error };\n if (outcome.transportError !== undefined) return { index: outcome.steps.length, error: outcome.transportError };\n return undefined;\n}\n",
7
7
  "/**\n * Root connection groups (round-trip follow-up, lane A2;\n * `DatabaseAdapter.connectionGroup`).\n *\n * A read's sibling relation loads outside any transaction: the runtime opens\n * one sub-lane per statement, each sub-lane issues ONE statement, and once the\n * group is sealed and every sub-lane issued or closed, the statements leave\n * TOGETHER, in sub-lane order, on ONE pooled connection — one one-Sync batch\n * (`./batch.ts`), so one round trip instead of one per sibling.\n *\n * This module is the group's bookkeeping only: the adapter hands it how to\n * prepare a statement and how to send the prepared steps (checkout, batch,\n * release — or one statement after another where the checked-out client cannot\n * batch). Failure semantics are those of sequential dispatch in sub-lane\n * order: a failed step's caller gets its mapped error; the steps PostgreSQL\n * skipped behind it reject with the aborted refusal naming that failure.\n */\n\nimport { VibeError } from \"@vibeorm/schema\";\nimport type { DatabaseAdapter, PipelineGroup, PipelineLane } from \"@vibeorm/runtime\";\nimport { transactionAbortedError } from \"@vibeorm/runtime/adapter-kit\";\nimport type { BatchOutcome, BatchStep } from \"./batch.ts\";\n\n// ─── Types ────────────────────────────────────────────────────────\n\n/** The `execute` parameters a sub-lane receives (the root's `execute` contract). */\nexport type ConnectionGroupExecute = Parameters<DatabaseAdapter[\"execute\"]>[0];\n\n/** One statement of a group, ready to send: its batch step and the call it came from. */\nexport type ConnectionGroupEntry = {\n /** The step for the one-Sync batch (values already serialized for the driver). */\n readonly step: BatchStep;\n /** The sub-lane's original `execute` call (for a send that cannot batch: `root.execute`). */\n readonly call: ConnectionGroupExecute;\n};\n\n/** What the adapter provides to a group. */\nexport type ConnectionGroupDriver = {\n /** The fields every sub-lane adapter carries (the root's declarations). */\n readonly base: Pick<DatabaseAdapter, \"dialect\" | \"provider\" | \"wire\" | \"budgets\" | \"roundTrips\" | \"formatArrayParam\">;\n /**\n * Serialize one statement for the batch. A value the driver refuses throws\n * (mapped): that sub-lane's call rejects with it and it holds nothing.\n */\n readonly prepare: (call: ConnectionGroupExecute) => BatchStep;\n /**\n * Send the group's statements, in order, as one round trip — or one after\n * another where the checked-out connection cannot batch, reporting the\n * statements after the first failure as skipped. Rejects only when nothing\n * was sent (a failed checkout, a closed adapter): every statement then\n * rejects with that error, mapped.\n */\n readonly send: (entries: readonly ConnectionGroupEntry[]) => Promise<BatchOutcome>;\n /** Map a driver failure to the adapter's typed error. */\n readonly mapError: (error: unknown) => VibeError;\n};\n\ntype Seat = {\n readonly index: number;\n open: boolean;\n /** The ONE statement this sub-lane issued, waiting for the send. */\n issued?: {\n readonly entry: ConnectionGroupEntry;\n readonly resolve: (rows: Record<string, unknown>[]) => void;\n readonly reject: (error: unknown) => void;\n };\n /** The sub-lane's statement was refused before it was queued (or a second one was attempted): it holds nothing. */\n done: boolean;\n};\n\n// ─── Errors ───────────────────────────────────────────────────────\n\n/** A broken use of a connection group — a runtime defect, refused before anything is sent. */\nexport function connectionGroupMisuse(params: { message: string }): VibeError {\n return new VibeError({ code: \"VIBE_INTERNAL\", message: `pipeline lane group: ${params.message}`, meta: { reason: \"pipeline-lane-group\" } });\n}\n\n// ─── The group ────────────────────────────────────────────────────\n\n/**\n * Open one connection group ({@link PipelineGroup}). Synchronous and free:\n * nothing is checked out until the group is sealed and every sub-lane issued\n * its statement or closed; a group that ends without a statement sends nothing.\n */\nexport function openConnectionGroup(params: { driver: ConnectionGroupDriver }): PipelineGroup {\n const { driver } = params;\n const seats: Seat[] = [];\n let sealed = false;\n let sent = false;\n\n const settle = (entries: readonly Seat[], outcome: BatchOutcome): void => {\n let failure: VibeError | undefined;\n entries.forEach((seat, index) => {\n const issued = seat.issued;\n if (issued === undefined) return;\n const step = outcome.steps[index];\n if (step === undefined) {\n // No answer (the connection failed): what the server did is unknown.\n const error = driver.mapError(outcome.transportError);\n failure ??= error;\n issued.reject(error);\n } else if (step.status === \"ok\") {\n issued.resolve(step.result.rows);\n } else if (step.status === \"failed\") {\n const error = driver.mapError(step.error);\n failure ??= error;\n issued.reject(error);\n } else {\n // PostgreSQL skipped it behind the failure (one implicit transaction).\n issued.reject(transactionAbortedError({ cause: failure }));\n }\n });\n };\n\n const flushIfReady = (): void => {\n if (!sealed || sent) return;\n for (const seat of seats) if (seat.open && seat.issued === undefined && !seat.done) return;\n sent = true;\n const entries = seats.filter((seat) => seat.issued !== undefined);\n if (entries.length === 0) return;\n const sending = new Promise<BatchOutcome>((resolve) => {\n resolve(driver.send(entries.map((seat) => (seat.issued as NonNullable<Seat[\"issued\"]>).entry)));\n });\n sending.then(\n (outcome) => { settle(entries, outcome); },\n (error: unknown) => {\n const mapped = driver.mapError(error);\n for (const seat of entries) seat.issued?.reject(mapped);\n },\n );\n };\n\n const refused = (message: string): (() => Promise<never>) => (): Promise<never> => Promise.reject(connectionGroupMisuse({ message }));\n\n const subAdapter = (seat: Seat): DatabaseAdapter => ({\n ...driver.base,\n execute: (call: ConnectionGroupExecute): Promise<Record<string, unknown>[]> => {\n if (seat.issued !== undefined || seat.done) return Promise.reject(connectionGroupMisuse({ message: \"a sub-lane issues ONE statement\" }));\n if (!seat.open || sent) return Promise.reject(connectionGroupMisuse({ message: \"a closed sub-lane issues nothing\" }));\n if (call.execution !== undefined) {\n seat.done = true;\n flushIfReady();\n return Promise.reject(connectionGroupMisuse({ message: \"a sub-lane statement takes no read options\" }));\n }\n // The executor turns a synchronous throw of `prepare` (a value the driver\n // refuses) into this statement's rejection: it fails alone, before\n // anything is sent, and holds nothing.\n const pending = new Promise<Record<string, unknown>[]>((resolve, reject) => {\n const step = driver.prepare(call);\n seat.issued = { entry: { step, call }, resolve, reject };\n });\n if (seat.issued === undefined) {\n seat.done = true;\n flushIfReady();\n return pending.then(undefined, (error: unknown) => { throw driver.mapError(error); });\n }\n flushIfReady();\n return pending;\n },\n executeUnsafe: refused(\"a sub-lane runs no raw statement\"),\n transaction: refused(\"a sub-lane opens no transaction\"),\n connect: refused(\"a sub-lane does not connect\"),\n disconnect: refused(\"a sub-lane does not disconnect\"),\n });\n\n return {\n lane: (): PipelineLane => {\n if (sealed) throw connectionGroupMisuse({ message: \"a sub-lane is opened only before the group is sealed\" });\n const seat: Seat = { index: seats.length, open: true, done: false };\n seats.push(seat);\n return {\n adapter: subAdapter(seat),\n close: (): void => {\n if (!seat.open) return;\n seat.open = false;\n flushIfReady();\n },\n };\n },\n seal: (): void => {\n if (sealed) return;\n sealed = true;\n flushIfReady();\n },\n };\n}\n",
8
8
  "/**\n * libpq's `sslrootcert=system` for node-postgres.\n *\n * Managed PostgreSQL providers (PlanetScale, among others) hand out URLs such\n * as `postgresql://…@host:5432/postgres?sslmode=verify-full&sslrootcert=system`.\n * In libpq (PostgreSQL 16+) the value `system` means \"load the trusted CA roots\n * of the SSL implementation\"; libpq then defaults `sslmode` to `verify-full`\n * and refuses any weaker mode (libpq-connect, `sslrootcert`). node-postgres\n * (pg 8.23 / pg-connection-string 2.14.1, the latest releases on 18.10.26, and\n * its master branch) reads every `sslrootcert` as a FILE path —\n * `fs.readFileSync(\"system\")` — so the provider's URL fails before connecting\n * with `ENOENT: no such file or directory, open 'system'`.\n *\n * {@link honourSystemRootCert} rewrites such a URL into node-postgres' own\n * spelling of the same contract: `sslrootcert` removed, `sslmode=verify-full`.\n * pg-connection-string then builds `ssl: {}` (plus any `sslcert`/`sslkey`),\n * and `tls.connect` runs with its defaults: `rejectUnauthorized: true` (chain\n * verified), the default `checkServerIdentity` against the host name\n * node-postgres passes as `servername` (an IP address is matched against the\n * certificate's IP entries, as in libpq), and — no `ca` given — the runtime's\n * default trust store.\n *\n * \"System roots\" in that store: Node's default store is its bundled Mozilla\n * root set (the program most operating-system stores derive from) plus\n * `NODE_EXTRA_CA_CERTS`; started with `--use-openssl-ca` it loads OpenSSL's\n * default locations, honouring `SSL_CERT_FILE` / `SSL_CERT_DIR` exactly as\n * libpq-with-OpenSSL does, and with `--use-system-ca` the operating system's\n * store. Bun's `node:tls` default is likewise its bundled root set plus\n * `NODE_EXTRA_CA_CERTS`. The adapter passes no `ca`, so whichever of these the\n * process chose applies — and connections reuse the runtime's parsed root\n * store instead of re-parsing ~150 certificates per connection.\n */\n\nimport { VibeError } from \"@vibeorm/schema\";\n\n/** The connection-string option a value came from, named in a refusal. */\nexport type ConnectionStringOption = \"connectionString\" | \"cancellationConnectionString\";\n\n/** The last value of a query key: pg-connection-string assigns entries in order, so the last one wins. */\nfunction lastValue(params: { search: URLSearchParams; key: string }): string | undefined {\n const values = params.search.getAll(params.key);\n return values.length === 0 ? undefined : values[values.length - 1];\n}\n\n/**\n * Rewrite a connection string carrying `sslrootcert=system` (libpq's \"trust the\n * system CA roots\") into the form node-postgres understands: the parameter\n * removed and `sslmode=verify-full` set, so the server certificate's chain and\n * host name are both verified against the runtime's default trust store (see\n * the module header). Any other string — no query, another `sslrootcert`, no\n * `sslrootcert` — is returned byte-for-byte unchanged.\n *\n * Follows libpq's rule: with `system`, an omitted `sslmode` means\n * `verify-full`, and every weaker mode is an error. node-postgres' own weaker\n * spellings count too: `sslmode=no-verify`, and an `ssl` parameter other than\n * `true` / `1`.\n *\n * @throws VibeError `VIBE_CONFIG` (`meta.reason: \"sslrootcert-system-weak-sslmode\"`)\n * for a weaker mode. Neither the message nor `meta` carries the URL.\n */\nexport function honourSystemRootCert(params: { connectionString: string; option: ConnectionStringOption }): string {\n const { connectionString, option } = params;\n const queryStart = connectionString.indexOf(\"?\");\n if (queryStart === -1) return connectionString;\n const hashStart = connectionString.indexOf(\"#\", queryStart);\n const queryEnd = hashStart === -1 ? connectionString.length : hashStart;\n const search = new URLSearchParams(connectionString.slice(queryStart + 1, queryEnd));\n if (lastValue({ search, key: \"sslrootcert\" }) !== \"system\") return connectionString;\n\n const sslmode = lastValue({ search, key: \"sslmode\" });\n const ssl = lastValue({ search, key: \"ssl\" });\n const weaker = sslmode !== undefined && sslmode !== \"verify-full\"\n ? { parameter: \"sslmode\", value: sslmode }\n : ssl !== undefined && ssl !== \"true\" && ssl !== \"1\"\n ? { parameter: \"ssl\", value: ssl }\n : undefined;\n if (weaker !== undefined) {\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message:\n `pgAdapter \\`${option}\\` combines sslrootcert=system with ${weaker.parameter}=${JSON.stringify(weaker.value)}. ` +\n \"libpq allows sslrootcert=system only with sslmode=verify-full (its default when sslmode is omitted): any certificate \" +\n \"the system trusts would otherwise vouch for a server that is not yours. Use sslmode=verify-full, or remove the setting.\",\n meta: { adapter: \"pg\", reason: \"sslrootcert-system-weak-sslmode\", option, parameter: weaker.parameter, value: weaker.value },\n });\n }\n\n search.delete(\"sslrootcert\");\n search.delete(\"ssl\");\n search.set(\"sslmode\", \"verify-full\");\n // URLSearchParams writes a space as \"+\"; both decode alike, \"%20\" keeps the URL readable.\n const query = search.toString().replace(/\\+/g, \"%20\");\n return `${connectionString.slice(0, queryStart)}?${query}${connectionString.slice(queryEnd)}`;\n}\n",
9
9
  "/**\n * One query at a time on a transaction's checked-out client (pg@9).\n *\n * node-postgres 8 queues a `client.query()` made while the client still runs\n * another one, and warns that this queue goes away in pg@9.0 (\"Calling\n * client.query() when the client is already executing a query is deprecated\n * and will be removed in pg@9.0\"). A transaction handle receives statements\n * concurrently — `Promise.all` on a callback-transaction handle, an un-awaited\n * call, a ROLLBACK behind a failed batch — so the adapter keeps that queue\n * itself: every call waits until the previous one SETTLED (the `await` pattern\n * node-postgres documents), and the calls reach the client in the order they\n * were made — the order the driver's own queue used. A call made while nothing\n * is outstanding reaches the client synchronously, as before.\n *\n * \"Settled\" is the driver's own promise (or a batch's `done`): on success it\n * settles at the statement's ReadyForQuery, so the next call finds the client\n * idle; after a server error it settles at the ErrorResponse, and the next call\n * waits inside node-postgres for that ReadyForQuery alone — never behind a\n * second queued query.\n */\n\n// ─── Types ────────────────────────────────────────────────────────\n\n/** The turn keeper of ONE checked-out client. */\nexport type ClientTurns = {\n /**\n * Run `send` (one `client.query()` call, or one batch) once every earlier\n * call of this client settled. Resolves or rejects with `send`'s own\n * outcome; a synchronous throw of `send` becomes its rejection.\n */\n readonly run: <T>(send: () => Promise<T>) => Promise<T>;\n /** Calls handed in that have not settled yet (the running one included). */\n readonly outstanding: () => number;\n /**\n * The rejection of the call that settled LAST, or `undefined` when it\n * fulfilled (or nothing settled yet). Read inside a turn, it is the outcome\n * of the call right before it — already known there, before any of that\n * call's own continuations ran (a burst of waiting statements reads it to\n * refuse what the server would answer with 25P02).\n */\n readonly lastFailure: () => { readonly error: unknown } | undefined;\n};\n\n// ─── Implementation ───────────────────────────────────────────────\n\n/** Start the turn keeper for one checked-out client. */\nexport function createClientTurns(): ClientTurns {\n let outstanding = 0;\n let failure: { readonly error: unknown } | undefined;\n /** Settles (never rejects) once the most recent call settled. */\n let previous: Promise<void> = Promise.resolve();\n const release = (): void => {\n outstanding -= 1;\n failure = undefined;\n };\n const fail = (error: unknown): void => {\n outstanding -= 1;\n failure = { error };\n };\n return {\n run: <T>(send: () => Promise<T>): Promise<T> => {\n const running: Promise<T> = outstanding === 0\n ? new Promise<T>((resolve) => {\n resolve(send());\n })\n : previous.then(send);\n outstanding += 1;\n previous = running.then(release, fail);\n return running;\n },\n outstanding: () => outstanding,\n lastFailure: () => failure,\n };\n}\n",
10
10
  "import pg from \"pg\";\nimport { VibeError } from \"@vibeorm/schema\";\nimport type { DatabaseAdapter } from \"@vibeorm/runtime\";\nimport { assertReadExecution, readCancelledError } from \"@vibeorm/runtime/adapter-kit\";\nimport { PG_READ_CANCELLATION } from \"./config.ts\";\nimport { pgErrorSqlstate, runMapped } from \"./errors.ts\";\nimport type { PgQueryConfig, PgQueryResultsLike, PgPoolClientLike } from \"./index.ts\";\n\ntype Execution = Parameters<DatabaseAdapter[\"execute\"]>[0];\ntype ControlClient = {\n connect(): Promise<void>;\n query(config: PgQueryConfig): Promise<PgQueryResultsLike>;\n end(): Promise<void>;\n on(event: \"error\", listener: (error: unknown) => void): unknown;\n};\n\n/** One pinned transaction's running-read transport. Original and control settlement are both awaited. */\nexport type PgReadCancellation = {\n readonly support: \"before-dispatch\" | \"running\";\n run(params: {\n config: PgQueryConfig;\n execution?: Execution[\"execution\"];\n onReadControl?: Execution[\"onReadControl\"];\n send: () => Promise<PgQueryResultsLike>;\n }): Promise<PgQueryResultsLike>;\n};\n\nfunction rowsOf(result: PgQueryResultsLike): Record<string, unknown>[] {\n return (Array.isArray(result) ? result.at(-1)?.rows : result.rows) ?? [];\n}\n\n/**\n * Official-driver control SQL seam. The target must already be in a transaction,\n * held exclusively until this run settles; every cancel attempt discards it.\n * PostgreSQL documents pg_cancel_backend as signal dispatch, not SQL settlement:\n * https://www.postgresql.org/docs/18/functions-admin.html#FUNCTIONS-ADMIN-SIGNAL\n */\nexport function createPgReadCancellation(params: {\n connectionString?: string;\n target: Pick<PgPoolClientLike, \"query\" | \"pipeline\" | \"connectionParameters\">;\n discard: () => void;\n /** Destroy exactly the held target on failed/unsettled cancellation, never a pool-wide close. */\n terminate: () => void;\n /** Hermetic driver injection; production uses the installed official pg.Client. */\n createControl?: (params: { connectionString: string }) => ControlClient;\n}): PgReadCancellation {\n const support = params.connectionString === undefined ? \"before-dispatch\" : \"running\";\n return {\n support,\n async run(query) {\n assertReadExecution({ execution: query.execution, effect: \"read\", support, provider: \"postgresql\", stage: \"waiting-for-connection\" });\n if (query.execution?.cancellation !== \"running\") return query.send();\n if (params.target.pipeline === true || (params.target.connectionParameters?.query_timeout ?? 0) > 0) {\n throw new VibeError({ code: \"VIBE_UNSUPPORTED_CAPABILITY\", message: \"Running cancellation requires a non-pipelined target without local query_timeout\", meta: { capability: \"readCancellation\", reason: \"target-lifetime\" } });\n }\n const address = params.connectionString;\n if (address === undefined) throw new VibeError({ code: \"VIBE_INTERNAL\", message: \"Running cancellation requires a control address\" });\n const token = `vibe_cancel_${crypto.randomUUID()}`;\n // URL keys override explicit pg config. Remove local query_timeout (not\n // SQL settlement) and pin the server/connection bound IN the URL itself.\n if (!URL.canParse(address)) throw new VibeError({ code: \"VIBE_CONFIG\", message: \"The PostgreSQL cancellation control address must be a URL\" });\n const url = new URL(address);\n url.searchParams.delete(\"query_timeout\");\n url.searchParams.set(\"connect_timeout\", String(PG_READ_CANCELLATION.controlTimeoutMs / 1_000));\n url.searchParams.set(\"statement_timeout\", String(PG_READ_CANCELLATION.controlTimeoutMs));\n url.searchParams.set(\"options\", `-c statement_timeout=${PG_READ_CANCELLATION.controlTimeoutMs} -c lock_timeout=${PG_READ_CANCELLATION.controlTimeoutMs}`);\n const control = await runMapped(async () => params.createControl?.({ connectionString: url.toString() }) ??\n new pg.Client({ connectionString: url.toString(), connectionTimeoutMillis: PG_READ_CANCELLATION.controlTimeoutMs, query_timeout: 0 }) as unknown as ControlClient);\n // Checked-out pg clients do not have pool error handlers. Own this one.\n control.on(\"error\", () => undefined);\n const signal = query.execution.signal;\n let cancel: Promise<void> | undefined;\n let attempted = false;\n let signalSent = false;\n let finished = false;\n let controlFailure: unknown;\n let terminated = false;\n let settlementTimer: ReturnType<typeof setTimeout> | undefined;\n let preflightAborted = false;\n const abortPreflight = (): void => {\n preflightAborted = true;\n params.discard();\n if (!terminated) { terminated = true; params.terminate(); }\n };\n let original: Promise<PgQueryResultsLike> | undefined;\n const account = (stage: \"preflight\" | \"cancel\", send: () => Promise<PgQueryResultsLike>): Promise<PgQueryResultsLike> =>\n runMapped(send).then(\n (result) => { query.onReadControl?.({ stage, rows: rowsOf(result).length }); return result; },\n (error: unknown) => { query.onReadControl?.({ stage, rows: 0 }); throw error; },\n );\n let listener: (() => void) | undefined;\n const operation = runMapped(() => control.connect()).then(async () => {\n assertReadExecution({ execution: query.execution, effect: \"read\", support, provider: \"postgresql\", stage: \"waiting-for-connection\" });\n // Transaction-local nonce survives transaction poolers and expires at\n // commit/rollback. Exact backend_start text avoids timestamp truncation.\n signal?.addEventListener(\"abort\", abortPreflight, { once: true });\n const witness = rowsOf(await account(\"preflight\", () => params.target.query({\n text: \"SELECT pg_backend_pid() AS pid, extract(epoch FROM backend_start)::text AS backend_start, datname, usename, set_config('application_name', $1, true) AS tag FROM pg_stat_activity WHERE pid = pg_backend_pid()\",\n values: [token],\n })))[0];\n signal?.removeEventListener(\"abort\", abortPreflight);\n if (preflightAborted) throw readCancelledError({ stage: \"waiting-for-connection\" });\n if (witness === undefined || typeof witness.pid !== \"number\" || typeof witness.backend_start !== \"string\" || typeof witness.datname !== \"string\" || typeof witness.usename !== \"string\" || witness.tag !== token) {\n throw new VibeError({ code: \"VIBE_UNSUPPORTED_CAPABILITY\", message: \"Cannot prove the exact PostgreSQL cancellation target\", meta: { capability: \"readCancellation\", reason: \"target-witness\" } });\n }\n assertReadExecution({ execution: query.execution, effect: \"read\", support, provider: \"postgresql\", stage: \"waiting-for-connection\" });\n listener = (): void => {\n if (finished || attempted) return;\n attempted = true;\n params.discard();\n const failControl = (error: unknown): never => {\n controlFailure = error;\n if (!terminated) { terminated = true; params.terminate(); }\n throw error;\n };\n settlementTimer = setTimeout(() => {\n controlFailure = new VibeError({ code: \"VIBE_ADAPTER\", message: \"PostgreSQL read did not settle after cancellation; its exact session was discarded\", meta: { reason: \"read-cancellation-unsettled\", databaseCancelled: false } });\n if (!terminated) { terminated = true; params.terminate(); }\n }, PG_READ_CANCELLATION.controlTimeoutMs);\n cancel = account(\"cancel\", () => control.query({\n text: \"SELECT pg_cancel_backend(pid) AS signalled FROM pg_stat_activity WHERE pid = $1 AND extract(epoch FROM backend_start)::text = $2 AND datname = $3 AND usename = $4 AND application_name = $5 AND state = 'active' AND pid <> pg_backend_pid()\",\n values: [witness.pid, witness.backend_start, witness.datname, witness.usename, token],\n })).then((result) => {\n signalSent = rowsOf(result)[0]?.signalled === true;\n if (!signalSent) failControl(new VibeError({ code: \"VIBE_UNSUPPORTED_CAPABILITY\", message: \"The control endpoint did not signal the exact PostgreSQL target\", meta: { capability: \"readCancellation\", reason: \"target-not-signalled\", databaseCancelled: false } }));\n }, failControl);\n // The original query may still be running; consume control rejection\n // now, then report it after both operations have drained.\n void cancel.then(() => undefined, () => undefined);\n };\n // Submit the target first. The event loop cannot interleave abort between\n // this synchronous send and listener registration.\n original = runMapped(query.send);\n signal?.addEventListener(\"abort\", listener, { once: true });\n if (signal?.aborted === true) listener();\n return original.then(\n async (result) => {\n finished = true;\n signal?.removeEventListener(\"abort\", listener!);\n if (cancel !== undefined) await cancel;\n if (controlFailure !== undefined) throw controlFailure;\n if (signal?.aborted === true) throw readCancelledError({ stage: \"running\" });\n return result;\n },\n async (error: unknown) => {\n finished = true;\n signal?.removeEventListener(\"abort\", listener!);\n if (cancel !== undefined) await cancel.then(() => undefined, () => undefined);\n // Attribution requires this operation's own successful control\n // signal AND the original server's 57014. A timeout alone stays as-is.\n const sqlstate = error instanceof VibeError ? error.meta.sqlstate : pgErrorSqlstate({ error });\n if (terminated && controlFailure !== undefined && sqlstate === undefined) throw controlFailure;\n if (attempted && signalSent && sqlstate === \"57014\") {\n const cancelled = readCancelledError({ stage: \"running\", databaseCancelled: true, cause: error });\n throw new VibeError({ code: cancelled.code, message: cancelled.message, meta: { ...cancelled.meta, sqlstate: \"57014\" }, cause: error });\n }\n throw error;\n },\n );\n });\n return operation.then(\n async (result) => { signal?.removeEventListener(\"abort\", abortPreflight); if (settlementTimer !== undefined) clearTimeout(settlementTimer); if (listener !== undefined) signal?.removeEventListener(\"abort\", listener); await runMapped(() => control.end()); return result; },\n async (error: unknown) => {\n signal?.removeEventListener(\"abort\", abortPreflight);\n if (settlementTimer !== undefined) clearTimeout(settlementTimer);\n if (listener !== undefined) signal?.removeEventListener(\"abort\", listener);\n await runMapped(() => control.end()).then(() => undefined, () => undefined);\n if (preflightAborted) throw readCancelledError({ stage: \"waiting-for-connection\", cause: error });\n throw error;\n },\n );\n },\n };\n}\n",
11
11
  "/** Bounds the independent PostgreSQL cancellation control path and post-abort settlement. */\nexport const PG_READ_CANCELLATION: Readonly<{ controlTimeoutMs: number }> = Object.freeze({\n controlTimeoutMs: 5_000,\n});\n",
12
- "/**\n * Driver-error mapping for node-postgres (`pg`).\n *\n * Constitution rule 5: a raw driver error never escapes an adapter. Every\n * failure becomes a `VibeError` with a stable code, the driver error attached\n * as `cause`, and the SQLSTATE (plus constraint/table/column when the server\n * reported them) in `meta`.\n */\n\nimport { VibeError, type VibeErrorCode } from \"@vibeorm/schema\";\n\n// ─── SQLSTATE table ───────────────────────────────────────────────\n\n/**\n * PostgreSQL SQLSTATE → stable VibeError code. Frozen and mirrored by tests;\n * anything absent from this table maps to `VIBE_ADAPTER`.\n */\nexport const PG_SQLSTATE_ERROR_CODES: Readonly<Record<string, VibeErrorCode>> = Object.freeze({\n /** exclusion_violation */\n \"23P01\": \"VIBE_EXCLUSION_VIOLATION\",\n /** unique_violation */\n \"23505\": \"VIBE_UNIQUE_VIOLATION\",\n /** foreign_key_violation */\n \"23503\": \"VIBE_FK_VIOLATION\",\n /** restrict_violation — PostgreSQL 18+ ON DELETE/UPDATE RESTRICT */\n \"23001\": \"VIBE_FK_VIOLATION\",\n /** not_null_violation */\n \"23502\": \"VIBE_VALIDATION\",\n /** check_violation */\n \"23514\": \"VIBE_VALIDATION\",\n /**\n * invalid_text_representation — a value the server cannot parse into the\n * column's type (out-of-range enum value, `\"abc\"` for an integer). Bad input,\n * so the same code sqlite reports for its enum CHECK violation.\n */\n \"22P02\": \"VIBE_VALIDATION\",\n /**\n * The other data-exception SQLSTATEs the same bad INPUT raises — a string\n * too long for varchar(n) (22001), a number outside the column's range\n * (22003), an unparseable date/time (22007) or one whose fields overflow\n * (22008). mysql maps its peers (1406 / 1264 / 1292) to VIBE_VALIDATION;\n * postgres reported them as VIBE_ADAPTER, so the same request was a 400 on\n * one dialect and a 500 on the other.\n */\n \"22001\": \"VIBE_VALIDATION\",\n \"22003\": \"VIBE_VALIDATION\",\n \"22007\": \"VIBE_VALIDATION\",\n \"22008\": \"VIBE_VALIDATION\",\n /**\n * insufficient_privilege — a denied table/column privilege, and the SQLSTATE a\n * native row-level-security policy raises when its WITH CHECK refuses a write.\n * Callers identify it by this code, never by message text.\n */\n \"42501\": \"VIBE_PERMISSION_DENIED\",\n /** serialization_failure */\n \"40001\": \"VIBE_TRANSACTION\",\n /** deadlock_detected */\n \"40P01\": \"VIBE_TRANSACTION\",\n /** query_canceled — statement_timeout fired */\n \"57014\": \"VIBE_TRANSACTION\",\n /**\n * lock_not_available — a `nowait` locking read whose rows were already\n * locked, OR a `lock_timeout` that expired while blocking. The server reports\n * both with this ONE SQLSTATE (verified on postgres 18.6: \"could not obtain\n * lock on row in relation\" and \"canceling statement due to lock timeout\"), so\n * VibeORM does not invent a distinction the server does not make. Nothing is\n * retried automatically — waiting, skipping or failing is the caller's policy.\n */\n \"55P03\": \"VIBE_LOCK_NOT_AVAILABLE\",\n /**\n * read_only_sql_transaction — a write inside a READ ONLY transaction\n * (`accessMode: \"readOnly\"`, or a server whose default is read-only, e.g. a\n * hot standby). Before round-trip EPIC 3 it fell through to VIBE_ADAPTER.\n */\n \"25006\": \"VIBE_TRANSACTION\",\n});\n\n/** SQLSTATEs that additionally explain themselves through `meta.reason`. */\nexport const PG_SQLSTATE_REASONS: Readonly<Record<string, string>> = Object.freeze({\n \"23P01\": \"exclusion-violation\",\n \"57014\": \"timeout\",\n \"55P03\": \"lock-not-available\",\n /** Same reason string mysql already uses for errno 1213 — one word per dialect. */\n \"40P01\": \"deadlock\",\n \"40001\": \"serialization-failure\",\n \"25006\": \"read-only-transaction\",\n});\n\n/**\n * The pooler remedy appended to a named-statement mismatch. Both SQLSTATEs mean\n * the backend's prepared names disagree with the client's: the session moved\n * to another backend between Parse and use.\n */\nconst NAMED_STATEMENT_POOLER_HINT =\n \"Hint: with preparedStatements: true every query must reach the backend that prepared its name. \" +\n \"Use a direct connection, session pooling, or PgBouncer 1.21+ with max_prepared_statements > 0; \" +\n \"behind a transaction-mode pooler without prepared-statement support, turn preparedStatements off.\";\n\n/**\n * SQLSTATEs whose message gets a remedy appended. The code stays what the\n * SQLSTATE table says (`VIBE_ADAPTER` for both); only the human-readable text\n * grows. Frozen and mirrored by tests. `0A000` (\"cached plan must not change\n * result type\") is deliberately absent: it is the generic feature_not_supported\n * class, so a prepared-statement hint would mislead on its other causes.\n */\nexport const PG_SQLSTATE_HINTS: Readonly<Record<string, string>> = Object.freeze({\n /** invalid_sql_statement_name — the backend does not know the name. */\n \"26000\": NAMED_STATEMENT_POOLER_HINT,\n /** duplicate_prepared_statement — the backend already holds the name. */\n \"42P05\": NAMED_STATEMENT_POOLER_HINT,\n});\n\n// ─── Reading driver errors ────────────────────────────────────────\n\n/**\n * A PostgreSQL SQLSTATE is exactly five digits/uppercase letters (e.g. `40P01`)\n * and every one PostgreSQL defines contains a digit. Requiring one keeps a\n * five-letter socket errno (`EPIPE`, `EPERM`) from passing as a server answer:\n * a COMMIT that failed with it is a lost connection, not a definite rollback\n * (fix lane FX-A, RV2 \"outside EPIC 3\").\n */\nconst SQLSTATE_PATTERN = /^(?=[A-Z]*\\d)[0-9A-Z]{5}$/;\n\nfunction readStringField(params: { source: Record<string, unknown>; key: string }): string | undefined {\n const value = params.source[params.key];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * Extract the SQLSTATE from a pg driver error. `pg` puts the server's SQLSTATE\n * on `error.code`; client-side failures (`ECONNREFUSED`, `ETIMEDOUT`, …) use\n * the same field for a non-SQLSTATE string, which this rejects.\n */\nexport function pgErrorSqlstate(params: { error: unknown }): string | undefined {\n const { error } = params;\n if (error === null || typeof error !== \"object\") return undefined;\n const code = readStringField({ source: error as Record<string, unknown>, key: \"code\" });\n return code !== undefined && SQLSTATE_PATTERN.test(code) ? code : undefined;\n}\n\n// ─── Mapping ──────────────────────────────────────────────────────\n\n/**\n * Map any error thrown by `pg` onto a `VibeError`.\n *\n * A `VibeError` passes through unchanged, so an error raised deeper inside the\n * ORM (or by a nested adapter call) is never re-wrapped.\n */\nexport function mapPgDriverError(params: { error: unknown }): VibeError {\n const { error } = params;\n if (error instanceof VibeError) return error;\n\n const source: Record<string, unknown> =\n error !== null && typeof error === \"object\" ? (error as Record<string, unknown>) : {};\n const sqlstate = pgErrorSqlstate({ error });\n const code: VibeErrorCode =\n (sqlstate === undefined ? undefined : PG_SQLSTATE_ERROR_CODES[sqlstate]) ?? \"VIBE_ADAPTER\";\n\n const meta: Record<string, unknown> = {};\n if (sqlstate !== undefined) meta.sqlstate = sqlstate;\n const constraint = readStringField({ source, key: \"constraint\" });\n if (constraint !== undefined) meta.constraint = constraint;\n const table = readStringField({ source, key: \"table\" });\n if (table !== undefined) meta.table = table;\n const column = readStringField({ source, key: \"column\" });\n if (column !== undefined) meta.column = column;\n const reason = sqlstate === undefined ? undefined : PG_SQLSTATE_REASONS[sqlstate];\n if (reason !== undefined) meta.reason = reason;\n\n const driverMessage =\n readStringField({ source, key: \"message\" }) ??\n (typeof error === \"string\" ? error : \"unknown postgres driver error\");\n const hint = sqlstate === undefined ? undefined : PG_SQLSTATE_HINTS[sqlstate];\n const message = hint === undefined ? driverMessage : `${driverMessage}. ${hint}`;\n\n return new VibeError({ code, message, meta, cause: error });\n}\n\n/** Run a driver call, mapping anything it throws onto a `VibeError`. */\nexport async function runMapped<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n throw mapPgDriverError({ error });\n }\n}\n",
12
+ "/**\n * Driver-error mapping for node-postgres (`pg`).\n *\n * Constitution rule 5: a raw driver error never escapes an adapter. Every\n * failure becomes a `VibeError` with a stable code, the driver error attached\n * as `cause`, and the SQLSTATE (plus constraint/table/column when the server\n * reported them) in `meta`.\n */\n\nimport { VibeError, type VibeErrorCode } from \"@vibeorm/schema\";\n\n// ─── SQLSTATE table ───────────────────────────────────────────────\n\n/**\n * PostgreSQL SQLSTATE → stable VibeError code. Frozen and mirrored by tests;\n * anything absent from this table maps to `VIBE_ADAPTER`.\n */\nexport const PG_SQLSTATE_ERROR_CODES: Readonly<Record<string, VibeErrorCode>> = Object.freeze({\n /** exclusion_violation */\n \"23P01\": \"VIBE_EXCLUSION_VIOLATION\",\n /** unique_violation */\n \"23505\": \"VIBE_UNIQUE_VIOLATION\",\n /** foreign_key_violation */\n \"23503\": \"VIBE_FK_VIOLATION\",\n /** restrict_violation — PostgreSQL 18+ ON DELETE/UPDATE RESTRICT */\n \"23001\": \"VIBE_FK_VIOLATION\",\n /** not_null_violation */\n \"23502\": \"VIBE_VALIDATION\",\n /** check_violation */\n \"23514\": \"VIBE_VALIDATION\",\n /**\n * invalid_text_representation — a value the server cannot parse into the\n * column's type (out-of-range enum value, `\"abc\"` for an integer). Bad input,\n * so the same code sqlite reports for its enum CHECK violation.\n */\n \"22P02\": \"VIBE_VALIDATION\",\n /**\n * The other data-exception SQLSTATEs the same bad INPUT raises — a string\n * too long for varchar(n) (22001), a number outside the column's range\n * (22003), an unparseable date/time (22007) or one whose fields overflow\n * (22008). mysql maps its peers (1406 / 1264 / 1292) to VIBE_VALIDATION;\n * postgres reported them as VIBE_ADAPTER, so the same request was a 400 on\n * one dialect and a 500 on the other.\n */\n \"22001\": \"VIBE_VALIDATION\",\n \"22003\": \"VIBE_VALIDATION\",\n \"22007\": \"VIBE_VALIDATION\",\n \"22008\": \"VIBE_VALIDATION\",\n /**\n * insufficient_privilege — a denied table/column privilege, and the SQLSTATE a\n * native row-level-security policy raises when its WITH CHECK refuses a write.\n * Callers identify it by this code, never by message text.\n */\n \"42501\": \"VIBE_PERMISSION_DENIED\",\n /** serialization_failure */\n \"40001\": \"VIBE_TRANSACTION\",\n /** deadlock_detected */\n \"40P01\": \"VIBE_TRANSACTION\",\n /** query_canceled — statement_timeout fired */\n \"57014\": \"VIBE_TRANSACTION\",\n /**\n * lock_not_available — a `nowait` locking read whose rows were already\n * locked, OR a `lock_timeout` that expired while blocking. The server reports\n * both with this ONE SQLSTATE (verified on postgres 18.6: \"could not obtain\n * lock on row in relation\" and \"canceling statement due to lock timeout\"), so\n * VibeORM does not invent a distinction the server does not make. Nothing is\n * retried automatically — waiting, skipping or failing is the caller's policy.\n */\n \"55P03\": \"VIBE_LOCK_NOT_AVAILABLE\",\n /**\n * read_only_sql_transaction — a write inside a READ ONLY transaction\n * (`accessMode: \"readOnly\"`, or a server whose default is read-only, e.g. a\n * hot standby). Before round-trip EPIC 3 it fell through to VIBE_ADAPTER.\n */\n \"25006\": \"VIBE_TRANSACTION\",\n});\n\n/** SQLSTATEs that additionally explain themselves through `meta.reason`. */\nexport const PG_SQLSTATE_REASONS: Readonly<Record<string, string>> = Object.freeze({\n \"23P01\": \"exclusion-violation\",\n \"57014\": \"timeout\",\n \"55P03\": \"lock-not-available\",\n /** Same reason string mysql already uses for errno 1213 — one word per dialect. */\n \"40P01\": \"deadlock\",\n \"40001\": \"serialization-failure\",\n \"25006\": \"read-only-transaction\",\n});\n\n/**\n * The pooler remedy appended to a named-statement mismatch. Both SQLSTATEs mean\n * the backend's prepared names disagree with the client's: the session moved\n * to another backend between Parse and use. It covers both kinds of names —\n * the ORM path's (`preparedStatements: true`) and the raw path's caller-chosen\n * ones (`executeUnsafe({ name })`, throughput request 1).\n */\nconst NAMED_STATEMENT_POOLER_HINT =\n \"Hint: with preparedStatements: true or a named raw statement, every query must reach the backend that prepared its name. \" +\n \"Use a direct connection, session pooling, or PgBouncer 1.21+ with max_prepared_statements > 0; \" +\n \"behind a transaction-mode pooler without prepared-statement support, turn preparedStatements off and send raw statements without a name.\";\n\n/**\n * SQLSTATEs whose message gets a remedy appended. The code stays what the\n * SQLSTATE table says (`VIBE_ADAPTER` for both); only the human-readable text\n * grows. Frozen and mirrored by tests. `0A000` (\"cached plan must not change\n * result type\") is deliberately absent: it is the generic feature_not_supported\n * class, so a prepared-statement hint would mislead on its other causes.\n */\nexport const PG_SQLSTATE_HINTS: Readonly<Record<string, string>> = Object.freeze({\n /** invalid_sql_statement_name — the backend does not know the name. */\n \"26000\": NAMED_STATEMENT_POOLER_HINT,\n /** duplicate_prepared_statement — the backend already holds the name. */\n \"42P05\": NAMED_STATEMENT_POOLER_HINT,\n});\n\n// ─── Reading driver errors ────────────────────────────────────────\n\n/**\n * A PostgreSQL SQLSTATE is exactly five digits/uppercase letters (e.g. `40P01`)\n * and every one PostgreSQL defines contains a digit. Requiring one keeps a\n * five-letter socket errno (`EPIPE`, `EPERM`) from passing as a server answer:\n * a COMMIT that failed with it is a lost connection, not a definite rollback\n * (fix lane FX-A, RV2 \"outside EPIC 3\").\n */\nconst SQLSTATE_PATTERN = /^(?=[A-Z]*\\d)[0-9A-Z]{5}$/;\n\nfunction readStringField(params: { source: Record<string, unknown>; key: string }): string | undefined {\n const value = params.source[params.key];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * Extract the SQLSTATE from a pg driver error. `pg` puts the server's SQLSTATE\n * on `error.code`; client-side failures (`ECONNREFUSED`, `ETIMEDOUT`, …) use\n * the same field for a non-SQLSTATE string, which this rejects.\n */\nexport function pgErrorSqlstate(params: { error: unknown }): string | undefined {\n const { error } = params;\n if (error === null || typeof error !== \"object\") return undefined;\n const code = readStringField({ source: error as Record<string, unknown>, key: \"code\" });\n return code !== undefined && SQLSTATE_PATTERN.test(code) ? code : undefined;\n}\n\n// ─── Mapping ──────────────────────────────────────────────────────\n\n/**\n * Map any error thrown by `pg` onto a `VibeError`.\n *\n * A `VibeError` passes through unchanged, so an error raised deeper inside the\n * ORM (or by a nested adapter call) is never re-wrapped.\n */\nexport function mapPgDriverError(params: { error: unknown }): VibeError {\n const { error } = params;\n if (error instanceof VibeError) return error;\n\n const source: Record<string, unknown> =\n error !== null && typeof error === \"object\" ? (error as Record<string, unknown>) : {};\n const sqlstate = pgErrorSqlstate({ error });\n const code: VibeErrorCode =\n (sqlstate === undefined ? undefined : PG_SQLSTATE_ERROR_CODES[sqlstate]) ?? \"VIBE_ADAPTER\";\n\n const meta: Record<string, unknown> = {};\n if (sqlstate !== undefined) meta.sqlstate = sqlstate;\n const constraint = readStringField({ source, key: \"constraint\" });\n if (constraint !== undefined) meta.constraint = constraint;\n const table = readStringField({ source, key: \"table\" });\n if (table !== undefined) meta.table = table;\n const column = readStringField({ source, key: \"column\" });\n if (column !== undefined) meta.column = column;\n const reason = sqlstate === undefined ? undefined : PG_SQLSTATE_REASONS[sqlstate];\n if (reason !== undefined) meta.reason = reason;\n\n const driverMessage =\n readStringField({ source, key: \"message\" }) ??\n (typeof error === \"string\" ? error : \"unknown postgres driver error\");\n const hint = sqlstate === undefined ? undefined : PG_SQLSTATE_HINTS[sqlstate];\n const message = hint === undefined ? driverMessage : `${driverMessage}. ${hint}`;\n\n return new VibeError({ code, message, meta, cause: error });\n}\n\n/** Run a driver call, mapping anything it throws onto a `VibeError`. */\nexport async function runMapped<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n throw mapPgDriverError({ error });\n }\n}\n",
13
13
  "/**\n * Parameter serialization for node-postgres — the ORM path and the raw path\n * differ, deliberately (see LEARNINGS.md).\n *\n * `pg` natively turns a JS array into a PostgreSQL array literal (`{1,2,3}`),\n * which is exactly what a raw query wants. The ORM hot path cannot tell whether\n * a JS array is destined for a `jsonb` column or for a scalar-list / `= ANY($n)`\n * parameter, so it JSON-stringifies arrays and objects — scalar-list values are\n * tagged with `PgArrayParam` by `formatArrayParam` and unwrapped here, reaching\n * the driver as the untouched JS array.\n */\n\n// ─── Scalar-list marker ───────────────────────────────────────────\n\n/**\n * Opaque token returned by `pgAdapter().formatArrayParam` marking a value as a\n * PostgreSQL array parameter (rather than a JSON value that happens to be an\n * array). The wrapped array reaches `pg` as-is; the driver serializes it.\n */\nexport class PgArrayParam {\n /** The untouched scalar-list values. */\n readonly values: unknown[];\n\n constructor(values: unknown[]) {\n this.values = values;\n }\n}\n\n// ─── Serialization ────────────────────────────────────────────────\n\n/**\n * `Date` → UTC ISO-8601 text (`2026-03-08T19:38:08.538Z`).\n *\n * node-postgres' own serializer writes the host's LOCAL wall-clock plus its\n * offset (`2026-03-08T20:38:08.538+01:00` under Europe/Oslo). A `timestamptz`\n * parameter keeps the instant either way, but a `timestamp without time zone`\n * or `date` parameter DISCARDS the offset (\"PostgreSQL will silently ignore\n * any time zone indication\"), so the stored wall-clock would depend on the\n * host's TZ — and differ from what bun:sql, PGlite and Prisma store for the\n * same `Date` (all UTC). The UTC spelling stores one value on every host and\n * matches the UTC read side (`EXACT_TYPES` in index.ts). Dates the ISO form\n * cannot spell (invalid, BC, beyond year 9999) keep the driver's serializer.\n */\nexport function serializeDate(params: { value: Date }): unknown {\n const { value } = params;\n const time = value.getTime();\n if (Number.isNaN(time)) return value;\n const year = value.getUTCFullYear();\n if (year < 1 || year > 9999) return value;\n return value.toISOString();\n}\n\n/** True for values `pg` must receive verbatim (binary, primitives, null). */\nfunction isDriverNativeValue(value: unknown): boolean {\n return (\n value === null ||\n value === undefined ||\n typeof value !== \"object\" ||\n ArrayBuffer.isView(value) ||\n value instanceof ArrayBuffer\n );\n}\n\n/**\n * ORM hot path: unwrap scalar-list markers, spell `Date` as UTC, JSON-stringify\n * plain objects **and** plain arrays (they can only be `json`/`jsonb` values\n * at this point).\n */\nexport function serializeParams(params: { values: readonly unknown[] }): unknown[] {\n return params.values.map((value) => {\n if (value instanceof PgArrayParam) return serializeList({ values: value.values });\n if (value instanceof Date) return serializeDate({ value });\n if (isDriverNativeValue(value)) return value;\n return JSON.stringify(value);\n });\n}\n\n/**\n * A scalar-list parameter: `Date` elements spelled as UTC (the driver's array\n * serializer would otherwise write them in local time); a list without dates\n * reaches `pg` as the untouched array.\n */\nfunction serializeList(params: { values: unknown[] }): unknown[] {\n const { values } = params;\n return values.some((value) => value instanceof Date)\n ? values.map((value) => (value instanceof Date ? serializeDate({ value }) : value))\n : values;\n}\n\n/**\n * Raw path (`$queryRaw*` / `$executeRaw*` / DDL): identical to\n * {@link serializeParams} except that plain JS arrays pass straight through, so\n * `db.$queryRawUnsafe('… WHERE \"id\" = ANY($1)', [1, 2, 3])` matches rows.\n *\n * Trade-off (v1 lesson): binding a JS array **into** a `jsonb` column from a raw\n * query means calling `JSON.stringify` yourself.\n */\nexport function serializeParamsRaw(params: { values: readonly unknown[] }): unknown[] {\n return params.values.map((value) => {\n if (value instanceof PgArrayParam) return serializeList({ values: value.values });\n if (Array.isArray(value)) return serializeList({ values: value });\n if (value instanceof Date) return serializeDate({ value });\n if (isDriverNativeValue(value)) return value;\n return JSON.stringify(value);\n });\n}\n",
14
14
  "/**\n * Pool configuration for the pool {@link pgAdapter} builds itself.\n *\n * Per-connection PostgreSQL settings travel in the `options` startup\n * parameter (`-c key=value` pairs the server parses at connect time), so every\n * pooled connection inherits them without a per-query round trip. Two\n * node-postgres facts shape the merge below, both read from the installed\n * driver (pg 8.23):\n *\n * - `ConnectionParameters` parses `connectionString` OVER the explicit config\n * (`Object.assign({}, config, parse(connectionString))`), so a URL that\n * already carries `?options=…` silently wins over `config.options`.\n * - `pg-connection-string` turns EVERY query parameter into a config key, so\n * `?options=-c search_path=x` arrives as `config.options`.\n *\n * Hence: with no `options` in the URL the setting rides `config.options`\n * (nothing to collide with); with one, the URL's value is EXTENDED in place\n * and a `plan_cache_mode` the URL already sets is left alone — the caller's\n * connection string is the more explicit statement of intent.\n */\n\nimport { VibeError } from \"@vibeorm/schema\";\n\n/**\n * PostgreSQL plan-cache behaviour for named prepared statements\n * (`preparedStatements: true`). `auto` (the server default) lets PostgreSQL\n * switch to a generic plan after ~5 executions — cheaper per call, but it can\n * pick worse indexes for range/LIKE/skewed filters; `force_custom_plan`\n * replans with the real parameter values every time and keeps almost the whole\n * prepared-statement gain (the saving is the parse/analyze and the protocol\n * round, not the plan — measured −17…−25 % on reads either way, see\n * `.ai/plans/26.09.08 - performance-join-strategy.md` §1.3).\n */\nexport type PlanCacheMode = \"auto\" | \"force_custom_plan\" | \"force_generic_plan\";\n\nconst PLAN_CACHE_MODES: readonly PlanCacheMode[] = [\"auto\", \"force_custom_plan\", \"force_generic_plan\"];\n\nfunction isPlanCacheMode(value: unknown): value is PlanCacheMode {\n return typeof value === \"string\" && (PLAN_CACHE_MODES as readonly string[]).includes(value);\n}\n\n/** Validate a `planCacheMode` option value; the string ends up inside a startup parameter verbatim. */\nexport function assertPlanCacheMode(params: { value: unknown }): PlanCacheMode {\n const { value } = params;\n if (isPlanCacheMode(value)) return value;\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message: `planCacheMode must be one of ${PLAN_CACHE_MODES.map((mode) => `\"${mode}\"`).join(\", \")}, received ${JSON.stringify(value)}`,\n meta: { planCacheMode: value, allowed: PLAN_CACHE_MODES },\n });\n}\n\n/** The `options` startup parameter and (possibly rewritten) connection string carrying it. */\nexport type StartupOptionsPlacement = {\n readonly connectionString: string | undefined;\n /** `undefined` when nothing needs setting, or the URL already sets the parameter itself. */\n readonly options: string | undefined;\n};\n\n/**\n * Place `plan_cache_mode` into the startup options, honouring what the URL\n * already carries (see the module header for the precedence rule).\n */\nexport function placePlanCacheMode(params: {\n connectionString: string | undefined;\n planCacheMode: PlanCacheMode;\n}): StartupOptionsPlacement {\n const { connectionString, planCacheMode } = params;\n if (planCacheMode === \"auto\") return { connectionString, options: undefined };\n const setting = `-c plan_cache_mode=${planCacheMode}`;\n\n if (connectionString === undefined || !URL.canParse(connectionString)) {\n return { connectionString, options: setting };\n }\n const url = new URL(connectionString);\n const existing = url.searchParams.get(\"options\");\n if (existing === null) {\n // Absent from the URL → the parsed URL carries no `options` key and\n // `config.options` survives the driver's merge untouched.\n return { connectionString, options: setting };\n }\n if (/(^|\\s)-c\\s*plan_cache_mode=/.test(existing)) {\n // The URL is the more explicit statement of intent; leave it alone.\n return { connectionString, options: undefined };\n }\n const merged = existing.trim().length === 0 ? setting : `${existing.trim()} ${setting}`;\n // The URL's own value wins in the driver, so the merge has to live THERE.\n url.searchParams.set(\"options\", merged);\n return { connectionString: url.toString(), options: merged };\n}\n\n/**\n * Validate an `idleTimeout` option value (AW-04): integer milliseconds from\n * 0 through 2,147,483,647. pg-pool passes it to `setTimeout`; larger values\n * overflow Node's signed 32-bit timer range and become a 1 ms timeout.\n *\n * @throws VibeError `VIBE_CONFIG` (`meta.reason: \"invalid-idle-timeout\"`).\n */\nexport function assertIdleTimeout(params: { value: unknown }): number {\n const { value } = params;\n if (typeof value === \"number\" && Number.isInteger(value) && value >= 0 && value <= 2_147_483_647) return value;\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message: \"pgAdapter `idleTimeout` must be integer milliseconds from 0 through 2,147,483,647 (0 keeps idle connections open).\",\n meta: { adapter: \"pg\", reason: \"invalid-idle-timeout\", option: \"idleTimeout\" },\n });\n}\n\n/**\n * Validate a `min` option value (V7): an integer from 0 through the pool's\n * `max`. pg-pool never idle-closes a connection while the pool holds `min` or\n * fewer; it does not open them in advance (`adapter.connect()` does).\n *\n * @throws VibeError `VIBE_CONFIG` (`meta.reason: \"invalid-pool-min\"`).\n */\nexport function assertPoolMin(params: { value: unknown; max: number }): number {\n const { value, max } = params;\n if (typeof value === \"number\" && Number.isInteger(value) && value >= 0 && value <= max) return value;\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message: `pgAdapter \\`min\\` must be an integer from 0 through \\`max\\` (${max}).`,\n meta: { adapter: \"pg\", reason: \"invalid-pool-min\", option: \"min\", max },\n });\n}\n\n/** Build the `pg.Pool` constructor config for an adapter-owned pool. */\nexport function buildPoolConfig(params: {\n connectionString: string | undefined;\n max: number;\n /** Connections pg-pool keeps open however long they idle (pg-pool's `min`). Absent = pg-pool's 0. */\n min?: number;\n statementTimeout?: number;\n connectionTimeout?: number;\n /** Milliseconds an idle pooled connection stays open (pg-pool's `idleTimeoutMillis`; `0` = never closed). Absent = pg-pool's 10 000. */\n idleTimeout?: number;\n planCacheMode?: PlanCacheMode;\n}): Record<string, unknown> {\n const { max, min, statementTimeout, connectionTimeout, idleTimeout } = params;\n const placement = placePlanCacheMode({\n connectionString: params.connectionString,\n planCacheMode: params.planCacheMode ?? \"auto\",\n });\n const config: Record<string, unknown> = { connectionString: placement.connectionString, max };\n if (min !== undefined) config.min = min;\n if (statementTimeout !== undefined) config.statement_timeout = statementTimeout;\n if (connectionTimeout !== undefined) config.connectionTimeoutMillis = connectionTimeout;\n if (idleTimeout !== undefined) config.idleTimeoutMillis = idleTimeout;\n if (placement.options !== undefined) config.options = placement.options;\n return config;\n}\n",
15
- "/**\n * Bounded prepared-statement NAME registry, shared per pool.\n *\n * With `preparedStatements: true` every SQL text that proves itself repeated\n * gets a stable name, so PostgreSQL keeps a cached plan for it. Three\n * properties matter, and the first version of this file had none of them:\n *\n * 1. **The bound has to be a bound on the SERVER** (F16). Evicting a local\n * mapping and minting a fresh name leaves the old prepared statement on\n * every backend that ever saw it — the local map stayed small while server\n * retention grew without limit. Nor can eviction be repaired with\n * `DEALLOCATE`: a name is prepared per CONNECTION, the adapter does not know\n * which pooled connections hold it, and deallocating behind node-postgres'\n * back invalidates its own per-client name registry (it would keep sending\n * the name and the server would refuse it).\n *\n * So the registry never re-uses a name for another text and never evicts:\n * it allocates at most `max` names, and once that budget is spent a new text\n * runs UNNAMED — bounded preparation fallback. Server retention is then\n * `max` per connection, permanently. Statements still bind their parameters;\n * only the server-side plan cache is skipped.\n *\n * 2. **One name never means two texts** (F18, EPIC H). Each adapter used to\n * start its own counter at zero, so two adapters on one pool both sent\n * `vibeorm_0` for different SQL and postgres refused the second\n * (\"Prepared statements must be unique\"). Worse, two INDEPENDENT registries\n * (two pools, two processes) whose sessions reach one backend — a pooler\n * that switches backends — could execute another registry's `vibeorm_0`\n * and return that statement's rows without any error. A name is therefore\n * derived from the text itself: `vibeorm_` + the SHA-256 of the exact\n * statement text, base32 (see {@link statementNameFor}). Equal names mean\n * equal texts in every registry, process and adapter version, so the worst\n * a foreign backend can do is refuse a name (26000/42P05), never run another\n * text under it. The registry is still shared per pool, which keeps one\n * budget per pool and stops N adapters from preparing the same text N times.\n * Only the text is hashed: node-postgres sends no parameter types with a\n * named Parse, and result parsers live on the client, not the backend.\n *\n * 3. **A one-off text must not spend the budget.** Because names never evict\n * (property 1), allocating on FIRST sight hands the whole budget to whatever\n * arrives first. Offset pagination emits a distinct text per page, so a\n * paginating workload used to burn all `max` names for the pool's lifetime\n * and leave every genuinely hot text unnamed thereafter. A name is therefore\n * allocated on the `promoteAfter`-th sighting of a text. Sightings live in\n * their own bounded LRU (capped at {@link SIGHTINGS_PER_NAME} × `max`);\n * evicting a sighting only delays a promotion, it can never name the wrong\n * text or exceed the budget. A hot text loses exactly one prepared\n * execution; a one-off text costs the server nothing.\n */\n\nimport { createHash } from \"node:crypto\";\n\n/** Sightings of a text before it earns a name. */\nconst DEFAULT_PROMOTE_AFTER = 2;\n\n/**\n * Sighting slots per name of budget. The sighting map is a pure heuristic —\n * over-sizing it only wastes memory, under-sizing it only delays promotions —\n * so a small multiple of the name budget is enough to see a repeat through a\n * burst of one-off texts.\n */\nconst SIGHTINGS_PER_NAME = 4;\n\n/** Prefix of every statement name this adapter prepares. */\nconst NAME_PREFIX = \"vibeorm_\";\n\n/** RFC 4648 base32 alphabet, lowercased: names stay valid unquoted SQL identifiers. */\nconst BASE32_ALPHABET = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n/**\n * The content-addressed prepared-statement name of `text`: `vibeorm_` + the\n * SHA-256 of its UTF-8 bytes in lowercase base32 without padding — 52\n * characters, 60 bytes in total, within PostgreSQL's 63-byte identifier limit\n * (NAMEDATALEN − 1), so the server never truncates two names into one. The same\n * text yields the same name in every registry, process and version.\n */\nexport function statementNameFor(params: { text: string }): string {\n const digest = createHash(\"sha256\").update(params.text, \"utf8\").digest();\n let name = NAME_PREFIX;\n let buffer = 0;\n let bits = 0;\n for (const byte of digest) {\n buffer = (buffer << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n name += BASE32_ALPHABET[(buffer >>> bits) & 31];\n }\n // Keep only the bits not yet emitted, so the shift never overflows.\n buffer &= (1 << bits) - 1;\n }\n if (bits > 0) name += BASE32_ALPHABET[(buffer << (5 - bits)) & 31];\n return name;\n}\n\n/** Registry mapping SQL text to the prepared-statement name `pg` should send. */\nexport type StatementNameCache = {\n /**\n * Stable statement name for `text` — or `undefined` meaning \"send this one\n * unnamed\", which is the answer until the text has been seen `promoteAfter`\n * times and again once the name budget is spent.\n */\n getName(params: { text: string }): string | undefined;\n /** Number of names allocated — diagnostics and tests. */\n size(): number;\n /** Number of texts tracked toward promotion — diagnostics and tests. */\n sightings(): number;\n};\n\n/**\n * Create a statement-name registry that allocates at most `max` names\n * ({@link statementNameFor} of the text), each on the `promoteAfter`-th sighting of its\n * text (default 2). Texts seen fewer times, and texts arriving after the budget\n * is spent, get no name and run unprepared, so the server's prepared-statement\n * retention stays bounded and a stream of one-off texts cannot consume it.\n */\nexport function createStatementNameCache(params: { max: number; promoteAfter?: number }): StatementNameCache {\n const max = Math.max(0, params.max);\n const promoteAfter = Math.max(1, params.promoteAfter ?? DEFAULT_PROMOTE_AFTER);\n const sightingsMax = max * SIGHTINGS_PER_NAME;\n /** Never evicted, never re-used: this map is the server-side bound. */\n const names = new Map<string, string>();\n /** Insertion-ordered, so the first key is the least recently seen text. */\n const sightings = new Map<string, number>();\n\n return {\n getName(nameParams: { text: string }): string | undefined {\n const { text } = nameParams;\n const existing = names.get(text);\n if (existing !== undefined) return existing;\n // Budget spent (and the `max: 0` case): nothing left to promote into, so\n // do not spend memory counting sightings either.\n if (names.size >= max) return undefined;\n\n const seen = (sightings.get(text) ?? 0) + 1;\n if (seen < promoteAfter) {\n // Re-insert to move the text to the most-recently-seen end.\n sightings.delete(text);\n sightings.set(text, seen);\n while (sightings.size > sightingsMax) {\n const oldest = sightings.keys().next();\n if (oldest.done === true) break;\n sightings.delete(oldest.value);\n }\n return undefined;\n }\n\n sightings.delete(text);\n const name = statementNameFor({ text });\n names.set(text, name);\n return name;\n },\n\n size(): number {\n return names.size;\n },\n\n sightings(): number {\n return sightings.size;\n },\n };\n}\n",
15
+ "/**\n * Bounded prepared-statement NAME registry, shared per pool.\n *\n * With `preparedStatements: true` every SQL text that proves itself repeated\n * gets a stable name, so PostgreSQL keeps a cached plan for it. Three\n * properties matter, and the first version of this file had none of them:\n *\n * 1. **The bound has to be a bound on the SERVER** (F16). Evicting a local\n * mapping and minting a fresh name leaves the old prepared statement on\n * every backend that ever saw it — the local map stayed small while server\n * retention grew without limit. Nor can eviction be repaired with\n * `DEALLOCATE`: a name is prepared per CONNECTION, the adapter does not know\n * which pooled connections hold it, and deallocating behind node-postgres'\n * back invalidates its own per-client name registry (it would keep sending\n * the name and the server would refuse it).\n *\n * So the registry never re-uses a name for another text and never evicts:\n * it allocates at most `max` names, and once that budget is spent a new text\n * runs UNNAMED — bounded preparation fallback. Server retention is then\n * `max` per connection, permanently. Statements still bind their parameters;\n * only the server-side plan cache is skipped.\n *\n * 2. **One name never means two texts** (F18, EPIC H). Each adapter used to\n * start its own counter at zero, so two adapters on one pool both sent\n * `vibeorm_0` for different SQL and postgres refused the second\n * (\"Prepared statements must be unique\"). Worse, two INDEPENDENT registries\n * (two pools, two processes) whose sessions reach one backend — a pooler\n * that switches backends — could execute another registry's `vibeorm_0`\n * and return that statement's rows without any error. A name is therefore\n * derived from the text itself: `vibeorm_` + the SHA-256 of the exact\n * statement text, base32 (see {@link statementNameFor}). Equal names mean\n * equal texts in every registry, process and adapter version, so the worst\n * a foreign backend can do is refuse a name (26000/42P05), never run another\n * text under it. The registry is still shared per pool, which keeps one\n * budget per pool and stops N adapters from preparing the same text N times.\n * Only the text is hashed: node-postgres sends no parameter types with a\n * named Parse, and result parsers live on the client, not the backend.\n *\n * 3. **A one-off text must not spend the budget.** Because names never evict\n * (property 1), allocating on FIRST sight hands the whole budget to whatever\n * arrives first. Offset pagination emits a distinct text per page, so a\n * paginating workload used to burn all `max` names for the pool's lifetime\n * and leave every genuinely hot text unnamed thereafter. A name is therefore\n * allocated on the `promoteAfter`-th sighting of a text. Sightings live in\n * their own bounded LRU (capped at {@link SIGHTINGS_PER_NAME} × `max`);\n * evicting a sighting only delays a promotion, it can never name the wrong\n * text or exceed the budget. A hot text loses exactly one prepared\n * execution; a one-off text costs the server nothing.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { VibeError } from \"@vibeorm/schema\";\n\n/** Sightings of a text before it earns a name. */\nconst DEFAULT_PROMOTE_AFTER = 2;\n\n/**\n * Sighting slots per name of budget. The sighting map is a pure heuristic —\n * over-sizing it only wastes memory, under-sizing it only delays promotions —\n * so a small multiple of the name budget is enough to see a repeat through a\n * burst of one-off texts.\n */\nconst SIGHTINGS_PER_NAME = 4;\n\n/** Prefix of every statement name this adapter prepares. */\nconst NAME_PREFIX = \"vibeorm_\";\n\n/** RFC 4648 base32 alphabet, lowercased: names stay valid unquoted SQL identifiers. */\nconst BASE32_ALPHABET = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n/**\n * The content-addressed prepared-statement name of `text`: `vibeorm_` + the\n * SHA-256 of its UTF-8 bytes in lowercase base32 without padding — 52\n * characters, 60 bytes in total, within PostgreSQL's 63-byte identifier limit\n * (NAMEDATALEN − 1), so the server never truncates two names into one. The same\n * text yields the same name in every registry, process and version.\n */\nexport function statementNameFor(params: { text: string }): string {\n const digest = createHash(\"sha256\").update(params.text, \"utf8\").digest();\n let name = NAME_PREFIX;\n let buffer = 0;\n let bits = 0;\n for (const byte of digest) {\n buffer = (buffer << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n name += BASE32_ALPHABET[(buffer >>> bits) & 31];\n }\n // Keep only the bits not yet emitted, so the shift never overflows.\n buffer &= (1 << bits) - 1;\n }\n if (bits > 0) name += BASE32_ALPHABET[(buffer << (5 - bits)) & 31];\n return name;\n}\n\n/** Registry mapping SQL text to the prepared-statement name `pg` should send. */\nexport type StatementNameCache = {\n /**\n * Stable statement name for `text` — or `undefined` meaning \"send this one\n * unnamed\", which is the answer until the text has been seen `promoteAfter`\n * times and again once the name budget is spent.\n */\n getName(params: { text: string }): string | undefined;\n /** Number of names allocated — diagnostics and tests. */\n size(): number;\n /** Number of texts tracked toward promotion — diagnostics and tests. */\n sightings(): number;\n};\n\n/**\n * Create a statement-name registry that allocates at most `max` names\n * ({@link statementNameFor} of the text), each on the `promoteAfter`-th sighting of its\n * text (default 2). Texts seen fewer times, and texts arriving after the budget\n * is spent, get no name and run unprepared, so the server's prepared-statement\n * retention stays bounded and a stream of one-off texts cannot consume it.\n */\nexport function createStatementNameCache(params: { max: number; promoteAfter?: number }): StatementNameCache {\n const max = Math.max(0, params.max);\n const promoteAfter = Math.max(1, params.promoteAfter ?? DEFAULT_PROMOTE_AFTER);\n const sightingsMax = max * SIGHTINGS_PER_NAME;\n /** Never evicted, never re-used: this map is the server-side bound. */\n const names = new Map<string, string>();\n /** Insertion-ordered, so the first key is the least recently seen text. */\n const sightings = new Map<string, number>();\n\n return {\n getName(nameParams: { text: string }): string | undefined {\n const { text } = nameParams;\n const existing = names.get(text);\n if (existing !== undefined) return existing;\n // Budget spent (and the `max: 0` case): nothing left to promote into, so\n // do not spend memory counting sightings either.\n if (names.size >= max) return undefined;\n\n const seen = (sightings.get(text) ?? 0) + 1;\n if (seen < promoteAfter) {\n // Re-insert to move the text to the most-recently-seen end.\n sightings.delete(text);\n sightings.set(text, seen);\n while (sightings.size > sightingsMax) {\n const oldest = sightings.keys().next();\n if (oldest.done === true) break;\n sightings.delete(oldest.value);\n }\n return undefined;\n }\n\n sightings.delete(text);\n const name = statementNameFor({ text });\n names.set(text, name);\n return name;\n },\n\n size(): number {\n return names.size;\n },\n\n sightings(): number {\n return sightings.size;\n },\n };\n}\n\n// ─── Caller-chosen raw names ───\n\n/**\n * The texts behind the caller-chosen statement names of the raw path\n * (throughput request 1), shared per pool like {@link StatementNameCache}.\n * One name means ONE text: node-postgres refuses a second text under a name\n * only on a connection that already prepared it, so the same caller bug would\n * fail on some connections and pass on others. The registry refuses it at the\n * call, before anything is sent, on every connection alike.\n *\n * Unbounded on purpose: the names are a caller's fixed set (each one is also\n * prepared on every connection that runs it); a name per value would grow the\n * server's prepared statements just as much.\n */\nexport type RawStatementNames = {\n /**\n * Admit `name` for `text`: the first text a name is used with is its text\n * for the pool's lifetime. A different text is refused with\n * `VIBE_VALIDATION`, `meta.reason: \"statement-name-reused\"`.\n */\n admit(params: { name: string; text: string }): void;\n};\n\n/** Create an empty {@link RawStatementNames} registry. */\nexport function createRawStatementNames(): RawStatementNames {\n const texts = new Map<string, string>();\n return {\n admit(params: { name: string; text: string }): void {\n const known = texts.get(params.name);\n if (known === undefined) {\n texts.set(params.name, params.text);\n return;\n }\n if (known === params.text) return;\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `statement name \"${params.name}\" already names another SQL text on this pool: one name means one text (give the new text its own name)`,\n meta: { adapter: \"pg\", reason: \"statement-name-reused\", name: params.name },\n });\n },\n };\n}\n",
16
16
  "/**\n * Char-code decoding of PostgreSQL's PLAIN timestamp wire text (performance\n * round 3, AW-03).\n *\n * node-postgres hands every `timestamptz` cell to pg-types' parser\n * (postgres-date: three regular expressions, `parseInt` per field, a split)\n * and every `timestamp` cell to this adapter's `parseZoneLessAsUtc` (a regular\n * expression, two `replace` calls and a template string before `new Date`).\n * The text PostgreSQL prints for the common case has a fixed layout, so one\n * pass over its character codes yields the same instant 2.5–3× cheaper.\n *\n * This function only ACCEPTS or DECLINES: it returns `undefined` for every\n * text outside the plain form, and the caller then runs today's parser\n * unchanged. It never adds a coercion of its own — an accepted text decodes\n * to exactly the instant today's parser returns (differential test\n * `tests/timestamp-text.test.ts`).\n */\n\n// ─── Plain timestamp text ─────────────────────────────────────\n\n// Plain (not frozen) module-private arrays: JavaScriptCore reads a frozen\n// array's elements ≈ 2× slower, which cost this parser half its gain.\n\n/** Days per month in a common year; February is checked separately. */\nconst DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n/** The digit positions of `YYYY-MM-DD HH:MM:SS`. */\nconst DIGIT_POSITIONS: readonly number[] = [0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18];\n\n/**\n * Decode `YYYY-MM-DD HH:MM:SS[.f{1,6}]` — followed by `±HH` or `±HH:MM` when\n * `zoned`, by nothing otherwise — as a `Date`: zone-less text is read as UTC\n * wall-clock time, zoned text at its offset. Fraction digits beyond the third\n * are truncated (as postgres-date and `parseZoneLessAsUtc` both do).\n *\n * Returns `undefined` — \"use today's parser\" — for anything else: years\n * before 1000 (`Date.UTC` maps 0–99 to 1900–1999), BC dates, `infinity`,\n * offsets with seconds (historic local mean time), date-only text, 7+\n * fraction digits, and out-of-range fields (month 13, February 30, hour 24,\n * second 60), so the fallback keeps every such text's current decoding.\n */\nexport function parsePlainTimestampText(params: { readonly text: string; readonly zoned: boolean }): Date | undefined {\n const { text, zoned } = params;\n const length = text.length;\n if (\n length < 19 ||\n text.charCodeAt(4) !== 45 ||\n text.charCodeAt(7) !== 45 ||\n text.charCodeAt(10) !== 32 ||\n text.charCodeAt(13) !== 58 ||\n text.charCodeAt(16) !== 58\n ) {\n return undefined;\n }\n for (let position = 0; position < DIGIT_POSITIONS.length; position++) {\n const code = text.charCodeAt(DIGIT_POSITIONS[position] as number);\n if (code < 48 || code > 57) return undefined;\n }\n const year =\n (text.charCodeAt(0) - 48) * 1000 + (text.charCodeAt(1) - 48) * 100 + (text.charCodeAt(2) - 48) * 10 + (text.charCodeAt(3) - 48);\n const month = (text.charCodeAt(5) - 48) * 10 + (text.charCodeAt(6) - 48);\n const day = (text.charCodeAt(8) - 48) * 10 + (text.charCodeAt(9) - 48);\n const hour = (text.charCodeAt(11) - 48) * 10 + (text.charCodeAt(12) - 48);\n const minute = (text.charCodeAt(14) - 48) * 10 + (text.charCodeAt(15) - 48);\n const second = (text.charCodeAt(17) - 48) * 10 + (text.charCodeAt(18) - 48);\n if (year < 1000 || month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 59) return undefined;\n if (day > 28) {\n const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n const days = month === 2 ? (leap ? 29 : 28) : (DAYS_IN_MONTH[month - 1] as number);\n if (day > days) return undefined;\n }\n\n let index = 19;\n let milliseconds = 0;\n if (index < length && text.charCodeAt(index) === 46) {\n index++;\n const start = index;\n while (index < length) {\n const code = text.charCodeAt(index);\n if (code < 48 || code > 57) break;\n if (index - start < 3) milliseconds = milliseconds * 10 + (code - 48);\n index++;\n }\n const digits = index - start;\n if (digits === 0 || digits > 6) return undefined;\n if (digits === 1) milliseconds *= 100;\n else if (digits === 2) milliseconds *= 10;\n }\n\n let offsetMinutes = 0;\n if (zoned) {\n if (index + 3 > length) return undefined;\n const sign = text.charCodeAt(index);\n if (sign !== 43 && sign !== 45) return undefined;\n const hours1 = text.charCodeAt(index + 1) - 48;\n const hours2 = text.charCodeAt(index + 2) - 48;\n if (hours1 < 0 || hours1 > 9 || hours2 < 0 || hours2 > 9) return undefined;\n offsetMinutes = (hours1 * 10 + hours2) * 60;\n index += 3;\n if (index < length) {\n // `±HH:MM` only; `±HH:MM:SS` (seconds offsets) declines to the fallback.\n if (index + 3 !== length || text.charCodeAt(index) !== 58) return undefined;\n const minutes1 = text.charCodeAt(index + 1) - 48;\n const minutes2 = text.charCodeAt(index + 2) - 48;\n if (minutes1 < 0 || minutes1 > 9 || minutes2 < 0 || minutes2 > 9) return undefined;\n offsetMinutes += minutes1 * 10 + minutes2;\n index = length;\n }\n if (sign === 45) offsetMinutes = -offsetMinutes;\n }\n if (index !== length) return undefined;\n\n return new Date(Date.UTC(year, month - 1, day, hour, minute, second, milliseconds) - offsetMinutes * 60_000);\n}\n",
17
17
  "/**\n * Transaction-control SQL text (postgres dialect).\n *\n * Kept apart from the adapter so the mapping from `TransactionOptions` to SQL\n * is unit-testable without a server, and so the timeout value is validated\n * before it is ever interpolated into a statement.\n */\n\nimport type { IsolationLevel } from \"@vibeorm/runtime\";\nimport { VibeError } from \"@vibeorm/schema\";\n\n/** VibeORM isolation level → PostgreSQL isolation level keyword. */\nexport const ISOLATION_LEVEL_SQL: Readonly<Record<IsolationLevel, string>> = Object.freeze({\n ReadCommitted: \"READ COMMITTED\",\n RepeatableRead: \"REPEATABLE READ\",\n Serializable: \"SERIALIZABLE\",\n});\n\n/**\n * `BEGIN`, with an `ISOLATION LEVEL` clause and/or `READ ONLY` when the caller\n * asked for them (`BEGIN ISOLATION LEVEL SERIALIZABLE, READ ONLY`).\n */\nexport function beginStatement(params: { isolationLevel?: IsolationLevel; readOnly?: boolean }): string {\n const { isolationLevel, readOnly } = params;\n const modes: string[] = [];\n if (isolationLevel !== undefined) modes.push(`ISOLATION LEVEL ${ISOLATION_LEVEL_SQL[isolationLevel]}`);\n if (readOnly === true) modes.push(\"READ ONLY\");\n return modes.length === 0 ? \"BEGIN\" : `BEGIN ${modes.join(\", \")}`;\n}\n\n/**\n * The whole opening of a transaction as ONE simple-protocol message (round-trip\n * EPIC 3, A-02): `BEGIN …` alone, or `BEGIN …; SET LOCAL statement_timeout = N`\n * when a timeout is requested — one wait instead of two. Both parts are\n * parameterless text built from validated values. PostgreSQL stops at the\n * first failing statement of the message and the driver rejects with that\n * error, so the caller sees BEGIN's or the SET's own error exactly as when they\n * were two messages; the adapter's ROLLBACK cleanup is unchanged.\n *\n * @throws VibeError `VIBE_VALIDATION` for an invalid timeout (before anything\n * is sent).\n */\nexport function openTransactionStatement(params: {\n isolationLevel?: IsolationLevel;\n readOnly?: boolean;\n timeout?: number;\n}): string {\n const begin = beginStatement(params);\n return params.timeout === undefined ? begin : `${begin}; ${statementTimeoutStatement({ timeout: params.timeout })}`;\n}\n\n/**\n * `SET LOCAL statement_timeout = <ms>` — transaction-scoped, so PostgreSQL\n * cancels an over-long statement with SQLSTATE 57014 (mapped to\n * `VIBE_TRANSACTION` with `meta.reason = \"timeout\"`).\n *\n * @throws VibeError `VIBE_VALIDATION` when the timeout is not a non-negative\n * integer — the value is interpolated into SQL, so it is never trusted blindly.\n */\nexport function statementTimeoutStatement(params: { timeout: number }): string {\n const { timeout } = params;\n if (!Number.isInteger(timeout) || timeout < 0) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `transaction timeout must be a non-negative integer of milliseconds, received ${String(timeout)}`,\n meta: { timeout },\n });\n }\n return `SET LOCAL statement_timeout = ${timeout}`;\n}\n\n// ─── Raw transaction control (session affinity) ─────────────────\n\n/** How a raw statement steers the adapter's session-affine raw transaction. */\nexport type RawTransactionControl = \"open\" | \"close\" | null;\n\nconst RAW_OPEN_PATTERN: RegExp = /^\\s*(?:begin|start\\s+transaction)\\b[^;]*;?\\s*$/i;\nconst RAW_CLOSE_PATTERN: RegExp = /^\\s*(?:commit|end|rollback|abort)(?:\\s+(?:transaction|work))?\\s*;?\\s*$/i;\n\n/**\n * Classify a raw statement as transaction control.\n *\n * @vibeorm/migrate drives transactional DDL by sending literal `BEGIN` /\n * `COMMIT` / `ROLLBACK` through its stateless `SqlExecutor` — sound only when\n * every statement in between rides the SAME connection. Without pinning, a\n * pooled `pool.query(\"BEGIN\")` sequence stays on one client only by LIFO\n * checkout luck; any concurrent traffic silently splits the transaction\n * across connections. The adapter uses this to pin one client for the whole\n * raw transaction (\"open\" checks out, \"close\" releases).\n *\n * Deliberately strict: only PURE single-statement control text matches\n * (`BEGIN`, `BEGIN ISOLATION LEVEL …;`, `COMMIT`, `ROLLBACK WORK`, `END`,\n * `ABORT`). Compound scripts, `ROLLBACK TO SAVEPOINT`, two-phase\n * `COMMIT PREPARED` and `COMMIT AND CHAIN` (which keeps a transaction open)\n * never engage the pinning.\n */\nexport function classifyRawTransactionControl(params: { text: string }): RawTransactionControl {\n if (RAW_OPEN_PATTERN.test(params.text)) return \"open\";\n if (RAW_CLOSE_PATTERN.test(params.text)) return \"close\";\n return null;\n}\n\n// ─── Raw text that rides a batch (performance audit round 2, C-01) ─\n\n/** A separator, a placeholder or dollar quote, a comment, or a NUL: the text may not be ONE plain statement. */\nconst NOT_PROVABLY_ONE_STATEMENT: RegExp = /[;$\\u0000]|--|\\/\\*/;\n/** Transaction control and COPY keep their own round trip (their effects on the session are the point). */\nconst OWN_TURN_VERBS: RegExp = /^\\s*(?:begin|start|commit|end|rollback|abort|savepoint|release|prepare|copy)\\b/i;\n\n/**\n * Whether raw text WITHOUT bound values is PROVABLY one statement whose result\n * and errors are the same in the extended protocol (a one-Sync batch) as in the\n * simple protocol node-postgres uses for it — so it may ride a batch behind\n * pending control (`BEGIN`, `SAVEPOINT`) like any bound statement.\n *\n * The proof is lexical and conservative:\n * - no `;` anywhere (PostgreSQL's grammar splits statements only on `;`, so a\n * non-blank text without one is ONE statement or a syntax error — the same\n * error in both protocols; a `;` inside a string literal is refused too);\n * - no `$` (a `$1` without values fails with a different SQLSTATE in each\n * protocol; dollar quoting is refused with it);\n * - no comment (`--`, `/*`) and not blank (an empty query has no statement);\n * - not transaction control (`BEGIN`, `COMMIT`, `ROLLBACK`, `SAVEPOINT`,\n * `RELEASE`, `PREPARE TRANSACTION`, …) and not `COPY` (its stdin refusal\n * text differs inside a batch).\n * Anything else keeps today's path: it goes alone, after its control was\n * confirmed.\n */\nexport function isSingleStatementText(params: { text: string }): boolean {\n const { text } = params;\n return text.trim() !== \"\" && !NOT_PROVABLY_ONE_STATEMENT.test(text) && !OWN_TURN_VERBS.test(text);\n}\n\n// ─── Nested transaction options (the cross-adapter contract) ──────\n\n// ONE copy, shared by every adapter through the runtime's adapter-kit;\n// re-exported here so this adapter's public surface is unchanged.\nexport { refuseNestedTransactionOptions } from \"@vibeorm/runtime/adapter-kit\";\n"
18
18
  ],
19
- "mappings": ";;AAmBA;AAAA,yBACE;AAAA,wBACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAgCA;AAAA;AAAA;AAAA;AAIF,sBAAS;AAET;;;ACnCA;AAoEA,IAAM,gBAA2D,MAAM;AAAA,EACrE,MAAM,QAAS,GAAyD;AAAA,EACxE,OAAO,OAAO,OAAO,iBAAiB,aACjC,MAAM,eACP;AAAA,GACH;AAGI,SAAS,oBAAoB,GAAY;AAAA,EAC9C,OAAO,iBAAiB;AAAA;AAUnB,SAAS,aAAa,CAAC,QAAsC;AAAA,EAClE,IAAI,iBAAiB;AAAA,IAAW,OAAO;AAAA,EACvC,MAAM,SAAS,OAAO;AAAA,EACtB,IAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,OAAO,aAAa;AAAA,IAAM,OAAO;AAAA,EAC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