Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions src/sql/postgres/protocol/FieldDescription.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -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<Container: super::new_reader::ReaderContext>(
Expand Down
8 changes: 7 additions & 1 deletion src/sql/postgres/types/Tag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -179,6 +179,12 @@ pg_tags! {
}

impl Tag {
/// 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 `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,
Expand Down
8 changes: 1 addition & 7 deletions src/sql_jsc/postgres/DataCell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
171 changes: 90 additions & 81 deletions src/sql_jsc/postgres/PostgresRequest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,60 @@ 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` 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.
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,
// No binary encoder for the rest (numeric, float4, time, int4[], ...), only a decoder.
_ => ParamEncoding::Text,
}
}

/// 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
} 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 }
}
}

pub(crate) fn write_bind<Context: WriterContext>(
name: &[u8],
cursor_name: &BunString,
Expand Down Expand Up @@ -80,41 +134,22 @@ pub(crate) fn write_bind<Context: WriterContext>(
// of parameters.
writer.short(len)?;

// Reused by the value section so a `toString()` that runs in between cannot change a decision.
let mut encodings: Vec<ParamEncoding> = Vec::with_capacity(parameter_fields.len());
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, &parameter_field) in parameter_fields.iter().enumerate() {
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)? {
encoding = encoding.for_value(value);
} else if iter.any_failed() {
return Err(AnyPostgresError::InvalidQueryBinding);
}
}

writer.short(tag.format_code())?;
writer.short(encoding.format_code())?;
encodings.push(encoding);
}

// The number of parameter values that follow (possibly zero). This
Expand All @@ -125,47 +160,29 @@ pub(crate) fn write_bind<Context: WriterContext>(
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 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");
// 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)"));

// 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 => {
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
.json_stringify_fast(global)
Expand All @@ -175,27 +192,27 @@ pub(crate) fn write_bind<Context: WriterContext>(
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)
.map_err(js_error_to_postgres)?,
)?;
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)?;
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,
)),
)));
Expand All @@ -206,23 +223,17 @@ pub(crate) fn write_bind<Context: WriterContext>(
writer.write(bytes)?;
l.write_excluding_self()?;
}
types::Tag::int4 => {
let l = writer.length()?;
writer.int4(value.coerce::<i32>(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::<i32>(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);
Expand All @@ -233,8 +244,6 @@ pub(crate) fn write_bind<Context: WriterContext>(
l.write_excluding_self()?;
}
}

i += 1;
}

let mut any_non_text_fields: bool = false;
Expand Down
Loading
Loading