From 30fab813b0bba98e4ac86396810d370431bc4317 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 03:56:18 +0000 Subject: [PATCH 1/5] sql(postgres): declare text format for Bind parameters that have no binary encoder write_bind picked each parameter's format code from Tag::is_binary_format_supported(), the list of types DataCell can decode from binary. The encoder only has binary arms for bool, int4, float8, timestamp(tz) and bytea. A parameter the server typed as numeric, real, time or real[] was declared binary but written as String(value), and an int4[] parameter was written as a single int4. The server then read text bytes as the binary representation: 08P01, 22P03 or 22008 errors, or a silently wrong real value. One ParamEncoding enum now drives both the format-code section and the value section of the Bind message. Types without a binary encoder are sent as text and parsed by the server. --- src/sql/postgres/types/Tag.rs | 3 + src/sql_jsc/postgres/PostgresRequest.rs | 172 ++++++++++-------- .../js/sql/postgres-bind-param-format.test.ts | 96 ++++++++++ 3 files changed, 197 insertions(+), 74 deletions(-) create mode 100644 test/js/sql/postgres-bind-param-format.test.ts diff --git a/src/sql/postgres/types/Tag.rs b/src/sql/postgres/types/Tag.rs index d08369ade3eb..ff5979976485 100644 --- a/src/sql/postgres/types/Tag.rs +++ b/src/sql/postgres/types/Tag.rs @@ -179,6 +179,9 @@ pg_tags! { } impl Tag { + /// Types whose binary wire format `DataCell` can decode, so result columns + /// of these types are requested in binary. Bind parameters are encoded by + /// a shorter list, `ParamEncoding` in `bun_sql_jsc`. pub fn is_binary_format_supported(self) -> bool { match self { // TODO: .int2_array, .float8_array, diff --git a/src/sql_jsc/postgres/PostgresRequest.rs b/src/sql_jsc/postgres/PostgresRequest.rs index f556d1e54c2a..fd7330ed05b7 100644 --- a/src/sql_jsc/postgres/PostgresRequest.rs +++ b/src/sql_jsc/postgres/PostgresRequest.rs @@ -49,6 +49,76 @@ pub enum MessageType { /// The PostgreSQL wire protocol uses 16-bit integers for parameter and column counts. const MAX_PARAMETERS: usize = u16::MAX as usize; +/// How `write_bind` puts one parameter value on the wire. Both the +/// format-code section and the value section of the Bind message are derived +/// from this, so they cannot disagree. +/// +/// This is the encode side only. `Tag::is_binary_format_supported` is the +/// decode side (result columns) and is wider: `DataCell` decodes binary +/// numeric, float4, time, int4[] and float4[], but nothing here encodes them. +#[derive(Clone, Copy)] +enum ParamEncoding { + /// `String(value)`, format 0. The server parses it as the parameter's type. + Text, + /// `JSON.stringify(value)`, format 0. + Json, + Bool, + Int4, + Float8, + /// int8 microseconds since 2000-01-01, for timestamp and timestamptz. + Timestamp, + Bytea, +} + +impl ParamEncoding { + fn for_tag(tag: types::Tag) -> ParamEncoding { + match tag { + types::Tag::json | types::Tag::jsonb => ParamEncoding::Json, + types::Tag::bool => ParamEncoding::Bool, + types::Tag::int4 => ParamEncoding::Int4, + types::Tag::float8 => ParamEncoding::Float8, + types::Tag::timestamp | types::Tag::timestamptz => ParamEncoding::Timestamp, + types::Tag::bytea => ParamEncoding::Bytea, + _ => ParamEncoding::Text, + } + } + + /// If they pass a value as a string, let's avoid attempting to 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. + fn for_value(self, value: JSValue) -> ParamEncoding { + if self.is_binary() && value.is_string() { + ParamEncoding::Text + } else { + self + } + } + + fn is_binary(self) -> bool { + match self { + ParamEncoding::Text | ParamEncoding::Json => false, + ParamEncoding::Bool + | ParamEncoding::Int4 + | ParamEncoding::Float8 + | ParamEncoding::Timestamp + | ParamEncoding::Bytea => true, + } + } + + fn format_code(self) -> Short { + if self.is_binary() { 1 } else { 0 } + } +} + +fn param_tag(parameter_field: Int4) -> types::Tag { + match Short::try_from(parameter_field) { + Ok(oid) => types::Tag(oid), + // Outside the `Short` range: a user-defined type, bound as text. + Err(_) => types::Tag::text, + } +} + pub(crate) fn write_bind( name: &[u8], cursor_name: &BunString, @@ -82,39 +152,17 @@ pub(crate) fn write_bind( let mut iter = QueryBindingIterator::init(values_array, columns_value, global) .map_err(js_error_to_postgres)?; - for i in 0..(len as usize) { - let parameter_field = parameter_fields[i]; - let is_custom_type = (Short::MAX as Int4) < parameter_field; - let tag: types::Tag = if is_custom_type { - types::Tag::text - } else { - types::Tag(Short::try_from(parameter_field).unwrap()) - }; - - let force_text = is_custom_type - || (tag.is_binary_format_supported() - && 'brk: { - iter.to(i as u32); - if let Some(value) = iter.next().map_err(js_error_to_postgres)? { - break 'brk value.is_string(); - } - if iter.any_failed() { - return Err(AnyPostgresError::InvalidQueryBinding); - } - break 'brk false; - }); - - if force_text { - // If they pass a value as a string, let's avoid attempting to - // 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. - writer.short(0)?; - continue; + for (i, ¶meter_field) in parameter_fields.iter().enumerate() { + let mut encoding = ParamEncoding::for_tag(param_tag(parameter_field)); + if encoding.is_binary() { + iter.to(i as u32); + if let Some(value) = iter.next().map_err(js_error_to_postgres)? { + encoding = encoding.for_value(value); + } else if iter.any_failed() { + return Err(AnyPostgresError::InvalidQueryBinding); + } } - - writer.short(tag.format_code())?; + writer.short(encoding.format_code())?; } // The number of parameter values that follow (possibly zero). This @@ -125,24 +173,16 @@ pub(crate) fn write_bind( iter.to(0); let mut i: usize = 0; while let Some(value) = iter.next().map_err(js_error_to_postgres)? { - let tag: types::Tag = 'brk: { - if i >= len as usize { - // parameter in array but not in parameter_fields - // this is probably a bug a bug in bun lets return .text here so the server will send a error 08P01 - // with will describe better the error saying exactly how many parameters are missing and are expected - // Example: - // SQL error: PostgresError: bind message supplies 0 parameters, but prepared statement "PSELECT * FROM test_table WHERE id=$1 .in$0" requires 1 - // errno: "08P01", - // code: "ERR_POSTGRES_SERVER_ERROR" - break 'brk types::Tag::text; - } - let parameter_field = parameter_fields[i]; - let is_custom_type = (Short::MAX as Int4) < parameter_field; - break 'brk if is_custom_type { - types::Tag::text - } else { - types::Tag(Short::try_from(parameter_field).unwrap()) - }; + let tag: types::Tag = match parameter_fields.get(i) { + Some(¶meter_field) => param_tag(parameter_field), + // parameter in array but not in parameter_fields + // this is probably a bug a bug in bun lets return .text here so the server will send a error 08P01 + // with will describe better the error saying exactly how many parameters are missing and are expected + // Example: + // SQL error: PostgresError: bind message supplies 0 parameters, but prepared statement "PSELECT * FROM test_table WHERE id=$1 .in$0" requires 1 + // errno: "08P01", + // code: "ERR_POSTGRES_SERVER_ERROR" + None => types::Tag::text, }; if value.is_empty_or_undefined_or_null() { bun_core::scoped_log!(Postgres, " -> NULL"); @@ -154,18 +194,8 @@ pub(crate) fn write_bind( } bun_core::scoped_log!(Postgres, " -> {}", tag.tag_name().unwrap_or("(unknown)")); - // If they pass a value as a string, let's avoid attempting to - // 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() { - types::Tag::text - } else { - tag - }; - match effective_tag { - types::Tag::jsonb | types::Tag::json => { + match ParamEncoding::for_tag(tag).for_value(value) { + ParamEncoding::Json => { // Use jsonStringifyFast for SIMD-optimized serialization let str = value .json_stringify_fast(global) @@ -175,12 +205,12 @@ pub(crate) fn write_bind( writer.write(slice.slice())?; l.write_excluding_self()?; } - types::Tag::bool => { + ParamEncoding::Bool => { let l = writer.length()?; writer.write(&[value.to_boolean() as u8])?; l.write_excluding_self()?; } - types::Tag::timestamp | types::Tag::timestamptz => { + ParamEncoding::Timestamp => { let l = writer.length()?; writer.int8( crate::postgres::types::date::from_js(global, value) @@ -188,7 +218,7 @@ pub(crate) fn write_bind( )?; l.write_excluding_self()?; } - types::Tag::bytea => { + ParamEncoding::Bytea => { let Some(buf) = value.as_array_buffer(global) else { let received = JSGlobalObject::determine_specific_type(global, value) .map_err(js_error_to_postgres)?; @@ -206,23 +236,17 @@ pub(crate) fn write_bind( writer.write(bytes)?; l.write_excluding_self()?; } - types::Tag::int4 => { - let l = writer.length()?; - writer.int4(value.coerce::(global).map_err(js_error_to_postgres)? as u32)?; - l.write_excluding_self()?; - } - types::Tag::int4_array => { + ParamEncoding::Int4 => { let l = writer.length()?; writer.int4(value.coerce::(global).map_err(js_error_to_postgres)? as u32)?; l.write_excluding_self()?; } - types::Tag::float8 => { + ParamEncoding::Float8 => { let l = writer.length()?; writer.f64(value.to_number(global).map_err(js_error_to_postgres)?)?; l.write_excluding_self()?; } - - _ => { + ParamEncoding::Text => { let str = BunString::from_js(value, global).map_err(js_error_to_postgres)?; if str.tag() == bun_core::Tag::Dead { return Err(AnyPostgresError::OutOfMemory); diff --git a/test/js/sql/postgres-bind-param-format.test.ts b/test/js/sql/postgres-bind-param-format.test.ts new file mode 100644 index 000000000000..b7d7f8414bf4 --- /dev/null +++ b/test/js/sql/postgres-bind-param-format.test.ts @@ -0,0 +1,96 @@ +// The Bind message declares a format code (0 = text, 1 = binary) for every +// parameter and then carries the encoded values. Bun only has binary encoders +// for bool, int4, float8, timestamp(tz) and bytea. Every other parameter type +// the server reports (numeric, real, time, int4[], real[], ...) is sent as +// `String(value)` and must be declared as text so the server parses it. +// +// Runs against a real Postgres server with the default `prepare: true`, where +// Bun binds with the parameter types from the server's ParameterDescription. + +import { SQL } from "bun"; +import { expect, test } from "bun:test"; +import { describeWithContainer } from "harness"; + +// Stand-in for a decimal.js / big.js style value: not a string, but its text +// form is what should reach the server. +class Textual { + constructor(public text: string) {} + toString() { + return this.text; + } +} + +describeWithContainer("postgres", { image: "postgres_plain" }, container => { + const connect = () => + new SQL({ + url: `postgres://bun_sql_test@${container.host}:${container.port}/bun_sql_test`, + max: 1, + }); + + test("object bound to a numeric, real or time column is sent as its text form", async () => { + await container.ready; + await using sql = connect(); + await sql`create temp table t (n numeric, r real, t time)`; + + const rows = await sql` + insert into t (n, r, t) + values (${new Textual("19.99")}, ${new Textual("1234")}, ${new Textual("12:34:56")}) + returning n::text as n, r::text as r, t::text as t`; + expect(rows[0]).toEqual({ n: "19.99", r: "1234", t: "12:34:56" }); + }); + + test("object bound to a $1::numeric / $1::real cast is sent as its text form", async () => { + await container.ready; + await using sql = connect(); + const rows = await sql`select ${new Textual("0.1")}::numeric::text as n, ${new Textual("2.5")}::real::text as r`; + expect(rows[0]).toEqual({ n: "0.1", r: "2.5" }); + }); + + test("sql.array() in the sql(object) helper works for int4[] and real[] columns", async () => { + await container.ready; + await using sql = connect(); + await sql`create temp table t (id int4, ia int4[], ra real[])`; + + const inserted = await sql` + insert into t ${sql({ id: 1, ia: sql.array([1, 2, 3], "INT4"), ra: sql.array([1.5, 2.5], "REAL") })} + returning ia::text as ia, ra::text as ra`; + expect(inserted[0]).toEqual({ ia: "{1,2,3}", ra: "{1.5,2.5}" }); + + const updated = await sql` + update t set ${sql({ ia: sql.array([4], "INT4"), ra: sql.array([0.25], "REAL") })} + where id = 1 + returning ia::text as ia, ra::text as ra`; + expect(updated[0]).toEqual({ ia: "{4}", ra: "{0.25}" }); + }); + + test("sql.array() passed to sql.unsafe() works for int4[] and real[] parameters", async () => { + await container.ready; + await using sql = connect(); + const rows = await sql.unsafe("select $1::int4[]::text as ia, $2::real[]::text as ra", [ + sql.array([7, 8], "INT4"), + sql.array([1.5], "REAL"), + ]); + expect(rows[0]).toEqual({ ia: "{7,8}", ra: "{1.5}" }); + }); + + test("parameters with a binary encoder still round-trip", async () => { + await container.ready; + await using sql = connect(); + await sql`create temp table t (b bool, i int4, f float8, ts timestamptz, bin bytea, r real, n numeric)`; + + const date = new Date("2024-01-02T03:04:05.678Z"); + const rows = await sql` + insert into t (b, i, f, ts, bin, r, n) + values (${true}, ${-123456}, ${1.25}, ${date}, ${Buffer.from([0, 1, 254, 255])}, ${"2.5"}, ${"12345678901234567890.5"}) + returning b, i, f, ts, bin, r::text as r, n::text as n`; + expect(rows[0]).toEqual({ + b: true, + i: -123456, + f: 1.25, + ts: date, + bin: Buffer.from([0, 1, 254, 255]), + r: "2.5", + n: "12345678901234567890.5", + }); + }); +}); From 97c62ca6b52f0f850ca9763c54699a5d9fbe403a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 11:05:24 +0000 Subject: [PATCH 2/5] sql(postgres): derive every OID-to-Tag mapping from Tag::from_oid and decide each Bind encoding once FieldDescription::type_tag truncated the result-column OID to 16 bits, while DataCell mapped an out-of-range OID to text. A user-defined type whose OID aliases a binary-decoded builtin modulo 65536 was requested in binary and then read as text. Tag::from_oid is now the only mapping, used for Bind parameters, result format codes and DataCell. write_bind now records each parameter's encoding while it writes the format codes and reuses it for the value section, so a getter or toString() that runs between the two sections cannot make them disagree. Adds mock-server tests that pin the Bind bytes for both cases, and a pgDecodeBind helper in wire-frames.ts. --- src/sql/postgres/protocol/FieldDescription.rs | 6 +- src/sql/postgres/types/Tag.rs | 10 +- src/sql_jsc/postgres/DataCell.rs | 8 +- src/sql_jsc/postgres/PostgresRequest.rs | 61 ++++----- .../js/sql/postgres-bind-param-format.test.ts | 122 +++++++++++++++++- test/js/sql/wire-frames.test.ts | 32 +++++ test/js/sql/wire-frames.ts | 53 ++++++++ 7 files changed, 248 insertions(+), 44 deletions(-) diff --git a/src/sql/postgres/protocol/FieldDescription.rs b/src/sql/postgres/protocol/FieldDescription.rs index 0f75e7cdf76d..af9f63735619 100644 --- a/src/sql/postgres/protocol/FieldDescription.rs +++ b/src/sql/postgres/protocol/FieldDescription.rs @@ -1,5 +1,5 @@ use crate::postgres::any_postgres_error::AnyPostgresError; -use crate::postgres::postgres_types::{self as types, Int4, Short}; +use crate::postgres::postgres_types::{self as types, Int4}; use crate::postgres::protocol::new_reader::NewReader; use crate::shared::column_identifier::ColumnIdentifier; @@ -13,9 +13,7 @@ pub struct FieldDescription { impl FieldDescription { pub fn type_tag(&self) -> types::Tag { - // `types::Tag` is a `#[repr(transparent)] struct(Short)` newtype over - // the OID, so wrap the truncated value directly. - types::Tag(self.type_oid as Short) + types::Tag::from_oid(self.type_oid) } pub(crate) fn decode_internal( diff --git a/src/sql/postgres/types/Tag.rs b/src/sql/postgres/types/Tag.rs index ff5979976485..3a2d54f0d20d 100644 --- a/src/sql/postgres/types/Tag.rs +++ b/src/sql/postgres/types/Tag.rs @@ -56,7 +56,7 @@ // varbit | 1562 | 1563 // numeric | 1700 | 1231 -use super::int_types::short as Short; +use super::int_types::{Int4, short as Short}; // Non-exhaustive: any `short` value is a valid `Tag`. A `#[repr(i16)] enum` // cannot hold arbitrary values, so model as a transparent newtype with @@ -179,6 +179,14 @@ pg_tags! { } impl Tag { + /// Maps a wire OID to a `Tag`. An OID outside the `Short` range is a + /// user-defined type and is handled as text. Every place that derives a + /// format code or picks a codec from an OID must go through this, so the + /// two sides agree. + pub fn from_oid(oid: Int4) -> Tag { + Short::try_from(oid).map_or(Tag::text, Tag) + } + /// Types whose binary wire format `DataCell` can decode, so result columns /// of these types are requested in binary. Bind parameters are encoded by /// a shorter list, `ParamEncoding` in `bun_sql_jsc`. diff --git a/src/sql_jsc/postgres/DataCell.rs b/src/sql_jsc/postgres/DataCell.rs index 3805c962fb08..02a0d8f09d2f 100644 --- a/src/sql_jsc/postgres/DataCell.rs +++ b/src/sql_jsc/postgres/DataCell.rs @@ -1268,13 +1268,7 @@ impl<'a> Putter<'a> { if IS_RAW { *cell = SQLDataCell::raw(optional_bytes); } else { - let tag = if (types::short::MAX as u32) < oid { - types::Tag::text - } else { - // types::Tag is `#[repr(transparent)] struct Tag(pub Short)` — - // construct directly, no transmute needed. - types::Tag(oid as types::short) - }; + let tag = field.type_tag(); *cell = if let Some(data) = optional_bytes { from_bytes( (field.binary || self.binary) && tag.is_binary_format_supported(), diff --git a/src/sql_jsc/postgres/PostgresRequest.rs b/src/sql_jsc/postgres/PostgresRequest.rs index fd7330ed05b7..4638c266bcf0 100644 --- a/src/sql_jsc/postgres/PostgresRequest.rs +++ b/src/sql_jsc/postgres/PostgresRequest.rs @@ -49,14 +49,14 @@ pub enum MessageType { /// The PostgreSQL wire protocol uses 16-bit integers for parameter and column counts. const MAX_PARAMETERS: usize = u16::MAX as usize; -/// How `write_bind` puts one parameter value on the wire. Both the -/// format-code section and the value section of the Bind message are derived -/// from this, so they cannot disagree. +/// How `write_bind` puts one parameter value on the wire. It is decided once +/// per parameter, and both the format-code section and the value section of +/// the Bind message are written from it, so they cannot disagree. /// /// This is the encode side only. `Tag::is_binary_format_supported` is the /// decode side (result columns) and is wider: `DataCell` decodes binary /// numeric, float4, time, int4[] and float4[], but nothing here encodes them. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug)] enum ParamEncoding { /// `String(value)`, format 0. The server parses it as the parameter's type. Text, @@ -111,14 +111,6 @@ impl ParamEncoding { } } -fn param_tag(parameter_field: Int4) -> types::Tag { - match Short::try_from(parameter_field) { - Ok(oid) => types::Tag(oid), - // Outside the `Short` range: a user-defined type, bound as text. - Err(_) => types::Tag::text, - } -} - pub(crate) fn write_bind( name: &[u8], cursor_name: &BunString, @@ -150,10 +142,14 @@ pub(crate) fn write_bind( // of parameters. writer.short(len)?; + // Decided once per parameter here and reused for the value section below, + // so a getter or `toString()` that runs in between cannot make the bytes + // disagree with the declared format code. + let mut encodings: Vec = Vec::with_capacity(parameter_fields.len()); let mut iter = QueryBindingIterator::init(values_array, columns_value, global) .map_err(js_error_to_postgres)?; for (i, ¶meter_field) in parameter_fields.iter().enumerate() { - let mut encoding = ParamEncoding::for_tag(param_tag(parameter_field)); + let mut encoding = ParamEncoding::for_tag(types::Tag::from_oid(parameter_field)); if encoding.is_binary() { iter.to(i as u32); if let Some(value) = iter.next().map_err(js_error_to_postgres)? { @@ -163,6 +159,7 @@ pub(crate) fn write_bind( } } writer.short(encoding.format_code())?; + encodings.push(encoding); } // The number of parameter values that follow (possibly zero). This @@ -173,28 +170,34 @@ pub(crate) fn write_bind( iter.to(0); let mut i: usize = 0; while let Some(value) = iter.next().map_err(js_error_to_postgres)? { - let tag: types::Tag = match parameter_fields.get(i) { - Some(¶meter_field) => param_tag(parameter_field), - // parameter in array but not in parameter_fields - // this is probably a bug a bug in bun lets return .text here so the server will send a error 08P01 - // with will describe better the error saying exactly how many parameters are missing and are expected - // Example: - // SQL error: PostgresError: bind message supplies 0 parameters, but prepared statement "PSELECT * FROM test_table WHERE id=$1 .in$0" requires 1 - // errno: "08P01", - // code: "ERR_POSTGRES_SERVER_ERROR" - None => types::Tag::text, - }; + // parameter in array but not in parameter_fields + // this is probably a bug a bug in bun lets return .text here so the server will send a error 08P01 + // with will describe better the error saying exactly how many parameters are missing and are expected + // Example: + // SQL error: PostgresError: bind message supplies 0 parameters, but prepared statement "PSELECT * FROM test_table WHERE id=$1 .in$0" requires 1 + // errno: "08P01", + // code: "ERR_POSTGRES_SERVER_ERROR" + let index = i; + i += 1; + let encoding = encodings.get(index).copied().unwrap_or(ParamEncoding::Text); if value.is_empty_or_undefined_or_null() { bun_core::scoped_log!(Postgres, " -> NULL"); // As a special case, -1 indicates a // NULL parameter value. No value bytes follow in the NULL case. writer.int4((-1i32) as u32)?; - i += 1; continue; } - bun_core::scoped_log!(Postgres, " -> {}", tag.tag_name().unwrap_or("(unknown)")); - - match ParamEncoding::for_tag(tag).for_value(value) { + bun_core::scoped_log!( + Postgres, + " -> {} as {:?}", + parameter_fields + .get(index) + .and_then(|&oid| types::Tag::from_oid(oid).tag_name()) + .unwrap_or("(unknown)"), + encoding + ); + + match encoding { ParamEncoding::Json => { // Use jsonStringifyFast for SIMD-optimized serialization let str = value @@ -257,8 +260,6 @@ pub(crate) fn write_bind( l.write_excluding_self()?; } } - - i += 1; } let mut any_non_text_fields: bool = false; diff --git a/test/js/sql/postgres-bind-param-format.test.ts b/test/js/sql/postgres-bind-param-format.test.ts index b7d7f8414bf4..f1b6ef6c4fd2 100644 --- a/test/js/sql/postgres-bind-param-format.test.ts +++ b/test/js/sql/postgres-bind-param-format.test.ts @@ -4,12 +4,26 @@ // the server reports (numeric, real, time, int4[], real[], ...) is sent as // `String(value)` and must be declared as text so the server parses it. // -// Runs against a real Postgres server with the default `prepare: true`, where +// The mock-server tests pin the exact Bind bytes. The container tests run the +// same cases against a real Postgres with the default `prepare: true`, where // Bun binds with the parameter types from the server's ParameterDescription. import { SQL } from "bun"; -import { expect, test } from "bun:test"; +import { describe, expect, test } from "bun:test"; import { describeWithContainer } from "harness"; +import { + type PgBind, + pgBindComplete, + pgCommandComplete, + pgDataRow, + pgDecodeBind, + pgMockServer, + pgNoData, + pgParameterDescription, + pgParseComplete, + pgReadyForQuery, + pgRowDescription, +} from "./wire-frames"; // Stand-in for a decimal.js / big.js style value: not a string, but its text // form is what should reach the server. @@ -20,6 +34,110 @@ class Textual { } } +/** + * Mock backend for one prepared query. Describe is answered with the given + * parameter OIDs and result columns, Execute with one `row`. Resolves with + * every Bind the client sent and the rows it decoded. + */ +async function runAgainstMock(opts: { + paramOids: number[]; + columns?: { name: string; typeOid: number }[]; + row?: (Buffer | null)[]; + query: (sql: SQL) => Promise; +}): Promise<{ binds: PgBind[]; rows: any }> { + const binds: PgBind[] = []; + const columns = opts.columns ?? []; + const { server, port } = await pgMockServer((type, body, socket) => { + switch (type) { + case "P": + return pgParseComplete(); + case "D": + return [pgParameterDescription(opts.paramOids), columns.length ? pgRowDescription(columns) : pgNoData()]; + case "B": + binds.push(pgDecodeBind(body)); + return pgBindComplete(); + case "E": + return opts.row ? [pgDataRow(opts.row), pgCommandComplete("SELECT 1")] : pgCommandComplete("SELECT 0"); + case "S": + return pgReadyForQuery(); + case "X": + socket.end(); + break; + } + }); + try { + await using sql = new SQL({ url: `postgres://u@127.0.0.1:${port}/db`, max: 1 }); + const rows = await opts.query(sql); + return { binds, rows }; + } finally { + server.close(); + } +} + +describe("Bind format codes (mock server)", () => { + test("parameters typed numeric, float4, time, int4[] and float4[] are declared and sent as text", async () => { + const { binds } = await runAgainstMock({ + // numeric, float4, time, int4_array, float4_array + paramOids: [1700, 700, 1083, 1007, 1021], + query: sql => + sql.unsafe("select $1, $2, $3, $4, $5", [ + new Textual("19.99"), + new Textual("1234"), + new Textual("12:34:56"), + sql.array([1, 2], "INT4"), + sql.array([1.5], "REAL"), + ]), + }); + expect(binds).toHaveLength(1); + expect({ + paramFormats: binds[0].paramFormats, + params: binds[0].params.map(p => p?.toString("latin1")), + }).toEqual({ + paramFormats: [0, 0, 0, 0, 0], + params: ["19.99", "1234", "12:34:56", `{"1","2"}`, "{1.5}"], + }); + }); + + test("parameters with a binary encoder are declared binary, a string value stays text", async () => { + const date = new Date("2000-01-01T00:00:01.000Z"); // 1_000_000 us after the Postgres epoch + const { binds } = await runAgainstMock({ + // bool, int4, float8, timestamptz, bytea, int4 (bound from a string) + paramOids: [16, 23, 701, 1184, 17, 23], + query: sql => sql.unsafe("select $1, $2, $3, $4, $5, $6", [true, 7, 1.5, date, Buffer.from([1, 2]), "8"]), + }); + expect(binds).toHaveLength(1); + expect({ paramFormats: binds[0].paramFormats, params: binds[0].params }).toEqual({ + paramFormats: [1, 1, 1, 1, 1, 0], + params: [ + Buffer.from([1]), + Buffer.from([0, 0, 0, 7]), + Buffer.from("3ff8000000000000", "hex"), + Buffer.from("00000000000f4240", "hex"), + Buffer.from([1, 2]), + Buffer.from("8"), + ], + }); + }); + + test("a result column whose OID is above 65535 is requested and decoded as text", async () => { + // 65552 = 65536 + 16: a user-defined type whose low 16 bits alias `bool`. + const { binds, rows } = await runAgainstMock({ + paramOids: [23], + columns: [ + { name: "custom", typeOid: 65552 }, + { name: "n", typeOid: 23 }, + ], + row: [Buffer.from("(42,t)"), Buffer.from([0, 0, 0, 9])], + query: sql => sql`select custom, n from t where n = ${9}`, + }); + expect(binds).toHaveLength(1); + expect({ resultFormats: binds[0].resultFormats, row: rows[0] }).toEqual({ + resultFormats: [0, 1], + row: { custom: "(42,t)", n: 9 }, + }); + }); +}); + describeWithContainer("postgres", { image: "postgres_plain" }, container => { const connect = () => new SQL({ diff --git a/test/js/sql/wire-frames.test.ts b/test/js/sql/wire-frames.test.ts index 38e7d9d9f3b2..505ec94b84c9 100644 --- a/test/js/sql/wire-frames.test.ts +++ b/test/js/sql/wire-frames.test.ts @@ -18,12 +18,44 @@ import { pgCopyDone, pgCopyOutResponse, pgDataRow, + pgDecodeBind, pgErrorResponse, pgMinimalReadyServer, pgReadyForQuery, pgRowDescription, } from "./wire-frames"; +test("pgDecodeBind decodes a §55.7 Bind body", () => { + // portal "", statement "S1", 2 format codes [1, 0], 2 params (4-byte int4 7, NULL), 1 result format [1] + const body = Buffer.from( + "\x00S1\x00" + + "\x00\x02\x00\x01\x00\x00" + + "\x00\x02" + + "\x00\x00\x00\x04\x00\x00\x00\x07" + + "\xff\xff\xff\xff" + + "\x00\x01\x00\x01", + "binary", + ); + expect(pgDecodeBind(body)).toEqual({ + portal: "", + statement: "S1", + paramFormats: [1, 0], + params: [Buffer.from([0, 0, 0, 7]), null], + resultFormats: [1], + }); + // 0 format codes means "all text"; 1 code applies to every parameter. + const none = Buffer.from( + "\x00\x00" + "\x00\x00" + "\x00\x02" + "\x00\x00\x00\x01a\x00\x00\x00\x01b" + "\x00\x00", + "binary", + ); + expect(pgDecodeBind(none).paramFormats).toEqual([0, 0]); + const one = Buffer.from( + "\x00\x00" + "\x00\x01\x00\x01" + "\x00\x02" + "\x00\x00\x00\x01a\x00\x00\x00\x01b" + "\x00\x00", + "binary", + ); + expect(pgDecodeBind(one).paramFormats).toEqual([1, 1]); +}); + test("mysqlLenencInt encodes per page_protocol_basic_dt_integers.html", () => { expect(mysqlLenencInt(0)).toEqual(Buffer.from([0x00])); expect(mysqlLenencInt(250)).toEqual(Buffer.from([0xfa])); diff --git a/test/js/sql/wire-frames.ts b/test/js/sql/wire-frames.ts index 6fc390f99d19..433320f2f6b8 100644 --- a/test/js/sql/wire-frames.ts +++ b/test/js/sql/wire-frames.ts @@ -231,6 +231,59 @@ export function pgParameterDescription(typeOids: number[]): Buffer { return pgRaw("t", body); } +// PostgreSQL FE/BE protocol §55.7 NoData: Byte1('n') Int32(4) +export function pgNoData(): Buffer { + return pgRaw("n", Buffer.alloc(0)); +} + +export type PgBind = { + portal: string; + statement: string; + /** One per parameter (expanded if the client sent 0 or 1 codes). 0 = text, 1 = binary. */ + paramFormats: number[]; + params: (Buffer | null)[]; + resultFormats: number[]; +}; + +// PostgreSQL FE/BE protocol §55.7 Bind (frontend): String(portal) String(statement) +// Int16(nFormats) Int16[nFormats] Int16(nParams) per param: Int32(len | -1) Byte[len] +// Int16(nResultFormats) Int16[nResultFormats] +// `body` is the message without the type byte and length, as pgReadFrontendMessages hands it out. +export function pgDecodeBind(body: Buffer): PgBind { + let o = 0; + const cstring = () => { + const end = body.indexOf(0, o); + const s = body.toString("utf8", o, end); + o = end + 1; + return s; + }; + const int16 = () => { + const v = body.readInt16BE(o); + o += 2; + return v; + }; + const portal = cstring(); + const statement = cstring(); + const formats: number[] = []; + for (let n = int16(), i = 0; i < n; i++) formats.push(int16()); + const params: (Buffer | null)[] = []; + for (let n = int16(), i = 0; i < n; i++) { + const len = body.readInt32BE(o); + o += 4; + if (len === -1) { + params.push(null); + } else { + params.push(Buffer.from(body.subarray(o, o + len))); + o += len; + } + } + const resultFormats: number[] = []; + for (let n = int16(), i = 0; i < n; i++) resultFormats.push(int16()); + const paramFormats = + formats.length === params.length ? formats : params.map(() => (formats.length === 1 ? formats[0] : 0)); + return { portal, statement, paramFormats, params, resultFormats }; +} + /** * Drain complete PostgreSQL frontend messages from `buffered`, calling * onMessage(type, body) for each; returns the leftover bytes. The very first From 8e0959d135385eed58281a2df096f11e1b0d9cbe Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 11:16:24 +0000 Subject: [PATCH 3/5] sql(postgres): shorten the new comments in Tag.rs and PostgresRequest.rs --- src/sql/postgres/types/Tag.rs | 9 ++------- src/sql_jsc/postgres/PostgresRequest.rs | 26 +++++-------------------- 2 files changed, 7 insertions(+), 28 deletions(-) diff --git a/src/sql/postgres/types/Tag.rs b/src/sql/postgres/types/Tag.rs index 3a2d54f0d20d..2163a5eecffd 100644 --- a/src/sql/postgres/types/Tag.rs +++ b/src/sql/postgres/types/Tag.rs @@ -179,17 +179,12 @@ pg_tags! { } impl Tag { - /// Maps a wire OID to a `Tag`. An OID outside the `Short` range is a - /// user-defined type and is handled as text. Every place that derives a - /// format code or picks a codec from an OID must go through this, so the - /// two sides agree. + /// The one OID-to-`Tag` mapping. An OID above `Short::MAX` is a user-defined type: text. pub fn from_oid(oid: Int4) -> Tag { Short::try_from(oid).map_or(Tag::text, Tag) } - /// Types whose binary wire format `DataCell` can decode, so result columns - /// of these types are requested in binary. Bind parameters are encoded by - /// a shorter list, `ParamEncoding` in `bun_sql_jsc`. + /// Types `DataCell` decodes from binary (result columns). Bind parameters use `ParamEncoding`. pub fn is_binary_format_supported(self) -> bool { match self { // TODO: .int2_array, .float8_array, diff --git a/src/sql_jsc/postgres/PostgresRequest.rs b/src/sql_jsc/postgres/PostgresRequest.rs index 4638c266bcf0..b7cc3109f2d7 100644 --- a/src/sql_jsc/postgres/PostgresRequest.rs +++ b/src/sql_jsc/postgres/PostgresRequest.rs @@ -49,13 +49,7 @@ pub enum MessageType { /// The PostgreSQL wire protocol uses 16-bit integers for parameter and column counts. const MAX_PARAMETERS: usize = u16::MAX as usize; -/// How `write_bind` puts one parameter value on the wire. It is decided once -/// per parameter, and both the format-code section and the value section of -/// the Bind message are written from it, so they cannot disagree. -/// -/// This is the encode side only. `Tag::is_binary_format_supported` is the -/// decode side (result columns) and is wider: `DataCell` decodes binary -/// numeric, float4, time, int4[] and float4[], but nothing here encodes them. +/// How `write_bind` encodes one parameter. Its format code and its value bytes both come from this. #[derive(Clone, Copy, Debug)] enum ParamEncoding { /// `String(value)`, format 0. The server parses it as the parameter's type. @@ -79,14 +73,12 @@ impl ParamEncoding { types::Tag::float8 => ParamEncoding::Float8, types::Tag::timestamp | types::Tag::timestamptz => ParamEncoding::Timestamp, types::Tag::bytea => ParamEncoding::Bytea, + // No binary encoder for the rest (numeric, float4, time, int4[], ...), only a decoder. _ => ParamEncoding::Text, } } - /// If they pass a value as a string, let's avoid attempting to 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 value is sent as text so that the server parses it (time zones and so on), not Bun. fn for_value(self, value: JSValue) -> ParamEncoding { if self.is_binary() && value.is_string() { ParamEncoding::Text @@ -142,9 +134,7 @@ pub(crate) fn write_bind( // of parameters. writer.short(len)?; - // Decided once per parameter here and reused for the value section below, - // so a getter or `toString()` that runs in between cannot make the bytes - // disagree with the declared format code. + // Reused by the value section so a `toString()` that runs in between cannot change a decision. let mut encodings: Vec = Vec::with_capacity(parameter_fields.len()); let mut iter = QueryBindingIterator::init(values_array, columns_value, global) .map_err(js_error_to_postgres)?; @@ -170,15 +160,9 @@ pub(crate) fn write_bind( iter.to(0); let mut i: usize = 0; while let Some(value) = iter.next().map_err(js_error_to_postgres)? { - // parameter in array but not in parameter_fields - // this is probably a bug a bug in bun lets return .text here so the server will send a error 08P01 - // with will describe better the error saying exactly how many parameters are missing and are expected - // Example: - // SQL error: PostgresError: bind message supplies 0 parameters, but prepared statement "PSELECT * FROM test_table WHERE id=$1 .in$0" requires 1 - // errno: "08P01", - // code: "ERR_POSTGRES_SERVER_ERROR" let index = i; i += 1; + // More values than parameters: the extras go out as text and the server reports 08P01. let encoding = encodings.get(index).copied().unwrap_or(ParamEncoding::Text); if value.is_empty_or_undefined_or_null() { bun_core::scoped_log!(Postgres, " -> NULL"); From b42cdb33ffeefc33d2b713ffd3779732d7f4073f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 11:21:49 +0000 Subject: [PATCH 4/5] sql(postgres): number the bytea type error by the value index after the loop restructure --- src/sql_jsc/postgres/PostgresRequest.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sql_jsc/postgres/PostgresRequest.rs b/src/sql_jsc/postgres/PostgresRequest.rs index b7cc3109f2d7..f14cfedd7f15 100644 --- a/src/sql_jsc/postgres/PostgresRequest.rs +++ b/src/sql_jsc/postgres/PostgresRequest.rs @@ -212,7 +212,7 @@ pub(crate) fn write_bind( return Err(js_error_to_postgres(global.throw_value( global.ERR_INVALID_ARG_TYPE(format_args!( "Query parameter ${} of type bytea must be a Buffer, TypedArray, ArrayBuffer or string. Received {}", - i + 1, + index + 1, received, )), ))); From 50144ba0b53d8bb062b24ad4243a85d0858ced4f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 11:47:18 +0000 Subject: [PATCH 5/5] ci: retrigger