@vibeorm/adapter-bun 6.2.1 → 6.2.3

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
@@ -59,7 +59,9 @@ By default the adapter runs bun:sql with `prepare: false`: every statement is an
59
59
 
60
60
  - Each connection keeps its 1,024 most recently used statements; bun:sql closes the others on the server.
61
61
  - After DDL that changes a statement's result columns (`ALTER COLUMN … TYPE`, or `ADD COLUMN` under `SELECT *`), bun:sql prepares the statement again on its next use and returns the row (`tests/node-postgres-parity.live.test.ts`). node-postgres named statements fail there with SQLSTATE `0A000` instead.
62
- - A string bound to a raw `::jsonb` slot is JSON-encoded again (see "Raw parameters").
62
+ - A named statement keeps the parameter types of its first parse, and a statement whose result columns stay the same (a `create` that returns only its `id`, a `createMany`) is not prepared again after a migration: it goes on binding its values as the old type. Measured on PostgreSQL 18 with a session in `America/New_York`: after `ALTER COLUMN … TYPE timestamptz(3)` on a `timestamp(3)` column, a `create` prepared before the migration stored `2026-01-15T12:00:00Z` as 17:00 UTC, without an error; the default unnamed mode stored 12:00. After a migration that changes a column's type, replace the adapter (`disconnect()`, then a new one) so every connection prepares its statements again.
63
+ - Every statement with bound values is named: bun:sql chooses named or unnamed for the whole connection, not per statement, so the adapter cannot leave a large statement unnamed. A bulk write near the 30 000-parameter budget in `VALUES` form then stays prepared on every connection that ran it, until bun:sql closes it (the 1,024 above) or the connection closes. Measured on PostgreSQL 18, one prepared `INSERT … VALUES` of 30 000 parameters (`int` columns) held 4.4–6.6 MB of server memory per connection, and 6.6–11 MB once PostgreSQL had also built a generic plan, which this mode's default `force_custom_plan` prevents. A call bound as one array per column (at least 100 rows that set the same fields, see [Bulk writes in several statements](https://github.com/vibeorm/vibeorm/blob/master/docs/queries.md#bulk-writes-in-several-statements)) has one parameter per column, so its prepared statement stays small.
64
+ - A string bound to a raw `json` / `jsonb` slot whose type the server takes from its context (`VALUES ($1)` into a jsonb column, a function argument) is JSON-encoded again. Behind a direct cast in the text the adapter respells the slot (`$1::jsonb` as `$1::text::jsonb`, `CAST($1 AS json)` as `CAST($1::text AS json)`), so the server parses the string as JSON, as in the default mode (see "Raw parameters").
63
65
  - 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.
64
66
  - 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.
65
67
 
@@ -113,7 +115,7 @@ Every top-level `transaction()`, with or without options, runs on a reserved con
113
115
 
114
116
  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.
115
117
 
116
- With `preparedStatements: true`, the array form `$transaction([...])` sends its operations in bursts, as on adapter-pg: after an operation sent as one statement, the next operation's first statement goes out right behind it, before its reply. A `timeout` does not switch bursts off (its bound rides behind `BEGIN`; PostgreSQL times each statement on its own). `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`, 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.
118
+ With `preparedStatements: true`, the array form `$transaction([...])` sends its operations in bursts, as on adapter-pg: after an operation sent as one statement, the next operation's first statement goes out right behind it, before its reply. A `timeout` does not switch bursts off (its bound rides behind `BEGIN`; PostgreSQL times each statement on its own). `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`, for an array inside a transaction, or with an `onQuery` / `$on("query")` listener. The statements of a bulk write that the parameter budget splits are pipelined the same way, behind the confirmed `BEGIN`: a `createManyAndReturn` of 25 000 rows bound as arrays (three statements) costs 2 or 3 round trips warm, against 5 with unnamed statements (`tests/round-trip-wire.live.test.ts`; bun:sql stops adding to a pipeline while 64 KB of a connection's writes are unsent, so a statement this large may wait for the reply before it). 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.
117
119
 
118
120
  Also with `preparedStatements: true` and without a `deadline` (round-trip parity with adapter-pg, 5.1):
119
121
 
@@ -151,14 +153,24 @@ Every driver failure becomes a `VibeError` with the driver error as `cause` and
151
153
  |---|---|---|---|
152
154
  | `23505` | unique_violation | `VIBE_UNIQUE_VIOLATION` | |
153
155
  | `23503` | foreign_key_violation | `VIBE_FK_VIOLATION` | |
156
+ | `23001` | restrict_violation (PostgreSQL 18+) | `VIBE_FK_VIOLATION` | |
157
+ | `23P01` | exclusion_violation | `VIBE_EXCLUSION_VIOLATION` | `"exclusion-violation"` |
154
158
  | `23502` | not_null_violation | `VIBE_VALIDATION` | |
155
159
  | `23514` | check_violation | `VIBE_VALIDATION` | |
156
160
  | `22P02` | invalid_text_representation | `VIBE_VALIDATION` | |
157
- | `40001` | serialization_failure | `VIBE_TRANSACTION` | |
158
- | `40P01` | deadlock_detected | `VIBE_TRANSACTION` | |
161
+ | `22001` `22003` `22007` `22008` | string too long, number out of range, bad or overflowing date/time | `VIBE_VALIDATION` | |
162
+ | `22021` | character_not_in_repertoire (a NUL in text) | `VIBE_VALIDATION` | `"unstorable-text"` |
163
+ | `22P05` | untranslatable_character (`\u0000` in jsonb) | `VIBE_VALIDATION` | `"unstorable-text"` |
164
+ | `42501` | insufficient_privilege (a row-level-security WITH CHECK too) | `VIBE_PERMISSION_DENIED` | |
165
+ | `40001` | serialization_failure | `VIBE_TRANSACTION` | `"serialization-failure"` |
166
+ | `40P01` | deadlock_detected | `VIBE_TRANSACTION` | `"deadlock"` |
159
167
  | `57014` | query_canceled (statement_timeout) | `VIBE_TRANSACTION` | `"timeout"` |
168
+ | `25006` | read_only_sql_transaction | `VIBE_TRANSACTION` | `"read-only-transaction"` |
169
+ | `55P03` | lock_not_available (`nowait`, `lock_timeout`) | `VIBE_LOCK_NOT_AVAILABLE` | `"lock-not-available"` |
160
170
  | anything else, including every `ERR_POSTGRES_*` connection or auth failure | | `VIBE_ADAPTER` | |
161
171
 
172
+ The client refuses a NUL (U+0000) in a `String` or jsonb field before the statement, with the same code and reason plus `meta.model` and `meta.field`; the `22021` and `22P05` rows cover raw SQL.
173
+
162
174
  A transaction callback's own error is rethrown untouched instead of being mapped as a driver failure.
163
175
 
164
176
  ## Links
package/dist/index.js CHANGED
@@ -146,7 +146,7 @@ function applyStartupOptions(params) {
146
146
  }
147
147
 
148
148
  // packages/adapter-bun/src/errors.ts
149
- import { POSTGRES_CONNECTION_SQLSTATES, RESULT_VALUE_LIMITS, postgresValueTooLarge, socketConnectionFact } from "@vibeorm/runtime/adapter-kit";
149
+ import { POSTGRES_CONNECTION_SQLSTATES, RESULT_VALUE_LIMITS, postgresTypeShadowRefusal, postgresValueTooLarge, socketConnectionFact } from "@vibeorm/runtime/adapter-kit";
150
150
  import { VibeError as VibeError3 } from "@vibeorm/schema";
151
151
  var BUN_SQLSTATE_ERROR_CODES = Object.freeze({
152
152
  "23P01": "VIBE_EXCLUSION_VIOLATION",
@@ -160,6 +160,8 @@ var BUN_SQLSTATE_ERROR_CODES = Object.freeze({
160
160
  "22003": "VIBE_VALIDATION",
161
161
  "22007": "VIBE_VALIDATION",
162
162
  "22008": "VIBE_VALIDATION",
163
+ "22021": "VIBE_VALIDATION",
164
+ "22P05": "VIBE_VALIDATION",
163
165
  "42501": "VIBE_PERMISSION_DENIED",
164
166
  "40001": "VIBE_TRANSACTION",
165
167
  "40P01": "VIBE_TRANSACTION",
@@ -173,7 +175,9 @@ var BUN_SQLSTATE_REASONS = Object.freeze({
173
175
  "55P03": "lock-not-available",
174
176
  "40P01": "deadlock",
175
177
  "40001": "serialization-failure",
176
- "25006": "read-only-transaction"
178
+ "25006": "read-only-transaction",
179
+ "22021": "unstorable-text",
180
+ "22P05": "unstorable-text"
177
181
  });
178
182
  var BUN_CONNECTION_FAILURE_CODES = Object.freeze({
179
183
  ERR_POSTGRES_CONNECTION_REFUSED: { reason: "connection-refused", mayHaveReachedServer: false },
@@ -206,6 +210,9 @@ function mapBunDriverError(params) {
206
210
  return error;
207
211
  const source = error !== null && typeof error === "object" ? error : {};
208
212
  const sqlstate = bunErrorSqlstate({ error });
213
+ const shadow = postgresTypeShadowRefusal({ sqlstate, message: readStringField({ source, key: "message" }), cause: error });
214
+ if (shadow !== undefined)
215
+ return shadow;
209
216
  const tooLarge = postgresValueTooLarge({ sqlstate, message: readStringField({ source, key: "message" }), detail: readStringField({ source, key: "detail" }) });
210
217
  const code = tooLarge ? "VIBE_RESULT_TOO_LARGE" : (sqlstate === undefined ? undefined : BUN_SQLSTATE_ERROR_CODES[sqlstate]) ?? "VIBE_ADAPTER";
211
218
  const meta = {};
@@ -247,12 +254,16 @@ import { Buffer } from "buffer";
247
254
  import { postgresExtendedDateText } from "@vibeorm/runtime/adapter-kit";
248
255
  import { VibeError as VibeError4 } from "@vibeorm/schema";
249
256
  function quoteElement(value) {
257
+ if (value.indexOf('"') === -1 && value.indexOf("\\") === -1)
258
+ return `"${value}"`;
250
259
  return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
251
260
  }
252
261
  function toPgArrayLiteral(values) {
253
262
  const elements = values.map((value) => {
254
263
  if (value === null || value === undefined)
255
264
  return "NULL";
265
+ if (typeof value === "string")
266
+ return quoteElement(value);
256
267
  if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") {
257
268
  return String(value);
258
269
  }
@@ -268,8 +279,6 @@ function toPgArrayLiteral(values) {
268
279
  meta: { driver: "bun:sql" }
269
280
  });
270
281
  }
271
- if (typeof value === "string")
272
- return quoteElement(value);
273
282
  if (typeof value === "object")
274
283
  return quoteElement(JSON.stringify(value));
275
284
  return quoteElement(String(value));
@@ -643,7 +652,7 @@ function orderedLaneMisuse(params) {
643
652
  }
644
653
  function executorFor(params) {
645
654
  const { dispatch, effect, guard, final } = params;
646
- const finalOf = final === undefined ? {} : { final: true, ...final.discardRows ? { discardRows: true } : {} };
655
+ const finalOf = params.preflight === true ? { preflight: true } : final === undefined ? {} : { final: true, ...final.discardRows ? { discardRows: true } : {} };
647
656
  return Object.assign((strings, ...values) => dispatch({
648
657
  effect,
649
658
  guard,
@@ -947,17 +956,20 @@ function bunAdapter(options) {
947
956
  if (lane.followed && lane.issued > 0) {
948
957
  return Promise.reject(orderedLaneMisuse({ message: "a lane that has a follower may issue ONE statement" }));
949
958
  }
950
- const first = lane.issued === 0;
951
- lane.issued += 1;
959
+ const preflight = send.preflight === true;
960
+ const ahead = lane.issued === 0;
961
+ const first = ahead && !preflight;
962
+ if (!preflight)
963
+ lane.issued += 1;
952
964
  const go = (before) => {
953
965
  if (before.kind === "closed") {
954
- if (first)
966
+ if (ahead)
955
967
  lane.settle(LANE_CLOSED);
956
968
  return Promise.reject(predecessorClosedError());
957
969
  }
958
970
  const failed = before.kind === "failed" ? { cause: before.cause } : lane.scope.failed;
959
971
  if (failed !== undefined) {
960
- if (first)
972
+ if (ahead)
961
973
  lane.settle({ kind: "failed", cause: failed.cause });
962
974
  return Promise.reject(refusalBehind(failed.cause));
963
975
  }
@@ -975,7 +987,7 @@ function bunAdapter(options) {
975
987
  return value;
976
988
  }, (error) => {
977
989
  lane.scope.failed ??= { cause: error };
978
- if (first)
990
+ if (ahead)
979
991
  lane.settle({ kind: "failed", cause: error });
980
992
  throw error;
981
993
  });
@@ -1021,7 +1033,7 @@ function bunAdapter(options) {
1021
1033
  return {
1022
1034
  ...base,
1023
1035
  dispatch: laneSend,
1024
- executor: ({ effect, guard, final }) => executorFor({ dispatch: laneSend, effect, guard, ...final === undefined ? {} : { final } }),
1036
+ executor: ({ effect, guard, final, preflight }) => executorFor({ dispatch: laneSend, effect, guard, ...final === undefined ? {} : { final }, ...preflight === true ? { preflight } : {} }),
1025
1037
  turn: () => {
1026
1038
  const before = lane.scope.lanes[lane.index - 1];
1027
1039
  if (!lane.open || before === undefined)
@@ -1217,7 +1229,10 @@ function bunAdapter(options) {
1217
1229
  });
1218
1230
  await wireProbe;
1219
1231
  } else {
1220
- await probeJsonWire(params.source, params.onReadControl);
1232
+ if (params.laneTurn !== undefined)
1233
+ await params.laneTurn().then(ignore, ignore);
1234
+ if (!wireSettled)
1235
+ await probeJsonWire(params.probe ?? params.source, params.onReadControl);
1221
1236
  }
1222
1237
  }
1223
1238
  assertReadExecution({ ...params, provider: PROVIDER, stage: "waiting-for-connection" });
@@ -1665,7 +1680,7 @@ function bunAdapter(options) {
1665
1680
  };
1666
1681
  const view = finalOf();
1667
1682
  const executor = control === undefined ? source : control.executor({ effect: execParams.effect, guard, ...wireSettled ? view : {} });
1668
- const result = runExecute({ source: executor, ...parentMode === "pool" ? {} : { scope }, ...execParams });
1683
+ const result = wireSettled || control === undefined ? runExecute({ source: executor, ...parentMode === "pool" ? {} : { scope }, ...execParams }) : runExecute({ source: executor, probe: control.executor({ effect: execParams.effect, guard, preflight: true }), laneTurn: control.turn, ...parentMode === "pool" ? {} : { scope }, ...execParams });
1669
1684
  return parentMode === "pool" ? result : result.catch((error) => abortTransactionOnStatementFailure({ scope, error }));
1670
1685
  } });
1671
1686
  },
@@ -1920,4 +1935,4 @@ export {
1920
1935
  validateTransactionDeadline2 as validateTransactionDeadline
1921
1936
  };
1922
1937
 
1923
- //# debugId=E6047DB19F14936B64756E2164756E21
1938
+ //# debugId=636207B21116F04C64756E2164756E21