@vibeorm/adapter-bun 4.1.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,9 +36,11 @@ await db.$disconnect();
36
36
  | `max` | `number` | `10` | Maximum pooled connections |
37
37
  | `statementTimeout` | `number` (ms) | — | Pool-wide `statement_timeout`, sent as a startup parameter so every connection inherits it; a per-transaction `timeout` overrides it |
38
38
  | `connectionTimeout` | `number` (ms) | URL `connect_timeout`, else none | Wait for a connection to be established. bun:sql expects seconds; the adapter converts |
39
- | `preparedStatements` | `boolean` | `false` | Use bun:sql's **named** prepared statements and run ORM-path queries as tagged templates. Off, every statement is an unnamed statement with text results — the node-postgres model. Read "Statements and values" before you turn it on |
39
+ | `preparedStatements` | `boolean` | `false` | Use bun:sql's **named** prepared statements and run ORM-path queries as tagged templates (on Bun 1.4.3 and newer, a statement whose placeholders are `$1 … $n` in order binds by `$n` through `sql.unsafe`, which names it the same way). Off, every statement is an unnamed statement with text results — the node-postgres model. Read "Statements and values" before you turn it on |
40
40
  | `stmtCacheMax` | `number` | `1000` | Maximum entries in the synthetic template cache (LRU); used only with `preparedStatements: true` |
41
- | `planCacheMode` | `"auto" \| "force_custom_plan" \| "force_generic_plan"` | `"force_custom_plan"` | PostgreSQL `plan_cache_mode` for every connection |
41
+ | `planCacheMode` | `"auto" \| "force_custom_plan" \| "force_generic_plan"` | `"auto"` (nothing sent); `"force_custom_plan"` with `preparedStatements: true` | PostgreSQL `plan_cache_mode` for every connection |
42
+
43
+ `planCacheMode` governs every plan the server caches on a connection: named statements, and also the plans of foreign-key checks, triggers and PL/pgSQL functions. An unnamed statement (the default mode) is planned for its own values whatever the setting says, so `force_custom_plan` there only made PostgreSQL replan the foreign-key check of every inserted row: `createMany` of 1000 rows took 20.3 ms with it and 16.2 ms without (adapter-pg, which sends no setting, 17.1 ms). With named statements the default stays `force_custom_plan`, so a named statement never switches to a generic plan after five executions.
42
44
 
43
45
  `planCacheMode` and `statementTimeout` merge into one `options` startup parameter, with adapter settings taking precedence over matching URL settings. Other URL settings are preserved. bun:sql forwards unrecognised URL parameters to the server, which rejects a client-side libpq option. The adapter therefore takes libpq's `connect_timeout` (whole seconds) out of the URL and uses it as `connectionTimeout`, so a URL written for node-postgres or `psql` connects here too; an explicit `connectionTimeout` option wins. Other client-side libpq options must not go in the URL. (The same forwarding is how a server setting reaches every connection: `?jit=off` on the URL disables JIT compilation for the pool — see `docs/dialect-notes.md` "PostgreSQL JIT and statistics".)
44
46
 
@@ -56,6 +58,7 @@ By default the adapter runs bun:sql with `prepare: false`: every statement is an
56
58
  - `int4[]` and `float4[]` values with a NULL element or more than one dimension are refused by bun:sql (`ERR_POSTGRES_NULLS_IN_ARRAY_NOT_SUPPORTED_YET`, `ERR_POSTGRES_MULTIDIMENSIONAL_ARRAY_NOT_SUPPORTED_YET`).
57
59
  - A string bound to a raw `::jsonb` slot is JSON-encoded again (see "Raw parameters").
58
60
  - A plain object bound to a raw slot that is not `json`/`jsonb` (for example `$1::text`) arrives as `[object Object]`; the default mode and node-postgres send its `JSON.stringify` text.
61
+ - Named statements live on the **backend** connection, and bun:sql chooses their names itself: the collision-resistant, content-addressed names of `@vibeorm/adapter-pg` do not apply here. Supported setups are a direct connection, session pooling, and PgBouncer 1.21 or later in transaction mode with `max_prepared_statements` above 0 (PgBouncer then prepares each statement on the backend it links the client to). Behind any other transaction-mode pooler (Supavisor, Neon's pooler, PgBouncer before 1.21 or with `max_prepared_statements = 0`) a connection can reach a backend that does not hold its names, or holds another client's statement under the same name; keep the default unnamed mode there. In every setup, a statement prepared before a migration creates a same-named table earlier in the unchanged `search_path` keeps reading the old table until the pool is replaced.
59
62
 
60
63
  ## Raw parameters
61
64
 
@@ -104,6 +107,8 @@ Every top-level `transaction()`, with or without options, runs on a reserved con
104
107
 
105
108
  Nested transactions become savepoints: the adapter issues `SAVEPOINT` / `RELEASE SAVEPOINT` / `ROLLBACK TO SAVEPOINT` SQL by hand on the reserved connection, with a name counter shared across the whole top-level transaction.
106
109
 
110
+ With `preparedStatements: true`, the array form `$transaction([...])` sends its operations in bursts, as on adapter-pg: after a count-only write sent as one statement (`createMany`, `updateMany`, `deleteMany`, `upsertMany`), the next operation's first statement goes out right behind it, before its reply. `$transaction([deleteMany, createMany, updateMany])` costs 3 round trips instead of 5 (BEGIN, the three statements, COMMIT); `[updateMany × N]` costs 3 instead of N + 2. `BEGIN` is still confirmed before the first write (bun:sql ends every query with its own Sync, so a write sent behind a failed BEGIN would commit on its own). When a statement of the burst fails on the server, the statements already sent behind it reach a transaction that is already aborted: PostgreSQL refuses them without running them (SQLSTATE `25P02`, reported as the aborted-transaction refusal naming the first failure), so nothing they would do happens — no row, no trigger, no sequence value. A statement whose failure bun:sql may raise before sending it (more than 65,535 parameters, a JS array, an invalid `Date` or one outside the years 1–9999, a document object) and one without bound values keep their own round trip instead. Not used in the default unnamed mode (bun:sql does not pipeline unnamed statements), under a `deadline` or a `timeout`, for an array inside a transaction, or with an `onQuery` / `$on("query")` listener. Results, error codes and meta, and what commits are the same as one operation after another; the timing differences the runtime names for bursts (an operation's arguments and JavaScript defaults are read up to one round trip earlier) apply here too.
111
+
107
112
  Nested handles share the root budget and expire when their own callback finishes. Deadline-bearing statements are serialized on the connection, so each checks the remaining time after earlier work completes. Server-cancellation mode installs a fresh `statement_timeout` before each adapter statement and before COMMIT. This does not cancel JavaScript callbacks, network waits or pool acquisition. Trusted raw SQL can change server settings, and a multi-command script applies PostgreSQL's timeout separately to its commands; it is not a hard wall-clock limit for the whole script. Use individual adapter calls when the total deadline must be checked between commands.
108
113
 
109
114
  If native savepoint recovery cannot be confirmed, the whole transaction is poisoned. Catching that error cannot permit further statements or a successful root commit. A lost COMMIT reply throws `VIBE_TRANSACTION` with `meta.outcome: "unknown"`. So does a COMMIT on a connection that was already dead before it (for example a backend terminated while the callback was still running): bun:sql gives no signal that tells "refused before sending" from "lost in flight", so this adapter cannot report that case as not committed, where adapter-pg can. When the callback fails and the cleanup ROLLBACK fails too (for example the backend was terminated), COMMIT was never sent: the callback's own error is thrown, like node-postgres, the transaction is not committed, and `transactionOutcomeOf({ error })` from `@vibeorm/runtime` reports `{ commit: "not-committed", commitSent: false, rollback: "failed", connection: "discarded" }`; a later use of the handle reports `meta.outcome: "not-committed"`. A deadline that refuses COMMIT stays the deadline error in that case too. No query or transaction callback is replayed. A reserved connection whose root rollback fails is closed rather than returned to the pool. A COMMIT the server answers with an error (a deferred unique or foreign-key constraint, a serialization failure) is a definite rollback and throws that error's own code, for example `VIBE_UNIQUE_VIOLATION`, exactly like node-postgres.
@@ -8,4 +8,13 @@
8
8
  export declare function refuseUnsupportedBun(params: {
9
9
  version: string;
10
10
  }): void;
11
+ /**
12
+ * Whether this Bun's `unsafe(text, values)` makes a NAMED statement on a
13
+ * `prepare: true` instance ({@link NAMED_UNSAFE_BUN_VERSION} and newer), so
14
+ * named mode can bind an ORM statement by `$n` instead of through a synthetic
15
+ * tagged template (B-04).
16
+ */
17
+ export declare function namedUnsafeBinds(params: {
18
+ version: string;
19
+ }): boolean;
11
20
  //# sourceMappingURL=bun-version.d.ts.map
package/dist/config.d.ts CHANGED
@@ -5,6 +5,14 @@
5
5
  * `Invalid Date`; 1.4.1, 1.4.2 and 1.4.3 pass the same probes.
6
6
  */
7
7
  export declare const MINIMUM_BUN_VERSION: string;
8
+ /**
9
+ * Oldest Bun on which `sql.unsafe(text, values)` on a `prepare: true` instance
10
+ * was OBSERVED to create a NAMED statement and pipeline it like a tagged
11
+ * template (performance audit round 2, B-04: wire capture on 1.4.3,
12
+ * `Parse name="P…"`, then `B E H S` warm). Older supported versions keep the
13
+ * synthetic templates: their `unsafe` behaviour was never measured.
14
+ */
15
+ export declare const NAMED_UNSAFE_BUN_VERSION: string;
8
16
  /**
9
17
  * PostgreSQL's limit on bound parameters in one statement (the Bind message
10
18
  * carries a 16-bit count).
@@ -14,12 +14,32 @@
14
14
  * hands its seconds to bun:sql's `connectionTimeout` constructor option.
15
15
  */
16
16
  /**
17
- * PostgreSQL plan-cache behaviour for the implicit prepared statements bun:sql
18
- * creates. `force_custom_plan` replans with the real parameter values (≈0.1 ms
19
- * per query) and keeps index selection optimal on range/LIKE/skewed filters —
20
- * `auto` lets PostgreSQL switch to a generic plan after ~5 executions.
17
+ * PostgreSQL plan-cache behaviour for every plan the server caches on the
18
+ * connection: the NAMED statements bun:sql keeps with `preparedStatements:
19
+ * true`, and the SPI plans of foreign-key checks, triggers and PL/pgSQL
20
+ * functions in every mode. `force_custom_plan` replans with the real parameter
21
+ * values (≈0.1 ms per query) and keeps index selection optimal on
22
+ * range/LIKE/skewed filters — `auto` lets PostgreSQL switch to a generic plan
23
+ * after ~5 executions. An unnamed statement (the default mode) is planned for
24
+ * its own values whatever this says.
21
25
  */
22
26
  export type PlanCacheMode = "auto" | "force_custom_plan" | "force_generic_plan";
27
+ /**
28
+ * The `plan_cache_mode` a connection gets when the caller sets none
29
+ * (performance audit round 2, B-01).
30
+ *
31
+ * - Unnamed statements (the default): `auto`. Every ORM statement is re-parsed
32
+ * and gets a custom plan anyway, so `force_custom_plan` changed only the SPI
33
+ * plans — it replanned the foreign-key check of every inserted row (measured:
34
+ * `createMany` of 1000 rows 20.3 → 16.2 ms, the same as adapter-pg, which
35
+ * sends no setting).
36
+ * - Named statements (`preparedStatements: true`): `force_custom_plan`, so a
37
+ * named statement never switches to a generic plan after five executions
38
+ * (reads with skewed filters were not measured under `auto`).
39
+ */
40
+ export declare function defaultPlanCacheMode(params: {
41
+ preparedStatements: boolean;
42
+ }): PlanCacheMode;
23
43
  /**
24
44
  * Build the `options` startup string, or `undefined` when nothing needs setting.
25
45
  *
package/dist/index.d.ts CHANGED
@@ -49,12 +49,17 @@ export type BunAdapterOptions = {
49
49
  * behave the same); `int4[]`/`float4[]` values with NULL elements or more
50
50
  * than one dimension are refused; a JSON text bound into a raw `::jsonb`
51
51
  * slot is stored as a JSON string. ORM-path queries also run as tagged
52
- * templates.
52
+ * templates — on Bun 1.4.3 and newer only those whose placeholders are not
53
+ * `$1 … $n` in order (the rest bind by `$n`, still named).
53
54
  */
54
55
  readonly preparedStatements?: boolean;
55
56
  /** Maximum entries in the synthetic template cache (default 1000, LRU). */
56
57
  readonly stmtCacheMax?: number;
57
- /** PostgreSQL `plan_cache_mode` for every connection (default `force_custom_plan`). */
58
+ /**
59
+ * PostgreSQL `plan_cache_mode` for every connection. Default: `auto` with
60
+ * unnamed statements (nothing is sent; the server's own default), and
61
+ * `force_custom_plan` with `preparedStatements: true`.
62
+ */
58
63
  readonly planCacheMode?: PlanCacheMode;
59
64
  };
60
65
  /**
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ function createBunSql(params) {
7
7
 
8
8
  // packages/adapter-bun/src/config.ts
9
9
  var MINIMUM_BUN_VERSION = "1.4.1";
10
+ var NAMED_UNSAFE_BUN_VERSION = "1.4.3";
10
11
  var MAX_BIND_PARAMETERS = 65535;
11
12
  var SESSION_CONNECTION = Object.freeze({
12
13
  max: 1,
@@ -24,6 +25,9 @@ function refuseUnsupportedBun(params) {
24
25
  meta: { bunVersion: params.version, minimumBunVersion: MINIMUM_BUN_VERSION }
25
26
  });
26
27
  }
28
+ function namedUnsafeBinds(params) {
29
+ return Bun.semver.satisfies(params.version, `>=${NAMED_UNSAFE_BUN_VERSION}`);
30
+ }
27
31
 
28
32
  // packages/adapter-bun/src/index.ts
29
33
  import { postgresDialect, renderDiagnostic } from "@vibeorm/sql";
@@ -41,7 +45,11 @@ import {
41
45
  transactionLifecycleRefusal,
42
46
  createSavepointScope,
43
47
  engineStatementBudgetMs,
48
+ findRefusedSetting,
44
49
  markTransactionAborted,
50
+ readTransactionSettings,
51
+ renderTransactionSettings,
52
+ transactionSettingRefusedError,
45
53
  runNestedSavepoint,
46
54
  runRootScope,
47
55
  scopeTurn,
@@ -55,6 +63,9 @@ import { VibeError as VibeError7 } from "@vibeorm/schema";
55
63
 
56
64
  // packages/adapter-bun/src/connection-url.ts
57
65
  import { VibeError as VibeError2 } from "@vibeorm/schema";
66
+ function defaultPlanCacheMode(params) {
67
+ return params.preparedStatements ? "force_custom_plan" : "auto";
68
+ }
58
69
  function buildStartupOptions(params) {
59
70
  const { planCacheMode, statementTimeout } = params;
60
71
  const parts = [];
@@ -450,6 +461,44 @@ import {
450
461
  var ignore = () => {
451
462
  return;
452
463
  };
464
+ var LANE_GO = Object.freeze({ kind: "go" });
465
+ var LANE_CLOSED = Object.freeze({ kind: "closed" });
466
+ function serverAnswered(params) {
467
+ const { values } = params;
468
+ if (values.length > MAX_BIND_PARAMETERS)
469
+ return false;
470
+ for (const value of values) {
471
+ if (value !== null && typeof value !== "string" && !(value instanceof Uint8Array))
472
+ return false;
473
+ }
474
+ return true;
475
+ }
476
+ function predecessorClosedError() {
477
+ return new VibeError7({
478
+ code: "VIBE_TRANSACTION",
479
+ message: "pipeline(): an earlier lane of this ordered scope closed without issuing its statement, so this statement was not sent " + "(the operation before it failed before it reached the database)",
480
+ meta: { reason: "pipeline-predecessor-closed" }
481
+ });
482
+ }
483
+ function orderedLaneMisuse(params) {
484
+ return new VibeError7({ code: "VIBE_INTERNAL", message: `pipeline(): ${params.message}`, meta: { reason: "pipeline-ordered-lane" } });
485
+ }
486
+ function executorFor(params) {
487
+ const { dispatch, effect, guard, lane } = params;
488
+ return Object.assign((strings, ...values) => dispatch({
489
+ effect,
490
+ guard,
491
+ extended: true,
492
+ ...lane === true ? { pipelinable: () => serverAnswered({ values }) } : {},
493
+ send: (connection) => connection(strings, ...values)
494
+ }), { unsafe: (text, values) => dispatch({
495
+ effect,
496
+ guard,
497
+ extended: values !== undefined && values.length > 0,
498
+ ...lane === true ? { pipelinable: () => values !== undefined && values.length > 0 && serverAnswered({ values }) } : {},
499
+ send: (connection) => connection.unsafe(text, values)
500
+ }) });
501
+ }
453
502
  var DIALECT = "postgres";
454
503
  var PROVIDER = "postgresql";
455
504
  var BUDGETS = Object.freeze({
@@ -461,6 +510,7 @@ var BUDGETS = Object.freeze({
461
510
  var WIRE_TEXT = Object.freeze({ dateTime: "native", json: "text", numbers: "native" });
462
511
  var WIRE_PARSED = Object.freeze({ dateTime: "native", json: "parsed", numbers: "native" });
463
512
  var ROUND_TRIPS = "network";
513
+ var READ_SNAPSHOT = Object.freeze({ isolationLevel: "RepeatableRead", accessMode: "readOnly" });
464
514
  function requireUrl(params) {
465
515
  const url = params.options?.url;
466
516
  if (typeof url === "string" && url.trim() !== "")
@@ -474,6 +524,8 @@ function requireUrl(params) {
474
524
  function bunAdapter(options) {
475
525
  refuseUnsupportedBun({ version: Bun.version });
476
526
  const usePrepared = options?.preparedStatements ?? false;
527
+ const pipelining = usePrepared ? "batched" : "ordered";
528
+ const namedUnsafe = usePrepared && namedUnsafeBinds({ version: Bun.version });
477
529
  const address = takeConnectTimeout({ url: requireUrl({ options }) });
478
530
  const templates = createTemplateCache({ max: options?.stmtCacheMax ?? 1000 });
479
531
  let activeWire = WIRE_TEXT;
@@ -551,7 +603,14 @@ function bunAdapter(options) {
551
603
  });
552
604
  if (ms !== null)
553
605
  steps.push(step(() => controlQuery({ connection: reserved, text: STATEMENT_BOUND_TEXT, values: [String(ms)] })));
554
- const statement = step(() => send.send(reserved));
606
+ let handed = false;
607
+ const statement = step(() => {
608
+ const query = send.send(reserved);
609
+ handed = true;
610
+ return query;
611
+ });
612
+ if (handed)
613
+ send.onSent?.();
555
614
  steps.push(statement);
556
615
  return Promise.allSettled(steps).then((settled) => {
557
616
  const failed = settled.find((outcome) => outcome.status === "rejected");
@@ -587,10 +646,126 @@ function bunAdapter(options) {
587
646
  return enqueue(send);
588
647
  return new Promise((resolve) => resolve(sendNow(send)));
589
648
  };
649
+ const refusalBehind = (cause) => {
650
+ if (openingFailure !== undefined)
651
+ return transactionAbortedError({ cause: openingFailure });
652
+ if (scope.state.poisoned !== null)
653
+ return scope.state.poisoned;
654
+ return transactionAbortedError({ cause: scope.state.aborted?.cause ?? cause });
655
+ };
656
+ const newLane = (orderedScope, index) => {
657
+ let resolveRelease = ignore;
658
+ const release = new Promise((resolve) => {
659
+ resolveRelease = resolve;
660
+ });
661
+ let settled = false;
662
+ return {
663
+ scope: orderedScope,
664
+ index,
665
+ open: true,
666
+ issued: 0,
667
+ followed: false,
668
+ release,
669
+ settle: (outcome) => {
670
+ if (settled)
671
+ return;
672
+ settled = true;
673
+ resolveRelease(outcome);
674
+ }
675
+ };
676
+ };
677
+ const laneDispatch = (lane, send) => {
678
+ if (lane.followed && lane.issued > 0) {
679
+ return Promise.reject(orderedLaneMisuse({ message: "a lane that has a follower may issue ONE statement" }));
680
+ }
681
+ const first = lane.issued === 0;
682
+ lane.issued += 1;
683
+ const go = (before) => {
684
+ if (before.kind === "closed") {
685
+ if (first)
686
+ lane.settle(LANE_CLOSED);
687
+ return Promise.reject(predecessorClosedError());
688
+ }
689
+ const failed = before.kind === "failed" ? { cause: before.cause } : lane.scope.failed;
690
+ if (failed !== undefined) {
691
+ if (first)
692
+ lane.settle({ kind: "failed", cause: failed.cause });
693
+ return Promise.reject(refusalBehind(failed.cause));
694
+ }
695
+ const pipelinable = first && send.pipelinable?.() === true;
696
+ return dispatch({
697
+ ...send,
698
+ onSent: () => {
699
+ send.onSent?.();
700
+ if (pipelinable)
701
+ lane.settle(LANE_GO);
702
+ }
703
+ }).then((value) => {
704
+ if (first)
705
+ lane.settle(LANE_GO);
706
+ return value;
707
+ }, (error) => {
708
+ lane.scope.failed ??= { cause: error };
709
+ if (first)
710
+ lane.settle({ kind: "failed", cause: error });
711
+ throw error;
712
+ });
713
+ };
714
+ const before = lane.scope.lanes[lane.index - 1];
715
+ return before === undefined ? go(LANE_GO) : before.release.then(go);
716
+ };
717
+ const ordered = {
718
+ open: (count) => {
719
+ const orderedScope = { lanes: [] };
720
+ for (let index = 0;index < count; index++)
721
+ orderedScope.lanes.push(newLane(orderedScope, index));
722
+ return [...orderedScope.lanes];
723
+ },
724
+ follow: (lane) => {
725
+ if (!lane.open)
726
+ throw orderedLaneMisuse({ message: "follow() on a closed lane" });
727
+ if (lane.followed || lane.scope.lanes.at(-1) !== lane)
728
+ throw orderedLaneMisuse({ message: "follow() opens one lane after the LAST lane of its scope" });
729
+ if (lane.issued > 0)
730
+ throw orderedLaneMisuse({ message: "follow() must come before the lane issues its statement" });
731
+ lane.followed = true;
732
+ const next = newLane(lane.scope, lane.scope.lanes.length);
733
+ lane.scope.lanes.push(next);
734
+ return next;
735
+ },
736
+ close: (lane) => {
737
+ if (!lane.open)
738
+ return;
739
+ lane.open = false;
740
+ if (lane.issued === 0)
741
+ lane.settle(LANE_CLOSED);
742
+ },
743
+ control: (lane) => {
744
+ const laneSend = (send) => send.cleanup === true || !lane.open ? dispatch(send) : laneDispatch(lane, send);
745
+ return {
746
+ deferred,
747
+ dispatch: laneSend,
748
+ executor: ({ effect, guard }) => executorFor({ dispatch: laneSend, effect, guard, lane: true }),
749
+ ordered,
750
+ turn: () => {
751
+ const before = lane.scope.lanes[lane.index - 1];
752
+ if (!lane.open || before === undefined)
753
+ return Promise.resolve();
754
+ return before.release.then((release) => {
755
+ if (release.kind === "closed")
756
+ throw predecessorClosedError();
757
+ if (release.kind === "failed")
758
+ throw refusalBehind(release.cause);
759
+ });
760
+ }
761
+ };
762
+ }
763
+ };
590
764
  return {
591
765
  deferred,
592
766
  dispatch,
593
- executor: ({ effect, guard }) => Object.assign((strings, ...values) => dispatch({ effect, guard, extended: true, send: (connection) => connection(strings, ...values) }), { unsafe: (text, values) => dispatch({ effect, guard, extended: values !== undefined && values.length > 0, send: (connection) => connection.unsafe(text, values) }) })
767
+ executor: ({ effect, guard }) => executorFor({ dispatch, effect, guard }),
768
+ ordered
594
769
  };
595
770
  }
596
771
  let rawSession = null;
@@ -602,7 +777,7 @@ function bunAdapter(options) {
602
777
  sqlOptions.connectionTimeout = address.seconds;
603
778
  }
604
779
  const startupOptions = buildStartupOptions({
605
- planCacheMode: options?.planCacheMode ?? "force_custom_plan",
780
+ planCacheMode: options?.planCacheMode ?? defaultPlanCacheMode({ preparedStatements: usePrepared }),
606
781
  statementTimeout: options?.statementTimeout
607
782
  });
608
783
  const url = startupOptions === undefined ? address.url : applyStartupOptions({ url: address.url, startupOptions });
@@ -667,8 +842,9 @@ function bunAdapter(options) {
667
842
  const values = serializeParams({ values: params.values, namedStatements: usePrepared });
668
843
  if (usePrepared) {
669
844
  const prepared = templates.getTemplate({ text: params.text });
670
- const bound = prepared.identityOrder && prepared.indices.length === values.length ? values : bindTemplateValues({ text: params.text, indices: prepared.indices, values });
671
- const result = bound.length > MAX_BIND_PARAMETERS ? await runMapped(() => params.source.unsafe(params.text, values)) : await runMapped(() => params.source(prepared.template, ...bound));
845
+ const identity = prepared.identityOrder && prepared.indices.length === values.length;
846
+ const bound = identity ? values : bindTemplateValues({ text: params.text, indices: prepared.indices, values });
847
+ const result = bound.length > MAX_BIND_PARAMETERS || namedUnsafe && identity && values.length > 0 ? await runMapped(() => params.source.unsafe(params.text, values)) : await runMapped(() => params.source(prepared.template, ...bound));
672
848
  observeResult({ scope: params.scope, effect: params.effect, result });
673
849
  return plainRows({ rows: finalRows({ result }) });
674
850
  }
@@ -701,6 +877,10 @@ function bunAdapter(options) {
701
877
  refuseNestedTransactionOptions({ options: nestedOptions, provider: PROVIDER });
702
878
  assertHandle();
703
879
  budget?.assertUsable({ stage: "nested" });
880
+ if (reservedControl.turn !== undefined) {
881
+ await reservedControl.turn();
882
+ assertHandle();
883
+ }
704
884
  const savepointControl = (statement, cleanup) => {
705
885
  if (reservedControl.deferred.routeSavepoint({ text: statement }) !== "send")
706
886
  return;
@@ -730,11 +910,14 @@ function bunAdapter(options) {
730
910
  validateTransactionDeadline({
731
911
  options: transactionOptions,
732
912
  support: BUDGETS.transactionDeadline,
733
- provider: PROVIDER
913
+ provider: PROVIDER,
914
+ settings: "transaction-local"
734
915
  });
735
916
  const readOnly = readOnlyRequested({ options: transactionOptions, provider: PROVIDER });
736
917
  const openingOptions = { isolationLevel: transactionOptions?.isolationLevel, readOnly };
737
918
  const eagerOpen = transactionOptions?.timeout === undefined ? null : openTransactionStatement({ ...openingOptions, timeout: transactionOptions.timeout });
919
+ const settings = readTransactionSettings({ settings: transactionOptions?.settings, provider: PROVIDER });
920
+ const settingsStatement = settings.length === 0 ? undefined : renderTransactionSettings({ settings });
738
921
  const reserved = await runMapped(() => pool.reserve());
739
922
  const budget = startTransactionBudget({ options: transactionOptions, provider: PROVIDER });
740
923
  const txScope = createSavepointScope();
@@ -742,19 +925,41 @@ function bunAdapter(options) {
742
925
  reserved,
743
926
  budget,
744
927
  scope: txScope,
745
- opening: eagerOpen === null ? beginStatement(openingOptions) : null
928
+ opening: eagerOpen === null && settingsStatement === undefined ? beginStatement(openingOptions) : null
746
929
  });
747
930
  const commit = { progress: "not-sent" };
748
931
  let discard = false;
932
+ let openingRollback;
933
+ const openWithSettings = async (statement) => {
934
+ await (eagerOpen === null ? controlQuery({ connection: reserved, text: beginStatement(openingOptions) }) : reserved.unsafe(eagerOpen)).then(undefined, (error) => {
935
+ throw mapBunDriverError({ error });
936
+ });
937
+ const failed = await controlQuery({ connection: reserved, text: statement.text, values: statement.values }).then(() => {
938
+ return;
939
+ }, (error) => ({ error }));
940
+ if (failed === undefined)
941
+ return;
942
+ const cause = mapBunDriverError({ error: failed.error });
943
+ if (typeof cause.meta.sqlstate !== "string")
944
+ throw cause;
945
+ openingRollback = await reserved.unsafe("ROLLBACK").then(() => "acknowledged", () => "failed");
946
+ if (openingRollback === "failed")
947
+ discard = true;
948
+ const setting = findRefusedSetting({ settings, cause });
949
+ throw transactionSettingRefusedError({ provider: PROVIDER, settings, setting, cause });
950
+ };
749
951
  try {
750
- if (eagerOpen !== null)
952
+ if (settingsStatement !== undefined)
953
+ await openWithSettings(settingsStatement);
954
+ else if (eagerOpen !== null)
751
955
  await runMapped(() => reserved.unsafe(eagerOpen));
752
956
  const txAdapter = createAdapter({
753
957
  source: reserved,
754
958
  parentMode: "tx",
755
959
  scope: txScope,
756
960
  budget,
757
- control
961
+ control,
962
+ ordered: usePrepared && budget.totalMs === null && eagerOpen === null
758
963
  });
759
964
  const result = await runRootScope({ scope: txScope, body: () => fn(txAdapter) });
760
965
  budget.assertUsable({ stage: "commit" });
@@ -784,7 +989,9 @@ function bunAdapter(options) {
784
989
  commit.progress = isConnectionLoss({ error }) ? "unanswered" : "answered";
785
990
  let rollback = "not-needed";
786
991
  try {
787
- if (control.deferred.opened()) {
992
+ if (openingRollback !== undefined)
993
+ rollback = openingRollback;
994
+ else if (control.deferred.opened()) {
788
995
  await control.dispatch({ extended: false, cleanup: true, send: (connection) => connection.unsafe("ROLLBACK") });
789
996
  rollback = "acknowledged";
790
997
  }
@@ -809,12 +1016,36 @@ function bunAdapter(options) {
809
1016
  reserved.release();
810
1017
  }
811
1018
  }
812
- return {
1019
+ const handle = {
813
1020
  dialect: DIALECT,
814
1021
  provider: PROVIDER,
815
1022
  budgets: BUDGETS,
816
1023
  readCancellation: "before-dispatch",
817
1024
  roundTrips: ROUND_TRIPS,
1025
+ readSnapshot: READ_SNAPSHOT,
1026
+ pipelining,
1027
+ ...params.ordered !== true || control === undefined ? {} : {
1028
+ orderedPipeline: true,
1029
+ pipeline: ({ lanes: count, ordered }) => {
1030
+ assertHandle();
1031
+ if (!Number.isSafeInteger(count) || count < 1) {
1032
+ throw new VibeError7({ code: "VIBE_VALIDATION", message: "pipeline() needs a positive whole number of lanes", meta: { lanes: count } });
1033
+ }
1034
+ if (ordered !== true)
1035
+ return Array.from({ length: count }, () => ({ adapter: handle, close: ignore }));
1036
+ const laneHandle = (lane) => ({
1037
+ adapter: createAdapter({ source, parentMode: "tx", scope, budget, control: control.ordered.control(lane) }),
1038
+ close: () => {
1039
+ control.ordered.close(lane);
1040
+ },
1041
+ follow: () => {
1042
+ assertHandle();
1043
+ return laneHandle(control.ordered.follow(lane));
1044
+ }
1045
+ });
1046
+ return control.ordered.open(count).map(laneHandle);
1047
+ }
1048
+ },
818
1049
  ...parentMode === "pool" ? {} : { rowChanges: () => {
819
1050
  assertHandle();
820
1051
  return readRowChanges({ scope });
@@ -880,6 +1111,7 @@ function bunAdapter(options) {
880
1111
  return toPgArrayLiteral(values);
881
1112
  }
882
1113
  };
1114
+ return handle;
883
1115
  }
884
1116
  function poolAdapter() {
885
1117
  return createAdapter({
@@ -976,7 +1208,10 @@ function bunAdapter(options) {
976
1208
  budgets: BUDGETS,
977
1209
  readCancellation: "before-dispatch",
978
1210
  roundTrips: ROUND_TRIPS,
1211
+ readSnapshot: READ_SNAPSHOT,
1212
+ pipelining,
979
1213
  transactionOutcome: "reported",
1214
+ transactionSettings: "transaction-local",
980
1215
  get wire() {
981
1216
  return activeWire;
982
1217
  },
@@ -1072,4 +1307,4 @@ export {
1072
1307
  validateTransactionDeadline2 as validateTransactionDeadline
1073
1308
  };
1074
1309
 
1075
- //# debugId=192DED291B6A505C64756E2164756E21
1310
+ //# debugId=86641AB4B943804564756E2164756E21
package/dist/index.js.map CHANGED
@@ -3,16 +3,16 @@
3
3
  "sources": ["../src/driver.ts", "../src/config.ts", "../src/bun-version.ts", "../src/index.ts", "../src/connection-url.ts", "../src/errors.ts", "../src/params.ts", "../src/template-cache.ts", "../src/transaction-sql.ts"],
4
4
  "sourcesContent": [
5
5
  "import { SQL } from \"bun\";\n\n/**\n * Internal constructor boundary; keeps the driver double out of the public\n * adapter API. Always the URL form: bun:sql's options-only form fills the\n * whole connection from the environment.\n */\nexport function createBunSql(params: { url: string; options: Record<string, unknown> }): SQL {\n return new SQL(params.url, params.options);\n}\n",
6
- "/**\n * Oldest Bun whose bun:sql the adapter accepts. Older releases — measured on\n * 1.3.14 with every adapter fix in place — hang after `COPY … TO STDOUT`,\n * read zone-less timestamps as host-local time and turn ±infinity dates into\n * `Invalid Date`; 1.4.1, 1.4.2 and 1.4.3 pass the same probes.\n */\nexport const MINIMUM_BUN_VERSION: string = \"1.4.1\";\n\n/**\n * PostgreSQL's limit on bound parameters in one statement (the Bind message\n * carries a 16-bit count).\n */\nexport const MAX_BIND_PARAMETERS: number = 65_535;\n\n/** Migration-only driver instance; never force-close the application's pool. */\nexport const SESSION_CONNECTION: Readonly<{ max: number; closeGraceSeconds: number }> = Object.freeze({\n max: 1,\n // Bun 1.3 treats timeout: 0 as unbounded. A positive millisecond closes only\n // this private instance after the session gate has drained dispatched work.\n closeGraceSeconds: 0.001,\n});\n",
7
- "import { VibeError } from \"@vibeorm/schema\";\nimport { MINIMUM_BUN_VERSION } from \"./config.ts\";\n\n/**\n * Refuse a Bun whose bun:sql the adapter does not support (see\n * {@link MINIMUM_BUN_VERSION}), at construction — before any statement can\n * meet one of that driver's known data bugs.\n *\n * @throws VibeError `VIBE_CONFIG`.\n */\nexport function refuseUnsupportedBun(params: { version: string }): void {\n if (Bun.semver.satisfies(params.version, `>=${MINIMUM_BUN_VERSION}`)) return;\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message:\n `@vibeorm/adapter-bun requires Bun ${MINIMUM_BUN_VERSION} or newer (running ${params.version}): older bun:sql ` +\n \"releases hang after COPY, read timestamps without a time zone in host-local time and turn infinity dates into Invalid Date. \" +\n \"Upgrade Bun, or use @vibeorm/adapter-pg.\",\n meta: { bunVersion: params.version, minimumBunVersion: MINIMUM_BUN_VERSION },\n });\n}\n",
8
- "/**\n * @vibeorm/adapter-bun — bun:sql (PostgreSQL) adapter for VibeORM v2.\n *\n * Uses Bun's built-in SQL driver and its internal connection pool. Owns\n * optional prepared statements (synthetic tagged templates), transactions\n * (nested → savepoints), array-literal parameter formatting and driver-error\n * mapping. Only `VibeError` ever escapes.\n */\n\nimport { createBunSql } from \"./driver.ts\";\nimport { MAX_BIND_PARAMETERS, SESSION_CONNECTION } from \"./config.ts\";\nimport { refuseUnsupportedBun } from \"./bun-version.ts\";\nimport { postgresDialect, renderDiagnostic } from \"@vibeorm/sql\";\nimport type {\n AdapterBudgetSupport,\n DatabaseAdapter,\n QueryResult,\n RowChangeCount,\n StatementEffect,\n TransactionOptions,\n WireFidelity,\n} from \"@vibeorm/runtime\";\nimport {\n assertReadExecution,\n runReadExecution,\n abortTransactionOnServerFailure,\n createDeferredControl,\n type DeferredControl,\n observeRowChanges,\n readRowChanges,\n statementRowChanges,\n createAdapterLifecycleGate,\n runPinnedSession,\n runShutdownCleanup,\n transactionLifecycleRefusal,\n createSavepointScope,\n type CommitProgress,\n engineStatementBudgetMs,\n markTransactionAborted,\n type RollbackOutcome,\n runNestedSavepoint,\n runRootScope,\n type SavepointScope,\n scopeTurn,\n settleFailedTransaction,\n startTransactionBudget,\n type TransactionBudget,\n transactionAbortedError,\n validateTransactionDeadline,\n readOnlyRequested,\n} from \"@vibeorm/runtime/adapter-kit\";\nimport { VibeError, type Dialect, type Provider } from \"@vibeorm/schema\";\nimport { applyStartupOptions, buildStartupOptions, takeConnectTimeout, type PlanCacheMode } from \"./connection-url.ts\";\nimport { mapBunDriverError, runMapped } from \"./errors.ts\";\nimport { serializeParams, serializeParamsRaw, toPgArrayLiteral } from \"./params.ts\";\nimport { bindTemplateValues, createTemplateCache } from \"./template-cache.ts\";\nimport {\n beginStatement,\n openTransactionStatement,\n classifyRawTransactionControl,\n refuseNestedTransactionOptions,\n STATEMENT_BOUND_TEXT,\n} from \"./transaction-sql.ts\";\n\n// ─── Minimal bun:sql surface ──────────────────────────────────────\n\n/**\n * What bun:sql resolves a query to: the row array, with driver metadata\n * (`count`, `command`) attached as properties.\n */\ntype BunRows = Record<string, unknown>[] & { count?: number; affectedRows?: number; command?: string };\n\ntype BunResults = BunRows | BunRows[] | null;\n\n/** Anything that executes SQL through bun:sql. */\ntype BunExecutor = {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<BunResults>;\n unsafe(text: string, values?: unknown[]): Promise<BunResults>;\n};\n\n/**\n * A connection checked out with `sql.reserve()` — must be released. Every\n * top-level transaction runs on one (round-trip EPIC 6): BEGIN, COMMIT and\n * savepoints are sent by hand, so they can ride with the next statement.\n */\ntype BunReserved = BunExecutor & { release(): void; close(): Promise<void> };\n\n/** The pool-level bun:sql client. */\ntype BunInstance = BunExecutor & {\n reserve(): Promise<BunReserved>;\n close(options?: { timeout: number }): Promise<void>;\n};\n\n/** Any bun:sql handle the adapter can be built on top of. */\ntype BunSource = BunInstance | BunReserved;\n\n/**\n * Whether a handle is the pool (can open a real transaction) or is already\n * inside one (must nest through savepoints).\n */\ntype ParentMode = \"pool\" | \"tx\";\n\n/**\n * One statement or control text for the reserved connection of a transaction\n * (round-trip EPIC 6, pipelining).\n */\ntype ReservedSend<T> = {\n /** The driver call, made on the reserved connection when its turn comes. Unmapped. */\n readonly send: (connection: BunExecutor) => Promise<T>;\n /** Sent through the extended protocol (a tagged template, or ≥1 bound value): bun:sql may pipeline it. */\n readonly extended: boolean;\n readonly effect?: StatementEffect | undefined;\n readonly stage?: \"statement\" | \"commit\";\n /** Rollback cleanup: takes no pending control, gets no bound and is never refused. */\n readonly cleanup?: boolean;\n /** Handle checks run right before sending (lifetime, poison). */\n readonly guard?: () => void;\n /**\n * Control steps ALREADY SENT right behind an awaited BEGIN (a `SAVEPOINT`\n * taken with it) whose replies this statement answers for. Never texts held\n * back: a refusal of this statement's own turn must not drop a savepoint\n * the gate already counts as opened (fix lane FX-A, RV5 MJ-1).\n */\n readonly riding?: readonly Promise<unknown>[];\n};\n\n/** Every send of ONE top-level transaction on its reserved connection goes through this. */\ntype ReservedControl = {\n /** Pending BEGIN / SAVEPOINT texts of this transaction. */\n readonly deferred: DeferredControl;\n /** Send one statement, with the pending control (and the deadline bound) ahead of it. */\n readonly dispatch: <T>(params: ReservedSend<T>) => Promise<T>;\n /** A bun:sql-shaped executor whose every call is dispatched through this control. */\n readonly executor: (params: { effect?: StatementEffect | undefined; guard: () => void }) => BunExecutor;\n};\n\nconst ignore = (): void => undefined;\n\n// ─── Options ──────────────────────────────────────────────────────\n\n/** Options for {@link bunAdapter}. */\nexport type BunAdapterOptions = {\n /**\n * PostgreSQL connection URL — required. The adapter never reads\n * `DATABASE_URL` (or any other environment variable) itself, and always\n * hands bun:sql this URL, so bun's own environment lookup (`POSTGRES_URL`,\n * `DATABASE_URL`, `PGHOST`, …) never chooses the server. A database named in\n * the URL path is pinned explicitly, because bun:sql would otherwise let\n * `PGDATABASE` replace it. Give a complete URL: bun:sql fills parts the URL\n * omits (user, database, …) from the `PG*` variables.\n */\n readonly url: string;\n /** Maximum pooled connections (default 10). */\n readonly max?: number;\n /**\n * Pool-wide `statement_timeout` in milliseconds, sent as a startup parameter\n * so every connection inherits it. A per-transaction `timeout` overrides it\n * for that transaction.\n */\n readonly statementTimeout?: number;\n /**\n * Milliseconds to wait for a connection to be established. Passed to bun:sql\n * as `connectionTimeout` (which expects **seconds**; converted here). Wins\n * over a libpq `connect_timeout` in the URL, which is otherwise honoured.\n */\n readonly connectionTimeout?: number;\n /**\n * Use bun:sql's NAMED prepared statements (default false).\n *\n * Off (the default) runs every statement as an unnamed statement with text\n * results — bun:sql's `prepare: false`, the node-postgres model: values,\n * parameter typing and DDL behaviour match `@vibeorm/adapter-pg`.\n *\n * On, bun:sql keeps one named statement per SQL text per connection,\n * pipelines, and reads results in its binary format, with these driver\n * consequences (README \"Statements and values\"): a statement whose result\n * type a later DDL change alters fails with SQLSTATE 0A000 on that\n * connection until the pool is replaced (node-postgres named statements\n * behave the same); `int4[]`/`float4[]` values with NULL elements or more\n * than one dimension are refused; a JSON text bound into a raw `::jsonb`\n * slot is stored as a JSON string. ORM-path queries also run as tagged\n * templates.\n */\n readonly preparedStatements?: boolean;\n /** Maximum entries in the synthetic template cache (default 1000, LRU). */\n readonly stmtCacheMax?: number;\n /** PostgreSQL `plan_cache_mode` for every connection (default `force_custom_plan`). */\n readonly planCacheMode?: PlanCacheMode;\n};\n\n// ─── Adapter ──────────────────────────────────────────────────────\n\nconst DIALECT: Dialect = \"postgres\";\nconst PROVIDER: Provider = \"postgresql\";\n\n/**\n * bun:sql wire (board #30, live-verified on both execute paths): timestamptz\n * → `Date`, int4/float8 → numbers. (int8 arrives as a string — BigInt\n * decoding is real work and never pruned.)\n *\n * The `json` half is NOT a constant, because bun:sql's answer changed between\n * Bun versions and this package supports a range of them: on Bun 1.3.14 the\n * tagged-template path parsed json/jsonb while `sql.unsafe` did not (board\n * #34 — declaring \"parsed\" there made the runtime prune the Json decoder and\n * leak raw strings), and on Bun 1.4.1 BOTH paths parse (leaving \"text\" makes\n * the guarded decode re-parse a stored top-level JSON string: `\"123\"` becomes\n * the number 123, `\"hello\"` throws). Either constant is wrong on one of those\n * runtimes, so the adapter OBSERVES its own driver once instead of guessing —\n * see {@link probeJsonWire}. {@link WIRE_TEXT} is the conservative claim it\n * starts from; no ORM rows are returned until the probe succeeds.\n */\n/**\n * Timing budgets this adapter genuinely enforces (EPIC 6).\n *\n * - `acquireTimeout: false` — `connectionTimeout` bounds establishment only.\n * Modern Bun supports reserve({ signal }), but implicit query/begin checkout\n * and older supported Bun versions do not provide that cancellation contract.\n * - `statementTimeout: \"all-statements\"` — a real PostgreSQL server, so\n * `statement_timeout` cancels ANY over-long statement, writes included.\n * - `transactionDeadline: \"cancel-running-statements\"` — the remaining budget\n * is handed to the SERVER before each statement, so the database itself stops\n * work that would outlive the deadline.\n */\nconst BUDGETS: AdapterBudgetSupport = Object.freeze({\n acquireTimeout: false,\n statementTimeout: \"all-statements\",\n transactionDeadline: \"cancel-running-statements\",\n accessModes: Object.freeze([\"readOnly\"] as const),\n} as const);\n\nconst WIRE_TEXT: WireFidelity = Object.freeze({ dateTime: \"native\", json: \"text\", numbers: \"native\" } as const);\n\n/** The same wire, for a driver observed to hand back parsed json. */\nconst WIRE_PARSED: WireFidelity = Object.freeze({ dateTime: \"native\", json: \"parsed\", numbers: \"native\" } 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 pool and\n * transaction facades carry the same declaration.\n */\nconst ROUND_TRIPS: NonNullable<DatabaseAdapter[\"roundTrips\"]> = \"network\";\n\n/**\n * The explicit URL this adapter will use. bun:sql given no URL builds its\n * whole connection from the environment, so a missing one is refused here,\n * before any driver instance exists.\n *\n * @throws VibeError `VIBE_CONFIG` (`meta.reason: \"missing-address\"`) when `url`\n * is absent or blank. The message never echoes a value.\n */\nfunction requireUrl(params: { options: BunAdapterOptions | undefined }): string {\n const url = params.options?.url;\n if (typeof url === \"string\" && url.trim() !== \"\") return url;\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message:\n \"bunAdapter needs an explicit address: pass `url` (a PostgreSQL URL). \" +\n \"The adapter does not read DATABASE_URL, POSTGRES_URL or the PG* environment variables.\",\n meta: { adapter: \"bun\", reason: \"missing-address\" },\n });\n}\n\n/**\n * Create a VibeORM adapter backed by bun:sql.\n *\n * Requires an explicit `url`; without one the factory throws `VIBE_CONFIG`\n * before any driver instance or connection exists.\n *\n * @example\n * ```ts\n * const adapter = bunAdapter({ url: \"postgresql://app:secret@db.internal:5432/app\", max: 10 });\n * await adapter.connect();\n * const rows = await adapter.execute({ text: 'SELECT * FROM \"User\" WHERE \"id\" = $1', values: [1] });\n * ```\n */\nexport function bunAdapter(options: BunAdapterOptions): DatabaseAdapter {\n refuseUnsupportedBun({ version: Bun.version });\n const usePrepared = options?.preparedStatements ?? false;\n // The address is taken once, here: an invalid `connect_timeout` is refused\n // at construction, and nothing later re-reads the options or the environment.\n const address = takeConnectTimeout({ url: requireUrl({ options }) });\n const templates = createTemplateCache({ max: options?.stmtCacheMax ?? 1000 });\n\n /**\n * The wire claim this adapter currently makes. Starts conservative and is\n * replaced at most once, by {@link probeJsonWire}'s observation. Every handle\n * this factory builds — pool, transaction, savepoint, reserved session —\n * reads this one variable, so a transaction can never disagree with its\n * parent (the contract requires transactional adapters to carry the same\n * declaration).\n */\n let activeWire: WireFidelity = WIRE_TEXT;\n let wireSettled = false;\n let wireProbe: Promise<void> | null = null;\n\n let instance: BunInstance | null = null;\n\n // ─── Reserved-connection control (round-trip EPIC 6, pipelining) ───\n\n /**\n * Control texts (BEGIN, COMMIT, SAVEPOINT, the deadline bound) as tagged\n * templates: constant texts on the EXTENDED protocol, which bun:sql\n * pipelines once they are warm on a connection. A separate cache, so ORM\n * traffic can never evict them.\n */\n const controlTemplates = createTemplateCache({ max: 64 });\n\n function controlQuery(params: { connection: BunExecutor; text: string; values?: readonly unknown[] }): Promise<BunResults> {\n return params.connection(controlTemplates.getTemplate({ text: params.text }).template, ...(params.values ?? []));\n }\n\n /**\n * The send discipline of one top-level transaction on its reserved\n * connection:\n *\n * - The opening (`BEGIN …`) and every `SAVEPOINT` wait in `deferred` and go\n * out back to back with the next statement. A transaction whose callback\n * sends nothing sends nothing.\n * - BEGIN rides only ahead of an extended READ: bun:sql syncs per query, so a\n * failed BEGIN would let a pipelined WRITE autocommit. Ahead of anything\n * else BEGIN is awaited first. A read that rode behind a BEGIN that failed\n * rejects with BEGIN's error, and every later statement is refused.\n * - Without a deadline, statements dispatched while the opening is\n * unconfirmed either ride too (extended reads, nobody queued) or wait for\n * it in call order. With a deadline, every send is one turn: [bound,\n * statement] back to back, after the previous turn finished.\n * - Burst failures: the FIRST failure of a burst is the error; a 25P02 reply\n * becomes the aborted refusal naming the failure that aborted the\n * transaction (replies arrive in order on one connection).\n */\n function createReservedControl(params: {\n reserved: BunReserved;\n budget: TransactionBudget;\n scope: SavepointScope;\n /** The deferred opening text, or `null` when the transaction was opened eagerly. */\n opening: string | null;\n }): ReservedControl {\n const { reserved, budget, scope } = params;\n const deferred = createDeferredControl({ opening: params.opening === null ? [] : [params.opening] });\n /** The deferred BEGIN failed: the server holds no transaction. */\n let openingFailure: VibeError | undefined;\n /** The BEGIN step while its reply is outstanding. */\n let openingStep: Promise<unknown> | null = null;\n /** Settles (never rejects) once BEGIN's reply is in and `openingFailure` is recorded. */\n let openingPending: Promise<void> | null = null;\n /** Started-marker of the last statement queued behind the unconfirmed opening. */\n let waitTail: Promise<void> | null = null;\n /** Deadline mode: one turn at a time. */\n let deadlineTail: Promise<void> = Promise.resolve();\n /** The latest server-reported failure, in reply order. */\n let lastFailure: VibeError | undefined;\n\n const step = <T>(query: () => Promise<T>): Promise<T> =>\n new Promise<T>((resolve) => resolve(query())).then(undefined, (error: unknown) => {\n const mapped = mapBunDriverError({ error });\n if (mapped.meta.sqlstate === \"25P02\") {\n throw transactionAbortedError({ cause: lastFailure ?? scope.state.aborted?.cause });\n }\n if (typeof mapped.meta.sqlstate === \"string\") lastFailure = mapped;\n throw mapped;\n });\n\n const trackOpening = (sent: Promise<unknown>): Promise<void> => {\n openingStep = sent;\n const settled: Promise<void> = sent\n .then(ignore, (error: unknown) => {\n openingFailure = mapBunDriverError({ error });\n })\n .then(() => {\n if (openingPending === settled) {\n openingPending = null;\n openingStep = null;\n }\n });\n openingPending = settled;\n return settled;\n };\n\n const ridesOpening = <T>(send: ReservedSend<T>): boolean => send.extended && send.effect === \"read\";\n\n const sendNow = <T>(send: ReservedSend<T>): Promise<T> => {\n const cleanup = send.cleanup === true;\n if (!cleanup) {\n if (openingFailure !== undefined) throw transactionAbortedError({ cause: openingFailure });\n budget.assertUsable({ stage: send.stage ?? \"statement\" });\n send.guard?.();\n }\n const carriesOpening = !cleanup && !deferred.opened();\n const control = cleanup ? [] : [...deferred.take()];\n if (carriesOpening && !ridesOpening(send)) {\n // BEGIN confirmed first: nothing but a read may run behind a BEGIN\n // that could fail. The statement then takes its own turn. A SAVEPOINT\n // taken with BEGIN goes out NOW, right behind it, and its reply is\n // answered by the statement's turn. Behind a failed BEGIN it fails in\n // autocommit with no effect, and the turn refuses with BEGIN's error.\n const [opening, ...rest] = control;\n const confirmed = trackOpening(step(() => controlQuery({ connection: reserved, text: opening as string })));\n const riding = rest.map((text) => {\n const sent = step(() => controlQuery({ connection: reserved, text }));\n // Reported through the statement's turn, or moot after its refusal.\n sent.catch(ignore);\n return sent;\n });\n const next: ReservedSend<T> = { ...send, riding };\n if (budget.totalMs !== null) return confirmed.then(() => sendNow(next));\n return enqueue(next);\n }\n const ms = cleanup ? null : engineStatementBudgetMs({ budget });\n const steps: Promise<unknown>[] = [...(send.riding ?? [])];\n // A read riding a BEGIN that is still unconfirmed answers with BEGIN's error.\n if (!cleanup && !carriesOpening && openingStep !== null) steps.push(openingStep);\n control.forEach((text, index) => {\n const sent = step(() => controlQuery({ connection: reserved, text }));\n if (index === 0 && carriesOpening) trackOpening(sent);\n steps.push(sent);\n });\n if (ms !== null) steps.push(step(() => controlQuery({ connection: reserved, text: STATEMENT_BOUND_TEXT, values: [String(ms)] })));\n const statement = step(() => send.send(reserved));\n steps.push(statement);\n return Promise.allSettled(steps).then((settled) => {\n const failed = settled.find((outcome): outcome is PromiseRejectedResult => outcome.status === \"rejected\");\n if (failed !== undefined) throw failed.reason;\n return statement;\n });\n };\n\n const enqueue = <T>(send: ReservedSend<T>): Promise<T> => {\n const prior = waitTail ?? openingPending ?? Promise.resolve();\n let markStarted: () => void = ignore;\n const started = new Promise<void>((resolve) => {\n markStarted = resolve;\n });\n waitTail = started;\n return prior.then(() => {\n try {\n return sendNow(send);\n } finally {\n if (waitTail === started) waitTail = null;\n markStarted();\n }\n });\n };\n\n const dispatch = <T>(send: ReservedSend<T>): Promise<T> => {\n if (budget.totalMs !== null) {\n const pending = deadlineTail.then(() => sendNow(send));\n // A failed turn must not strand the next one (or ROLLBACK).\n deadlineTail = pending.then(ignore, ignore);\n return pending;\n }\n if (openingPending !== null && (waitTail !== null || !ridesOpening(send))) return enqueue(send);\n return new Promise<T>((resolve) => resolve(sendNow(send)));\n };\n\n return {\n deferred,\n dispatch,\n executor: ({ effect, guard }) => Object.assign(\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<BunResults> =>\n dispatch({ effect, guard, extended: true, send: (connection) => connection(strings, ...values) }),\n { unsafe: (text: string, values?: unknown[]): Promise<BunResults> =>\n // `unsafe(text)` / `unsafe(text, [])` may go as a simple query: never pipelined behind BEGIN.\n dispatch({ effect, guard, extended: values !== undefined && values.length > 0, send: (connection) => connection.unsafe(text, values) }) },\n ),\n };\n }\n\n /**\n * The reserved connection 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`; bun:sql refuses\n * transaction control through `sql.unsafe()` on a pooled instance\n * (`ERR_POSTGRES_UNSAFE_TRANSACTION`), so a pure `BEGIN` reserves one\n * connection, every raw statement until the matching `COMMIT`/`ROLLBACK`\n * rides it, and the close releases it. The ORM path (`execute`) and\n * `transaction()` stay on the pool — they never participate in a raw\n * transaction. Concurrent raw transactions on one adapter are unsupported\n * (they were driver-refused before this pinning existed).\n */\n let rawSession: BunReserved | null = null;\n\n function createSqlInstance(params: { max: number }): BunInstance {\n // bun:sql's own default is named statements; off, the adapter matches\n // node-postgres (see BunAdapterOptions.preparedStatements).\n const sqlOptions: Record<string, unknown> = { max: params.max, prepare: usePrepared };\n if (options?.connectionTimeout !== undefined) {\n // bun:sql expects seconds; the VibeORM surface is milliseconds everywhere.\n sqlOptions.connectionTimeout = Math.max(1, Math.ceil(options.connectionTimeout / 1000));\n } else if (address.seconds !== undefined) {\n sqlOptions.connectionTimeout = address.seconds;\n }\n\n const startupOptions = buildStartupOptions({\n planCacheMode: options?.planCacheMode ?? \"force_custom_plan\",\n statementTimeout: options?.statementTimeout,\n });\n const url = startupOptions === undefined ? address.url : applyStartupOptions({ url: address.url, startupOptions });\n\n if (URL.canParse(url)) {\n const path = new URL(url).pathname;\n // Native Bun currently lets PGDATABASE override the URL path. Pin only\n // a supplied database; omitted components retain the driver's defaults.\n if (path.length > 1) sqlOptions.database = decodeURIComponent(path.slice(1));\n }\n return createBunSql({ url, options: sqlOptions }) as unknown as BunInstance;\n }\n\n function getSql(): BunInstance {\n instance ??= createSqlInstance({ max: options?.max ?? 10 });\n return instance;\n }\n\n /**\n * Ask THIS driver, once, whether it parses json on the path the ORM reads\n * rows over — the same `execute` path, prepared or unsafe as configured, so\n * the answer describes the traffic the claim is applied to.\n *\n * Runs on the handle that is already in hand (pool, transaction or reserved\n * session): a `SELECT` is harmless inside a transaction, and probing the pool\n * from inside one could deadlock an adapter configured with `max: 1`.\n * Failure refuses this operation. A later call can observe the wire again;\n * no user statement or transaction is retried.\n */\n async function probeJsonWire(source: BunExecutor, onReadControl?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"onReadControl\"]): Promise<void> {\n const probe = renderDiagnostic({ dialect: postgresDialect, query: \"postgresJsonWire\" });\n const result = await runMapped(() => usePrepared\n ? source(templates.getTemplate({ text: probe.text }).template)\n : source.unsafe(probe.text, [])).then(\n (result) => { onReadControl?.({ stage: \"preflight\", rows: finalRows({ result }).length }); return result; },\n (error: unknown) => { onReadControl?.({ stage: \"preflight\", rows: 0 }); throw error; },\n );\n const rows = finalRows({ result });\n const probed = rows[0]?.probe;\n if (typeof probed === \"object\" && probed !== null && \"__vibeorm\" in probed && probed.__vibeorm === 1) activeWire = WIRE_PARSED;\n else if (typeof probed === \"string\" && /^\\{\\s*\"__vibeorm\"\\s*:\\s*1\\s*\\}$/.test(probed)) activeWire = WIRE_TEXT;\n else {\n throw new VibeError({\n code: \"VIBE_ADAPTER\",\n message: \"Bun returned an unrecognized JSON wire probe result; no ORM statement was sent\",\n meta: { reason: \"json-wire-probe\" },\n });\n }\n wireSettled = true;\n }\n\n function observeResult(params: { scope?: SavepointScope; effect?: StatementEffect; result: BunResults }): void {\n if (params.scope === undefined) return;\n const result = params.result;\n const results: BunRows[] = result === null ? [[]] : Array.isArray(result[0]) ? result as BunRows[] : [result as BunRows];\n if (results.length === 0) observeRowChanges({ scope: params.scope, count: statementRowChanges({ effect: params.effect }) });\n for (const rows of results) observeRowChanges({ scope: params.scope, count: statementRowChanges({ effect: params.effect, count: rows.count ?? rows.affectedRows, rows: rows.length, resultRows: rows }) });\n }\n\n async function runExecute(params: {\n source: BunExecutor;\n text: string;\n values: unknown[];\n scope?: SavepointScope;\n effect?: StatementEffect;\n execution?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"execution\"];\n onReadControl?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"onReadControl\"];\n }): Promise<Record<string, unknown>[]> {\n assertReadExecution({ ...params, provider: PROVIDER, stage: \"waiting-for-connection\" });\n // One extra round trip on the first ORM query of this adapter's life; a\n // single boolean test on every one after it. It must complete BEFORE the\n // first rows are handed back, because the runtime reads `wire` to build\n // that read's decode plan.\n if (!wireSettled) {\n if (params.scope === undefined) {\n wireProbe ??= probeJsonWire(params.source, params.onReadControl).finally(() => { wireProbe = null; });\n await wireProbe;\n } else {\n // A transaction handle probes on its OWN connection and never waits\n // for the pool's probe: that probe needs a free pool connection, and\n // every one may be held by a transaction waiting here — a cold\n // adapter with all connections in transactions would hang forever.\n await probeJsonWire(params.source, params.onReadControl);\n }\n }\n assertReadExecution({ ...params, provider: PROVIDER, stage: \"waiting-for-connection\" });\n const values = serializeParams({ values: params.values, namedStatements: usePrepared });\n if (usePrepared) {\n // F19: a tagged template binds POSITIONALLY, one value per gap — so the\n // values follow the placeholder ORDER found in the text (`$2, $1` binds\n // backwards otherwise, and a repeated `$1` needs its value twice).\n const prepared = templates.getTemplate({ text: params.text });\n const bound = prepared.identityOrder && prepared.indices.length === values.length\n ? values\n : bindTemplateValues({ text: params.text, indices: prepared.indices, values });\n // A placeholder repeated in the text is bound once per gap; past the\n // protocol's limit that expansion would refuse a statement whose own\n // parameter count is legal, so it runs by `$n` instead.\n const result = bound.length > MAX_BIND_PARAMETERS\n ? await runMapped(() => params.source.unsafe(params.text, values))\n : await runMapped(() => params.source(prepared.template, ...bound));\n observeResult({ scope: params.scope, effect: params.effect, result });\n return plainRows({ rows: finalRows({ result }) });\n }\n const result = await runMapped(() => params.source.unsafe(params.text, values));\n observeResult({ scope: params.scope, effect: params.effect, result });\n return plainRows({ rows: finalRows({ result }) });\n }\n\n async function runExecuteUnsafe(params: {\n source: BunExecutor;\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, namedStatements: usePrepared });\n const result = await runMapped(() => params.source.unsafe(params.text, values));\n observeResult({ scope: params.scope, effect: params.effect, result });\n const rows = finalRows({ result });\n return { rows: plainRows({ rows }), affectedRows: readAffectedRows({ rows }) };\n }\n\n /**\n * Build the adapter facade over any bun:sql handle. `parentMode` decides\n * whether a nested `transaction()` opens a real transaction or a savepoint;\n * `scope` is shared by reference across one top-level transaction, and the\n * savepoint gate serializes overlapping sibling savepoints (F14) on BOTH the\n * driver-managed and the manual path.\n */\n function createAdapter(params: {\n source: BunSource;\n parentMode: ParentMode;\n scope: SavepointScope;\n /** The enclosing transaction's budget; absent on the pool-level adapter. */\n budget?: TransactionBudget;\n lifetime?: { active: boolean };\n /** The reserved connection's send discipline; absent on the pool-level adapter. */\n control?: ReservedControl;\n }): DatabaseAdapter {\n const { source, parentMode, scope, budget, lifetime, control } = params;\n\n function assertHandle(): void {\n budget?.assertUsable({ stage: \"statement\" });\n if (lifetime?.active === false) {\n throw new VibeError({\n code: \"VIBE_TRANSACTION\",\n message: \"this savepoint callback has finished; its transaction handle has expired\",\n meta: { reason: \"expired\" },\n });\n }\n if (scope.state.poisoned !== null) throw scope.state.poisoned;\n }\n\n /**\n * Nested transaction: a savepoint on the reserved connection, driven by\n * hand. EPIC 6: `SAVEPOINT` rides with the body's first statement; a body\n * that sent nothing sends neither its RELEASE nor its ROLLBACK TO.\n */\n async function transactionViaSavepoint<T>(\n reservedControl: ReservedControl,\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n nestedOptions?: TransactionOptions,\n ): Promise<T> {\n refuseNestedTransactionOptions({ options: nestedOptions, provider: PROVIDER });\n assertHandle();\n budget?.assertUsable({ stage: \"nested\" });\n const savepointControl = (statement: string, cleanup: boolean): Promise<unknown> | undefined => {\n if (reservedControl.deferred.routeSavepoint({ text: statement }) !== \"send\") return undefined;\n return reservedControl.dispatch({\n extended: true,\n ...(cleanup ? { cleanup: true } : {}),\n send: (connection) => controlQuery({ connection, text: statement }),\n });\n };\n return runNestedSavepoint({\n scope,\n execute: (statement) => savepointControl(statement, false),\n cleanup: (statement: string) => savepointControl(statement, true),\n body: async (child) => {\n assertHandle();\n const childLifetime = { active: true };\n try {\n return await fn(createAdapter({ source, parentMode: \"tx\", scope: child, budget, lifetime: childLifetime, control: reservedControl }));\n } finally {\n childLifetime.active = false;\n }\n },\n });\n }\n\n /** Top-level transaction on the pool. */\n async function transactionViaPool<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n const pool = source as BunInstance;\n\n // Refuse an unsupportable budget before any connection is taken.\n validateTransactionDeadline({\n options: transactionOptions,\n support: BUDGETS.transactionDeadline,\n provider: PROVIDER,\n });\n\n const readOnly = readOnlyRequested({ options: transactionOptions, provider: PROVIDER });\n\n // Round-trip EPIC 6: EVERY top-level transaction reserves one connection\n // and drives control by hand, so BEGIN / SAVEPOINT / the deadline bound\n // can ride with the next statement (see createReservedControl). With a\n // `timeout` the opening stays EPIC 3's ONE eager simple-protocol message\n // (BEGIN […]; SET LOCAL statement_timeout = N), validated here, before\n // the reservation, so its errors surface before the callback runs.\n const openingOptions = { isolationLevel: transactionOptions?.isolationLevel, readOnly };\n const eagerOpen = transactionOptions?.timeout === undefined\n ? null\n : openTransactionStatement({ ...openingOptions, timeout: transactionOptions.timeout });\n const reserved = await runMapped(() => pool.reserve());\n // The deadline clock starts HERE: the connection is reserved, so waiting\n // for it is not charged against the caller's transaction budget.\n const budget = startTransactionBudget({ options: transactionOptions, provider: PROVIDER });\n const txScope = createSavepointScope();\n const control = createReservedControl({\n reserved,\n budget,\n scope: txScope,\n opening: eagerOpen === null ? beginStatement(openingOptions) : null,\n });\n /**\n * How far COMMIT got — the only input of the commit outcome (EPIC T). A\n * holder, because the `send` callback below moves it out of sight of\n * the compiler's narrowing.\n */\n const commit: { progress: CommitProgress } = { progress: \"not-sent\" };\n let discard = false;\n try {\n if (eagerOpen !== null) await runMapped(() => reserved.unsafe(eagerOpen));\n const txAdapter = createAdapter({\n source: reserved,\n parentMode: \"tx\",\n scope: txScope,\n budget,\n control,\n });\n const result = await runRootScope({ scope: txScope, body: () => fn(txAdapter) });\n // An expired budget must never commit, however the callback ended.\n budget.assertUsable({ stage: \"commit\" });\n if (!control.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 const reply = await control.dispatch({\n extended: true,\n effect: \"write\",\n stage: \"commit\",\n send: (connection) => {\n commit.progress = \"sent\";\n return controlQuery({ connection, text: \"COMMIT\" });\n },\n });\n // An aborted transaction's COMMIT is answered with a ROLLBACK tag and\n // no error: the outcome is a certain rollback.\n if (finalRows({ result: reply }).command === \"ROLLBACK\") {\n commit.progress = \"answered\";\n throw transactionAbortedError({ cause: txScope.state.aborted?.cause });\n }\n budget.close({ outcome: \"committed\" });\n return result;\n } catch (error) {\n if (txScope.state.poisoned !== null) discard = true;\n // A failed COMMIT is an unknown outcome only when the connection was\n // lost; a server answer with a SQLSTATE (a deferred FK, a\n // serialization failure) is a definite rollback and raises that\n // precise error, as on adapter-pg (EPIC 6 decision 2, RV5 MJ-3).\n if (commit.progress === \"sent\") commit.progress = isConnectionLoss({ error }) ? \"unanswered\" : \"answered\";\n let rollback: RollbackOutcome = \"not-needed\";\n try {\n // A deferred opening that never left the client left nothing to undo.\n if (control.deferred.opened()) {\n await control.dispatch({ extended: false, cleanup: true, send: (connection) => connection.unsafe(\"ROLLBACK\") });\n rollback = \"acknowledged\";\n }\n } catch {\n // The rollback that should have cleaned up failed. `SET LOCAL` reverts\n // with the transaction, but this session's transaction state can no\n // longer be asserted, so the reserved connection is closed. The\n // commit outcome does not change: it follows from how far COMMIT got.\n discard = true;\n rollback = \"failed\";\n }\n // Only a COMMIT whose answer was lost hides the outcome from the\n // caller. A failure before COMMIT keeps its own error even when the\n // cleanup ROLLBACK failed too, like node-postgres (EPIC T: the facts\n // ride beside it, read with `transactionOutcomeOf({ error })`).\n const own = commit.progress === \"unanswered\" && txScope.state.poisoned === null\n ? unknownOutcome({ cause: error })\n : error;\n throw settleFailedTransaction({\n error: own,\n provider: PROVIDER,\n budget,\n scope: txScope,\n commit: commit.progress,\n rollback,\n connection: discard ? \"discarded\" : \"returned\",\n });\n } finally {\n if (discard) await runMapped(() => reserved.close());\n else reserved.release();\n }\n }\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n budgets: BUDGETS,\n readCancellation: \"before-dispatch\",\n roundTrips: ROUND_TRIPS,\n ...(parentMode === \"pool\" ? {} : { rowChanges: (): RowChangeCount => { assertHandle(); return readRowChanges({ scope }); } }),\n get wire(): WireFidelity {\n return activeWire;\n },\n\n async execute(execParams) {\n return runReadExecution({ ...execParams, provider: PROVIDER, run: async () => {\n assertHandle();\n const turn = scopeTurn({ scope });\n if (turn !== undefined) await turn;\n assertHandle();\n const guard = (): void => { assertHandle(); assertReadExecution({ ...execParams, provider: PROVIDER, stage: \"waiting-for-connection\" }); };\n const executor = control === undefined ? source : control.executor({ effect: execParams.effect, guard });\n const result = runExecute({ source: executor, ...(parentMode === \"pool\" ? {} : { scope }), ...execParams });\n // Inside a transaction a server-reported failure aborts it (postgres):\n // record it so a callback that swallows it cannot commit nothing. The\n // pool-level handle has no transaction to abort.\n return parentMode === \"pool\"\n ? result\n : result.catch((error: unknown) => abortTransactionOnStatementFailure({ scope, error }));\n } });\n },\n\n async executeUnsafe(execParams) {\n assertHandle();\n const turn = scopeTurn({ scope });\n if (turn !== undefined) await turn;\n assertHandle();\n const executor = control === undefined ? source : control.executor({ effect: execParams.effect, guard: assertHandle });\n const result = runExecuteUnsafe({ source: executor, ...(parentMode === \"pool\" ? {} : { scope }), ...execParams });\n return parentMode === \"pool\"\n ? result\n : result.catch((error: unknown) => abortTransactionOnStatementFailure({ scope, error }));\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n return control === undefined\n ? transactionViaPool(fn, transactionOptions)\n : transactionViaSavepoint(control, fn, transactionOptions);\n },\n\n async connect(): Promise<void> {\n if (parentMode !== \"pool\") {\n // The open transaction owns this connection; an expired handle keeps\n // its own refusal (checked first).\n assertHandle();\n throw transactionLifecycleRefusal({ method: \"connect\" });\n }\n const reserved = await runMapped(() => (source as BunInstance).reserve());\n try {\n // Round-trip EPIC 3 (A-13): settle the JSON wire probe here, on the\n // connection already in hand, so the first ORM statement does not\n // pay it. A failure rejects connect() and leaves the wire unsettled:\n // the lazy path in runExecute probes again, as after any failed probe.\n // A probe already in flight (a first query's, on the pool) settles\n // the wire by itself: never wait for it while holding this\n // reservation — on a one-connection pool that probe needs it\n // (fix lane FX-A, RV2 MJ-2).\n if (!wireSettled && wireProbe === null) {\n wireProbe = probeJsonWire(reserved).finally(() => { wireProbe = null; });\n await wireProbe;\n }\n } finally {\n reserved.release();\n }\n },\n\n async disconnect(): Promise<void> {\n if (parentMode !== \"pool\") {\n assertHandle();\n throw transactionLifecycleRefusal({ method: \"disconnect\" });\n }\n await runMapped(() => (source as BunInstance).close());\n instance = null;\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return toPgArrayLiteral(values);\n },\n };\n }\n\n /** Pool-level facade — the bun:sql client is created on first use. */\n function poolAdapter(): DatabaseAdapter {\n return createAdapter({\n source: getSql(),\n parentMode: \"pool\",\n scope: createSavepointScope(),\n });\n }\n\n /**\n * Final cleanup, run ONCE by the lifecycle gate after every admitted\n * operation settled — a pending raw BEGIN has published its session, and\n * every admitted `withSession` has closed its private pool. Rolls back an\n * abandoned raw transaction, then closes the instance. A failed ROLLBACK is\n * reported as `disconnect()`'s outcome (the instance still closes, and\n * takes the session with it); the session is released either way, because\n * bun:sql does not settle its pool's pending count when a reserved\n * connection closes (see `withSession`).\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 rawSession = null;\n await runMapped(() => session.unsafe(\"ROLLBACK\")).then(\n () => { session.release(); },\n (error: unknown) => { session.release(); throw error; },\n );\n },\n async (): Promise<void> => {\n if (instance === null) return;\n const closing = instance;\n instance = null;\n await runMapped(() => closing.close());\n },\n ],\n });\n }\n\n const lifecycle = createAdapterLifecycleGate({ driver: \"bun\", 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 // Bun 1.3 does not decrement its pool's pending counter when a reserved\n // connection closes or dies. Own a private one-connection driver instance\n // so cleanup cannot hang or force-close unrelated application work.\n const sessionPool = createSqlInstance({ max: SESSION_CONNECTION.max });\n const close = (): Promise<void> => runMapped(() => sessionPool.close({ timeout: SESSION_CONNECTION.closeGraceSeconds }));\n const reserved = await runMapped(() => sessionPool.reserve()).catch(async (cause: unknown) => {\n await close().catch((cleanupCause: unknown) => {\n if (cause instanceof VibeError) throw new VibeError({ code: cause.code, message: cause.message, meta: { ...cause.meta, cleanupCause }, cause });\n throw cause;\n });\n throw cause;\n });\n return runPinnedSession({\n run,\n execute: async (query) => (await runExecuteUnsafe({ source: reserved, ...query })).rows,\n isLost: (error) => error instanceof VibeError && isConnectionLoss({ error }),\n release: close,\n });\n },\n\n async execute(params) {\n return runExecute({ source: getSql(), ...params });\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 rawSession = null;\n try {\n return await runExecuteUnsafe({ source: session, ...params });\n } finally {\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({ source: rawSession, ...params });\n }\n if (control === \"open\") {\n const reserved = await runMapped(() => getSql().reserve());\n try {\n const result = await runExecuteUnsafe({ source: reserved, ...params });\n rawSession = reserved;\n return result;\n } catch (error) {\n reserved.release();\n throw error;\n }\n }\n return runExecuteUnsafe({ source: getSql(), ...params });\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n return poolAdapter().transaction(fn, transactionOptions);\n },\n\n async connect(): Promise<void> {\n return poolAdapter().connect();\n },\n };\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n budgets: BUDGETS,\n readCancellation: \"before-dispatch\",\n roundTrips: ROUND_TRIPS,\n transactionOutcome: \"reported\",\n get wire(): WireFidelity {\n return activeWire;\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, 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, private session pools included\n * — then closes the instance, once. Repeated calls share that completion.\n * A new adapter 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 toPgArrayLiteral(values);\n },\n };\n}\n\n/**\n * Rows affected by a bun:sql statement: the driver attaches `count` (and, on\n * some versions, `affectedRows`) to the returned array; otherwise the number of\n * returned rows is the best available answer.\n */\nfunction readAffectedRows(params: { rows: BunRows }): number {\n const { rows } = params;\n if (typeof rows.count === \"number\") return rows.count;\n if (typeof rows.affectedRows === \"number\") return rows.affectedRows;\n return rows.length;\n}\n\n/**\n * The rows as a plain `Array`, like node-postgres' `result.rows`. bun:sql\n * resolves to its own `SQLResultArray`, which carries `count`, `command`,\n * `affectedRows` and `lastInsertRowid` as own properties — a caller that\n * compares, spreads or clones a `findMany` result would otherwise see them.\n */\nfunction plainRows(params: { rows: BunRows }): Record<string, unknown>[] {\n return Array.from(params.rows);\n}\n\n/** Bun's simple protocol returns an outer array for scripts; final command wins. */\nfunction finalRows(params: { result: BunResults }): BunRows {\n const { result } = params;\n if (result === null) return [];\n return Array.isArray(result[0]) ? (result as BunRows[]).at(-1) ?? [] : result as BunRows;\n}\n\n/**\n * Whether a mapped failure means the CONNECTION is gone rather than the server\n * having answered: no SQLSTATE at all (socket-level or a driver refusal), class\n * 08 (connection exception) or an admin/crash shutdown (57P01–57P03). The same\n * rule as `@vibeorm/adapter-pg`: it pins a session as lost and decides whether\n * a failed COMMIT's 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 statement failure inside a transaction. A server-reported failure aborts\n * the transaction ({@link abortTransactionOnServerFailure}). bun:sql also\n * refuses a statement with more than 65,535 parameters BEFORE sending it,\n * where node-postgres sends it and the server aborts the transaction (08P01) —\n * so that refusal aborts it here too, and a callback that catches it cannot\n * commit the transaction's other writes.\n */\nfunction abortTransactionOnStatementFailure(params: { scope: SavepointScope; error: unknown }): never {\n const { scope, error } = params;\n if (error instanceof VibeError && error.meta.driverCode === \"ERR_POSTGRES_TOO_MANY_PARAMETERS\") {\n markTransactionAborted({ scope, cause: error });\n }\n return abortTransactionOnServerFailure({ scope, error });\n}\n\nfunction unknownOutcome(params: { cause: unknown; reason?: string }): VibeError {\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message: \"Bun could not confirm transaction recovery or completion; the outcome is unknown. Nothing is retried automatically.\",\n meta: { reason: params.reason ?? \"transaction-outcome-unknown\", outcome: \"unknown\" },\n cause: params.cause,\n });\n}\n\n// ─── Re-exports (driver-error table, params, helpers) ─────────────\n\nexport {\n BUN_SQLSTATE_ERROR_CODES,\n BUN_SQLSTATE_REASONS,\n bunErrorSqlstate,\n mapBunDriverError,\n} from \"./errors.ts\";\nexport { serializeParams, serializeParamsRaw, toPgArrayLiteral } from \"./params.ts\";\nexport { applyStartupOptions, buildStartupOptions } from \"./connection-url.ts\";\nexport type { PlanCacheMode } from \"./connection-url.ts\";\nexport { createSavepointCounter, nextSavepointName } from \"@vibeorm/runtime/adapter-kit\";\nexport type { SavepointCounter } from \"@vibeorm/runtime/adapter-kit\";\nexport { createTemplateCache, templateChunks } from \"./template-cache.ts\";\nexport type { TemplateCache } from \"./template-cache.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",
9
- "/**\n * Connection-URL handling for bun:sql.\n *\n * Per-connection PostgreSQL settings (`plan_cache_mode`, `statement_timeout`)\n * travel in the `options` startup parameter, which the server parses for\n * `-c key=value` pairs — so every connection in bun's internal pool inherits\n * them without a per-query round trip.\n *\n * v1 lesson (LEARNINGS.md): bun:sql forwards *unrecognised* URL parameters to\n * the server as runtime configuration, so a libpq client-side option such as\n * `connect_timeout` reaches PostgreSQL, which rejects it as an unrecognised\n * configuration parameter (42704). A URL written for libpq or node-postgres\n * still works here: {@link takeConnectTimeout} removes `connect_timeout` and\n * hands its seconds to bun:sql's `connectionTimeout` constructor option.\n */\n\nimport { VibeError } from \"@vibeorm/schema\";\n\n/**\n * PostgreSQL plan-cache behaviour for the implicit prepared statements bun:sql\n * creates. `force_custom_plan` replans with the real parameter values (≈0.1 ms\n * per query) and keeps index selection optimal on range/LIKE/skewed filters —\n * `auto` lets PostgreSQL switch to a generic plan after ~5 executions.\n */\nexport type PlanCacheMode = \"auto\" | \"force_custom_plan\" | \"force_generic_plan\";\n\n/**\n * Build the `options` startup string, or `undefined` when nothing needs setting.\n *\n * @throws VibeError `VIBE_VALIDATION` when `statementTimeout` is not a\n * non-negative integer — the value ends up inside the startup string verbatim.\n */\nexport function buildStartupOptions(params: {\n planCacheMode: PlanCacheMode;\n statementTimeout?: number;\n}): string | undefined {\n const { planCacheMode, statementTimeout } = params;\n const parts: string[] = [];\n if (planCacheMode !== \"auto\") parts.push(`-c plan_cache_mode=${planCacheMode}`);\n if (statementTimeout !== undefined) {\n if (!Number.isInteger(statementTimeout) || statementTimeout < 0) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `statementTimeout must be a non-negative integer of milliseconds, received ${String(statementTimeout)}`,\n meta: { statementTimeout },\n });\n }\n parts.push(`-c statement_timeout=${statementTimeout}`);\n }\n return parts.length === 0 ? undefined : parts.join(\" \");\n}\n\n/**\n * Remove libpq's client-side `connect_timeout` (whole seconds) from a URL and\n * return its value, so the URL bun:sql forwards to the server no longer carries\n * it. `0` or a negative value means \"no limit\" in libpq and yields\n * `undefined`. A URL bun cannot parse is returned unchanged.\n *\n * @throws VibeError `VIBE_VALIDATION` when the value is not an integer.\n */\nexport function takeConnectTimeout(params: { url: string }): { url: string; seconds?: number } {\n if (!URL.canParse(params.url)) return { url: params.url };\n const url = new URL(params.url);\n const raw = url.searchParams.get(\"connect_timeout\");\n if (raw === null) return { url: params.url };\n const seconds = Number(raw.trim());\n if (raw.trim() === \"\" || !Number.isInteger(seconds)) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `connect_timeout in the connection URL must be an integer number of seconds, received \"${raw}\"`,\n meta: { connectTimeout: raw },\n });\n }\n url.searchParams.delete(\"connect_timeout\");\n url.search = url.searchParams.toString().replace(/\\+/g, \"%20\");\n return seconds > 0 ? { url: url.toString(), seconds } : { url: url.toString() };\n}\n\n/** Merge startup settings into one `options` key; adapter settings take precedence. */\nexport function applyStartupOptions(params: { url: string; startupOptions: string }): string {\n if (!URL.canParse(params.url)) {\n throw new VibeError({ code: \"VIBE_VALIDATION\", message: \"invalid PostgreSQL connection URL\" });\n }\n const url = new URL(params.url);\n const merged = [...url.searchParams.getAll(\"options\"), params.startupOptions].filter(Boolean).join(\" \");\n url.searchParams.set(\"options\", merged);\n url.search = url.searchParams.toString().replace(/\\+/g, \"%20\");\n return url.toString();\n}\n",
6
+ "/**\n * Oldest Bun whose bun:sql the adapter accepts. Older releases — measured on\n * 1.3.14 with every adapter fix in place — hang after `COPY … TO STDOUT`,\n * read zone-less timestamps as host-local time and turn ±infinity dates into\n * `Invalid Date`; 1.4.1, 1.4.2 and 1.4.3 pass the same probes.\n */\nexport const MINIMUM_BUN_VERSION: string = \"1.4.1\";\n\n/**\n * Oldest Bun on which `sql.unsafe(text, values)` on a `prepare: true` instance\n * was OBSERVED to create a NAMED statement and pipeline it like a tagged\n * template (performance audit round 2, B-04: wire capture on 1.4.3,\n * `Parse name=\"P…\"`, then `B E H S` warm). Older supported versions keep the\n * synthetic templates: their `unsafe` behaviour was never measured.\n */\nexport const NAMED_UNSAFE_BUN_VERSION: string = \"1.4.3\";\n\n/**\n * PostgreSQL's limit on bound parameters in one statement (the Bind message\n * carries a 16-bit count).\n */\nexport const MAX_BIND_PARAMETERS: number = 65_535;\n\n/** Migration-only driver instance; never force-close the application's pool. */\nexport const SESSION_CONNECTION: Readonly<{ max: number; closeGraceSeconds: number }> = Object.freeze({\n max: 1,\n // Bun 1.3 treats timeout: 0 as unbounded. A positive millisecond closes only\n // this private instance after the session gate has drained dispatched work.\n closeGraceSeconds: 0.001,\n});\n",
7
+ "import { VibeError } from \"@vibeorm/schema\";\nimport { MINIMUM_BUN_VERSION, NAMED_UNSAFE_BUN_VERSION } from \"./config.ts\";\n\n/**\n * Refuse a Bun whose bun:sql the adapter does not support (see\n * {@link MINIMUM_BUN_VERSION}), at construction — before any statement can\n * meet one of that driver's known data bugs.\n *\n * @throws VibeError `VIBE_CONFIG`.\n */\nexport function refuseUnsupportedBun(params: { version: string }): void {\n if (Bun.semver.satisfies(params.version, `>=${MINIMUM_BUN_VERSION}`)) return;\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message:\n `@vibeorm/adapter-bun requires Bun ${MINIMUM_BUN_VERSION} or newer (running ${params.version}): older bun:sql ` +\n \"releases hang after COPY, read timestamps without a time zone in host-local time and turn infinity dates into Invalid Date. \" +\n \"Upgrade Bun, or use @vibeorm/adapter-pg.\",\n meta: { bunVersion: params.version, minimumBunVersion: MINIMUM_BUN_VERSION },\n });\n}\n\n/**\n * Whether this Bun's `unsafe(text, values)` makes a NAMED statement on a\n * `prepare: true` instance ({@link NAMED_UNSAFE_BUN_VERSION} and newer), so\n * named mode can bind an ORM statement by `$n` instead of through a synthetic\n * tagged template (B-04).\n */\nexport function namedUnsafeBinds(params: { version: string }): boolean {\n return Bun.semver.satisfies(params.version, `>=${NAMED_UNSAFE_BUN_VERSION}`);\n}\n",
8
+ "/**\n * @vibeorm/adapter-bun — bun:sql (PostgreSQL) adapter for VibeORM v2.\n *\n * Uses Bun's built-in SQL driver and its internal connection pool. Owns\n * optional prepared statements (synthetic tagged templates), transactions\n * (nested → savepoints), array-literal parameter formatting and driver-error\n * mapping. Only `VibeError` ever escapes.\n */\n\nimport { createBunSql } from \"./driver.ts\";\nimport { MAX_BIND_PARAMETERS, SESSION_CONNECTION } from \"./config.ts\";\nimport { namedUnsafeBinds, refuseUnsupportedBun } from \"./bun-version.ts\";\nimport { postgresDialect, renderDiagnostic } from \"@vibeorm/sql\";\nimport type {\n AdapterBudgetSupport,\n DatabaseAdapter,\n PipelineLane,\n QueryResult,\n RowChangeCount,\n StatementEffect,\n TransactionOptions,\n WireFidelity,\n} from \"@vibeorm/runtime\";\nimport {\n assertReadExecution,\n runReadExecution,\n abortTransactionOnServerFailure,\n createDeferredControl,\n type DeferredControl,\n observeRowChanges,\n readRowChanges,\n statementRowChanges,\n createAdapterLifecycleGate,\n runPinnedSession,\n runShutdownCleanup,\n transactionLifecycleRefusal,\n createSavepointScope,\n type CommitProgress,\n engineStatementBudgetMs,\n findRefusedSetting,\n markTransactionAborted,\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 readOnlyRequested,\n} from \"@vibeorm/runtime/adapter-kit\";\nimport { VibeError, type Dialect, type Provider } from \"@vibeorm/schema\";\nimport { applyStartupOptions, buildStartupOptions, defaultPlanCacheMode, takeConnectTimeout, type PlanCacheMode } from \"./connection-url.ts\";\nimport { mapBunDriverError, runMapped } from \"./errors.ts\";\nimport { serializeParams, serializeParamsRaw, toPgArrayLiteral } from \"./params.ts\";\nimport { bindTemplateValues, createTemplateCache } from \"./template-cache.ts\";\nimport {\n beginStatement,\n openTransactionStatement,\n classifyRawTransactionControl,\n refuseNestedTransactionOptions,\n STATEMENT_BOUND_TEXT,\n} from \"./transaction-sql.ts\";\n\n// ─── Minimal bun:sql surface ──────────────────────────────────────\n\n/**\n * What bun:sql resolves a query to: the row array, with driver metadata\n * (`count`, `command`) attached as properties.\n */\ntype BunRows = Record<string, unknown>[] & { count?: number; affectedRows?: number; command?: string };\n\ntype BunResults = BunRows | BunRows[] | null;\n\n/** Anything that executes SQL through bun:sql. */\ntype BunExecutor = {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<BunResults>;\n unsafe(text: string, values?: unknown[]): Promise<BunResults>;\n};\n\n/**\n * A connection checked out with `sql.reserve()` — must be released. Every\n * top-level transaction runs on one (round-trip EPIC 6): BEGIN, COMMIT and\n * savepoints are sent by hand, so they can ride with the next statement.\n */\ntype BunReserved = BunExecutor & { release(): void; close(): Promise<void> };\n\n/** The pool-level bun:sql client. */\ntype BunInstance = BunExecutor & {\n reserve(): Promise<BunReserved>;\n close(options?: { timeout: number }): Promise<void>;\n};\n\n/** Any bun:sql handle the adapter can be built on top of. */\ntype BunSource = BunInstance | BunReserved;\n\n/**\n * Whether a handle is the pool (can open a real transaction) or is already\n * inside one (must nest through savepoints).\n */\ntype ParentMode = \"pool\" | \"tx\";\n\n/**\n * One statement or control text for the reserved connection of a transaction\n * (round-trip EPIC 6, pipelining).\n */\ntype ReservedSend<T> = {\n /** The driver call, made on the reserved connection when its turn comes. Unmapped. */\n readonly send: (connection: BunExecutor) => Promise<T>;\n /** Sent through the extended protocol (a tagged template, or ≥1 bound value): bun:sql may pipeline it. */\n readonly extended: boolean;\n readonly effect?: StatementEffect | undefined;\n readonly stage?: \"statement\" | \"commit\";\n /** Rollback cleanup: takes no pending control, gets no bound and is never refused. */\n readonly cleanup?: boolean;\n /** Handle checks run right before sending (lifetime, poison). */\n readonly guard?: () => void;\n /**\n * Control steps ALREADY SENT right behind an awaited BEGIN (a `SAVEPOINT`\n * taken with it) whose replies this statement answers for. Never texts held\n * back: a refusal of this statement's own turn must not drop a savepoint\n * the gate already counts as opened (fix lane FX-A, RV5 MJ-1).\n */\n readonly riding?: readonly Promise<unknown>[];\n /**\n * Ordered scopes (B-02): whether every failure of this statement is answered\n * by the SERVER — see {@link serverAnswered}. Asked lazily, by a lane only.\n */\n readonly pipelinable?: () => boolean;\n /** Called once the statement was handed to the driver (never when a check refused it first). */\n readonly onSent?: () => void;\n};\n\n/** Every send of ONE top-level transaction on its reserved connection goes through this. */\ntype ReservedControl = {\n /** Pending BEGIN / SAVEPOINT texts of this transaction. */\n readonly deferred: DeferredControl;\n /** Send one statement, with the pending control (and the deadline bound) ahead of it. */\n readonly dispatch: <T>(params: ReservedSend<T>) => Promise<T>;\n /** A bun:sql-shaped executor whose every call is dispatched through this control. */\n readonly executor: (params: { effect?: StatementEffect | undefined; guard: () => void }) => BunExecutor;\n /** The ordered scopes of this transaction (array `$transaction` bursts, B-02). */\n readonly ordered: OrderedScopes;\n /**\n * Lane controls only: settles once every earlier lane of the scope let this\n * lane send; rejects with the refusal its statement would get. A nested\n * transaction on the lane waits for it first, so the `SAVEPOINT` it defers can\n * only ride with this lane's own statement, never with an earlier lane's.\n */\n readonly turn?: () => Promise<void>;\n};\n\n// ─── Ordered scopes (array `$transaction` bursts, B-02) ──────────────\n\n/**\n * How a lane of an ordered scope lets the NEXT lane send: `go` once its first\n * statement was handed to the driver as one whose failures the server answers\n * (or once it settled successfully), `closed` when the lane closed without\n * issuing one, `failed` when its first statement failed (or was refused)\n * before the next lane was let go.\n */\ntype LaneRelease = { readonly kind: \"go\" } | { readonly kind: \"closed\" } | { readonly kind: \"failed\"; readonly cause: unknown };\n\n/** One lane of an ordered scope on the reserved connection. */\ntype OrderedLane = {\n readonly scope: OrderedScope;\n /** Position in the scope. */\n readonly index: number;\n open: boolean;\n /** Statements this lane issued into the scope (cleanup control is not counted). */\n issued: number;\n /** A later lane follows this one: it may issue ONE statement. */\n followed: boolean;\n /** Settles once, with how this lane lets the next one send. */\n readonly release: Promise<LaneRelease>;\n /** Settle {@link OrderedLane.release}; later calls are ignored. */\n readonly settle: (release: LaneRelease) => void;\n};\n\n/** One ordered scope: its lanes in order, closed ones included (the prefix rule reads them). */\ntype OrderedScope = {\n readonly lanes: OrderedLane[];\n /** The first failure of one of its statements: nothing of the scope is sent after it. */\n failed?: { readonly cause: unknown };\n};\n\n/** The ordered scopes of ONE top-level transaction. */\ntype OrderedScopes = {\n /** Open a new scope of `count` lanes. */\n readonly open: (count: number) => readonly OrderedLane[];\n /** Open the lane right after `lane`, the last lane of its scope; `lane` may then issue one statement. */\n readonly follow: (lane: OrderedLane) => OrderedLane;\n /** The lane's operation settled. Idempotent. */\n readonly close: (lane: OrderedLane) => void;\n /** The transaction's control seen through `lane`: its statements obey the scope's order. */\n readonly control: (lane: OrderedLane) => ReservedControl;\n};\n\nconst ignore = (): void => undefined;\n\nconst LANE_GO: LaneRelease = Object.freeze({ kind: \"go\" } as const);\nconst LANE_CLOSED: LaneRelease = Object.freeze({ kind: \"closed\" } as const);\n\n/**\n * Whether bun:sql answers every failure of a statement with these bound values\n * from the SERVER, so a later lane's statement may be sent right behind it\n * (B-02): within the protocol's parameter limit, and every value one bun:sql\n * sends as text without a check of its own — a string, `null`, or bytes (named\n * mode binds parameters in the text format, measured on Bun 1.4.3). Anything\n * else (a JS array, a `Date` the ISO form cannot spell, a document) may be\n * refused by the driver BEFORE it is sent; a statement sent behind such a\n * refusal would run in a transaction that is not aborted, so the next lane then\n * waits for this statement's reply instead.\n */\nfunction serverAnswered(params: { values: readonly unknown[] }): boolean {\n const { values } = params;\n if (values.length > MAX_BIND_PARAMETERS) return false;\n for (const value of values) {\n if (value !== null && typeof value !== \"string\" && !(value instanceof Uint8Array)) return false;\n }\n return true;\n}\n\n/** An ordered-scope statement whose earlier lane closed without issuing one: it is never sent (B-02, as adapter-pg). */\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 bun:sql-shaped executor whose every call goes through `dispatch`. `lane`:\n * the calls are statements of an ordered-scope lane, which asks whether each\n * one may be followed before its reply ({@link ReservedSend.pipelinable}).\n */\nfunction executorFor(params: {\n dispatch: ReservedControl[\"dispatch\"];\n effect?: StatementEffect | undefined;\n guard: () => void;\n lane?: true;\n}): BunExecutor {\n const { dispatch, effect, guard, lane } = params;\n return Object.assign(\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<BunResults> => dispatch({\n effect,\n guard,\n extended: true,\n ...(lane === true ? { pipelinable: (): boolean => serverAnswered({ values }) } : {}),\n send: (connection) => connection(strings, ...values),\n }),\n { unsafe: (text: string, values?: unknown[]): Promise<BunResults> => dispatch({\n effect,\n guard,\n // `unsafe(text)` / `unsafe(text, [])` may go as a simple query: never pipelined behind BEGIN.\n extended: values !== undefined && values.length > 0,\n ...(lane === true ? { pipelinable: (): boolean => values !== undefined && values.length > 0 && serverAnswered({ values }) } : {}),\n send: (connection) => connection.unsafe(text, values),\n }) },\n );\n}\n\n// ─── Options ──────────────────────────────────────────────────────\n\n/** Options for {@link bunAdapter}. */\nexport type BunAdapterOptions = {\n /**\n * PostgreSQL connection URL — required. The adapter never reads\n * `DATABASE_URL` (or any other environment variable) itself, and always\n * hands bun:sql this URL, so bun's own environment lookup (`POSTGRES_URL`,\n * `DATABASE_URL`, `PGHOST`, …) never chooses the server. A database named in\n * the URL path is pinned explicitly, because bun:sql would otherwise let\n * `PGDATABASE` replace it. Give a complete URL: bun:sql fills parts the URL\n * omits (user, database, …) from the `PG*` variables.\n */\n readonly url: string;\n /** Maximum pooled connections (default 10). */\n readonly max?: number;\n /**\n * Pool-wide `statement_timeout` in milliseconds, sent as a startup parameter\n * so every connection inherits it. A per-transaction `timeout` overrides it\n * for that transaction.\n */\n readonly statementTimeout?: number;\n /**\n * Milliseconds to wait for a connection to be established. Passed to bun:sql\n * as `connectionTimeout` (which expects **seconds**; converted here). Wins\n * over a libpq `connect_timeout` in the URL, which is otherwise honoured.\n */\n readonly connectionTimeout?: number;\n /**\n * Use bun:sql's NAMED prepared statements (default false).\n *\n * Off (the default) runs every statement as an unnamed statement with text\n * results — bun:sql's `prepare: false`, the node-postgres model: values,\n * parameter typing and DDL behaviour match `@vibeorm/adapter-pg`.\n *\n * On, bun:sql keeps one named statement per SQL text per connection,\n * pipelines, and reads results in its binary format, with these driver\n * consequences (README \"Statements and values\"): a statement whose result\n * type a later DDL change alters fails with SQLSTATE 0A000 on that\n * connection until the pool is replaced (node-postgres named statements\n * behave the same); `int4[]`/`float4[]` values with NULL elements or more\n * than one dimension are refused; a JSON text bound into a raw `::jsonb`\n * slot is stored as a JSON string. ORM-path queries also run as tagged\n * templates — on Bun 1.4.3 and newer only those whose placeholders are not\n * `$1 … $n` in order (the rest bind by `$n`, still named).\n */\n readonly preparedStatements?: boolean;\n /** Maximum entries in the synthetic template cache (default 1000, LRU). */\n readonly stmtCacheMax?: number;\n /**\n * PostgreSQL `plan_cache_mode` for every connection. Default: `auto` with\n * unnamed statements (nothing is sent; the server's own default), and\n * `force_custom_plan` with `preparedStatements: true`.\n */\n readonly planCacheMode?: PlanCacheMode;\n};\n\n// ─── Adapter ──────────────────────────────────────────────────────\n\nconst DIALECT: Dialect = \"postgres\";\nconst PROVIDER: Provider = \"postgresql\";\n\n/**\n * bun:sql wire (board #30, live-verified on both execute paths): timestamptz\n * → `Date`, int4/float8 → numbers. (int8 arrives as a string — BigInt\n * decoding is real work and never pruned.)\n *\n * The `json` half is NOT a constant, because bun:sql's answer changed between\n * Bun versions and this package supports a range of them: on Bun 1.3.14 the\n * tagged-template path parsed json/jsonb while `sql.unsafe` did not (board\n * #34 — declaring \"parsed\" there made the runtime prune the Json decoder and\n * leak raw strings), and on Bun 1.4.1 BOTH paths parse (leaving \"text\" makes\n * the guarded decode re-parse a stored top-level JSON string: `\"123\"` becomes\n * the number 123, `\"hello\"` throws). Either constant is wrong on one of those\n * runtimes, so the adapter OBSERVES its own driver once instead of guessing —\n * see {@link probeJsonWire}. {@link WIRE_TEXT} is the conservative claim it\n * starts from; no ORM rows are returned until the probe succeeds.\n */\n/**\n * Timing budgets this adapter genuinely enforces (EPIC 6).\n *\n * - `acquireTimeout: false` — `connectionTimeout` bounds establishment only.\n * Modern Bun supports reserve({ signal }), but implicit query/begin checkout\n * and older supported Bun versions do not provide that cancellation contract.\n * - `statementTimeout: \"all-statements\"` — a real PostgreSQL server, so\n * `statement_timeout` cancels ANY over-long statement, writes included.\n * - `transactionDeadline: \"cancel-running-statements\"` — the remaining budget\n * is handed to the SERVER before each statement, so the database itself stops\n * work that would outlive the deadline.\n */\nconst BUDGETS: AdapterBudgetSupport = Object.freeze({\n acquireTimeout: false,\n statementTimeout: \"all-statements\",\n transactionDeadline: \"cancel-running-statements\",\n accessModes: Object.freeze([\"readOnly\"] as const),\n} as const);\n\nconst WIRE_TEXT: WireFidelity = Object.freeze({ dateTime: \"native\", json: \"text\", numbers: \"native\" } as const);\n\n/** The same wire, for a driver observed to hand back parsed json. */\nconst WIRE_PARSED: WireFidelity = Object.freeze({ dateTime: \"native\", json: \"parsed\", numbers: \"native\" } 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 pool and\n * transaction facades carry the same declaration.\n */\nconst ROUND_TRIPS: NonNullable<DatabaseAdapter[\"roundTrips\"]> = \"network\";\n\n/** `$all`'s snapshot: a read-only REPEATABLE READ transaction reads ONE snapshot and never fails with a serialization error. */\nconst READ_SNAPSHOT: NonNullable<DatabaseAdapter[\"readSnapshot\"]> = Object.freeze({ isolationLevel: \"RepeatableRead\", accessMode: \"readOnly\" } as const);\n\n/**\n * The explicit URL this adapter will use. bun:sql given no URL builds its\n * whole connection from the environment, so a missing one is refused here,\n * before any driver instance exists.\n *\n * @throws VibeError `VIBE_CONFIG` (`meta.reason: \"missing-address\"`) when `url`\n * is absent or blank. The message never echoes a value.\n */\nfunction requireUrl(params: { options: BunAdapterOptions | undefined }): string {\n const url = params.options?.url;\n if (typeof url === \"string\" && url.trim() !== \"\") return url;\n throw new VibeError({\n code: \"VIBE_CONFIG\",\n message:\n \"bunAdapter needs an explicit address: pass `url` (a PostgreSQL URL). \" +\n \"The adapter does not read DATABASE_URL, POSTGRES_URL or the PG* environment variables.\",\n meta: { adapter: \"bun\", reason: \"missing-address\" },\n });\n}\n\n/**\n * Create a VibeORM adapter backed by bun:sql.\n *\n * Requires an explicit `url`; without one the factory throws `VIBE_CONFIG`\n * before any driver instance or connection exists.\n *\n * @example\n * ```ts\n * const adapter = bunAdapter({ url: \"postgresql://app:secret@db.internal:5432/app\", max: 10 });\n * await adapter.connect();\n * const rows = await adapter.execute({ text: 'SELECT * FROM \"User\" WHERE \"id\" = $1', values: [1] });\n * ```\n */\nexport function bunAdapter(options: BunAdapterOptions): DatabaseAdapter {\n refuseUnsupportedBun({ version: Bun.version });\n const usePrepared = options?.preparedStatements ?? false;\n /**\n * bun:sql pipelines NAMED statements by itself: concurrent statements on a\n * transaction's reserved connection share a round trip (pinned live by\n * `tests/round-trip-wire.live.test.ts`, \"concurrent: 3 statements\" — 2 turns\n * named, 5 unnamed). Unnamed statements are not pipelined. No lanes needed\n * for that; the ORDERED scopes of the array `$transaction` (B-02) only fix\n * the order in which a burst's statements reach the connection.\n */\n const pipelining: NonNullable<DatabaseAdapter[\"pipelining\"]> = usePrepared ? \"batched\" : \"ordered\";\n /**\n * B-04: on Bun 1.4.3+, `unsafe(text, values)` on a `prepare: true` instance\n * makes a named statement itself, so named mode binds an ORM statement whose\n * placeholders are `$1 … $n` in order by `$n`, without a synthetic template.\n */\n const namedUnsafe = usePrepared && namedUnsafeBinds({ version: Bun.version });\n // The address is taken once, here: an invalid `connect_timeout` is refused\n // at construction, and nothing later re-reads the options or the environment.\n const address = takeConnectTimeout({ url: requireUrl({ options }) });\n const templates = createTemplateCache({ max: options?.stmtCacheMax ?? 1000 });\n\n /**\n * The wire claim this adapter currently makes. Starts conservative and is\n * replaced at most once, by {@link probeJsonWire}'s observation. Every handle\n * this factory builds — pool, transaction, savepoint, reserved session —\n * reads this one variable, so a transaction can never disagree with its\n * parent (the contract requires transactional adapters to carry the same\n * declaration).\n */\n let activeWire: WireFidelity = WIRE_TEXT;\n let wireSettled = false;\n let wireProbe: Promise<void> | null = null;\n\n let instance: BunInstance | null = null;\n\n // ─── Reserved-connection control (round-trip EPIC 6, pipelining) ───\n\n /**\n * Control texts (BEGIN, COMMIT, SAVEPOINT, the deadline bound) as tagged\n * templates: constant texts on the EXTENDED protocol, which bun:sql\n * pipelines once they are warm on a connection. A separate cache, so ORM\n * traffic can never evict them.\n */\n const controlTemplates = createTemplateCache({ max: 64 });\n\n function controlQuery(params: { connection: BunExecutor; text: string; values?: readonly unknown[] }): Promise<BunResults> {\n return params.connection(controlTemplates.getTemplate({ text: params.text }).template, ...(params.values ?? []));\n }\n\n /**\n * The send discipline of one top-level transaction on its reserved\n * connection:\n *\n * - The opening (`BEGIN …`) and every `SAVEPOINT` wait in `deferred` and go\n * out back to back with the next statement. A transaction whose callback\n * sends nothing sends nothing.\n * - BEGIN rides only ahead of an extended READ: bun:sql syncs per query, so a\n * failed BEGIN would let a pipelined WRITE autocommit. Ahead of anything\n * else BEGIN is awaited first. A read that rode behind a BEGIN that failed\n * rejects with BEGIN's error, and every later statement is refused.\n * - Without a deadline, statements dispatched while the opening is\n * unconfirmed either ride too (extended reads, nobody queued) or wait for\n * it in call order. With a deadline, every send is one turn: [bound,\n * statement] back to back, after the previous turn finished.\n * - Burst failures: the FIRST failure of a burst is the error; a 25P02 reply\n * becomes the aborted refusal naming the failure that aborted the\n * transaction (replies arrive in order on one connection).\n */\n function createReservedControl(params: {\n reserved: BunReserved;\n budget: TransactionBudget;\n scope: SavepointScope;\n /** The deferred opening text, or `null` when the transaction was opened eagerly. */\n opening: string | null;\n }): ReservedControl {\n const { reserved, budget, scope } = params;\n const deferred = createDeferredControl({ opening: params.opening === null ? [] : [params.opening] });\n /** The deferred BEGIN failed: the server holds no transaction. */\n let openingFailure: VibeError | undefined;\n /** The BEGIN step while its reply is outstanding. */\n let openingStep: Promise<unknown> | null = null;\n /** Settles (never rejects) once BEGIN's reply is in and `openingFailure` is recorded. */\n let openingPending: Promise<void> | null = null;\n /** Started-marker of the last statement queued behind the unconfirmed opening. */\n let waitTail: Promise<void> | null = null;\n /** Deadline mode: one turn at a time. */\n let deadlineTail: Promise<void> = Promise.resolve();\n /** The latest server-reported failure, in reply order. */\n let lastFailure: VibeError | undefined;\n\n const step = <T>(query: () => Promise<T>): Promise<T> =>\n new Promise<T>((resolve) => resolve(query())).then(undefined, (error: unknown) => {\n const mapped = mapBunDriverError({ error });\n if (mapped.meta.sqlstate === \"25P02\") {\n throw transactionAbortedError({ cause: lastFailure ?? scope.state.aborted?.cause });\n }\n if (typeof mapped.meta.sqlstate === \"string\") lastFailure = mapped;\n throw mapped;\n });\n\n const trackOpening = (sent: Promise<unknown>): Promise<void> => {\n openingStep = sent;\n const settled: Promise<void> = sent\n .then(ignore, (error: unknown) => {\n openingFailure = mapBunDriverError({ error });\n })\n .then(() => {\n if (openingPending === settled) {\n openingPending = null;\n openingStep = null;\n }\n });\n openingPending = settled;\n return settled;\n };\n\n const ridesOpening = <T>(send: ReservedSend<T>): boolean => send.extended && send.effect === \"read\";\n\n const sendNow = <T>(send: ReservedSend<T>): Promise<T> => {\n const cleanup = send.cleanup === true;\n if (!cleanup) {\n if (openingFailure !== undefined) throw transactionAbortedError({ cause: openingFailure });\n budget.assertUsable({ stage: send.stage ?? \"statement\" });\n send.guard?.();\n }\n const carriesOpening = !cleanup && !deferred.opened();\n const control = cleanup ? [] : [...deferred.take()];\n if (carriesOpening && !ridesOpening(send)) {\n // BEGIN confirmed first: nothing but a read may run behind a BEGIN\n // that could fail. The statement then takes its own turn. A SAVEPOINT\n // taken with BEGIN goes out NOW, right behind it, and its reply is\n // answered by the statement's turn. Behind a failed BEGIN it fails in\n // autocommit with no effect, and the turn refuses with BEGIN's error.\n const [opening, ...rest] = control;\n const confirmed = trackOpening(step(() => controlQuery({ connection: reserved, text: opening as string })));\n const riding = rest.map((text) => {\n const sent = step(() => controlQuery({ connection: reserved, text }));\n // Reported through the statement's turn, or moot after its refusal.\n sent.catch(ignore);\n return sent;\n });\n const next: ReservedSend<T> = { ...send, riding };\n if (budget.totalMs !== null) return confirmed.then(() => sendNow(next));\n return enqueue(next);\n }\n const ms = cleanup ? null : engineStatementBudgetMs({ budget });\n const steps: Promise<unknown>[] = [...(send.riding ?? [])];\n // A read riding a BEGIN that is still unconfirmed answers with BEGIN's error.\n if (!cleanup && !carriesOpening && openingStep !== null) steps.push(openingStep);\n control.forEach((text, index) => {\n const sent = step(() => controlQuery({ connection: reserved, text }));\n if (index === 0 && carriesOpening) trackOpening(sent);\n steps.push(sent);\n });\n if (ms !== null) steps.push(step(() => controlQuery({ connection: reserved, text: STATEMENT_BOUND_TEXT, values: [String(ms)] })));\n let handed = false;\n const statement = step(() => {\n const query = send.send(reserved);\n handed = true;\n return query;\n });\n // After `step` returned: the driver call is queued ahead of anything the\n // signal sends next.\n if (handed) send.onSent?.();\n steps.push(statement);\n return Promise.allSettled(steps).then((settled) => {\n const failed = settled.find((outcome): outcome is PromiseRejectedResult => outcome.status === \"rejected\");\n if (failed !== undefined) throw failed.reason;\n return statement;\n });\n };\n\n const enqueue = <T>(send: ReservedSend<T>): Promise<T> => {\n const prior = waitTail ?? openingPending ?? Promise.resolve();\n let markStarted: () => void = ignore;\n const started = new Promise<void>((resolve) => {\n markStarted = resolve;\n });\n waitTail = started;\n return prior.then(() => {\n try {\n return sendNow(send);\n } finally {\n if (waitTail === started) waitTail = null;\n markStarted();\n }\n });\n };\n\n const dispatch = <T>(send: ReservedSend<T>): Promise<T> => {\n if (budget.totalMs !== null) {\n const pending = deadlineTail.then(() => sendNow(send));\n // A failed turn must not strand the next one (or ROLLBACK).\n deadlineTail = pending.then(ignore, ignore);\n return pending;\n }\n if (openingPending !== null && (waitTail !== null || !ridesOpening(send))) return enqueue(send);\n return new Promise<T>((resolve) => resolve(sendNow(send)));\n };\n\n // ─── Ordered scopes (array `$transaction` bursts, B-02) ───\n //\n // bun:sql pipelines warm NAMED statements by itself; it cannot be told which\n // statements belong together, and ends every query with its own Sync. An\n // ordered scope is therefore a GATE, not a batch: a lane's statements go to\n // `dispatch` only once the lane before it let them go, so they reach the\n // connection in lane order, and a leader's statement and its follower's\n // share a flight. BEGIN is still confirmed before any write (`sendNow`).\n // The lane before lets go once its first statement was HANDED to the driver\n // when every failure of it is answered by the server ({@link serverAnswered}):\n // a later statement then reaches a server that already holds the failure,\n // and its 25P02 reply becomes the aborted refusal (`step`), with no effect.\n // Otherwise it lets go only after that statement's reply, and after a\n // failure nothing behind it is sent.\n\n /** The refusal a scope statement gets behind `cause`: the transaction's own refusal when it has one. */\n const refusalBehind = (cause: unknown): VibeError => {\n if (openingFailure !== undefined) return transactionAbortedError({ cause: openingFailure });\n if (scope.state.poisoned !== null) return scope.state.poisoned;\n return transactionAbortedError({ cause: scope.state.aborted?.cause ?? cause });\n };\n\n const newLane = (orderedScope: OrderedScope, index: number): OrderedLane => {\n let resolveRelease: (release: LaneRelease) => void = ignore;\n const release = new Promise<LaneRelease>((resolve) => {\n resolveRelease = resolve;\n });\n let settled = false;\n return {\n scope: orderedScope,\n index,\n open: true,\n issued: 0,\n followed: false,\n release,\n settle: (outcome) => {\n if (settled) return;\n settled = true;\n resolveRelease(outcome);\n },\n };\n };\n\n /** One non-cleanup statement of an open lane: it waits for the lane before it, then goes to `dispatch`. */\n const laneDispatch = <T>(lane: OrderedLane, send: ReservedSend<T>): Promise<T> => {\n if (lane.followed && lane.issued > 0) {\n return Promise.reject(orderedLaneMisuse({ message: \"a lane that has a follower may issue ONE statement\" }));\n }\n const first = lane.issued === 0;\n lane.issued += 1;\n const go = (before: LaneRelease): Promise<T> => {\n if (before.kind === \"closed\") {\n if (first) lane.settle(LANE_CLOSED);\n return Promise.reject(predecessorClosedError());\n }\n const failed = before.kind === \"failed\" ? { cause: before.cause } : lane.scope.failed;\n if (failed !== undefined) {\n if (first) lane.settle({ kind: \"failed\", cause: failed.cause });\n return Promise.reject(refusalBehind(failed.cause));\n }\n const pipelinable = first && send.pipelinable?.() === true;\n return dispatch<T>({\n ...send,\n onSent: () => {\n send.onSent?.();\n if (pipelinable) lane.settle(LANE_GO);\n },\n }).then(\n (value) => {\n if (first) lane.settle(LANE_GO);\n return value;\n },\n (error: unknown) => {\n lane.scope.failed ??= { cause: error };\n if (first) lane.settle({ kind: \"failed\", cause: error });\n throw error;\n },\n );\n };\n const before = lane.scope.lanes[lane.index - 1];\n return before === undefined ? go(LANE_GO) : before.release.then(go);\n };\n\n const ordered: OrderedScopes = {\n open: (count) => {\n const orderedScope: OrderedScope = { lanes: [] };\n for (let index = 0; index < count; index++) orderedScope.lanes.push(newLane(orderedScope, index));\n return [...orderedScope.lanes];\n },\n follow: (lane) => {\n if (!lane.open) throw orderedLaneMisuse({ message: \"follow() on a closed lane\" });\n if (lane.followed || lane.scope.lanes.at(-1) !== lane) throw orderedLaneMisuse({ message: \"follow() opens one lane after the LAST lane of its scope\" });\n if (lane.issued > 0) throw orderedLaneMisuse({ message: \"follow() must come before the lane issues its statement\" });\n lane.followed = true;\n const next = newLane(lane.scope, lane.scope.lanes.length);\n lane.scope.lanes.push(next);\n return next;\n },\n close: (lane) => {\n if (!lane.open) return;\n lane.open = false;\n // A later lane's statements behind a lane that never issued are refused, never sent.\n if (lane.issued === 0) lane.settle(LANE_CLOSED);\n },\n control: (lane) => {\n // A closed lane's handle sends as the transaction handle does; cleanup\n // control (ROLLBACK TO and its RELEASE) is never held.\n const laneSend = <T>(send: ReservedSend<T>): Promise<T> =>\n send.cleanup === true || !lane.open ? dispatch(send) : laneDispatch(lane, send);\n return {\n deferred,\n dispatch: laneSend,\n executor: ({ effect, guard }) => executorFor({ dispatch: laneSend, effect, guard, lane: true }),\n ordered,\n turn: (): Promise<void> => {\n const before = lane.scope.lanes[lane.index - 1];\n if (!lane.open || before === undefined) return Promise.resolve();\n return before.release.then((release) => {\n if (release.kind === \"closed\") throw predecessorClosedError();\n if (release.kind === \"failed\") throw refusalBehind(release.cause);\n });\n },\n };\n },\n };\n\n return {\n deferred,\n dispatch,\n executor: ({ effect, guard }) => executorFor({ dispatch, effect, guard }),\n ordered,\n };\n }\n\n /**\n * The reserved connection 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`; bun:sql refuses\n * transaction control through `sql.unsafe()` on a pooled instance\n * (`ERR_POSTGRES_UNSAFE_TRANSACTION`), so a pure `BEGIN` reserves one\n * connection, every raw statement until the matching `COMMIT`/`ROLLBACK`\n * rides it, and the close releases it. The ORM path (`execute`) and\n * `transaction()` stay on the pool — they never participate in a raw\n * transaction. Concurrent raw transactions on one adapter are unsupported\n * (they were driver-refused before this pinning existed).\n */\n let rawSession: BunReserved | null = null;\n\n function createSqlInstance(params: { max: number }): BunInstance {\n // bun:sql's own default is named statements; off, the adapter matches\n // node-postgres (see BunAdapterOptions.preparedStatements).\n const sqlOptions: Record<string, unknown> = { max: params.max, prepare: usePrepared };\n if (options?.connectionTimeout !== undefined) {\n // bun:sql expects seconds; the VibeORM surface is milliseconds everywhere.\n sqlOptions.connectionTimeout = Math.max(1, Math.ceil(options.connectionTimeout / 1000));\n } else if (address.seconds !== undefined) {\n sqlOptions.connectionTimeout = address.seconds;\n }\n\n const startupOptions = buildStartupOptions({\n planCacheMode: options?.planCacheMode ?? defaultPlanCacheMode({ preparedStatements: usePrepared }),\n statementTimeout: options?.statementTimeout,\n });\n const url = startupOptions === undefined ? address.url : applyStartupOptions({ url: address.url, startupOptions });\n\n if (URL.canParse(url)) {\n const path = new URL(url).pathname;\n // Native Bun currently lets PGDATABASE override the URL path. Pin only\n // a supplied database; omitted components retain the driver's defaults.\n if (path.length > 1) sqlOptions.database = decodeURIComponent(path.slice(1));\n }\n return createBunSql({ url, options: sqlOptions }) as unknown as BunInstance;\n }\n\n function getSql(): BunInstance {\n instance ??= createSqlInstance({ max: options?.max ?? 10 });\n return instance;\n }\n\n /**\n * Ask THIS driver, once, whether it parses json on the path the ORM reads\n * rows over — the same `execute` path, prepared or unsafe as configured, so\n * the answer describes the traffic the claim is applied to.\n *\n * Runs on the handle that is already in hand (pool, transaction or reserved\n * session): a `SELECT` is harmless inside a transaction, and probing the pool\n * from inside one could deadlock an adapter configured with `max: 1`.\n * Failure refuses this operation. A later call can observe the wire again;\n * no user statement or transaction is retried.\n */\n async function probeJsonWire(source: BunExecutor, onReadControl?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"onReadControl\"]): Promise<void> {\n const probe = renderDiagnostic({ dialect: postgresDialect, query: \"postgresJsonWire\" });\n const result = await runMapped(() => usePrepared\n ? source(templates.getTemplate({ text: probe.text }).template)\n : source.unsafe(probe.text, [])).then(\n (result) => { onReadControl?.({ stage: \"preflight\", rows: finalRows({ result }).length }); return result; },\n (error: unknown) => { onReadControl?.({ stage: \"preflight\", rows: 0 }); throw error; },\n );\n const rows = finalRows({ result });\n const probed = rows[0]?.probe;\n if (typeof probed === \"object\" && probed !== null && \"__vibeorm\" in probed && probed.__vibeorm === 1) activeWire = WIRE_PARSED;\n else if (typeof probed === \"string\" && /^\\{\\s*\"__vibeorm\"\\s*:\\s*1\\s*\\}$/.test(probed)) activeWire = WIRE_TEXT;\n else {\n throw new VibeError({\n code: \"VIBE_ADAPTER\",\n message: \"Bun returned an unrecognized JSON wire probe result; no ORM statement was sent\",\n meta: { reason: \"json-wire-probe\" },\n });\n }\n wireSettled = true;\n }\n\n function observeResult(params: { scope?: SavepointScope; effect?: StatementEffect; result: BunResults }): void {\n if (params.scope === undefined) return;\n const result = params.result;\n const results: BunRows[] = result === null ? [[]] : Array.isArray(result[0]) ? result as BunRows[] : [result as BunRows];\n if (results.length === 0) observeRowChanges({ scope: params.scope, count: statementRowChanges({ effect: params.effect }) });\n for (const rows of results) observeRowChanges({ scope: params.scope, count: statementRowChanges({ effect: params.effect, count: rows.count ?? rows.affectedRows, rows: rows.length, resultRows: rows }) });\n }\n\n async function runExecute(params: {\n source: BunExecutor;\n text: string;\n values: unknown[];\n scope?: SavepointScope;\n effect?: StatementEffect;\n execution?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"execution\"];\n onReadControl?: Parameters<DatabaseAdapter[\"execute\"]>[0][\"onReadControl\"];\n }): Promise<Record<string, unknown>[]> {\n assertReadExecution({ ...params, provider: PROVIDER, stage: \"waiting-for-connection\" });\n // One extra round trip on the first ORM query of this adapter's life; a\n // single boolean test on every one after it. It must complete BEFORE the\n // first rows are handed back, because the runtime reads `wire` to build\n // that read's decode plan.\n if (!wireSettled) {\n if (params.scope === undefined) {\n wireProbe ??= probeJsonWire(params.source, params.onReadControl).finally(() => { wireProbe = null; });\n await wireProbe;\n } else {\n // A transaction handle probes on its OWN connection and never waits\n // for the pool's probe: that probe needs a free pool connection, and\n // every one may be held by a transaction waiting here — a cold\n // adapter with all connections in transactions would hang forever.\n await probeJsonWire(params.source, params.onReadControl);\n }\n }\n assertReadExecution({ ...params, provider: PROVIDER, stage: \"waiting-for-connection\" });\n const values = serializeParams({ values: params.values, namedStatements: usePrepared });\n if (usePrepared) {\n // F19: a tagged template binds POSITIONALLY, one value per gap — so the\n // values follow the placeholder ORDER found in the text (`$2, $1` binds\n // backwards otherwise, and a repeated `$1` needs its value twice).\n const prepared = templates.getTemplate({ text: params.text });\n const identity = prepared.identityOrder && prepared.indices.length === values.length;\n const bound = identity\n ? values\n : bindTemplateValues({ text: params.text, indices: prepared.indices, values });\n // A placeholder repeated in the text is bound once per gap; past the\n // protocol's limit that expansion would refuse a statement whose own\n // parameter count is legal, so it runs by `$n` instead. B-04: where\n // `unsafe` names its statement itself, a `$1 … $n` text with exactly n\n // values binds the same values by `$n` as through the template, so it\n // skips the template (and its rest-argument spread). Without values it\n // keeps the template: `unsafe(text, [])` may go as a simple query.\n const result = bound.length > MAX_BIND_PARAMETERS || (namedUnsafe && identity && values.length > 0)\n ? await runMapped(() => params.source.unsafe(params.text, values))\n : await runMapped(() => params.source(prepared.template, ...bound));\n observeResult({ scope: params.scope, effect: params.effect, result });\n return plainRows({ rows: finalRows({ result }) });\n }\n const result = await runMapped(() => params.source.unsafe(params.text, values));\n observeResult({ scope: params.scope, effect: params.effect, result });\n return plainRows({ rows: finalRows({ result }) });\n }\n\n async function runExecuteUnsafe(params: {\n source: BunExecutor;\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, namedStatements: usePrepared });\n const result = await runMapped(() => params.source.unsafe(params.text, values));\n observeResult({ scope: params.scope, effect: params.effect, result });\n const rows = finalRows({ result });\n return { rows: plainRows({ rows }), affectedRows: readAffectedRows({ rows }) };\n }\n\n /**\n * Build the adapter facade over any bun:sql handle. `parentMode` decides\n * whether a nested `transaction()` opens a real transaction or a savepoint;\n * `scope` is shared by reference across one top-level transaction, and the\n * savepoint gate serializes overlapping sibling savepoints (F14) on BOTH the\n * driver-managed and the manual path.\n */\n function createAdapter(params: {\n source: BunSource;\n parentMode: ParentMode;\n scope: SavepointScope;\n /** The enclosing transaction's budget; absent on the pool-level adapter. */\n budget?: TransactionBudget;\n lifetime?: { active: boolean };\n /** The reserved connection's send discipline; absent on the pool-level adapter. */\n control?: ReservedControl;\n /**\n * This handle offers ordered scopes (`orderedPipeline`, B-02): only the\n * top-level handle of a named-statement transaction without a `deadline`\n * or a `timeout`. Lane and nested handles never do.\n */\n ordered?: boolean;\n }): DatabaseAdapter {\n const { source, parentMode, scope, budget, lifetime, control } = params;\n\n function assertHandle(): void {\n budget?.assertUsable({ stage: \"statement\" });\n if (lifetime?.active === false) {\n throw new VibeError({\n code: \"VIBE_TRANSACTION\",\n message: \"this savepoint callback has finished; its transaction handle has expired\",\n meta: { reason: \"expired\" },\n });\n }\n if (scope.state.poisoned !== null) throw scope.state.poisoned;\n }\n\n /**\n * Nested transaction: a savepoint on the reserved connection, driven by\n * hand. EPIC 6: `SAVEPOINT` rides with the body's first statement; a body\n * that sent nothing sends neither its RELEASE nor its ROLLBACK TO.\n */\n async function transactionViaSavepoint<T>(\n reservedControl: ReservedControl,\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n nestedOptions?: TransactionOptions,\n ): Promise<T> {\n refuseNestedTransactionOptions({ options: nestedOptions, provider: PROVIDER });\n assertHandle();\n budget?.assertUsable({ stage: \"nested\" });\n // A lane of an ordered scope: the SAVEPOINT this defers must ride with\n // this lane's statement, never with an earlier lane's still unsent one.\n if (reservedControl.turn !== undefined) {\n await reservedControl.turn();\n assertHandle();\n }\n const savepointControl = (statement: string, cleanup: boolean): Promise<unknown> | undefined => {\n if (reservedControl.deferred.routeSavepoint({ text: statement }) !== \"send\") return undefined;\n return reservedControl.dispatch({\n extended: true,\n ...(cleanup ? { cleanup: true } : {}),\n send: (connection) => controlQuery({ connection, text: statement }),\n });\n };\n return runNestedSavepoint({\n scope,\n execute: (statement) => savepointControl(statement, false),\n cleanup: (statement: string) => savepointControl(statement, true),\n body: async (child) => {\n assertHandle();\n const childLifetime = { active: true };\n try {\n return await fn(createAdapter({ source, parentMode: \"tx\", scope: child, budget, lifetime: childLifetime, control: reservedControl }));\n } finally {\n childLifetime.active = false;\n }\n },\n });\n }\n\n /** Top-level transaction on the pool. */\n async function transactionViaPool<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n const pool = source as BunInstance;\n\n // Refuse an unsupportable budget before any connection is taken.\n validateTransactionDeadline({\n options: transactionOptions,\n support: BUDGETS.transactionDeadline,\n provider: PROVIDER,\n settings: \"transaction-local\",\n });\n\n const readOnly = readOnlyRequested({ options: transactionOptions, provider: PROVIDER });\n\n // Round-trip EPIC 6: EVERY top-level transaction reserves one connection\n // and drives control by hand, so BEGIN / SAVEPOINT / the deadline bound\n // can ride with the next statement (see createReservedControl). With a\n // `timeout` the opening stays EPIC 3's ONE eager simple-protocol message\n // (BEGIN […]; SET LOCAL statement_timeout = N), validated here, before\n // the reservation, so its errors surface before the callback runs.\n const openingOptions = { isolationLevel: transactionOptions?.isolationLevel, readOnly };\n const eagerOpen = transactionOptions?.timeout === undefined\n ? null\n : openTransactionStatement({ ...openingOptions, timeout: transactionOptions.timeout });\n // TU-02: transaction settings, validated and rendered before the\n // reservation. None = today's path, byte for byte.\n const settings = readTransactionSettings({ settings: transactionOptions?.settings, provider: PROVIDER });\n const settingsStatement = settings.length === 0 ? undefined : renderTransactionSettings({ settings });\n const reserved = await runMapped(() => pool.reserve());\n // The deadline clock starts HERE: the connection is reserved, so waiting\n // for it is not charged against the caller's transaction budget.\n const budget = startTransactionBudget({ options: transactionOptions, provider: PROVIDER });\n const txScope = createSavepointScope();\n const control = createReservedControl({\n reserved,\n budget,\n scope: txScope,\n // With settings (TU-02) the opening is sent eagerly (`openWithSettings`).\n opening: eagerOpen === null && settingsStatement === undefined ? beginStatement(openingOptions) : null,\n });\n /**\n * How far COMMIT got — the only input of the commit outcome (EPIC T). A\n * holder, because the `send` callback below moves it out of sight of\n * the compiler's narrowing.\n */\n const commit: { progress: CommitProgress } = { progress: \"not-sent\" };\n let discard = false;\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. BEGIN is confirmed before the bound settings statement is sent:\n * bun:sql's independent query Sync boundaries do not skip that statement\n * after a failed opening. A refused setting (a server answer) is rolled\n * back and attributed from its original diagnostic.\n */\n const openWithSettings = async (statement: TransactionSettingsStatement): Promise<void> => {\n await (eagerOpen === null\n ? controlQuery({ connection: reserved, text: beginStatement(openingOptions) })\n : reserved.unsafe(eagerOpen)).then(undefined, (error: unknown) => {\n throw mapBunDriverError({ error });\n });\n const failed = await controlQuery({ connection: reserved, text: statement.text, values: statement.values }).then(\n () => undefined,\n (error: unknown) => ({ error }),\n );\n if (failed === undefined) return;\n const cause = mapBunDriverError({ 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 reserved.unsafe(\"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) await openWithSettings(settingsStatement);\n else if (eagerOpen !== null) await runMapped(() => reserved.unsafe(eagerOpen));\n const txAdapter = createAdapter({\n source: reserved,\n parentMode: \"tx\",\n scope: txScope,\n budget,\n control,\n // B-02: ordered scopes (array `$transaction` bursts) only where\n // bun:sql pipelines (named statements), and only where no statement\n // keeps its own turn: no deadline bound, no eager `timeout` opening.\n ordered: usePrepared && budget.totalMs === null && eagerOpen === null,\n });\n const result = await runRootScope({ scope: txScope, body: () => fn(txAdapter) });\n // An expired budget must never commit, however the callback ended.\n budget.assertUsable({ stage: \"commit\" });\n if (!control.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 const reply = await control.dispatch({\n extended: true,\n effect: \"write\",\n stage: \"commit\",\n send: (connection) => {\n commit.progress = \"sent\";\n return controlQuery({ connection, text: \"COMMIT\" });\n },\n });\n // An aborted transaction's COMMIT is answered with a ROLLBACK tag and\n // no error: the outcome is a certain rollback.\n if (finalRows({ result: reply }).command === \"ROLLBACK\") {\n commit.progress = \"answered\";\n throw transactionAbortedError({ cause: txScope.state.aborted?.cause });\n }\n budget.close({ outcome: \"committed\" });\n return result;\n } catch (error) {\n if (txScope.state.poisoned !== null) discard = true;\n // A failed COMMIT is an unknown outcome only when the connection was\n // lost; a server answer with a SQLSTATE (a deferred FK, a\n // serialization failure) is a definite rollback and raises that\n // precise error, as on adapter-pg (EPIC 6 decision 2, RV5 MJ-3).\n if (commit.progress === \"sent\") commit.progress = isConnectionLoss({ error }) ? \"unanswered\" : \"answered\";\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 (control.deferred.opened()) {\n await control.dispatch({ extended: false, cleanup: true, send: (connection) => connection.unsafe(\"ROLLBACK\") });\n rollback = \"acknowledged\";\n }\n } catch {\n // The rollback that should have cleaned up failed. `SET LOCAL` reverts\n // with the transaction, but this session's transaction state can no\n // longer be asserted, so the reserved connection is closed. The\n // commit outcome does not change: it follows from how far COMMIT got.\n discard = true;\n rollback = \"failed\";\n }\n // Only a COMMIT whose answer was lost hides the outcome from the\n // caller. A failure before COMMIT keeps its own error even when the\n // cleanup ROLLBACK failed too, like node-postgres (EPIC T: the facts\n // ride beside it, read with `transactionOutcomeOf({ error })`).\n const own = commit.progress === \"unanswered\" && txScope.state.poisoned === null\n ? unknownOutcome({ cause: error })\n : error;\n throw settleFailedTransaction({\n error: own,\n provider: PROVIDER,\n budget,\n scope: txScope,\n commit: commit.progress,\n rollback,\n connection: discard ? \"discarded\" : \"returned\",\n });\n } finally {\n if (discard) await runMapped(() => reserved.close());\n else reserved.release();\n }\n }\n\n const handle: DatabaseAdapter = {\n dialect: DIALECT,\n provider: PROVIDER,\n budgets: BUDGETS,\n readCancellation: \"before-dispatch\",\n roundTrips: ROUND_TRIPS,\n readSnapshot: READ_SNAPSHOT,\n pipelining,\n ...(params.ordered !== true || control === undefined ? {} : {\n orderedPipeline: true as const,\n pipeline: ({ lanes: count, ordered }: { lanes: number; ordered?: true }): readonly PipelineLane[] => {\n assertHandle();\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 // `$all` (an unordered scope): bun:sql pipelines concurrent named\n // statements by itself, so every lane is this handle, as before.\n if (ordered !== true) return Array.from({ length: count }, (): PipelineLane => ({ adapter: handle, close: ignore }));\n const laneHandle = (lane: OrderedLane): PipelineLane => ({\n adapter: createAdapter({ source, parentMode: \"tx\", scope, budget, control: control.ordered.control(lane) }),\n close: (): void => { control.ordered.close(lane); },\n follow: (): PipelineLane => {\n assertHandle();\n return laneHandle(control.ordered.follow(lane));\n },\n });\n return control.ordered.open(count).map(laneHandle);\n },\n }),\n ...(parentMode === \"pool\" ? {} : { rowChanges: (): RowChangeCount => { assertHandle(); return readRowChanges({ scope }); } }),\n get wire(): WireFidelity {\n return activeWire;\n },\n\n async execute(execParams) {\n return runReadExecution({ ...execParams, provider: PROVIDER, run: async () => {\n assertHandle();\n const turn = scopeTurn({ scope });\n if (turn !== undefined) await turn;\n assertHandle();\n const guard = (): void => { assertHandle(); assertReadExecution({ ...execParams, provider: PROVIDER, stage: \"waiting-for-connection\" }); };\n const executor = control === undefined ? source : control.executor({ effect: execParams.effect, guard });\n const result = runExecute({ source: executor, ...(parentMode === \"pool\" ? {} : { scope }), ...execParams });\n // Inside a transaction a server-reported failure aborts it (postgres):\n // record it so a callback that swallows it cannot commit nothing. The\n // pool-level handle has no transaction to abort.\n return parentMode === \"pool\"\n ? result\n : result.catch((error: unknown) => abortTransactionOnStatementFailure({ scope, error }));\n } });\n },\n\n async executeUnsafe(execParams) {\n assertHandle();\n const turn = scopeTurn({ scope });\n if (turn !== undefined) await turn;\n assertHandle();\n const executor = control === undefined ? source : control.executor({ effect: execParams.effect, guard: assertHandle });\n const result = runExecuteUnsafe({ source: executor, ...(parentMode === \"pool\" ? {} : { scope }), ...execParams });\n return parentMode === \"pool\"\n ? result\n : result.catch((error: unknown) => abortTransactionOnStatementFailure({ scope, error }));\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n return control === undefined\n ? transactionViaPool(fn, transactionOptions)\n : transactionViaSavepoint(control, fn, transactionOptions);\n },\n\n async connect(): Promise<void> {\n if (parentMode !== \"pool\") {\n // The open transaction owns this connection; an expired handle keeps\n // its own refusal (checked first).\n assertHandle();\n throw transactionLifecycleRefusal({ method: \"connect\" });\n }\n const reserved = await runMapped(() => (source as BunInstance).reserve());\n try {\n // Round-trip EPIC 3 (A-13): settle the JSON wire probe here, on the\n // connection already in hand, so the first ORM statement does not\n // pay it. A failure rejects connect() and leaves the wire unsettled:\n // the lazy path in runExecute probes again, as after any failed probe.\n // A probe already in flight (a first query's, on the pool) settles\n // the wire by itself: never wait for it while holding this\n // reservation — on a one-connection pool that probe needs it\n // (fix lane FX-A, RV2 MJ-2).\n if (!wireSettled && wireProbe === null) {\n wireProbe = probeJsonWire(reserved).finally(() => { wireProbe = null; });\n await wireProbe;\n }\n } finally {\n reserved.release();\n }\n },\n\n async disconnect(): Promise<void> {\n if (parentMode !== \"pool\") {\n assertHandle();\n throw transactionLifecycleRefusal({ method: \"disconnect\" });\n }\n await runMapped(() => (source as BunInstance).close());\n instance = null;\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return toPgArrayLiteral(values);\n },\n };\n return handle;\n }\n\n /** Pool-level facade — the bun:sql client is created on first use. */\n function poolAdapter(): DatabaseAdapter {\n return createAdapter({\n source: getSql(),\n parentMode: \"pool\",\n scope: createSavepointScope(),\n });\n }\n\n /**\n * Final cleanup, run ONCE by the lifecycle gate after every admitted\n * operation settled — a pending raw BEGIN has published its session, and\n * every admitted `withSession` has closed its private pool. Rolls back an\n * abandoned raw transaction, then closes the instance. A failed ROLLBACK is\n * reported as `disconnect()`'s outcome (the instance still closes, and\n * takes the session with it); the session is released either way, because\n * bun:sql does not settle its pool's pending count when a reserved\n * connection closes (see `withSession`).\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 rawSession = null;\n await runMapped(() => session.unsafe(\"ROLLBACK\")).then(\n () => { session.release(); },\n (error: unknown) => { session.release(); throw error; },\n );\n },\n async (): Promise<void> => {\n if (instance === null) return;\n const closing = instance;\n instance = null;\n await runMapped(() => closing.close());\n },\n ],\n });\n }\n\n const lifecycle = createAdapterLifecycleGate({ driver: \"bun\", 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 // Bun 1.3 does not decrement its pool's pending counter when a reserved\n // connection closes or dies. Own a private one-connection driver instance\n // so cleanup cannot hang or force-close unrelated application work.\n const sessionPool = createSqlInstance({ max: SESSION_CONNECTION.max });\n const close = (): Promise<void> => runMapped(() => sessionPool.close({ timeout: SESSION_CONNECTION.closeGraceSeconds }));\n const reserved = await runMapped(() => sessionPool.reserve()).catch(async (cause: unknown) => {\n await close().catch((cleanupCause: unknown) => {\n if (cause instanceof VibeError) throw new VibeError({ code: cause.code, message: cause.message, meta: { ...cause.meta, cleanupCause }, cause });\n throw cause;\n });\n throw cause;\n });\n return runPinnedSession({\n run,\n execute: async (query) => (await runExecuteUnsafe({ source: reserved, ...query })).rows,\n isLost: (error) => error instanceof VibeError && isConnectionLoss({ error }),\n release: close,\n });\n },\n\n async execute(params) {\n return runExecute({ source: getSql(), ...params });\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 rawSession = null;\n try {\n return await runExecuteUnsafe({ source: session, ...params });\n } finally {\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({ source: rawSession, ...params });\n }\n if (control === \"open\") {\n const reserved = await runMapped(() => getSql().reserve());\n try {\n const result = await runExecuteUnsafe({ source: reserved, ...params });\n rawSession = reserved;\n return result;\n } catch (error) {\n reserved.release();\n throw error;\n }\n }\n return runExecuteUnsafe({ source: getSql(), ...params });\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n return poolAdapter().transaction(fn, transactionOptions);\n },\n\n async connect(): Promise<void> {\n return poolAdapter().connect();\n },\n };\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n budgets: BUDGETS,\n readCancellation: \"before-dispatch\",\n roundTrips: ROUND_TRIPS,\n readSnapshot: READ_SNAPSHOT,\n pipelining,\n transactionOutcome: \"reported\",\n transactionSettings: \"transaction-local\",\n get wire(): WireFidelity {\n return activeWire;\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, 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, private session pools included\n * — then closes the instance, once. Repeated calls share that completion.\n * A new adapter 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 toPgArrayLiteral(values);\n },\n };\n}\n\n/**\n * Rows affected by a bun:sql statement: the driver attaches `count` (and, on\n * some versions, `affectedRows`) to the returned array; otherwise the number of\n * returned rows is the best available answer.\n */\nfunction readAffectedRows(params: { rows: BunRows }): number {\n const { rows } = params;\n if (typeof rows.count === \"number\") return rows.count;\n if (typeof rows.affectedRows === \"number\") return rows.affectedRows;\n return rows.length;\n}\n\n/**\n * The rows as a plain `Array`, like node-postgres' `result.rows`. bun:sql\n * resolves to its own `SQLResultArray`, which carries `count`, `command`,\n * `affectedRows` and `lastInsertRowid` as own properties — a caller that\n * compares, spreads or clones a `findMany` result would otherwise see them.\n */\nfunction plainRows(params: { rows: BunRows }): Record<string, unknown>[] {\n return Array.from(params.rows);\n}\n\n/** Bun's simple protocol returns an outer array for scripts; final command wins. */\nfunction finalRows(params: { result: BunResults }): BunRows {\n const { result } = params;\n if (result === null) return [];\n return Array.isArray(result[0]) ? (result as BunRows[]).at(-1) ?? [] : result as BunRows;\n}\n\n/**\n * Whether a mapped failure means the CONNECTION is gone rather than the server\n * having answered: no SQLSTATE at all (socket-level or a driver refusal), class\n * 08 (connection exception) or an admin/crash shutdown (57P01–57P03). The same\n * rule as `@vibeorm/adapter-pg`: it pins a session as lost and decides whether\n * a failed COMMIT's 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 statement failure inside a transaction. A server-reported failure aborts\n * the transaction ({@link abortTransactionOnServerFailure}). bun:sql also\n * refuses a statement with more than 65,535 parameters BEFORE sending it,\n * where node-postgres sends it and the server aborts the transaction (08P01) —\n * so that refusal aborts it here too, and a callback that catches it cannot\n * commit the transaction's other writes.\n */\nfunction abortTransactionOnStatementFailure(params: { scope: SavepointScope; error: unknown }): never {\n const { scope, error } = params;\n if (error instanceof VibeError && error.meta.driverCode === \"ERR_POSTGRES_TOO_MANY_PARAMETERS\") {\n markTransactionAborted({ scope, cause: error });\n }\n return abortTransactionOnServerFailure({ scope, error });\n}\n\nfunction unknownOutcome(params: { cause: unknown; reason?: string }): VibeError {\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message: \"Bun could not confirm transaction recovery or completion; the outcome is unknown. Nothing is retried automatically.\",\n meta: { reason: params.reason ?? \"transaction-outcome-unknown\", outcome: \"unknown\" },\n cause: params.cause,\n });\n}\n\n// ─── Re-exports (driver-error table, params, helpers) ─────────────\n\nexport {\n BUN_SQLSTATE_ERROR_CODES,\n BUN_SQLSTATE_REASONS,\n bunErrorSqlstate,\n mapBunDriverError,\n} from \"./errors.ts\";\nexport { serializeParams, serializeParamsRaw, toPgArrayLiteral } from \"./params.ts\";\nexport { applyStartupOptions, buildStartupOptions } from \"./connection-url.ts\";\nexport type { PlanCacheMode } from \"./connection-url.ts\";\nexport { createSavepointCounter, nextSavepointName } from \"@vibeorm/runtime/adapter-kit\";\nexport type { SavepointCounter } from \"@vibeorm/runtime/adapter-kit\";\nexport { createTemplateCache, templateChunks } from \"./template-cache.ts\";\nexport type { TemplateCache } from \"./template-cache.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",
9
+ "/**\n * Connection-URL handling for bun:sql.\n *\n * Per-connection PostgreSQL settings (`plan_cache_mode`, `statement_timeout`)\n * travel in the `options` startup parameter, which the server parses for\n * `-c key=value` pairs — so every connection in bun's internal pool inherits\n * them without a per-query round trip.\n *\n * v1 lesson (LEARNINGS.md): bun:sql forwards *unrecognised* URL parameters to\n * the server as runtime configuration, so a libpq client-side option such as\n * `connect_timeout` reaches PostgreSQL, which rejects it as an unrecognised\n * configuration parameter (42704). A URL written for libpq or node-postgres\n * still works here: {@link takeConnectTimeout} removes `connect_timeout` and\n * hands its seconds to bun:sql's `connectionTimeout` constructor option.\n */\n\nimport { VibeError } from \"@vibeorm/schema\";\n\n/**\n * PostgreSQL plan-cache behaviour for every plan the server caches on the\n * connection: the NAMED statements bun:sql keeps with `preparedStatements:\n * true`, and the SPI plans of foreign-key checks, triggers and PL/pgSQL\n * functions in every mode. `force_custom_plan` replans with the real parameter\n * values (≈0.1 ms per query) and keeps index selection optimal on\n * range/LIKE/skewed filters — `auto` lets PostgreSQL switch to a generic plan\n * after ~5 executions. An unnamed statement (the default mode) is planned for\n * its own values whatever this says.\n */\nexport type PlanCacheMode = \"auto\" | \"force_custom_plan\" | \"force_generic_plan\";\n\n/**\n * The `plan_cache_mode` a connection gets when the caller sets none\n * (performance audit round 2, B-01).\n *\n * - Unnamed statements (the default): `auto`. Every ORM statement is re-parsed\n * and gets a custom plan anyway, so `force_custom_plan` changed only the SPI\n * plans — it replanned the foreign-key check of every inserted row (measured:\n * `createMany` of 1000 rows 20.3 → 16.2 ms, the same as adapter-pg, which\n * sends no setting).\n * - Named statements (`preparedStatements: true`): `force_custom_plan`, so a\n * named statement never switches to a generic plan after five executions\n * (reads with skewed filters were not measured under `auto`).\n */\nexport function defaultPlanCacheMode(params: { preparedStatements: boolean }): PlanCacheMode {\n return params.preparedStatements ? \"force_custom_plan\" : \"auto\";\n}\n\n/**\n * Build the `options` startup string, or `undefined` when nothing needs setting.\n *\n * @throws VibeError `VIBE_VALIDATION` when `statementTimeout` is not a\n * non-negative integer — the value ends up inside the startup string verbatim.\n */\nexport function buildStartupOptions(params: {\n planCacheMode: PlanCacheMode;\n statementTimeout?: number;\n}): string | undefined {\n const { planCacheMode, statementTimeout } = params;\n const parts: string[] = [];\n if (planCacheMode !== \"auto\") parts.push(`-c plan_cache_mode=${planCacheMode}`);\n if (statementTimeout !== undefined) {\n if (!Number.isInteger(statementTimeout) || statementTimeout < 0) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `statementTimeout must be a non-negative integer of milliseconds, received ${String(statementTimeout)}`,\n meta: { statementTimeout },\n });\n }\n parts.push(`-c statement_timeout=${statementTimeout}`);\n }\n return parts.length === 0 ? undefined : parts.join(\" \");\n}\n\n/**\n * Remove libpq's client-side `connect_timeout` (whole seconds) from a URL and\n * return its value, so the URL bun:sql forwards to the server no longer carries\n * it. `0` or a negative value means \"no limit\" in libpq and yields\n * `undefined`. A URL bun cannot parse is returned unchanged.\n *\n * @throws VibeError `VIBE_VALIDATION` when the value is not an integer.\n */\nexport function takeConnectTimeout(params: { url: string }): { url: string; seconds?: number } {\n if (!URL.canParse(params.url)) return { url: params.url };\n const url = new URL(params.url);\n const raw = url.searchParams.get(\"connect_timeout\");\n if (raw === null) return { url: params.url };\n const seconds = Number(raw.trim());\n if (raw.trim() === \"\" || !Number.isInteger(seconds)) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `connect_timeout in the connection URL must be an integer number of seconds, received \"${raw}\"`,\n meta: { connectTimeout: raw },\n });\n }\n url.searchParams.delete(\"connect_timeout\");\n url.search = url.searchParams.toString().replace(/\\+/g, \"%20\");\n return seconds > 0 ? { url: url.toString(), seconds } : { url: url.toString() };\n}\n\n/** Merge startup settings into one `options` key; adapter settings take precedence. */\nexport function applyStartupOptions(params: { url: string; startupOptions: string }): string {\n if (!URL.canParse(params.url)) {\n throw new VibeError({ code: \"VIBE_VALIDATION\", message: \"invalid PostgreSQL connection URL\" });\n }\n const url = new URL(params.url);\n const merged = [...url.searchParams.getAll(\"options\"), params.startupOptions].filter(Boolean).join(\" \");\n url.searchParams.set(\"options\", merged);\n url.search = url.searchParams.toString().replace(/\\+/g, \"%20\");\n return url.toString();\n}\n",
10
10
  "/**\n * Driver-error mapping for `bun:sql`.\n *\n * bun:sql raises `SQL.PostgresError` for server failures and for client-side\n * problems alike. Server failures carry the PostgreSQL SQLSTATE — depending on\n * the Bun version on `code` or on `errno` — while client-side failures use a\n * `ERR_POSTGRES_*` identifier in `code`. Both shapes are read here, so the\n * mapping is stable across Bun versions. Constitution rule 5: only `VibeError`\n * escapes the adapter.\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 (including every `ERR_POSTGRES_*` connection\n * or auth failure) maps to `VIBE_ADAPTER`.\n */\nexport const BUN_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 /** Data exceptions the same bad input raises (mirrors adapter-pg): too long, out of range, bad datetime, datetime overflow. */\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 on already-locked rows, or an\n * expired `lock_timeout`. Postgres reports both with this one SQLSTATE.\n */\n \"55P03\": \"VIBE_LOCK_NOT_AVAILABLE\",\n /** read_only_sql_transaction — a write inside a READ ONLY transaction (mirrors adapter-pg). */\n \"25006\": \"VIBE_TRANSACTION\",\n});\n\n/** SQLSTATEs that additionally explain themselves through `meta.reason`. */\nexport const BUN_SQLSTATE_REASONS: Readonly<Record<string, string>> = Object.freeze({\n \"23P01\": \"exclusion-violation\",\n \"57014\": \"timeout\",\n \"55P03\": \"lock-not-available\",\n \"40P01\": \"deadlock\",\n \"40001\": \"serialization-failure\",\n \"25006\": \"read-only-transaction\",\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, mirrors adapter-pg).\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 bun:sql error, accepting it on either `code` or\n * `errno`. `ERR_POSTGRES_*` identifiers are not SQLSTATEs and yield `undefined`.\n */\nexport function bunErrorSqlstate(params: { error: unknown }): string | undefined {\n const { error } = params;\n if (error === null || typeof error !== \"object\") return undefined;\n const source = error as Record<string, unknown>;\n for (const key of [\"code\", \"errno\"]) {\n const value = readStringField({ source, key });\n if (value !== undefined && SQLSTATE_PATTERN.test(value)) return value;\n }\n return undefined;\n}\n\n// ─── Mapping ──────────────────────────────────────────────────────\n\n/**\n * Map any error thrown by bun:sql 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 mapBunDriverError(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 = bunErrorSqlstate({ error });\n const code: VibeErrorCode =\n (sqlstate === undefined ? undefined : BUN_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 : BUN_SQLSTATE_REASONS[sqlstate];\n if (reason !== undefined) meta.reason = reason;\n // Keep bun's own identifier when it is not a SQLSTATE — it is the only clue\n // a connection/auth/protocol failure carries.\n const driverCode = readStringField({ source, key: \"code\" });\n if (driverCode !== undefined && driverCode !== sqlstate) meta.driverCode = driverCode;\n\n const message =\n readStringField({ source, key: \"message\" }) ??\n (typeof error === \"string\" ? error : \"unknown bun:sql driver error\");\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 mapBunDriverError({ error });\n }\n}\n",
11
11
  "/**\n * Parameter serialization for bun:sql: the values node-postgres would send.\n *\n * Live-verified on Bun 1.4.1 and 1.4.3 (`tests/node-postgres-parity.live.test.ts`):\n * - bun:sql types a JS number itself (int32 → `int4`, anything else →\n * `float8`) and lets the SERVER cast from that type, so numbers, bigints and\n * booleans go out as text and the server reads them as the slot's own type;\n * - a plain JS array bound to a scalar-list column (`text[]`, `int[]`) is NOT\n * turned into a PostgreSQL array literal by bun:sql — it arrives as `a,b` and\n * the server rejects it with `malformed array literal`. Scalar lists therefore\n * have to be pre-rendered with {@link toPgArrayLiteral}, which is exactly what\n * the adapter's `formatArrayParam` returns;\n * - with NAMED statements (`preparedStatements: true`) bun:sql learns each\n * slot's type first and JSON-encodes whatever is bound to a `json`/`jsonb`\n * slot, a string included; with unnamed statements (the default) a string is\n * sent as text and the server parses it, like node-postgres.\n *\n * Hence the split (LEARNINGS.md): the ORM path only respells scalars (scalar\n * lists already arrived as literal strings, Json values as JSON text bound\n * through `::text::jsonb`), while the raw path renders plain JS arrays as array\n * literals so `db.$queryRawUnsafe('… = ANY($1)', [1, 2, 3])` matches rows.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport { VibeError } from \"@vibeorm/schema\";\n\n// ─── PostgreSQL array literals ────────────────────────────────────\n\n/** Quote and escape one array element: `\"` and `\\` are the special characters. */\nfunction quoteElement(value: string): string {\n return `\"${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/**\n * Render a JS array as a PostgreSQL array literal string.\n *\n * Element handling:\n * - `null` / `undefined` → unquoted `NULL`\n * - `number` / `bigint` / `boolean` → unquoted primitive\n * - `Date` → quoted ISO-8601 (PostgreSQL cannot parse `String(date)`)\n * - `string` → quoted, with `\"` and `\\` escaped (so commas, braces and quotes\n * inside an element are safe)\n * - any other object, **including a nested array** → quoted `JSON.stringify`,\n * which is what a `Json[]` scalar list needs (PostgreSQL scalar lists are\n * one-dimensional, so a nested array is a JSON value, not a matrix)\n * - `Uint8Array` (including `Buffer`) → quoted PostgreSQL bytea hex\n * - other binary views / `ArrayBuffer` → unsupported, throws\n *\n * @throws VibeError `VIBE_VALIDATION` for unsupported binary elements.\n */\nexport function toPgArrayLiteral(values: readonly unknown[]): string {\n const elements = values.map((value) => {\n if (value === null || value === undefined) return \"NULL\";\n if (typeof value === \"number\" || typeof value === \"bigint\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value instanceof Date) return quoteElement(value.toISOString());\n if (value instanceof Uint8Array) {\n return quoteElement(`\\\\x${Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString(\"hex\")}`);\n }\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: \"binary values are not supported inside a postgres array literal\",\n meta: { driver: \"bun:sql\" },\n });\n }\n if (typeof value === \"string\") return quoteElement(value);\n if (typeof value === \"object\") return quoteElement(JSON.stringify(value));\n return quoteElement(String(value));\n });\n return `{${elements.join(\",\")}}`;\n}\n\n// ─── Serialization ────────────────────────────────────────────────\n\n/**\n * `Date` → UTC ISO-8601 text (`2026-03-08T19:38:08.538Z`), the same spelling\n * the array literal above uses.\n *\n * bun:sql serializes a `Date` by the parameter's RESOLVED postgres type\n * (LEARNINGS): fine for `timestamp`/`timestamptz` (UTC text), but a `date`\n * parameter gets `Date#toString()` — `Sun Mar 08 2026 23:30:00 GMT+0000\n * (Coordinated Universal Time)` — which the server rejects in every host TZ\n * (live on Bun 1.4.3: `invalid input syntax for type date` under UTC, `time\n * zone \"gmt-0400\" not recognized` under America/New_York). The ISO text\n * parses for all three, and pins the UTC wall-clock contract the codec table\n * and the other postgres adapters share. Dates the ISO form cannot spell\n * (invalid, BC, beyond year 9999) keep the driver's serializer.\n */\nexport function serializeDate(params: { value: Date }): unknown {\n const { value } = params;\n if (Number.isNaN(value.getTime())) return value;\n const year = value.getUTCFullYear();\n if (year < 1 || year > 9999) return value;\n return value.toISOString();\n}\n\n/**\n * Numbers, bigints and booleans as their text spelling — what node-postgres\n * sends (`prepareValue` → `toString()`).\n *\n * bun:sql types a JS number by its own rule (int32 → `int4`, anything else →\n * `float8`) and binds it in that type, so the SERVER casts: `0.1` into an\n * `int4` slot is silently stored as `0`, `0.30000000000000004` into `numeric`\n * becomes `0.3`, and `0.1` compared with a `real` column matches nothing,\n * because the column widens to `float8` instead of the literal narrowing to\n * `real`. Text lets the server read the literal as the slot's own type —\n * exact, or refused with SQLSTATE 22P02 exactly like node-postgres.\n */\nfunction serializeScalar(value: unknown): unknown {\n if (typeof value === \"number\" || typeof value === \"bigint\" || typeof value === \"boolean\") return String(value);\n if (value instanceof Date) return serializeDate({ value });\n return value;\n}\n\n/** A JSON document node-postgres would `JSON.stringify`: any object that is not a Date or binary. */\nfunction isJsonDocument(value: unknown): boolean {\n return typeof value === \"object\" && value !== null && !(value instanceof Date) &&\n !ArrayBuffer.isView(value) && !(value instanceof ArrayBuffer);\n}\n\n/**\n * ORM hot path, node-postgres's rules (`@vibeorm/adapter-pg` `serializeParams`):\n * scalars as text ({@link serializeScalar}), `Date` as UTC ISO text\n * ({@link serializeDate}), any other object or array as `JSON.stringify` text,\n * binary untouched.\n *\n * The runtime itself binds no objects here — scalar lists arrive as\n * array-literal strings from `formatArrayParam`, Json values as JSON text bound\n * through `::text::jsonb`, Bytes as `Uint8Array` — but a direct\n * `adapter.execute` caller binding a document gets the same result as on\n * adapter-pg. With `namedStatements` (the adapter's `preparedStatements: true`)\n * objects stay objects: bun:sql JSON-encodes them for a `json`/`jsonb` slot\n * itself, and would encode pre-stringified text a second time.\n */\nexport function serializeParams(params: { values: readonly unknown[]; namedStatements?: boolean }): unknown[] {\n const stringifyDocuments = params.namedStatements !== true;\n return params.values.map((value) => stringifyDocuments && isJsonDocument(value) ? JSON.stringify(value) : serializeScalar(value));\n}\n\n/**\n * Raw path: the node-postgres rules (`prepareValue`), so a raw statement binds\n * the same text on both postgres adapters — plain JS arrays as PostgreSQL\n * array literals (`db.$queryRawUnsafe('… WHERE \"id\" = ANY($1)', [1, 2, 3])`\n * matches rows), any other object except binary as `JSON.stringify` text,\n * scalars as text ({@link serializeScalar}). `namedStatements` keeps objects as\n * objects, for the reason given at {@link serializeParams}.\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[]; namedStatements?: boolean }): unknown[] {\n const stringifyDocuments = params.namedStatements !== true;\n return params.values.map((value) => {\n if (Array.isArray(value)) return toPgArrayLiteral(value);\n return stringifyDocuments && isJsonDocument(value) ? JSON.stringify(value) : serializeScalar(value);\n });\n}\n",
12
- "/**\n * Synthetic tagged-template cache — bun:sql's prepared-statement path.\n *\n * bun:sql only creates a *named* prepared statement (one PostgreSQL keeps a\n * plan for) when the query arrives as a tagged template. Generated SQL is a\n * plain string, so with `preparedStatements: true` the adapter turns each SQL\n * text into a synthetic `TemplateStringsArray` — split at its `$1`, `$2`, …\n * placeholders — and reuses that same object identity for every execution.\n *\n * A tagged template binds its values POSITIONALLY, one per gap, so the split\n * has to keep two things a plain `text.split(/\\$\\d+/)` throws away (F19):\n *\n * - **which** placeholder each gap is. `SELECT $2, $1` has to bind\n * `values[1]` then `values[0]`, and a repeated `$1` needs its value bound at\n * every occurrence — otherwise the statement silently returns other rows, or\n * reaches the server with too few parameters and fails to parse.\n * - **where** a `$n` is not a placeholder at all: inside a string literal, a\n * quoted identifier, a line or block comment, or a dollar-quoted body. A\n * split there tears the literal apart and produces invalid SQL.\n *\n * The cache is LRU-bounded so a long-running process never grows it without\n * limit.\n */\n\nimport { VibeError } from \"@vibeorm/schema\";\n\n/** A SQL text split for bun:sql, with the placeholder index behind each gap. */\nexport type PreparedTemplate = {\n /** The synthetic template; stable by identity so bun:sql can cache its plan. */\n readonly template: TemplateStringsArray;\n /** 1-based `$n` for each gap, in TEXT order (`SELECT $2, $1` → `[2, 1]`). */\n readonly indices: readonly number[];\n /** Every gap is $1, $2, ... exactly once, with no reordering. */\n readonly identityOrder: boolean;\n};\n\n/** LRU map from SQL text to the synthetic template used to execute it. */\nexport type TemplateCache = {\n /** Template for `text`, creating one on first sight. Stable by identity. */\n getTemplate(params: { text: string }): PreparedTemplate;\n /** Number of texts currently held — diagnostics and tests. */\n size(): number;\n};\n\n// ─── Scanning ─────────────────────────────────────────────────────\n\n/** Is this character part of an unquoted SQL identifier? */\nfunction isIdentChar(char: string | undefined): boolean {\n if (char === undefined) return false;\n return /[A-Za-z0-9_]/.test(char);\n}\n\n/**\n * Index just past a quoted run starting at `start` (`'…'` or `\"…\"`). A doubled\n * quote (`''`, `\"\"`) continues the run — postgres' own escape. A backslash\n * escapes the next character ONLY in an `E'…'` string; with the default\n * `standard_conforming_strings = on` a backslash inside an ordinary literal is\n * just a backslash, and treating it as an escape would run past the literal's\n * real end.\n */\nfunction skipQuoted(text: string, start: number, quote: string): number {\n const escaping =\n quote === \"'\" && (text[start - 1] === \"e\" || text[start - 1] === \"E\") && !isIdentChar(text[start - 2]);\n let index = start + 1;\n while (index < text.length) {\n const char = text[index];\n if (escaping && char === \"\\\\\") {\n index += 2;\n continue;\n }\n if (char === quote) {\n if (text[index + 1] === quote) {\n index += 2;\n continue;\n }\n return index + 1;\n }\n index += 1;\n }\n return text.length; // unterminated — the driver reports it, not this scanner\n}\n\n/** Index just past a block comment, honouring postgres' nesting. */\nfunction skipBlockComment(text: string, start: number): number {\n let depth = 0;\n let index = start;\n while (index < text.length) {\n if (text[index] === \"/\" && text[index + 1] === \"*\") {\n depth += 1;\n index += 2;\n continue;\n }\n if (text[index] === \"*\" && text[index + 1] === \"/\") {\n depth -= 1;\n index += 2;\n if (depth === 0) return index;\n continue;\n }\n index += 1;\n }\n return text.length;\n}\n\n/**\n * Index just past a dollar-quoted body (`$$…$$`, `$tag$…$tag$`) starting at\n * `start`, or `-1` when no dollar quote opens there. `$1` never matches: a tag\n * has to start with a letter or underscore.\n */\nfunction skipDollarQuoted(text: string, start: number): number {\n const opener = /^\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$/.exec(text.slice(start));\n if (opener === null) return -1;\n const tag = opener[0];\n const close = text.indexOf(tag, start + tag.length);\n return close === -1 ? text.length : close + tag.length;\n}\n\n/**\n * Split `text` at its real `$n` placeholders. `chunks.length` is always\n * `indices.length + 1`, which is exactly the shape a tagged template needs.\n */\nexport function scanPlaceholders(params: { text: string }): PreparedTemplate {\n const { text } = params;\n const chunks: string[] = [];\n const indices: number[] = [];\n let chunkStart = 0;\n let index = 0;\n\n while (index < text.length) {\n const char = text[index];\n if (char === \"'\" || char === '\"') {\n index = skipQuoted(text, index, char);\n continue;\n }\n if (char === \"-\" && text[index + 1] === \"-\") {\n const newline = text.indexOf(\"\\n\", index);\n index = newline === -1 ? text.length : newline + 1;\n continue;\n }\n if (char === \"/\" && text[index + 1] === \"*\") {\n index = skipBlockComment(text, index);\n continue;\n }\n if (char === \"$\") {\n const dollarEnd = skipDollarQuoted(text, index);\n if (dollarEnd !== -1) {\n index = dollarEnd;\n continue;\n }\n let digits = index + 1;\n while (digits < text.length && text[digits] !== undefined && /[0-9]/.test(text[digits] as string)) digits += 1;\n if (digits > index + 1) {\n chunks.push(text.slice(chunkStart, index));\n indices.push(Number(text.slice(index + 1, digits)));\n chunkStart = digits;\n index = digits;\n continue;\n }\n }\n index += 1;\n }\n\n chunks.push(text.slice(chunkStart));\n const template = Object.assign(chunks, { raw: chunks }) as unknown as TemplateStringsArray;\n return { template, indices, identityOrder: indices.every((placeholder, index) => placeholder === index + 1) };\n}\n\n/**\n * Split a SQL text on `$n` placeholders into the literal chunks around them.\n *\n * Kept for callers that only want the chunks; it is quote-, comment- and\n * dollar-quote-aware through {@link scanPlaceholders}, so `'$1'` inside a\n * string literal is NOT a split point.\n */\nexport function templateChunks(params: { text: string }): string[] {\n return [...scanPlaceholders(params).template];\n}\n\n// ─── Binding ──────────────────────────────────────────────────────\n\n/**\n * The values to hand a synthetic template, in gap order: `$n` picks\n * `values[n - 1]`, a repeated placeholder repeats its value.\n *\n * A `$n` with no matching value is REFUSED (`VIBE_VALIDATION`) rather than\n * bound to `undefined` — misbinding is exactly the failure mode F19 records.\n */\nexport function bindTemplateValues(params: {\n text: string;\n indices: readonly number[];\n values: readonly unknown[];\n}): unknown[] {\n const { text, indices, values } = params;\n return indices.map((placeholder) => {\n if (placeholder < 1 || placeholder > values.length) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `bun:sql prepared statement references $${placeholder} but only ${values.length} parameter(s) were given`,\n meta: { text, placeholder, provided: values.length },\n });\n }\n return values[placeholder - 1];\n });\n}\n\n// ─── Cache ────────────────────────────────────────────────────────\n\n/**\n * Create a template cache holding at most `max` texts (least recently used\n * evicted first).\n */\nexport function createTemplateCache(params: { max: number }): TemplateCache {\n const { max } = params;\n const templates = new Map<string, PreparedTemplate>();\n\n return {\n getTemplate(templateParams: { text: string }): PreparedTemplate {\n const { text } = templateParams;\n const existing = templates.get(text);\n if (existing !== undefined) {\n // Re-insert to mark most-recently-used.\n templates.delete(text);\n templates.set(text, existing);\n return existing;\n }\n const prepared = scanPlaceholders({ text });\n if (templates.size >= max) {\n const oldest = templates.keys().next().value;\n if (oldest !== undefined) templates.delete(oldest);\n }\n templates.set(text, prepared);\n return prepared;\n },\n\n size(): number {\n return templates.size;\n },\n };\n}\n",
12
+ "/**\n * Synthetic tagged-template cache — bun:sql's prepared-statement path.\n *\n * bun:sql only creates a *named* prepared statement (one PostgreSQL keeps a\n * plan for) when the query arrives as a tagged template. Generated SQL is a\n * plain string, so with `preparedStatements: true` the adapter turns each SQL\n * text into a synthetic `TemplateStringsArray` — split at its `$1`, `$2`, …\n * placeholders — and reuses that same object identity for every execution.\n *\n * A tagged template binds its values POSITIONALLY, one per gap, so the split\n * has to keep two things a plain `text.split(/\\$\\d+/)` throws away (F19):\n *\n * - **which** placeholder each gap is. `SELECT $2, $1` has to bind\n * `values[1]` then `values[0]`, and a repeated `$1` needs its value bound at\n * every occurrence — otherwise the statement silently returns other rows, or\n * reaches the server with too few parameters and fails to parse.\n * - **where** a `$n` is not a placeholder at all: inside a string literal, a\n * quoted identifier, a line or block comment, or a dollar-quoted body. A\n * split there tears the literal apart and produces invalid SQL.\n *\n * The cache is LRU-bounded so a long-running process never grows it without\n * limit.\n *\n * From Bun 1.4.3 `sql.unsafe(text, values)` names its statement too (B-04), so\n * the adapter uses the template there only for a text whose placeholders are\n * not `$1 … $n` in order with exactly n values, or that binds no value; the\n * scan still decides which.\n */\n\nimport { VibeError } from \"@vibeorm/schema\";\n\n/** A SQL text split for bun:sql, with the placeholder index behind each gap. */\nexport type PreparedTemplate = {\n /** The synthetic template; stable by identity so bun:sql can cache its plan. */\n readonly template: TemplateStringsArray;\n /** 1-based `$n` for each gap, in TEXT order (`SELECT $2, $1` → `[2, 1]`). */\n readonly indices: readonly number[];\n /** Every gap is $1, $2, ... exactly once, with no reordering. */\n readonly identityOrder: boolean;\n};\n\n/** LRU map from SQL text to the synthetic template used to execute it. */\nexport type TemplateCache = {\n /** Template for `text`, creating one on first sight. Stable by identity. */\n getTemplate(params: { text: string }): PreparedTemplate;\n /** Number of texts currently held — diagnostics and tests. */\n size(): number;\n};\n\n// ─── Scanning ─────────────────────────────────────────────────────\n\n/** Is this character part of an unquoted SQL identifier? */\nfunction isIdentChar(char: string | undefined): boolean {\n if (char === undefined) return false;\n return /[A-Za-z0-9_]/.test(char);\n}\n\n/**\n * Index just past a quoted run starting at `start` (`'…'` or `\"…\"`). A doubled\n * quote (`''`, `\"\"`) continues the run — postgres' own escape. A backslash\n * escapes the next character ONLY in an `E'…'` string; with the default\n * `standard_conforming_strings = on` a backslash inside an ordinary literal is\n * just a backslash, and treating it as an escape would run past the literal's\n * real end.\n */\nfunction skipQuoted(text: string, start: number, quote: string): number {\n const escaping =\n quote === \"'\" && (text[start - 1] === \"e\" || text[start - 1] === \"E\") && !isIdentChar(text[start - 2]);\n let index = start + 1;\n while (index < text.length) {\n const char = text[index];\n if (escaping && char === \"\\\\\") {\n index += 2;\n continue;\n }\n if (char === quote) {\n if (text[index + 1] === quote) {\n index += 2;\n continue;\n }\n return index + 1;\n }\n index += 1;\n }\n return text.length; // unterminated — the driver reports it, not this scanner\n}\n\n/** Index just past a block comment, honouring postgres' nesting. */\nfunction skipBlockComment(text: string, start: number): number {\n let depth = 0;\n let index = start;\n while (index < text.length) {\n if (text[index] === \"/\" && text[index + 1] === \"*\") {\n depth += 1;\n index += 2;\n continue;\n }\n if (text[index] === \"*\" && text[index + 1] === \"/\") {\n depth -= 1;\n index += 2;\n if (depth === 0) return index;\n continue;\n }\n index += 1;\n }\n return text.length;\n}\n\n/**\n * Index just past a dollar-quoted body (`$$…$$`, `$tag$…$tag$`) starting at\n * `start`, or `-1` when no dollar quote opens there. `$1` never matches: a tag\n * has to start with a letter or underscore.\n */\nfunction skipDollarQuoted(text: string, start: number): number {\n const opener = /^\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$/.exec(text.slice(start));\n if (opener === null) return -1;\n const tag = opener[0];\n const close = text.indexOf(tag, start + tag.length);\n return close === -1 ? text.length : close + tag.length;\n}\n\n/**\n * Split `text` at its real `$n` placeholders. `chunks.length` is always\n * `indices.length + 1`, which is exactly the shape a tagged template needs.\n */\nexport function scanPlaceholders(params: { text: string }): PreparedTemplate {\n const { text } = params;\n const chunks: string[] = [];\n const indices: number[] = [];\n let chunkStart = 0;\n let index = 0;\n\n while (index < text.length) {\n const char = text[index];\n if (char === \"'\" || char === '\"') {\n index = skipQuoted(text, index, char);\n continue;\n }\n if (char === \"-\" && text[index + 1] === \"-\") {\n const newline = text.indexOf(\"\\n\", index);\n index = newline === -1 ? text.length : newline + 1;\n continue;\n }\n if (char === \"/\" && text[index + 1] === \"*\") {\n index = skipBlockComment(text, index);\n continue;\n }\n if (char === \"$\") {\n const dollarEnd = skipDollarQuoted(text, index);\n if (dollarEnd !== -1) {\n index = dollarEnd;\n continue;\n }\n let digits = index + 1;\n while (digits < text.length && text[digits] !== undefined && /[0-9]/.test(text[digits] as string)) digits += 1;\n if (digits > index + 1) {\n chunks.push(text.slice(chunkStart, index));\n indices.push(Number(text.slice(index + 1, digits)));\n chunkStart = digits;\n index = digits;\n continue;\n }\n }\n index += 1;\n }\n\n chunks.push(text.slice(chunkStart));\n const template = Object.assign(chunks, { raw: chunks }) as unknown as TemplateStringsArray;\n return { template, indices, identityOrder: indices.every((placeholder, index) => placeholder === index + 1) };\n}\n\n/**\n * Split a SQL text on `$n` placeholders into the literal chunks around them.\n *\n * Kept for callers that only want the chunks; it is quote-, comment- and\n * dollar-quote-aware through {@link scanPlaceholders}, so `'$1'` inside a\n * string literal is NOT a split point.\n */\nexport function templateChunks(params: { text: string }): string[] {\n return [...scanPlaceholders(params).template];\n}\n\n// ─── Binding ──────────────────────────────────────────────────────\n\n/**\n * The values to hand a synthetic template, in gap order: `$n` picks\n * `values[n - 1]`, a repeated placeholder repeats its value.\n *\n * A `$n` with no matching value is REFUSED (`VIBE_VALIDATION`) rather than\n * bound to `undefined` — misbinding is exactly the failure mode F19 records.\n */\nexport function bindTemplateValues(params: {\n text: string;\n indices: readonly number[];\n values: readonly unknown[];\n}): unknown[] {\n const { text, indices, values } = params;\n return indices.map((placeholder) => {\n if (placeholder < 1 || placeholder > values.length) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `bun:sql prepared statement references $${placeholder} but only ${values.length} parameter(s) were given`,\n meta: { text, placeholder, provided: values.length },\n });\n }\n return values[placeholder - 1];\n });\n}\n\n// ─── Cache ────────────────────────────────────────────────────────\n\n/**\n * Create a template cache holding at most `max` texts (least recently used\n * evicted first).\n */\nexport function createTemplateCache(params: { max: number }): TemplateCache {\n const { max } = params;\n const templates = new Map<string, PreparedTemplate>();\n\n return {\n getTemplate(templateParams: { text: string }): PreparedTemplate {\n const { text } = templateParams;\n const existing = templates.get(text);\n if (existing !== undefined) {\n // Re-insert to mark most-recently-used.\n templates.delete(text);\n templates.set(text, existing);\n return existing;\n }\n const prepared = scanPlaceholders({ text });\n if (templates.size >= max) {\n const oldest = templates.keys().next().value;\n if (oldest !== undefined) templates.delete(oldest);\n }\n templates.set(text, prepared);\n return prepared;\n },\n\n size(): number {\n return templates.size;\n },\n };\n}\n",
13
13
  "/**\n * Transaction-control SQL text (postgres dialect, bun:sql flavour).\n *\n * Used by the reserved-connection path, which issues `BEGIN` itself so that\n * isolation level and statement timeout can be applied — bun:sql's\n * `sql.begin(fn)` fast path takes no such options.\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 reserved-path transaction as ONE simple-protocol\n * message (round-trip EPIC 3, A-05): `BEGIN …` alone, or `BEGIN …; SET LOCAL\n * statement_timeout = N` when a timeout is requested — one wait instead of\n * two. Parameterless text from validated values; PostgreSQL stops at the first\n * failing statement and the driver rejects with that error, so the caller sees\n * BEGIN's or the SET's own error exactly as when they were two messages.\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 * The cancel deadline's per-statement bound (round-trip EPIC 6): a CONSTANT\n * extended-protocol text, with the milliseconds bound as a string `$1`, so\n * bun:sql keeps it prepared and pipelines it with the statement it bounds.\n * `is_local = true` makes it transaction-scoped, like `SET LOCAL`.\n */\nexport const STATEMENT_BOUND_TEXT: string = \"SELECT set_config('statement_timeout', $1, true)\";\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. The adapter uses this\n * to pin one connection for the whole raw transaction (\"open\" reserves,\n * \"close\" releases). On a pooled bun:sql instance an unpinned `BEGIN` is\n * refused outright by the driver (`ERR_POSTGRES_UNSAFE_TRANSACTION`); other\n * pool drivers would only work by checkout luck.\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// ─── 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"
14
14
  ],
15
- "mappings": ";;AAAA;AAOO,SAAS,YAAY,CAAC,QAAgE;AAAA,EAC3F,OAAO,IAAI,IAAI,OAAO,KAAK,OAAO,OAAO;AAAA;;;ACFpC,IAAM,sBAA8B;AAMpC,IAAM,sBAA8B;AAGpC,IAAM,qBAA2E,OAAO,OAAO;AAAA,EACpG,KAAK;AAAA,EAGL,mBAAmB;AACrB,CAAC;;;ACpBD;AAUO,SAAS,oBAAoB,CAAC,QAAmC;AAAA,EACtE,IAAI,IAAI,OAAO,UAAU,OAAO,SAAS,KAAK,qBAAqB;AAAA,IAAG;AAAA,EACtE,MAAM,IAAI,UAAU;AAAA,IAClB,MAAM;AAAA,IACN,SACE,qCAAqC,yCAAyC,OAAO,6BACrF,iIACA;AAAA,IACF,MAAM,EAAE,YAAY,OAAO,SAAS,mBAAmB,oBAAoB;AAAA,EAC7E,CAAC;AAAA;;;ACPH;AAUA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6BA,sBAAS;;;ACnCT,sBAAS;AAgBF,SAAS,mBAAmB,CAAC,QAGb;AAAA,EACrB,QAAQ,eAAe,qBAAqB;AAAA,EAC5C,MAAM,QAAkB,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AE,QAAQ,OAAO,UAAU,+BAA+B,SAAS,UAAU;AAAA,IACnF,OAAO,OAAO;AAAA,EAChB,CAAC;AAAA;",
16
+ "debugId": "86641AB4B943804564756E2164756E21",
17
17
  "names": []
18
18
  }
@@ -20,6 +20,11 @@
20
20
  *
21
21
  * The cache is LRU-bounded so a long-running process never grows it without
22
22
  * limit.
23
+ *
24
+ * From Bun 1.4.3 `sql.unsafe(text, values)` names its statement too (B-04), so
25
+ * the adapter uses the template there only for a text whose placeholders are
26
+ * not `$1 … $n` in order with exactly n values, or that binds no value; the
27
+ * scan still decides which.
23
28
  */
24
29
  /** A SQL text split for bun:sql, with the placeholder index behind each gap. */
25
30
  export type PreparedTemplate = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibeorm/adapter-bun",
3
- "version": "4.1.0",
3
+ "version": "4.3.0",
4
4
  "description": "bun:sql (Postgres) adapter for VibeORM v2",
5
5
  "keywords": [
6
6
  "orm",
@@ -43,9 +43,9 @@
43
43
  "bun": ">=1.4.1"
44
44
  },
45
45
  "dependencies": {
46
- "@vibeorm/runtime": "4.1.0",
47
- "@vibeorm/schema": "4.1.0",
48
- "@vibeorm/sql": "4.1.0"
46
+ "@vibeorm/runtime": "4.3.0",
47
+ "@vibeorm/schema": "4.3.0",
48
+ "@vibeorm/sql": "4.3.0"
49
49
  },
50
50
  "publishConfig": {
51
51
  "access": "public"