Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
acec2d8
sql: implement Query.cancel() for postgres
robobun Jul 5, 2026
d920eab
sql: only send a postgres CancelRequest for the query the backend is …
robobun Jul 5, 2026
771c008
sql: release the postgres query's connection edge on the failure paths
robobun Jul 5, 2026
6109374
sql: reject a cancelled query when it first runs, not inside cancel()
robobun Sep 6, 2026
df87e6e
sql: trim the comments on the postgres cancel path
robobun Sep 6, 2026
43d3780
sql: bound the postgres cancel connection's connect attempt too
robobun Sep 6, 2026
afef5ca
sql: one-line the two comments on the postgres cancel socket
robobun Sep 6, 2026
f119b73
sql: move the cancel-before-run tests into their own file
robobun Sep 6, 2026
7a18dc7
ci: retrigger
robobun Sep 6, 2026
d54d683
Merge branch 'main' into farm/4be26dfa/postgres-query-cancel
robobun Sep 6, 2026
4f1d494
sql: release the pending-request count when a queued query is cancelled
robobun Sep 6, 2026
b377317
Merge branch 'main' into farm/4be26dfa/postgres-query-cancel
robobun Sep 24, 2026
907bd97
sql: reject a cancelled pipelined query through the in-flight rejection
robobun Sep 24, 2026
60a71df
sql: let the query handler reject a query cancelled before it runs
robobun Sep 24, 2026
e72981d
sql: shorten the discard_response doc comment
robobun Sep 24, 2026
ae6e96a
sql: say in the error when a cancelled query still runs on the server
robobun Sep 24, 2026
74fb430
sql: pass the port of the cancel connection as a number
robobun Sep 24, 2026
f3d7df8
sql(postgres): move the allocate-and-dial block of createConnection i…
robobun Sep 25, 2026
39297bb
Merge branch 'robobun/4be26dfa/postgres-connection-open' into farm/4b…
robobun Sep 25, 2026
78dcace
sql(postgres): open the cancel connection from the session, in native…
robobun Sep 25, 2026
81b6310
sql: test that a cancel connection never goes out in the clear for a …
robobun Sep 25, 2026
ec1eec7
sql: shorten the send_cancel_request doc comment
robobun Sep 25, 2026
ac3e96d
Merge branch 'robobun/4be26dfa/postgres-connection-open' into farm/4b…
robobun Sep 25, 2026
c0e36e3
sql(postgres): return the connect error from open and throw it in cre…
robobun Sep 25, 2026
3ccf2df
sql: log a cancel connection that cannot be dialed
robobun Sep 25, 2026
c2b627f
sql(postgres): build the strings of a connection in one constructor
robobun Sep 25, 2026
59d46e3
Merge branch 'robobun/4be26dfa/postgres-connection-open' into farm/4b…
robobun Sep 25, 2026
998a6fa
sql(postgres): name the functions that build and store the connection…
robobun Sep 25, 2026
819cd9c
sql(postgres): write the terminators of the connection strings
robobun Sep 25, 2026
6eb94ff
Merge branch 'robobun/4be26dfa/postgres-connection-open' into farm/4b…
robobun Sep 25, 2026
df941a0
sql(postgres): let the process exit after a dial that never opens, an…
robobun Sep 25, 2026
3b664c6
docs(sql): say that a late cancel request can stop the next query
robobun Sep 25, 2026
e8b81f9
test(sql): check that the cancel connection verifies the host name of…
robobun Sep 25, 2026
358721d
Merge branch 'main' into farm/4be26dfa/postgres-query-cancel
robobun Sep 30, 2026
76a436e
sql(postgres): send no CancelRequest for a query that ended during th…
robobun Sep 30, 2026
c55aa7a
test(sql): give the pg_sleep poll of the real-server cancel test a de…
robobun Sep 30, 2026
950a49c
sql(postgres): cancel a query whose session closed, and decide at the…
robobun Sep 30, 2026
2bd4fe5
Merge branch 'main' into farm/4be26dfa/postgres-query-cancel
robobun Oct 2, 2026
a46f129
sql(postgres): keep a query off the wire when the code of its paramet…
robobun Oct 2, 2026
3570e33
test(sql): cancel() while only the Parse of a query is on the wire
robobun Oct 2, 2026
e1c5315
sql(postgres): shorten two comments
robobun Oct 2, 2026
52e8500
test(sql): close the pool of each round of the GC test with its scope
robobun Oct 3, 2026
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
11 changes: 9 additions & 2 deletions docs/runtime/sql.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -440,14 +440,21 @@ const result = await sql.unsafe("SELECT " + dangerous + " FROM users WHERE id =
### Execute and Cancelling Queries

Queries are lazy: they only start executing when awaited or run with `.execute()`.
To cancel a running query, call `cancel()` on the query object.
To cancel a running query, call `cancel()` on the query object. A cancelled query
rejects instead of resolving.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

```ts
const query = sql`SELECT * FROM users`.execute();
const query = sql`SELECT pg_sleep(30)`.execute();
setTimeout(() => query.cancel(), 100);

// PostgresError: canceling statement due to user request (SQLSTATE 57014)
await query;
```

PostgreSQL can only stop a running query from a separate connection, so `cancel()`
opens one and sends a `CancelRequest` on it. A query that has not reached the
server yet never runs at all, and rejects with `ERR_POSTGRES_QUERY_CANCELLED`.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

---

## Database Environment Variables
Expand Down
7 changes: 6 additions & 1 deletion packages/bun-types/sql.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,12 @@ declare module "bun" {
cancelled: boolean;

/**
* Cancels the executing query
* Cancels the query and rejects its promise with the adapter's
* query-cancelled error (for example `ERR_POSTGRES_QUERY_CANCELLED`).
*
* For PostgreSQL, a query the backend has already started is stopped with a
* `CancelRequest` sent on a second connection, and rejects with whatever the
* server reports instead (SQLSTATE 57014).
*/
cancel(): Query<T>;
Comment thread
robobun marked this conversation as resolved.
Resolved

Expand Down
40 changes: 40 additions & 0 deletions src/js/internal/sql/postgres.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ const {

const cmds = ["", "INSERT", "DELETE", "UPDATE", "MERGE", "SELECT", "MOVE", "FETCH", "COPY"];

// How long the connection opened for a CancelRequest waits for the backend to
// close it before giving up.
Comment thread
robobun marked this conversation as resolved.
Resolved
const CANCEL_REQUEST_TIMEOUT_SECONDS = 5;

const escapeBackslash = /\\/g;
const escapeQuote = /"/g;

Expand Down Expand Up @@ -416,6 +420,42 @@ class PostgresAdapter
return '"' + str.replaceAll('"', '""').replaceAll(".", '"."') + '"';
}

/**
* A backend running a query reads nothing until it finishes, so the only way
* to stop it is a CancelRequest on a second connection. The backend handles
* that message before authentication and before any SSL negotiation, and it
* carries no credentials beyond the pid/secret pair the server itself handed
* out in BackendKeyData, so the cancel connection stays plaintext, the way
* libpq's PQcancel() sends it.
*/
Comment thread
robobun marked this conversation as resolved.
Resolved
sendCancelRequest(request: Uint8Array): void {
const { path, hostname, port } = this.connectionInfo;
const address = path ? { unix: path } : { hostname, port };

Bun.connect({
...address,
socket: {
open(socket) {
socket.write(request);
socket.flush();
// The backend closes the connection once it has acted on the request.
// Bound the wait so a peer that never answers cannot pin the event loop.
Comment thread
robobun marked this conversation as resolved.
Resolved
socket.timeout(CANCEL_REQUEST_TIMEOUT_SECONDS);
Comment thread
robobun marked this conversation as resolved.
Resolved
},
timeout(socket) {
socket.end();
},
// The backend never replies to a CancelRequest, but Bun.connect requires
// a reader.
Comment thread
robobun marked this conversation as resolved.
Resolved
data() {},
// Cancelling is best effort: a request that never reaches the server
// just leaves the query running, which is what happens today anyway.
Comment thread
robobun marked this conversation as resolved.
Resolved
connectError() {},
error() {},
},
});
}

connectionClosedError() {
return new PostgresError("Connection closed", {
code: "ERR_POSTGRES_CONNECTION_CLOSED",
Expand Down
22 changes: 17 additions & 5 deletions src/js/internal/sql/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ const PublicPromise = Promise;

export interface BaseQueryHandle<Connection> {
done?(): void;
cancel?(): void;
/**
* Abort a query the handle already dispatched. Returns the request bytes the
* adapter has to deliver out-of-band (Postgres sends a CancelRequest on a
* second connection), or undefined when nothing has to reach the server.
*/
Comment thread
robobun marked this conversation as resolved.
Resolved
cancel?(): Uint8Array | undefined;
setMode(mode: SQLQueryResultMode): void;
run(connection: Connection, query: Query<any, any>): void | Promise<void>;
}
Expand Down Expand Up @@ -218,11 +223,18 @@ class Query<T, Handle extends BaseQueryHandle<any>> extends PublicPromise<T> {

this[_queryStatus] |= SQLQueryStatus.cancelled;

if (status & SQLQueryStatus.executed) {
const handle = this.#getQueryHandle();
if (!(status & SQLQueryStatus.executed)) {
// Never dispatched, so no connection will ever settle this promise.
this.reject(this[_adapter].queryCancelledError());
return this;
}

const handle = this.#getQueryHandle();

if (handle) {
handle.cancel?.();
if (handle) {
const cancelRequest = handle.cancel?.();
if (cancelRequest) {
this[_adapter].sendCancelRequest?.(cancelRequest);
}
}

Expand Down
7 changes: 7 additions & 0 deletions src/js/internal/sql/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2140,6 +2140,13 @@ export interface DatabaseAdapter<Connection, ConnectionHandle, QueryHandle> {
connectionClosedError(): Error;
queryCancelledError(): Error;
invalidTransactionStateError(message: string): Error;

/**
* Deliver a `Query.cancel()` request that cannot travel on the query's own
* connection, because that connection is busy running the query being
* cancelled. Postgres opens a second connection to the same server for it.
*/
Comment thread
robobun marked this conversation as resolved.
Resolved
sendCancelRequest?(request: Uint8Array): void;
}

export default {
Expand Down
8 changes: 7 additions & 1 deletion src/runtime/api/sql.classes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,13 @@ for (const type of types) {
length: 1,
},
},
values: ["pendingValue", "target", "columns", "binding"],
// Postgres cancels a running query by sending a CancelRequest on a
// second connection, so its query handle has to remember which
// connection it was dispatched to.
Comment thread
robobun marked this conversation as resolved.
Resolved
values:
type === "PostgresSQL"
? ["pendingValue", "target", "columns", "binding", "connection"]
: ["pendingValue", "target", "columns", "binding"],
estimatedSize: true,
}),
);
Expand Down
1 change: 1 addition & 0 deletions src/sql/postgres/AnyPostgresError.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub enum AnyPostgresError {
OutOfMemory,
Overflow,
PBKDFD2,
QueryCancelled,
SASL_SIGNATURE_MISMATCH,
SASL_SIGNATURE_INVALID_BASE64,
ShortRead,
Expand Down
16 changes: 16 additions & 0 deletions src/sql/postgres/protocol/BackendKeyData.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use super::new_reader::NewReader;
use crate::postgres::AnyPostgresError;

/// Protocol §55.2.3: the request code a CancelRequest carries in place of the
/// protocol version, `(1234 << 16) | 5678`.
Comment thread
robobun marked this conversation as resolved.
Resolved
const CANCEL_REQUEST_CODE: u32 = 80877102;

#[derive(Default)]
pub struct BackendKeyData {
pub process_id: u32,
Expand All @@ -14,6 +18,18 @@ impl BackendKeyData {
Self::decode_internal(NewReader { wrapped: context })
}

/// Protocol §55.2.3 CancelRequest: `Int32(16) Int32(80877102) Int32(pid) Int32(secret)`.
/// It has no message-type byte because it is only ever sent as the first
/// message of a *separate* connection, which the backend then closes.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn cancel_request(&self) -> [u8; 16] {
let mut packet = [0u8; 16];
packet[0..4].copy_from_slice(&16u32.to_be_bytes());
packet[4..8].copy_from_slice(&CANCEL_REQUEST_CODE.to_be_bytes());
packet[8..12].copy_from_slice(&self.process_id.to_be_bytes());
packet[12..16].copy_from_slice(&self.secret_key.to_be_bytes());
packet
}

pub fn decode_internal<Container: super::new_reader::ReaderContext>(
mut reader: NewReader<Container>,
) -> Result<Self, AnyPostgresError> {
Expand Down
5 changes: 3 additions & 2 deletions src/sql_jsc/jsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ use core::ptr::NonNull;
pub use bun_jsc::{
ArrayBuffer, CallFrame, CoerceTo, ErrorBuilder, ErrorCode, ExternColumnIdentifier,
ExternColumnIdentifierValue, GlobalRef, JSArrayIterator, JSCell, JSGlobalObject, JSObject,
JSType, JSValue, JsCell, JsError, JsRef, JsResult, MarkedArgumentBuffer, StringJsc,
StrongOptional, ThrowFmtArgs, ZigStringJsc, bun_string_jsc, host_fn,
JSType, JSUint8Array, JSValue, JsCell, JsError, JsRef, JsResult, MarkedArgumentBuffer,
StringJsc, StrongOptional, ThrowFmtArgs, ZigStringJsc, bun_string_jsc, host_fn,
};

/// Re-export — `bun_jsc` now defines `IntegerRange` at its crate root and the
Expand Down Expand Up @@ -623,6 +623,7 @@ pub mod codegen {
impl_js_class {
binding,
columns,
connection,
pendingValue,
target
}
Expand Down
9 changes: 9 additions & 0 deletions src/sql_jsc/postgres/PostgresSQLConnection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1572,6 +1572,15 @@ impl PostgresSQLConnection {
))
}

/// True when `request` is the head of the FIFO, i.e. the one the backend is
/// executing right now. Requests behind the head have either not been
/// written at all, or were pipelined onto the wire and the backend has not
/// reached them yet.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn is_current_request(&self, request: *const PostgresSQLQuery) -> bool {
let q = self.requests.get();
q.readable_length() > 0 && core::ptr::eq(q.peek_item(0).cast_const(), request)
}

/// Drop the queue-held intrusive ref on `request` and pop one entry from
/// the FIFO head. One audited `unsafe` here replaces the per-site
/// `unsafe { PostgresSQLQuery::deref(ptr) }; self.requests.with_mut(|q| q.discard(1));`
Expand Down
95 changes: 90 additions & 5 deletions src/sql_jsc/postgres/PostgresSQLQuery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,36 @@ impl PostgresSQLQuery {
let Some(target_value) = self.get_target(global_object, true) else {
return;
};
self.run_reject_callback(global_object, this_value, target_value, err);
}

/// Reject the promise of a request whose Bind/Execute is already on the wire.
///
/// Unlike [`on_js_error`](Self::on_js_error) this leaves `status`, `target`
/// and the strong `this_value` alone: the backend is going to answer this
/// request no matter what, and the connection has to keep the FIFO entry to
/// consume those answers in order. `Status::Fail` would make `advance()`
/// discard the entry and the next BindComplete would land on the wrong
/// request. The request then finishes down the normal path, where
/// `Query.resolve()` on an already rejected promise is a no-op.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn reject_in_place(&self, err: JSValue, global_object: &JSGlobalObject) {
let _deref = self.ref_guard();
let Some(this_value) = self.this_value.get().try_get() else {
return;
};
let Some(target_value) = self.get_target(global_object, false) else {
return;
};
self.run_reject_callback(global_object, this_value, target_value, err);
}

fn run_reject_callback(
&self,
global_object: &JSGlobalObject,
this_value: JSValue,
target_value: JSValue,
err: JSValue,
) {
// SAFETY: JS-thread only; short-lived `&mut` to the singleton VM, no other live borrow.
let vm = crate::jsc::VirtualMachine::get().as_mut();
let function = vm
Expand Down Expand Up @@ -277,6 +306,7 @@ impl PostgresSQLQuery {
js::binding_set_cached(this_value, global_object, JSValue::ZERO);
js::pending_value_set_cached(this_value, global_object, JSValue::ZERO);
js::target_set_cached(this_value, global_object, JSValue::ZERO);
js::connection_set_cached(this_value, global_object, JSValue::ZERO);
}

pub fn on_result(
Expand Down Expand Up @@ -471,7 +501,8 @@ impl PostgresSQLQuery {
// duration of this call, satisfying the `ParentRef` outlives-holder
// invariant. R-2: shared borrow — every connection field accessed below is
// `Cell`/`JsCell`.
let Some(connection) = postgres_sql_connection::js::from_js_ref(arguments[0]) else {
let connection_value = arguments[0];
let Some(connection) = postgres_sql_connection::js::from_js_ref(connection_value) else {
return Err(
global_object.throw(format_args!("connection must be a PostgresSQLConnection"))
);
Expand Down Expand Up @@ -566,6 +597,7 @@ impl PostgresSQLQuery {

this.this_value.with_mut(|r| r.upgrade(global_object));
js::target_set_cached(this_value, global_object, query);
js::connection_set_cached(this_value, global_object, connection_value);
if this.status.get() == Status::Running {
connection.flush_data_and_reset_timeout();
} else {
Expand Down Expand Up @@ -837,6 +869,7 @@ impl PostgresSQLQuery {
this.this_value.with_mut(|r| r.upgrade(global_object));

js::target_set_cached(this_value, global_object, query);
js::connection_set_cached(this_value, global_object, connection_value);
if did_write {
connection.flush_data_and_reset_timeout();
} else {
Expand All @@ -848,15 +881,67 @@ impl PostgresSQLQuery {
Ok(JSValue::UNDEFINED)
}

/// Returns the CancelRequest packet the caller must deliver on a second
/// connection, or `undefined` when there is nothing for the server to stop.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn do_cancel(
this: &Self,
global_object: &JSGlobalObject,
callframe: &CallFrame,
) -> JsResult<JSValue> {
let _ = callframe;
let _ = global_object;
let _ = this;
let this_value = callframe.this();
// No connection cached means `run()` never bound this query to one, so
// the pool still owes it a connection (or it already finished). Either
// way there is nothing on the wire to cancel.
Comment thread
robobun marked this conversation as resolved.
Resolved
let Some(connection_value) = js::connection_get_cached(this_value) else {
return Ok(JSValue::UNDEFINED);
};
let Some(connection) = postgres_sql_connection::js::from_js_ref(connection_value) else {
return Ok(JSValue::UNDEFINED);
};

Ok(JSValue::UNDEFINED)
let status = this.status.get();
if matches!(status, Status::Success | Status::Fail) {
return Ok(JSValue::UNDEFINED);
}

// A CancelRequest names the backend *process*, not a statement, so it
// stops whatever that backend is running: the request at the head of the
// connection's FIFO. Sending one for any other request would kill an
// unrelated query, so everything else is settled locally.
Comment thread
robobun marked this conversation as resolved.
Resolved
if status == Status::Pending || !connection.is_current_request(core::ptr::from_ref(this)) {
let err = postgres_error_to_js(
global_object,
Some(b"Query cancelled"),
AnyPostgresError::QueryCancelled,
);
if status == Status::Pending {
// Nothing of this request is on the wire. Failing it keeps the
// backend from ever running it: advance() discards a Fail entry
// instead of writing its Bind/Execute.
Comment thread
robobun marked this conversation as resolved.
Resolved
this.on_js_error(err, global_object);
} else {
// Pipelined onto the wire behind the head request, so the backend
// will run it regardless. Reject the promise but leave the entry
// in the FIFO to consume the answers that are already coming.
Comment thread
robobun marked this conversation as resolved.
Resolved
this.reject_in_place(err, global_object);
}
return Ok(JSValue::UNDEFINED);
}

// Copy the key out before allocating into the JS heap, so no `JsCell`
// borrow is live across a call that can re-enter.
Comment thread
robobun marked this conversation as resolved.
Resolved
let (process_id, packet) = {
let key = connection.backend_key_data.get();
(key.process_id, key.cancel_request())
};
// The server never sent BackendKeyData, so it cannot be asked to cancel
// anything. The query keeps running.
Comment thread
robobun marked this conversation as resolved.
Resolved
if process_id == 0 {
return Ok(JSValue::UNDEFINED);
}
Ok(crate::jsc::JSUint8Array::from_bytes_copy(
global_object,
&packet,
))
}
}
1 change: 1 addition & 0 deletions src/sql_jsc/postgres/error_jsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ pub(crate) fn postgres_error_to_js(
NullsInArrayNotSupportedYet => b"ERR_POSTGRES_NULLS_IN_ARRAY_NOT_SUPPORTED_YET",
Overflow => b"ERR_POSTGRES_OVERFLOW",
PBKDFD2 => b"ERR_POSTGRES_AUTHENTICATION_FAILED_PBKDF2",
QueryCancelled => b"ERR_POSTGRES_QUERY_CANCELLED",
SASL_SIGNATURE_MISMATCH => b"ERR_POSTGRES_SASL_SIGNATURE_MISMATCH",
SASL_SIGNATURE_INVALID_BASE64 => b"ERR_POSTGRES_SASL_SIGNATURE_INVALID_BASE64",
TLSNotAvailable => b"ERR_POSTGRES_TLS_NOT_AVAILABLE",
Expand Down
Loading
Loading