@vibeorm/adapter-bun 6.2.2 → 6.2.4

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
@@ -131,7 +131,7 @@ What adapter-bun cannot match: `BEGIN` ahead of a write (one round trip more tha
131
131
 
132
132
  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.
133
133
 
134
- 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.
134
+ 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. So is the connection of a transaction or a raw `BEGIN` session on which a statement failed with SQLSTATE class 08, 53, 57, 58 or XX (a `statement_timeout` included), whatever the transaction's outcome: such a backend can stay broken for every later statement (pg_search 0.25, paradedb/paradedb#5810), and `transactionOutcomeOf` reports `connection: "discarded"`. A statement outside a transaction runs on bun:sql's own pool, which keeps its connection after a server error. 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.
135
135
 
136
136
  A statement with more than 65,535 parameters is refused by bun:sql before it reaches the server; node-postgres sends it and the server aborts the transaction. Inside a transaction the adapter treats that refusal as an abort too, so a callback that catches it cannot commit the transaction's other writes.
137
137
 
@@ -153,14 +153,24 @@ Every driver failure becomes a `VibeError` with the driver error as `cause` and
153
153
  |---|---|---|---|
154
154
  | `23505` | unique_violation | `VIBE_UNIQUE_VIOLATION` | |
155
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"` |
156
158
  | `23502` | not_null_violation | `VIBE_VALIDATION` | |
157
159
  | `23514` | check_violation | `VIBE_VALIDATION` | |
158
160
  | `22P02` | invalid_text_representation | `VIBE_VALIDATION` | |
159
- | `40001` | serialization_failure | `VIBE_TRANSACTION` | |
160
- | `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"` |
161
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"` |
162
170
  | anything else, including every `ERR_POSTGRES_*` connection or auth failure | | `VIBE_ADAPTER` | |
163
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
+
164
174
  A transaction callback's own error is rethrown untouched instead of being mapped as a driver failure.
165
175
 
166
176
  ## Links
package/dist/index.js CHANGED
@@ -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 },
@@ -723,7 +727,7 @@ function bunAdapter(options) {
723
727
  return connection(prepared.template, ...bindTemplateValues({ text: step.text, indices: prepared.indices, values: step.values }));
724
728
  }
725
729
  function createReservedControl(params) {
726
- const { reserved, budget, scope } = params;
730
+ const { reserved, budget, scope, observeFailure } = params;
727
731
  const deferred = createDeferredControl({ opening: params.opening === null ? [] : [params.opening], deferReleases: true });
728
732
  let openingFailure;
729
733
  let openingStep = null;
@@ -739,6 +743,7 @@ function bunAdapter(options) {
739
743
  let settingsSent = false;
740
744
  const step = (query) => new Promise((resolve) => resolve(query())).then(undefined, (error) => {
741
745
  const mapped = mapBunDriverError({ error });
746
+ observeFailure(mapped);
742
747
  if (mapped.meta.sqlstate === "25P02") {
743
748
  throw transactionAbortedError({ cause: lastFailure ?? scope.state.aborted?.cause });
744
749
  }
@@ -768,6 +773,7 @@ function bunAdapter(options) {
768
773
  settingsSent = true;
769
774
  return new Promise((resolve) => resolve(controlStep({ connection: reserved, step: deferredStep }))).then(undefined, (error) => {
770
775
  const mapped = mapBunDriverError({ error });
776
+ observeFailure(mapped);
771
777
  if (mapped.meta.sqlstate === "25P02")
772
778
  throw transactionAbortedError({ cause: lastFailure ?? scope.state.aborted?.cause });
773
779
  if (typeof mapped.meta.sqlstate !== "string")
@@ -1159,6 +1165,7 @@ function bunAdapter(options) {
1159
1165
  return base;
1160
1166
  }
1161
1167
  let rawSession = null;
1168
+ const brokenRawSessions = new WeakSet;
1162
1169
  function createSqlInstance(params) {
1163
1170
  const sqlOptions = { max: params.max, prepare: usePrepared };
1164
1171
  if (options?.connectionTimeout !== undefined) {
@@ -1462,6 +1469,16 @@ function bunAdapter(options) {
1462
1469
  const eagerOpening = settingsStatement !== undefined && !settingsDeferred || timeout !== undefined && (!usePrepared || timeout > MAX_STATEMENT_TIMEOUT_MS);
1463
1470
  const eagerOpen = eagerOpening && timeout !== undefined ? openTransactionStatement({ ...openingOptions, timeout }) : null;
1464
1471
  const reserved = await runMapped(() => pool.reserve());
1472
+ let sessionBroken = false;
1473
+ const observeFailure = (error) => {
1474
+ if (breaksSession({ error }))
1475
+ sessionBroken = true;
1476
+ };
1477
+ const watched = (sending) => sending.then(undefined, (error) => {
1478
+ const mapped = mapBunDriverError({ error });
1479
+ observeFailure(mapped);
1480
+ throw mapped;
1481
+ });
1465
1482
  const budget = startTransactionBudget({ options: transactionOptions, provider: PROVIDER });
1466
1483
  const txScope = createSavepointScope();
1467
1484
  const control = createReservedControl({
@@ -1470,6 +1487,7 @@ function bunAdapter(options) {
1470
1487
  scope: txScope,
1471
1488
  opening: eagerOpening ? null : beginStatement(openingOptions),
1472
1489
  commits: usePrepared && budget.totalMs === null,
1490
+ observeFailure,
1473
1491
  ...settingsDeferred ? {
1474
1492
  openingSettings: {
1475
1493
  text: settingsStatement.text,
@@ -1487,10 +1505,8 @@ function bunAdapter(options) {
1487
1505
  let discard = false;
1488
1506
  let openingRollback;
1489
1507
  const openWithSettings = async (statement) => {
1490
- await (eagerOpen === null ? controlQuery({ connection: reserved, text: beginStatement(openingOptions) }) : reserved.unsafe(eagerOpen)).then(undefined, (error) => {
1491
- throw mapBunDriverError({ error });
1492
- });
1493
- const failed = await controlQuery({ connection: reserved, text: statement.text, values: statement.values }).then(() => {
1508
+ await watched(eagerOpen === null ? controlQuery({ connection: reserved, text: beginStatement(openingOptions) }) : reserved.unsafe(eagerOpen));
1509
+ const failed = await watched(controlQuery({ connection: reserved, text: statement.text, values: statement.values })).then(() => {
1494
1510
  return;
1495
1511
  }, (error) => ({ error }));
1496
1512
  if (failed === undefined)
@@ -1508,7 +1524,7 @@ function bunAdapter(options) {
1508
1524
  if (eagerOpening && settingsStatement !== undefined)
1509
1525
  await openWithSettings(settingsStatement);
1510
1526
  else if (eagerOpen !== null)
1511
- await runMapped(() => reserved.unsafe(eagerOpen));
1527
+ await watched(new Promise((resolve) => resolve(reserved.unsafe(eagerOpen))));
1512
1528
  const txAdapter = createAdapter({
1513
1529
  source: reserved,
1514
1530
  parentMode: "tx",
@@ -1587,10 +1603,10 @@ function bunAdapter(options) {
1587
1603
  scope: txScope,
1588
1604
  commit: commit.progress,
1589
1605
  rollback,
1590
- connection: discard ? "discarded" : "returned"
1606
+ connection: discard || sessionBroken ? "discarded" : "returned"
1591
1607
  });
1592
1608
  } finally {
1593
- if (discard)
1609
+ if (discard || sessionBroken)
1594
1610
  await runMapped(() => reserved.close());
1595
1611
  else
1596
1612
  reserved.release();
@@ -1701,6 +1717,7 @@ function bunAdapter(options) {
1701
1717
  }
1702
1718
  const opened = await Promise.allSettled(Array.from({ length: Math.max(1, poolMin) }, () => runMapped(() => source.reserve())));
1703
1719
  const held = opened.flatMap((outcome) => outcome.status === "fulfilled" ? [outcome.value] : []);
1720
+ let broken;
1704
1721
  try {
1705
1722
  const failed = opened.find((outcome) => outcome.status === "rejected");
1706
1723
  if (failed !== undefined)
@@ -1710,11 +1727,19 @@ function bunAdapter(options) {
1710
1727
  wireProbe = probeJsonWire(reserved).finally(() => {
1711
1728
  wireProbe = null;
1712
1729
  });
1713
- await wireProbe;
1730
+ await wireProbe.catch((error) => {
1731
+ if (breaksSession({ error }))
1732
+ broken = reserved;
1733
+ throw error;
1734
+ });
1714
1735
  }
1715
1736
  } finally {
1716
- for (const reserved of held)
1717
- reserved.release();
1737
+ for (const reserved of held) {
1738
+ if (reserved === broken)
1739
+ await runMapped(() => reserved.close());
1740
+ else
1741
+ reserved.release();
1742
+ }
1718
1743
  }
1719
1744
  },
1720
1745
  async disconnect() {
@@ -1789,16 +1814,24 @@ function bunAdapter(options) {
1789
1814
  async executeUnsafe(params) {
1790
1815
  const control = classifyRawTransactionControl({ text: params.text });
1791
1816
  if (rawSession !== null) {
1817
+ const session = rawSession;
1818
+ const run = () => runExecuteUnsafe({ source: session, ...params }).catch((error) => {
1819
+ if (breaksSession({ error }))
1820
+ brokenRawSessions.add(session);
1821
+ throw error;
1822
+ });
1792
1823
  if (control === "close") {
1793
- const session = rawSession;
1794
1824
  rawSession = null;
1795
1825
  try {
1796
- return await runExecuteUnsafe({ source: session, ...params });
1826
+ return await run();
1797
1827
  } finally {
1798
- session.release();
1828
+ if (brokenRawSessions.has(session))
1829
+ await runMapped(() => session.close());
1830
+ else
1831
+ session.release();
1799
1832
  }
1800
1833
  }
1801
- return runExecuteUnsafe({ source: rawSession, ...params });
1834
+ return run();
1802
1835
  }
1803
1836
  if (control === "open") {
1804
1837
  const reserved = await runMapped(() => getSql().reserve());
@@ -1807,7 +1840,10 @@ function bunAdapter(options) {
1807
1840
  rawSession = reserved;
1808
1841
  return result;
1809
1842
  } catch (error) {
1810
- reserved.release();
1843
+ if (breaksSession({ error }))
1844
+ await runMapped(() => reserved.close());
1845
+ else
1846
+ reserved.release();
1811
1847
  throw error;
1812
1848
  }
1813
1849
  }
@@ -1886,6 +1922,11 @@ function isConnectionLoss(params) {
1886
1922
  const sqlstate = error.meta.sqlstate;
1887
1923
  return typeof sqlstate !== "string" || sqlstate.startsWith("08") || ["57P01", "57P02", "57P03"].includes(sqlstate);
1888
1924
  }
1925
+ var NEVER_REUSE_SQLSTATE_CLASSES = new Set(["08", "53", "57", "58", "XX"]);
1926
+ function breaksSession(params) {
1927
+ const sqlstate = mapBunDriverError({ error: params.error }).meta.sqlstate;
1928
+ return typeof sqlstate === "string" && NEVER_REUSE_SQLSTATE_CLASSES.has(sqlstate.slice(0, 2));
1929
+ }
1889
1930
  function abortTransactionOnStatementFailure(params) {
1890
1931
  const { scope, error } = params;
1891
1932
  if (error instanceof VibeError7 && error.meta.driverCode === "ERR_POSTGRES_TOO_MANY_PARAMETERS") {
@@ -1931,4 +1972,4 @@ export {
1931
1972
  validateTransactionDeadline2 as validateTransactionDeadline
1932
1973
  };
1933
1974
 
1934
- //# debugId=14B12078538F8EA664756E2164756E21
1975
+ //# debugId=4048BAE98B89598864756E2164756E21