@vibeorm/adapter-bun 5.0.0 → 5.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -3
- package/dist/index.d.ts +3 -2
- package/dist/index.js +106 -12
- package/dist/index.js.map +7 -6
- package/dist/params.d.ts +3 -1
- package/dist/raw-json-text.d.ts +55 -0
- package/dist/template-cache.d.ts +5 -0
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -67,15 +67,18 @@ By default the adapter runs bun:sql with `prepare: false`: every statement is an
|
|
|
67
67
|
|
|
68
68
|
Trusted parameterless SQL scripts remain supported. The raw result contains the final command's rows and affected-row count; preceding commands still execute once. Empty final DDL results remain empty. The first ORM query observes Bun's JSON wire format, on the connection it already holds. A failed or unrecognized observation rejects that operation before its user statement is sent; a later call can probe again on a healthy connection.
|
|
69
69
|
|
|
70
|
-
Raw parameters follow node-postgres: a JS **array** becomes a PostgreSQL array literal (for `= ANY($1)`), any other plain object is sent as `JSON.stringify` text, and a string is sent as text, so the server parses JSON text bound to a `::jsonb` slot.
|
|
70
|
+
Raw parameters follow node-postgres: a JS **array** becomes a PostgreSQL array literal (for `= ANY($1)`), any other plain object is sent as `JSON.stringify` text, and a string is sent as text, so the server parses JSON text bound to a `::jsonb` slot.
|
|
71
|
+
|
|
72
|
+
With `preparedStatements: true`, bun:sql types each parameter by the OID the server infers for its slot and JSON-encodes **whatever JavaScript value** is bound to a `json`/`jsonb` slot, a string included. No JavaScript value is sent as raw text into such a slot (a `Buffer` makes the slot `bytea`, `JSON.rawJSON` refuses objects). So the adapter respells the slot: when every reference of a placeholder in the raw text is a direct cast to the same type, `$n::jsonb` / `$n::json` or `CAST($n AS jsonb)`, and its original JS value is a string, the statement goes out with `$n::text::jsonb`. The server then parses the text as in the default mode: byte-exact for `json`, every digit of a number kept, invalid JSON refused with SQLSTATE `22P02` (`VIBE_VALIDATION`). Every non-string input keeps its previous behavior. In particular, raw arrays, numbers, bigints, booleans and dates are serialized to text and can still become JSON strings in named mode; objects and `null` keep Bun's existing encoding. Measured on Bun 1.4.4 / PostgreSQL 18 (`tests/raw-jsonb.live.test.ts` here and in `@vibeorm/adapter-pg`):
|
|
71
73
|
|
|
72
74
|
| `$executeRaw` … `VALUES (${value}::jsonb)` | adapter-bun (default) | adapter-bun, `preparedStatements: true` | adapter-pg |
|
|
73
75
|
|---|---|---|---|
|
|
74
76
|
| `{ a: 1 }` (JS object) | `object` | `object` | `object` |
|
|
75
|
-
| `'{"a":1}'` (pre-encoded text) | `object` | **`string`** | `object` |
|
|
77
|
+
| `'{"a":1}'` (pre-encoded text) | `object` | `object` (5.0.1 and older: **`string`**) | `object` |
|
|
76
78
|
| `'{"a":1}'` through `${value}::text::jsonb` | `object` | `object` | `object` |
|
|
79
|
+
| `'{"a":1}'` into a jsonb column with no cast (`VALUES (${value})`) | `object` | **`string`** | `object` |
|
|
77
80
|
|
|
78
|
-
`::text::jsonb` is the spelling that is correct in every mode, and it is what the ORM path renders for every `Json` field (`jsonParamCast` in the postgres dialect). A JSON array bound into a json column from raw SQL needs `JSON.stringify
|
|
81
|
+
The last row is the limit: a slot whose type the server infers from its context (a column, a function argument) is not visible in the text, so bun:sql still JSON-encodes a string bound there. `::text::jsonb` is the spelling that is correct in every mode, and it is what the ORM path renders for every `Json` field (`jsonParamCast` in the postgres dialect); the ORM path is not respelled. A placeholder cast to `json` in one place and `jsonb` in another keeps its text too. A JSON array bound into a json column from raw SQL needs `JSON.stringify`, because a raw JS array is an array literal.
|
|
79
82
|
|
|
80
83
|
Raw results are the driver's own values. bun:sql returns some types differently from node-postgres in raw queries: `uuid[]` and `citext[]` as the array-literal string (`"{…}"`), `interval`, `point` and `circle` as PostgreSQL's text (`"1 day 02:00:00"`, `"(1,2)"`; node-postgres returns objects), and `xid` as a number. The ORM path decodes list fields the same way on both adapters. One difference reaches the ORM path too: bun:sql reads a date or timestamp before year 1 (`BC`) as `Invalid Date`, where node-postgres returns the date.
|
|
81
84
|
|
|
@@ -115,6 +118,8 @@ With `preparedStatements: true`, the array form `$transaction([...])` sends its
|
|
|
115
118
|
Also with `preparedStatements: true` and without a `deadline` (round-trip parity with adapter-pg, 5.1):
|
|
116
119
|
|
|
117
120
|
- **COMMIT travels with the last statement** (`withCommit`): behind the last operation of an array, behind the last read of `$all`, behind a `commitWith` statement and behind the last relation wave of a read that ends a reads-only transaction, wherever the runtime asks adapter-pg for it. `[findUnique, count]` and `$all { a, b }` cost 1 round trip instead of 2; `[deleteMany, createMany, updateMany]` 2 instead of 3. COMMIT rides only behind a statement whose every failure the server answers (as above), with no savepoint open and nothing else of the transaction still to be sent; then a failure before it aborts the transaction and the server answers COMMIT with ROLLBACK, so nothing commits. A deferred constraint refused at COMMIT rejects the transaction with that error (`VIBE_FK_VIOLATION`, …), as adapter-pg. A statement after the riding COMMIT is refused (`VIBE_TRANSACTION`, `meta.reason: "commit-sent"`).
|
|
121
|
+
- A callback transaction's `commitWith` / `commitQuery` statement (the framework sends its last write this way) rides too: a callback with one write costs BEGIN · write · [statement, COMMIT] = 3 round trips instead of 4, and `commitQuery` returns its rows after COMMIT. A failing statement rolls everything back with the same error and `commit: "not-committed"` as adapter-pg. Two facts of `transactionOutcomeOf` differ there, and both are true: bun:sql ends every query with its own Sync, so the server runs the riding COMMIT in the aborted transaction and answers ROLLBACK (`commitSent: true`, `rollback: "not-needed"`), where adapter-pg's one-Sync batch has the server skip COMMIT and then sends ROLLBACK (`commitSent: false`, `rollback: "acknowledged"`). Pinned in `tests/commit-with-ride.live.test.ts`.
|
|
122
|
+
- **Default unnamed statements: no ride.** No `withCommit` view is offered, and the statement and COMMIT take one round trip each (4 for the callback above), as with an `onQuery` listener. Measured on Bun 1.4.4: with `prepare: false` bun:sql waits for each statement's reply before it writes the next query, so a bound statement and COMMIT cost 2 waits whether COMMIT is a simple or an extended query (with named statements: 1). The ride needs `preparedStatements: true`.
|
|
118
123
|
- **Sibling relation loads** of a `"query"`-strategy read share one round trip inside a transaction (lane groups, `PipelineLane.group`) and in autocommit (`connectionGroup`; in the default mode they run on idle pooled connections in parallel instead). A callback transaction reading a row with 3 sibling relations costs 3 round trips instead of 5.
|
|
119
124
|
- **Bound statements nobody reads** (`deferStatement`: native-RLS claims, the `advisoryLock` option) ride with the next statement; ahead of a write, behind the confirmed `BEGIN`.
|
|
120
125
|
- **The transaction `timeout`** (`statement_timeout` bound) and, with `deferSettings: true`, the **transaction `settings`** wait behind `BEGIN` and ride with the first statement, in that order, ahead of the claims. A read callback with a `timeout` costs 2 round trips instead of 3, `[findMany, count]` with a `timeout` 1 instead of 2, settings + one read 2 instead of 4, settings + one write 3 instead of 4; a callback that sends nothing sends nothing. A refused deferred setting rejects the first statement with the `setting-refused` error (`meta.deferred: true`), as on adapter-pg. A `timeout` above PostgreSQL's limit keeps the eager opening. With the default unnamed statements both stay eager: Bun pipelines nothing unnamed, so deferring would save no round trip (and an unnamed deferred `timeout` would cost one more than the one eager message).
|
package/dist/index.d.ts
CHANGED
|
@@ -57,8 +57,9 @@ export type BunAdapterOptions = {
|
|
|
57
57
|
* type a later DDL change alters fails with SQLSTATE 0A000 on that
|
|
58
58
|
* connection until the pool is replaced (node-postgres named statements
|
|
59
59
|
* behave the same); `int4[]`/`float4[]` values with NULL elements or more
|
|
60
|
-
* than one dimension are refused
|
|
61
|
-
*
|
|
60
|
+
* than one dimension are refused. A raw JSON text string in an explicit
|
|
61
|
+
* scalar json/jsonb cast is sent through text first; inferred JSON slots
|
|
62
|
+
* retain Bun's JSON-string encoding. ORM-path queries also run as tagged
|
|
62
63
|
* templates — on Bun 1.4.3 and newer only those whose placeholders are not
|
|
63
64
|
* `$1 … $n` in order (the rest bind by `$n`, still named).
|
|
64
65
|
*/
|
package/dist/index.js
CHANGED
|
@@ -298,7 +298,7 @@ import { VibeError as VibeError5 } from "@vibeorm/schema";
|
|
|
298
298
|
function isIdentChar(char) {
|
|
299
299
|
if (char === undefined)
|
|
300
300
|
return false;
|
|
301
|
-
return /[A-Za-z0-9_]/.test(char);
|
|
301
|
+
return /[A-Za-z0-9_$\u0080-\uFFFF]/.test(char);
|
|
302
302
|
}
|
|
303
303
|
function skipQuoted(text, start, quote) {
|
|
304
304
|
const escaping = quote === "'" && (text[start - 1] === "e" || text[start - 1] === "E") && !isIdentChar(text[start - 2]);
|
|
@@ -341,13 +341,32 @@ function skipBlockComment(text, start) {
|
|
|
341
341
|
return text.length;
|
|
342
342
|
}
|
|
343
343
|
function skipDollarQuoted(text, start) {
|
|
344
|
-
const opener = /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.exec(text.slice(start));
|
|
344
|
+
const opener = /^\$(?:[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_\u0080-\uFFFF]*)?\$/.exec(text.slice(start));
|
|
345
345
|
if (opener === null)
|
|
346
346
|
return -1;
|
|
347
347
|
const tag = opener[0];
|
|
348
348
|
const close = text.indexOf(tag, start + tag.length);
|
|
349
349
|
return close === -1 ? text.length : close + tag.length;
|
|
350
350
|
}
|
|
351
|
+
function skipSqlTrivia(params) {
|
|
352
|
+
const { text } = params;
|
|
353
|
+
let index = params.start;
|
|
354
|
+
while (index < text.length) {
|
|
355
|
+
if (/[ \t\n\r\f\v]/.test(text[index])) {
|
|
356
|
+
index += 1;
|
|
357
|
+
} else if (text[index] === "-" && text[index + 1] === "-") {
|
|
358
|
+
index += 2;
|
|
359
|
+
while (index < text.length && text[index] !== `
|
|
360
|
+
` && text[index] !== "\r")
|
|
361
|
+
index += 1;
|
|
362
|
+
} else if (text[index] === "/" && text[index + 1] === "*") {
|
|
363
|
+
index = skipBlockComment(text, index);
|
|
364
|
+
} else {
|
|
365
|
+
break;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return index;
|
|
369
|
+
}
|
|
351
370
|
function scanPlaceholders(params) {
|
|
352
371
|
const { text } = params;
|
|
353
372
|
const chunks = [];
|
|
@@ -355,19 +374,20 @@ function scanPlaceholders(params) {
|
|
|
355
374
|
let chunkStart = 0;
|
|
356
375
|
let index = 0;
|
|
357
376
|
while (index < text.length) {
|
|
377
|
+
const afterTrivia = skipSqlTrivia({ text, start: index });
|
|
378
|
+
if (afterTrivia !== index) {
|
|
379
|
+
index = afterTrivia;
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
358
382
|
const char = text[index];
|
|
359
383
|
if (char === "'" || char === '"') {
|
|
360
384
|
index = skipQuoted(text, index, char);
|
|
361
385
|
continue;
|
|
362
386
|
}
|
|
363
|
-
if (char
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
continue;
|
|
368
|
-
}
|
|
369
|
-
if (char === "/" && text[index + 1] === "*") {
|
|
370
|
-
index = skipBlockComment(text, index);
|
|
387
|
+
if (char !== undefined && /[A-Za-z_\u0080-\uFFFF]/.test(char)) {
|
|
388
|
+
index += 1;
|
|
389
|
+
while (isIdentChar(text[index]))
|
|
390
|
+
index += 1;
|
|
371
391
|
continue;
|
|
372
392
|
}
|
|
373
393
|
if (char === "$") {
|
|
@@ -436,6 +456,78 @@ function createTemplateCache(params) {
|
|
|
436
456
|
};
|
|
437
457
|
}
|
|
438
458
|
|
|
459
|
+
// packages/adapter-bun/src/raw-json-text.ts
|
|
460
|
+
var JSON_TYPE = /^(jsonb?)(?![A-Za-z0-9_$\u0080-\uFFFF])/i;
|
|
461
|
+
var CAST_OPEN = /(?:^|[^A-Za-z0-9_$.\u0080-\uFFFF])CAST[ \t\n\r\f\v]*\([ \t\n\r\f\v]*$/i;
|
|
462
|
+
var AS_TOKEN = /^AS(?![A-Za-z0-9_$\u0080-\uFFFF])/i;
|
|
463
|
+
function castOf(params) {
|
|
464
|
+
const { after } = params;
|
|
465
|
+
const start = skipSqlTrivia({ text: after, start: 0 });
|
|
466
|
+
const direct = after.startsWith("::", start);
|
|
467
|
+
if (!direct && !(start > 0 && AS_TOKEN.test(after.slice(start)) && CAST_OPEN.test(params.before)))
|
|
468
|
+
return null;
|
|
469
|
+
const typeStart = skipSqlTrivia({ text: after, start: start + 2 });
|
|
470
|
+
const type = JSON_TYPE.exec(after.slice(typeStart));
|
|
471
|
+
if (type === null)
|
|
472
|
+
return null;
|
|
473
|
+
const end = skipSqlTrivia({ text: after, start: typeStart + type[0].length });
|
|
474
|
+
if (direct ? after[end] === "[" || after[end] === "." : after[end] !== ")")
|
|
475
|
+
return null;
|
|
476
|
+
return type[1].toLowerCase();
|
|
477
|
+
}
|
|
478
|
+
function planJsonSlots(params) {
|
|
479
|
+
const { template, indices } = scanPlaceholders({ text: params.text });
|
|
480
|
+
if (indices.length === 0)
|
|
481
|
+
return null;
|
|
482
|
+
const chunks = [...template];
|
|
483
|
+
const casts = new Map;
|
|
484
|
+
indices.forEach((placeholder, gap) => {
|
|
485
|
+
const cast = castOf({ before: chunks[gap] ?? "", after: chunks[gap + 1] ?? "" });
|
|
486
|
+
const seen = casts.get(placeholder);
|
|
487
|
+
casts.set(placeholder, seen === undefined || seen === cast ? cast : null);
|
|
488
|
+
});
|
|
489
|
+
const slots = new Set;
|
|
490
|
+
for (const [placeholder, cast] of casts)
|
|
491
|
+
if (cast !== null)
|
|
492
|
+
slots.add(placeholder);
|
|
493
|
+
return slots.size === 0 ? null : { chunks, indices, slots };
|
|
494
|
+
}
|
|
495
|
+
function createJsonTextRespeller(params) {
|
|
496
|
+
const max = Math.max(1, params.max);
|
|
497
|
+
const plans = new Map;
|
|
498
|
+
const planOf = (text) => {
|
|
499
|
+
const known = plans.get(text);
|
|
500
|
+
if (known !== undefined) {
|
|
501
|
+
plans.delete(text);
|
|
502
|
+
plans.set(text, known);
|
|
503
|
+
return known;
|
|
504
|
+
}
|
|
505
|
+
const plan = planJsonSlots({ text });
|
|
506
|
+
plans.set(text, plan);
|
|
507
|
+
if (plans.size > max)
|
|
508
|
+
plans.delete(plans.keys().next().value);
|
|
509
|
+
return plan;
|
|
510
|
+
};
|
|
511
|
+
return {
|
|
512
|
+
respell: ({ text, values }) => {
|
|
513
|
+
if (values.length === 0)
|
|
514
|
+
return text;
|
|
515
|
+
const plan = planOf(text);
|
|
516
|
+
if (plan === null)
|
|
517
|
+
return text;
|
|
518
|
+
let respelled = false;
|
|
519
|
+
let out = plan.chunks[0] ?? "";
|
|
520
|
+
plan.indices.forEach((placeholder, gap) => {
|
|
521
|
+
const asText = plan.slots.has(placeholder) && typeof values[placeholder - 1] === "string";
|
|
522
|
+
if (asText)
|
|
523
|
+
respelled = true;
|
|
524
|
+
out += `$${placeholder}${asText ? "::text" : ""}${plan.chunks[gap + 1] ?? ""}`;
|
|
525
|
+
});
|
|
526
|
+
return respelled ? out : text;
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
|
|
439
531
|
// packages/adapter-bun/src/transaction-sql.ts
|
|
440
532
|
import { VibeError as VibeError6 } from "@vibeorm/schema";
|
|
441
533
|
import { refuseNestedTransactionOptions } from "@vibeorm/runtime/adapter-kit";
|
|
@@ -596,6 +688,7 @@ function bunAdapter(options) {
|
|
|
596
688
|
const namedUnsafe = usePrepared && namedUnsafeBinds({ version: Bun.version });
|
|
597
689
|
const address = takeConnectTimeout({ url: takeSystemRootCert({ url: requireUrl({ options }) }) });
|
|
598
690
|
const templates = createTemplateCache({ max: options?.stmtCacheMax ?? 1000 });
|
|
691
|
+
const jsonText = usePrepared ? createJsonTextRespeller({ max: options?.stmtCacheMax ?? 1000 }) : null;
|
|
599
692
|
let activeWire = WIRE_TEXT;
|
|
600
693
|
let wireSettled = false;
|
|
601
694
|
let wireProbe = null;
|
|
@@ -1130,7 +1223,8 @@ function bunAdapter(options) {
|
|
|
1130
1223
|
}
|
|
1131
1224
|
async function runExecuteUnsafe(params) {
|
|
1132
1225
|
const values = params.values === undefined ? undefined : serializeParamsRaw({ values: params.values, namedStatements: usePrepared });
|
|
1133
|
-
const
|
|
1226
|
+
const text = jsonText === null || params.values === undefined ? params.text : jsonText.respell({ text: params.text, values: params.values });
|
|
1227
|
+
const result = await runMapped(() => params.source.unsafe(text, values));
|
|
1134
1228
|
observeResult({ scope: params.scope, effect: params.effect, result });
|
|
1135
1229
|
const rows = finalRows({ result });
|
|
1136
1230
|
return { rows: plainRows({ rows }), affectedRows: readAffectedRows({ rows }) };
|
|
@@ -1810,4 +1904,4 @@ export {
|
|
|
1810
1904
|
validateTransactionDeadline2 as validateTransactionDeadline
|
|
1811
1905
|
};
|
|
1812
1906
|
|
|
1813
|
-
//# debugId=
|
|
1907
|
+
//# debugId=B468C154EBB4425A64756E2164756E21
|