From 0319ea40080be0224dd63d585f3edb579734a987 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 30 Aug 2026 06:32:49 +0000 Subject: [PATCH 1/8] postgres: send a string parameter bound to json/jsonb verbatim A string parameter bound to a json or jsonb placeholder already carries the JSON text. Re-serializing it with JSON.stringify turned the document into a JSON string scalar on the wire, so json_typeof($1::json) reported string and json_to_recordset failed. Send the string bytes as-is, like node-postgres and postgres.js. Non-string values keep the stringify path. Fixes #40942 --- src/sql_jsc/postgres/PostgresRequest.rs | 19 ++++- .../js/sql/postgres-json-string-param.test.ts | 75 +++++++++++++++++++ 2 files changed, 90 insertions(+), 4 deletions(-) create mode 100644 test/js/sql/postgres-json-string-param.test.ts diff --git a/src/sql_jsc/postgres/PostgresRequest.rs b/src/sql_jsc/postgres/PostgresRequest.rs index dfed47bee818..e10b3d3f22b3 100644 --- a/src/sql_jsc/postgres/PostgresRequest.rs +++ b/src/sql_jsc/postgres/PostgresRequest.rs @@ -166,10 +166,21 @@ pub(crate) fn write_bind( }; match effective_tag { types::Tag::jsonb | types::Tag::json => { - // Use jsonStringifyFast for SIMD-optimized serialization - let str = value - .json_stringify_fast(global) - .map_err(js_error_to_postgres)?; + // A string parameter already carries the JSON text. Send it + // verbatim (like node-postgres and postgres.js); stringifying + // it again would turn the document into a JSON string scalar. + let str = if value.is_string() { + let str = BunString::from_js(value, global).map_err(js_error_to_postgres)?; + if str.tag() == bun_core::Tag::Dead { + return Err(AnyPostgresError::OutOfMemory); + } + str + } else { + // Use jsonStringifyFast for SIMD-optimized serialization + value + .json_stringify_fast(global) + .map_err(js_error_to_postgres)? + }; let slice = str.to_utf8(); let l = writer.length()?; writer.write(slice.slice())?; diff --git a/test/js/sql/postgres-json-string-param.test.ts b/test/js/sql/postgres-json-string-param.test.ts new file mode 100644 index 000000000000..acf8f8ce155f --- /dev/null +++ b/test/js/sql/postgres-json-string-param.test.ts @@ -0,0 +1,75 @@ +import { SQL } from "bun"; +import { expect, test } from "bun:test"; +import { describeWithContainer } from "harness"; + +// https://github.com/oven-sh/bun/issues/40942 +// A string parameter bound to a json/jsonb placeholder carries the JSON text +// itself and must be sent verbatim, not re-stringified into a JSON string +// scalar. This matches node-postgres and postgres.js. +describeWithContainer("postgres json string parameters", { image: "postgres_plain" }, container => { + const options = () => + ({ + db: "bun_sql_test", + username: "bun_sql_test", + host: container.host, + port: container.port, + max: 1, + }) as const; + + test("string parameter bound to ::json is sent as the JSON text itself", async () => { + await container.ready; + await using sql = new SQL(options()); + const payload = JSON.stringify([{ id: 1, name: "a" }]); + const [row] = await sql`select json_typeof(${payload}::json) as kind, ${payload}::json as value`; + expect(row).toEqual({ kind: "array", value: [{ id: 1, name: "a" }] }); + }); + + test("string parameter bound to ::jsonb is sent as the JSON text itself", async () => { + await container.ready; + await using sql = new SQL(options()); + const payload = JSON.stringify({ a: "hello", b: 42 }); + const [row] = await sql`select jsonb_typeof(${payload}::jsonb) as kind, ${payload}::jsonb as value`; + expect(row).toEqual({ kind: "object", value: { a: "hello", b: 42 } }); + }); + + test("json_to_recordset accepts a stringified array parameter", async () => { + await container.ready; + await using sql = new SQL(options()); + const payload = JSON.stringify([ + { id: 1, name: "a" }, + { id: 2, name: "b" }, + ]); + const rows = await sql.unsafe("select * from json_to_recordset($1::json) as x(id int, name text)", [payload]); + expect(rows).toEqual([ + { id: 1, name: "a" }, + { id: 2, name: "b" }, + ]); + }); + + test("object parameter bound to ::json is still stringified", async () => { + await container.ready; + await using sql = new SQL(options()); + const [row] = await sql`select json_typeof(${{ a: 1 }}::json) as kind, ${{ a: 1 }}::json as value`; + expect(row).toEqual({ kind: "object", value: { a: 1 } }); + }); + + test("string parameter bound to ::json with prepare: false", async () => { + await container.ready; + await using sql = new SQL({ ...options(), prepare: false }); + const payload = JSON.stringify([{ id: 1 }]); + const [row] = await sql`select json_typeof(${payload}::json) as kind`; + expect(row).toEqual({ kind: "array" }); + }); + + test("non-JSON string bound to ::json fails on the server", async () => { + await container.ready; + await using sql = new SQL(options()); + let error: Error | undefined; + try { + await sql`select ${"not json"}::json as x`; + } catch (e) { + error = e as Error; + } + expect(error?.message).toMatch(/invalid input syntax for type json/); + }); +}); From a3c9289102138ce51ef14389c39a0fbfff32f134 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 30 Aug 2026 07:52:28 +0000 Subject: [PATCH 2/8] postgres: widen the string escape hatch to json/jsonb instead of a new branch Route a string bound to json/jsonb through the existing text arm. The wire bytes are identical (json/jsonb are text-format either way). Add a non-ASCII payload test and use .execute() before .rejects in the error test (see #40949). --- src/sql_jsc/postgres/PostgresRequest.rs | 30 ++++++++----------- .../js/sql/postgres-json-string-param.test.ts | 23 +++++++++----- 2 files changed, 29 insertions(+), 24 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresRequest.rs b/src/sql_jsc/postgres/PostgresRequest.rs index e10b3d3f22b3..8ff7242be544 100644 --- a/src/sql_jsc/postgres/PostgresRequest.rs +++ b/src/sql_jsc/postgres/PostgresRequest.rs @@ -158,29 +158,25 @@ pub(crate) fn write_bind( // convert it to the binary representation. This minimizes the room // for mistakes on our end, such as stripping the timezone // differently than what Postgres does when given a timestamp with - // timezone. - let effective_tag = if tag.is_binary_format_supported() && value.is_string() { + // timezone. A string bound to json/jsonb already carries the JSON + // text, so send it verbatim (like node-postgres and postgres.js); + // stringifying it again would turn the document into a JSON string + // scalar. json/jsonb are text-format either way, so the format code + // written above does not change. + let effective_tag = if value.is_string() + && (tag.is_binary_format_supported() + || matches!(tag, types::Tag::json | types::Tag::jsonb)) + { types::Tag::text } else { tag }; match effective_tag { types::Tag::jsonb | types::Tag::json => { - // A string parameter already carries the JSON text. Send it - // verbatim (like node-postgres and postgres.js); stringifying - // it again would turn the document into a JSON string scalar. - let str = if value.is_string() { - let str = BunString::from_js(value, global).map_err(js_error_to_postgres)?; - if str.tag() == bun_core::Tag::Dead { - return Err(AnyPostgresError::OutOfMemory); - } - str - } else { - // Use jsonStringifyFast for SIMD-optimized serialization - value - .json_stringify_fast(global) - .map_err(js_error_to_postgres)? - }; + // Use jsonStringifyFast for SIMD-optimized serialization + let str = value + .json_stringify_fast(global) + .map_err(js_error_to_postgres)?; let slice = str.to_utf8(); let l = writer.length()?; writer.write(slice.slice())?; diff --git a/test/js/sql/postgres-json-string-param.test.ts b/test/js/sql/postgres-json-string-param.test.ts index acf8f8ce155f..81e4a979c5f4 100644 --- a/test/js/sql/postgres-json-string-param.test.ts +++ b/test/js/sql/postgres-json-string-param.test.ts @@ -32,6 +32,17 @@ describeWithContainer("postgres json string parameters", { image: "postgres_plai expect(row).toEqual({ kind: "object", value: { a: "hello", b: 42 } }); }); + test("non-ASCII JSON text round-trips through the verbatim path", async () => { + await container.ready; + await using sql = new SQL(options()); + // "café" is Latin-1 in JSC's 8-bit representation, "🚀"/"世界" force + // UTF-16, so one payload covers both transcode arms of the verbatim path. + const doc = { name: "caf\u00e9\u{1F680}", text: "\u4e16\u754c" }; + const payload = JSON.stringify(doc); + const [row] = await sql`select jsonb_typeof(${payload}::jsonb) as kind, ${payload}::jsonb as value`; + expect(row).toEqual({ kind: "object", value: doc }); + }); + test("json_to_recordset accepts a stringified array parameter", async () => { await container.ready; await using sql = new SQL(options()); @@ -64,12 +75,10 @@ describeWithContainer("postgres json string parameters", { image: "postgres_plai test("non-JSON string bound to ::json fails on the server", async () => { await container.ready; await using sql = new SQL(options()); - let error: Error | undefined; - try { - await sql`select ${"not json"}::json as x`; - } catch (e) { - error = e as Error; - } - expect(error?.message).toMatch(/invalid input syntax for type json/); + // .execute() because `expect(query).rejects` on the lazy Query hangs: + // https://github.com/oven-sh/bun/issues/40949 + await expect(sql`select ${"not json"}::json as x`.execute()).rejects.toThrow( + /invalid input syntax for type json/, + ); }); }); From 3df90fd25c4843e69ee7283b581a59dffd9a2931 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 30 Aug 2026 07:53:36 +0000 Subject: [PATCH 3/8] postgres: trim the bind escape hatch comment --- src/sql_jsc/postgres/PostgresRequest.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresRequest.rs b/src/sql_jsc/postgres/PostgresRequest.rs index 8ff7242be544..93d984e1221a 100644 --- a/src/sql_jsc/postgres/PostgresRequest.rs +++ b/src/sql_jsc/postgres/PostgresRequest.rs @@ -158,11 +158,9 @@ pub(crate) fn write_bind( // convert it to the binary representation. This minimizes the room // for mistakes on our end, such as stripping the timezone // differently than what Postgres does when given a timestamp with - // timezone. A string bound to json/jsonb already carries the JSON - // text, so send it verbatim (like node-postgres and postgres.js); - // stringifying it again would turn the document into a JSON string - // scalar. json/jsonb are text-format either way, so the format code - // written above does not change. + // timezone. A string bound to json/jsonb is the JSON text itself: + // send it verbatim, like node-postgres, instead of stringifying it + // into a JSON string scalar. let effective_tag = if value.is_string() && (tag.is_binary_format_supported() || matches!(tag, types::Tag::json | types::Tag::jsonb)) From 418a9b5e503fee9fd44bae44d30329185753918a Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2026 07:56:14 +0000 Subject: [PATCH 4/8] [autofix.ci] apply automated fixes --- test/js/sql/postgres-json-string-param.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/test/js/sql/postgres-json-string-param.test.ts b/test/js/sql/postgres-json-string-param.test.ts index 81e4a979c5f4..7e1b971bfa01 100644 --- a/test/js/sql/postgres-json-string-param.test.ts +++ b/test/js/sql/postgres-json-string-param.test.ts @@ -77,8 +77,6 @@ describeWithContainer("postgres json string parameters", { image: "postgres_plai await using sql = new SQL(options()); // .execute() because `expect(query).rejects` on the lazy Query hangs: // https://github.com/oven-sh/bun/issues/40949 - await expect(sql`select ${"not json"}::json as x`.execute()).rejects.toThrow( - /invalid input syntax for type json/, - ); + await expect(sql`select ${"not json"}::json as x`.execute()).rejects.toThrow(/invalid input syntax for type json/); }); }); From 60261ba1e169657f4d0fe8405da8a795e10c2a16 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 30 Aug 2026 08:03:32 +0000 Subject: [PATCH 5/8] test: cover the Latin-1 and UTF-16 transcode arms separately --- test/js/sql/postgres-json-string-param.test.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/test/js/sql/postgres-json-string-param.test.ts b/test/js/sql/postgres-json-string-param.test.ts index 7e1b971bfa01..3ec9a49e4f3f 100644 --- a/test/js/sql/postgres-json-string-param.test.ts +++ b/test/js/sql/postgres-json-string-param.test.ts @@ -35,12 +35,15 @@ describeWithContainer("postgres json string parameters", { image: "postgres_plai test("non-ASCII JSON text round-trips through the verbatim path", async () => { await container.ready; await using sql = new SQL(options()); - // "café" is Latin-1 in JSC's 8-bit representation, "🚀"/"世界" force - // UTF-16, so one payload covers both transcode arms of the verbatim path. - const doc = { name: "caf\u00e9\u{1F680}", text: "\u4e16\u754c" }; - const payload = JSON.stringify(doc); - const [row] = await sql`select jsonb_typeof(${payload}::jsonb) as kind, ${payload}::jsonb as value`; - expect(row).toEqual({ kind: "object", value: doc }); + // A JS string is 8-bit or 16-bit as a whole, so two documents cover both + // transcode arms: "café" stays Latin-1, the emoji/CJK one forces UTF-16. + const latin1Doc = { name: "caf\u00e9" }; + const utf16Doc = { name: "\u{1F680}", text: "\u4e16\u754c" }; + for (const doc of [latin1Doc, utf16Doc]) { + const payload = JSON.stringify(doc); + const [row] = await sql`select jsonb_typeof(${payload}::jsonb) as kind, ${payload}::jsonb as value`; + expect(row).toEqual({ kind: "object", value: doc }); + } }); test("json_to_recordset accepts a stringified array parameter", async () => { From 25ee32d1d6ce16eb7d3f860563ef1f66faaec5ff Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 30 Aug 2026 08:27:14 +0000 Subject: [PATCH 6/8] test: parameterize the transcode cases with test.each --- .../js/sql/postgres-json-string-param.test.ts | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/test/js/sql/postgres-json-string-param.test.ts b/test/js/sql/postgres-json-string-param.test.ts index 3ec9a49e4f3f..2e05112b914c 100644 --- a/test/js/sql/postgres-json-string-param.test.ts +++ b/test/js/sql/postgres-json-string-param.test.ts @@ -32,18 +32,17 @@ describeWithContainer("postgres json string parameters", { image: "postgres_plai expect(row).toEqual({ kind: "object", value: { a: "hello", b: 42 } }); }); - test("non-ASCII JSON text round-trips through the verbatim path", async () => { + // A JS string is 8-bit or 16-bit as a whole, so two documents cover both + // transcode arms: "café" stays Latin-1, the emoji/CJK one forces UTF-16. + test.each([ + ["Latin-1", { name: "caf\u00e9" }], + ["UTF-16", { name: "\u{1F680}", text: "\u4e16\u754c" }], + ])("non-ASCII JSON text (%s) round-trips through the verbatim path", async (_label, doc) => { await container.ready; await using sql = new SQL(options()); - // A JS string is 8-bit or 16-bit as a whole, so two documents cover both - // transcode arms: "café" stays Latin-1, the emoji/CJK one forces UTF-16. - const latin1Doc = { name: "caf\u00e9" }; - const utf16Doc = { name: "\u{1F680}", text: "\u4e16\u754c" }; - for (const doc of [latin1Doc, utf16Doc]) { - const payload = JSON.stringify(doc); - const [row] = await sql`select jsonb_typeof(${payload}::jsonb) as kind, ${payload}::jsonb as value`; - expect(row).toEqual({ kind: "object", value: doc }); - } + const payload = JSON.stringify(doc); + const [row] = await sql`select jsonb_typeof(${payload}::jsonb) as kind, ${payload}::jsonb as value`; + expect(row).toEqual({ kind: "object", value: doc }); }); test("json_to_recordset accepts a stringified array parameter", async () => { From 8dc6fbb199a530b3df916496fabf732c0f6fc674 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 15 Sep 2026 17:31:26 +0000 Subject: [PATCH 7/8] postgres: cover json/jsonb column inserts, document how json parameters are sent Add tests for a stringified value inserted into json and jsonb columns with no cast, and through the sql() insert helper. Correct the test header: node-postgres sends a string verbatim, postgres.js stringifies it again. Document the rule in docs/runtime/sql.mdx. --- docs/runtime/sql.mdx | 15 ++++++++ .../js/sql/postgres-json-string-param.test.ts | 35 +++++++++++++++++-- 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/docs/runtime/sql.mdx b/docs/runtime/sql.mdx index e14b2b9b54b0..f96c58d2e0df 100644 --- a/docs/runtime/sql.mdx +++ b/docs/runtime/sql.mdx @@ -304,6 +304,21 @@ await sql`INSERT INTO users ${sql(user, "name", "email")}`; // Only inserts name and email columns, ignoring other fields ``` +### `json` and `jsonb` values (PostgreSQL) + +When a parameter has the type `json` or `jsonb`, Bun serializes an object or an array with `JSON.stringify`. Bun sends a string as it is, so the string must contain JSON text. `node-postgres` treats a string the same way. Code that calls `JSON.stringify` on the value first works with both clients. + +```ts +// Both statements store the object {"theme": "dark"} +await sql`INSERT INTO settings (data) VALUES (${{ theme: "dark" }})`; +await sql`INSERT INTO settings (data) VALUES (${JSON.stringify({ theme: "dark" })})`; + +// To store a string, a number, or a boolean, pass it through JSON.stringify +await sql`INSERT INTO settings (data) VALUES (${JSON.stringify("dark")})`; +``` + +A string that is not JSON text, such as `${"dark"}`, fails with `invalid input syntax for type json`. + --- ## Query Results diff --git a/test/js/sql/postgres-json-string-param.test.ts b/test/js/sql/postgres-json-string-param.test.ts index 2e05112b914c..767ec19a53dd 100644 --- a/test/js/sql/postgres-json-string-param.test.ts +++ b/test/js/sql/postgres-json-string-param.test.ts @@ -2,10 +2,10 @@ import { SQL } from "bun"; import { expect, test } from "bun:test"; import { describeWithContainer } from "harness"; -// https://github.com/oven-sh/bun/issues/40942 +// https://github.com/oven-sh/bun/issues/28819 // A string parameter bound to a json/jsonb placeholder carries the JSON text // itself and must be sent verbatim, not re-stringified into a JSON string -// scalar. This matches node-postgres and postgres.js. +// scalar. This matches node-postgres. postgres.js stringifies the string again. describeWithContainer("postgres json string parameters", { image: "postgres_plain" }, container => { const options = () => ({ @@ -59,6 +59,37 @@ describeWithContainer("postgres json string parameters", { image: "postgres_plai ]); }); + // No cast: the column type alone makes the server report json/jsonb for the + // parameter. This is the statement shape ORMs such as drizzle send. + test("stringified values inserted into json and jsonb columns keep their JSON type", async () => { + await container.ready; + await using sql = new SQL(options()); + await sql`create temp table json_string_param (id serial primary key, j json, jb jsonb)`; + for (const value of [{ hello: "world" }, [1, 2, 3], 42, "text", null]) { + const text = JSON.stringify(value); + await sql`insert into json_string_param (j, jb) values (${text}, ${text})`; + } + const rows = await sql` + select json_typeof(j) as j_kind, jsonb_typeof(jb) as jb_kind, j, jb + from json_string_param order by id`; + expect(rows).toEqual([ + { j_kind: "object", jb_kind: "object", j: { hello: "world" }, jb: { hello: "world" } }, + { j_kind: "array", jb_kind: "array", j: [1, 2, 3], jb: [1, 2, 3] }, + { j_kind: "number", jb_kind: "number", j: 42, jb: 42 }, + { j_kind: "string", jb_kind: "string", j: "text", jb: "text" }, + { j_kind: "null", jb_kind: "null", j: null, jb: null }, + ]); + }); + + test("sql() insert helper sends stringified values verbatim", async () => { + await container.ready; + await using sql = new SQL(options()); + await sql`create temp table json_string_param_helper (j json, jb jsonb)`; + const row = { j: JSON.stringify([1, 2, 3]), jb: JSON.stringify({ a: 1 }) }; + const [inserted] = await sql`insert into json_string_param_helper ${sql(row)} returning j, jb`; + expect(inserted).toEqual({ j: [1, 2, 3], jb: { a: 1 } }); + }); + test("object parameter bound to ::json is still stringified", async () => { await container.ready; await using sql = new SQL(options()); From aaffd7435c282edec04129468e5908bb474fde28 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 15 Sep 2026 17:38:12 +0000 Subject: [PATCH 8/8] docs: note that JSON null needs JSON.stringify(null) for json/jsonb parameters --- docs/runtime/sql.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/runtime/sql.mdx b/docs/runtime/sql.mdx index f96c58d2e0df..42ff86b8a6f4 100644 --- a/docs/runtime/sql.mdx +++ b/docs/runtime/sql.mdx @@ -313,8 +313,10 @@ When a parameter has the type `json` or `jsonb`, Bun serializes an object or an await sql`INSERT INTO settings (data) VALUES (${{ theme: "dark" }})`; await sql`INSERT INTO settings (data) VALUES (${JSON.stringify({ theme: "dark" })})`; -// To store a string, a number, or a boolean, pass it through JSON.stringify +// To store a string, a number, a boolean, or null, pass it through JSON.stringify. +// A bare null binds as SQL NULL, not as the JSON value null. await sql`INSERT INTO settings (data) VALUES (${JSON.stringify("dark")})`; +await sql`INSERT INTO settings (data) VALUES (${JSON.stringify(null)})`; ``` A string that is not JSON text, such as `${"dark"}`, fails with `invalid input syntax for type json`.