Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 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
2 changes: 2 additions & 0 deletions src/sql/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,8 @@ pub mod postgres {
pub mod stack_reader;
#[path = "StartupMessage.rs"]
pub mod startup_message;
#[path = "TransactionStatusIndicator.rs"]
pub mod transaction_status_indicator;

// ── flat re-exports for `bun_sql_jsc` (Decode/Write trait surface) ──
pub use new_reader::ReaderContext;
Expand Down
1 change: 1 addition & 0 deletions src/sql/postgres/PostgresProtocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,4 @@ pub use crate::postgres::protocol::sasl_initial_response::SASLInitialResponse;
pub use crate::postgres::protocol::sasl_response::SASLResponse;
pub use crate::postgres::protocol::stack_reader::StackReader;
pub use crate::postgres::protocol::startup_message::StartupMessage;
pub use crate::postgres::protocol::transaction_status_indicator::TransactionStatusIndicator;
23 changes: 23 additions & 0 deletions src/sql/postgres/protocol/ErrorResponse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,29 @@ impl fmt::Display for ErrorResponse {
}

impl ErrorResponse {
/// True when the server-side prepared statement is gone (SQLSTATE `26000`)
/// or its cached plan is stale (SQLSTATE `0A000` from routine
/// `RevalidateCachedQuery`; `0A000` alone is the generic
/// feature_not_supported class). Mirrors pgjdbc `willHealViaReparse`.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn invalidates_prepared_statement(&self) -> bool {
let mut code_26000 = false;
let mut code_0a000 = false;
let mut routine_revalidate = false;
for m in &self.messages {
match m {
FieldMessage::Code(code) => {
code_26000 = code.eq_ascii(b"26000");
code_0a000 = code.eq_ascii(b"0A000");
}
FieldMessage::Routine(r) => {
routine_revalidate = r.eq_ascii(b"RevalidateCachedQuery");
}
_ => {}
}
}
code_26000 || (code_0a000 && routine_revalidate)
}

pub fn decode_internal<Container: super::new_reader::ReaderContext>(
mut reader: NewReader<Container>,
) -> Result<Self, AnyPostgresError> {
Expand Down
21 changes: 16 additions & 5 deletions src/sql/postgres/protocol/ReadyForQuery.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
use super::new_reader::NewReader;
use super::transaction_status_indicator::TransactionStatusIndicator;
use crate::postgres::AnyPostgresError;

#[derive(Default)]
pub struct ReadyForQuery {}
pub struct ReadyForQuery {
pub status: TransactionStatusIndicator,
}

impl Default for ReadyForQuery {
fn default() -> Self {
Self {
status: TransactionStatusIndicator::I,
}
}
}

impl ReadyForQuery {
pub fn decode_internal<Container: super::new_reader::ReaderContext>(
mut reader: NewReader<Container>,
) -> Result<Self, AnyPostgresError> {
reader.length()?;

// transaction status indicator
reader.int::<u8>()?;
Ok(Self {})
let status = reader.int::<u8>()?;
Ok(Self {
status: TransactionStatusIndicator(status),
})
}
}
11 changes: 11 additions & 0 deletions src/sql/postgres/protocol/TransactionStatusIndicator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Any u8 value is valid storage (the wire can carry bytes outside {I, T, E}).
// A Rust `#[repr(u8)] enum` would be UB for such values, so this is a
// transparent u8 newtype with associated consts instead.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[repr(transparent)]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct TransactionStatusIndicator(pub u8);

impl TransactionStatusIndicator {
/// if idle (not in a transaction block)
pub const I: Self = Self(b'I');
}
112 changes: 100 additions & 12 deletions src/sql_jsc/postgres/PostgresSQLConnection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,10 @@ pub struct PostgresSQLConnection {
// so `vm_mut()`'s `&mut *as_ptr()` is sound.
pub(crate) vm: BackRef<VirtualMachine>,
pub(crate) statements: JsCell<PreparedStatementsMap>,
/// Transaction status byte from the last ReadyForQuery; gates the
/// re-prepare retry (a retry inside a transaction block masks 0A000/26000
/// with 25P02).
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) tx_status: Cell<protocol::TransactionStatusIndicator>,
pub(crate) prepared_statement_id: Cell<u64>,
pub(crate) pending_activity_count: AtomicU32,
// Self-wrapper back-ref (the JS object that owns this payload). Stored as a
Expand Down Expand Up @@ -1195,6 +1199,7 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR
core::ptr::NonNull::new(VirtualMachine::get_mut_ptr()).expect("vm singleton"),
),
statements: JsCell::new(PreparedStatementsMap::default()),
tx_status: Cell::new(protocol::TransactionStatusIndicator::I),
prepared_statement_id: Cell::new(0),
pending_activity_count: AtomicU32::new(0),
js_value: JsCell::new(crate::jsc::JsRef::empty()),
Expand Down Expand Up @@ -1549,6 +1554,49 @@ impl PostgresSQLConnection {
}
}

/// Move the head request behind every request whose bytes are already on
/// the wire and behind earlier re-queued retries. Replies are attributed
/// to the FIFO head, so a retry must not sit in front of an in-flight
/// request.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn requeue_for_retry(&self, request: &PostgresSQLQuery) {
self.requests.with_mut(|q| {
if !q.front().is_some_and(|f| core::ptr::eq(f.as_ptr(), request)) {
return;
}
let Some(head) = q.pop_front() else { return };
let at = q
.iter()
.position(|r| {
r.status.get() == QueryStatus::Pending && !r.flags.get().reprepared
})
.unwrap_or(q.len());
debug_assert!(
q.iter().skip(at).all(|r| !matches!(
r.status.get(),
QueryStatus::Binding | QueryStatus::Running | QueryStatus::PartialResponse
)) && !self.flags.get().contains(ConnectionFlags::WAITING_TO_PREPARE),
"retry inserted ahead of a request that is on the wire"
);
q.insert(at, head);
});
}

/// Remove the cache entry for `stmt` unless re-entrant JS already replaced it.
fn evict_statement(&self, stmt: &PostgresSQLStatement) {
let stmt_ptr: *const PostgresSQLStatement = core::ptr::from_ref(stmt);
self.statements.with_mut(|m| {
let name = &stmt.signature.name[..];
if m.get(name).is_some_and(|p| {
core::ptr::eq(
p.as_ref().map_or(core::ptr::null(), |p| p.as_ptr()),
stmt_ptr,
)
}) {
m.remove(name);
}
});
}

pub(crate) fn has_query_running(&self) -> bool {
!self
.flags
Expand Down Expand Up @@ -2484,7 +2532,8 @@ impl PostgresSQLConnection {
// parameter_status dropped at scope end
}
MessageType::ReadyForQuery => {
let _ready_for_query = protocol::ReadyForQuery::decode_internal(reader.reborrow())?;
let ready_for_query = protocol::ReadyForQuery::decode_internal(reader.reborrow())?;
self.tx_status.set(ready_for_query.status);

if self.status.get() != Status::Connected
&& !matches!(self.authentication_state.get(), AuthenticationState::Ok)
Expand Down Expand Up @@ -2964,6 +3013,7 @@ impl PostgresSQLConnection {
debug!("ErrorResponse: {}", err);
return Err(AnyPostgresError::ExpectedRequest);
};
let invalidates = err.invalidates_prepared_statement();
// Convert to JS while we still own `err` — materialize the JS value once and route through
// `on_js_error` to avoid double-ownership of the non-Clone ErrorResponse.
let js_err =
Expand All @@ -2975,18 +3025,56 @@ impl PostgresSQLConnection {
crate::postgres::postgres_sql_statement::Error::Protocol(err),
);
// The request still holds another ref; this cannot drop to 0.
let stmt_ptr: *const PostgresSQLStatement = core::ptr::from_ref(&*stmt);
self.statements.with_mut(|m| {
let name = &stmt.signature.name[..];
if m.get(name).is_some_and(|p| {
core::ptr::eq(
p.as_ref().map_or(core::ptr::null(), |p| p.as_ptr()),
stmt_ptr,
)
}) {
m.remove(name);
self.evict_statement(stmt);
} else if invalidates
// Only an answer to Bind reports a missing or stale
// statement; after BindComplete the SQLSTATE comes from
// the query itself and rows may have arrived.
Comment thread
robobun marked this conversation as resolved.
Resolved
&& request.status.get() == QueryStatus::Binding
&& !stmt.signature.prepared_statement_name.is_empty()
&& matches!(
stmt.status,
StatementStatus::Prepared | StatementStatus::Pending
)
{
// Prepared: the server-side name is gone or stale.
// Pending: a pipelined sibling's ErrorResponse already
// reset it under a fresh name; this Bind named the old one.
Comment thread
robobun marked this conversation as resolved.
Resolved
let already_reset = stmt.status == StatementStatus::Pending;
if !already_reset {
// Evict so later queries with this signature re-prepare.
self.evict_statement(stmt);
}
// Retry only when the session is idle (inside a
// transaction the retry Parse would be rejected 25P02).
Comment thread
robobun marked this conversation as resolved.
Resolved
if !request.flags.get().reprepared
&& self.tx_status.get() == protocol::TransactionStatusIndicator::I
&& self.nonpipelinable_requests.get() == 0
{
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
debug!("re-preparing invalidated statement (SQLSTATE {})", err);
self.finish_request(&request);
if !already_reset {
let id = self.prepared_statement_id.get();
self.prepared_statement_id.set(id + 1);
stmt.reset_for_reprepare(id);
Comment thread
robobun marked this conversation as resolved.
Resolved
if let Some(statement) = request.statement.get().as_ref() {
let _ = self.statements.with_mut(|m| {
m.put(&statement.signature.name, Some(statement.clone()))
});
}
}
});
request.status.set(QueryStatus::Pending);
request.update_flags(|f| {
f.reprepared = true;
f.binary = false;
});
self.note_request_pending();
// Siblings still on the wire answer first; the
// re-Parse waits for the pipeline to drain.
Comment thread
robobun marked this conversation as resolved.
Resolved
self.requeue_for_retry(&request);
self.update_ref();
return Ok(());
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}
}
// If `err` was not moved into stmt above, it drops here automatically.
Expand Down
3 changes: 3 additions & 0 deletions src/sql_jsc/postgres/PostgresSQLQuery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ pub struct Flags {
/// `None` when `finish_request` consumes that contribution, so the
/// decrement is idempotent across its call sites.
pub(crate) counter: RequestCounter,
/// Set after one transparent re-prepare on 26000/0A000; caps retries at 1.
pub(crate) reprepared: bool,
pub(crate) result_mode: PostgresSQLQueryResultMode,
}

Expand All @@ -105,6 +107,7 @@ impl Default for Flags {
simple: false,
discard_response: false,
counter: RequestCounter::None,
reprepared: false,
result_mode: PostgresSQLQueryResultMode::Objects,
}
}
Expand Down
12 changes: 12 additions & 0 deletions src/sql_jsc/postgres/PostgresSQLStatement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,18 @@ impl Error {
pub use bun_sql::shared::statement_status::Status;

impl PostgresSQLStatement {
/// Reset to pre-Parse state under a fresh server-side name so `advance()`
/// re-Parses after a 26000/0A000 invalidation. The statement stays cached
/// as `Pending` while Binds under the previous name may still be on the
/// wire. `fields` and `parameters` stay: those siblings decode under them,
/// and the re-Parse's Describe replaces them.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn reset_for_reprepare(&mut self, prepared_statement_id: u64) {
self.status = Status::Pending;
self.error_response = None;
self.signature
.set_prepared_statement_name(prepared_statement_id);
}

pub(crate) fn check_for_duplicate_fields(&mut self) {
if !self.needs_duplicate_check {
return;
Expand Down
41 changes: 22 additions & 19 deletions src/sql_jsc/postgres/Signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@ impl Signature {

// No explicit `Drop` impl needed: the `Box<[T]>` fields free the four owned slices automatically.

/// `P` + 40 bytes of `name` + `$` + up to 20 digits ≤ Postgres' 63-byte
/// identifier limit.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn set_prepared_statement_name(&mut self, prepared_statement_id: u64) {
use std::io::Write;
let mut v: Vec<u8> = Vec::new();
write!(
&mut v,
"P{}${}",
bstr::BStr::new(&self.name[..self.name.len().min(40)]),
prepared_statement_id,
)
.expect("unreachable");
self.prepared_statement_name = v.into_boxed_slice();
}

// JSError (from QueryBindingIterator /
// Tag::from_js), OOM, and InvalidQueryBinding are collapsed to the
// crate-wide `crate::Error`.
Expand Down Expand Up @@ -91,26 +106,14 @@ impl Signature {
if iter.any_failed() {
return Err(crate::Error::InvalidQueryBinding);
}
// max u64 length is 20, max prepared_statement_name length is 63
let prepared_statement_name: Box<[u8]> = if unnamed {
Box::default()
} else {
use std::io::Write;
let mut v: Vec<u8> = Vec::new();
write!(
&mut v,
"P{}${}",
bstr::BStr::new(&name[..name.len().min(40)]),
prepared_statement_id,
)
.expect("unreachable");
v.into_boxed_slice()
};

Ok(Signature {
prepared_statement_name,
let mut sig = Signature {
prepared_statement_name: Box::default(),
name: name.into_boxed_slice(),
fields: fields.into_boxed_slice(),
})
};
if !unnamed {
sig.set_prepared_statement_name(prepared_statement_id);
}
Ok(sig)
}
}
Loading
Loading