Skip to content
Closed
Show file tree
Hide file tree
Changes from 41 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
12 changes: 10 additions & 2 deletions docs/runtime/sql.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -469,14 +469,22 @@ const result = await sql.unsafe("SELECT * FROM users WHERE id = :id", { id: 1 })
### 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 query, call `cancel()` on the query object.

```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;
```

On PostgreSQL, what `cancel()` does depends on how far the query got:

- A query that was started and that Bun has not sent yet never runs. It rejects with `ERR_POSTGRES_QUERY_CANCELLED`.
- A query that the server is running can only be stopped from a separate connection. Bun opens one to the same server, encrypted when the session is, and sends a `CancelRequest` on it. This is a request. If the server stops the query, the query rejects with SQLSTATE `57014`. If the query finishes first, it resolves as usual, and the request can stop the next query on that connection instead. The server also ignores a request that arrives before the query does, which can happen when you cancel a query with megabytes of parameters at once. A server that sent no cancel key when the connection opened, as some connection poolers do, cannot be asked: the query runs on.
- A query that Bun already sent behind another query on the same connection also rejects with `ERR_POSTGRES_QUERY_CANCELLED`, but the server still runs it. The `hint` of the error says so. An `INSERT` or `UPDATE` in such a query still takes effect, so do not retry it blindly.

---

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

/**
* Cancels the executing query
* Requests cancellation of the query.
*
* For PostgreSQL, a query that was started and is not sent yet never runs.
* It rejects with `ERR_POSTGRES_QUERY_CANCELLED`. A query the server is
* running is cancelled with a `CancelRequest` on a second connection. If
* the server stops the query, it rejects with SQLSTATE 57014. If the query
* finishes first, it resolves as usual, and the request can stop the next
* query on that connection instead. The server ignores a request that
* arrives before the query does. A query that was already sent behind
* another query rejects with `ERR_POSTGRES_QUERY_CANCELLED` and a `hint`,
* but the server still runs it.
*/
cancel(): Query<T>;
Comment thread
robobun marked this conversation as resolved.
Resolved

Expand Down
6 changes: 5 additions & 1 deletion src/runtime/api/sql.classes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ for (const type of types) {
length: 1,
},
},
values: ["pendingValue", "target", "columns", "binding"],
// `connection` lets a Postgres query find its BackendKeyData for cancel().
values:
type === "PostgresSQL"
? ["pendingValue", "target", "columns", "binding", "connection"]
: ["pendingValue", "target", "columns", "binding"],
estimatedSize: true,
}),
);
Expand Down
6 changes: 6 additions & 0 deletions src/runtime/hw_exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,11 @@ mod sql_hooks {
// `ssl_config_from_js`; sql_jsc's `SSLConfig::drop` guards null/double.
drop(unsafe { bun_core::heap::take(this.cast::<crate::socket::SSLConfig>()) });
}
unsafe fn ssl_config_clone(this: *const c_void) -> *mut c_void {
// SAFETY: `this` is a live boxed `SSLConfig` from `ssl_config_from_js`.
let config = unsafe { &*this.cast::<crate::socket::SSLConfig>() }.clone();
bun_core::heap::into_raw(Box::new(config)).cast::<c_void>()
}
unsafe fn ssl_config_as_usockets_client(
this: *const c_void,
) -> bun_uws::us_bun_socket_context_options_t {
Expand Down Expand Up @@ -295,6 +300,7 @@ mod sql_hooks {
ssl_ctx_get_or_create,
ssl_config_from_js,
ssl_config_free,
ssl_config_clone,
ssl_config_as_usockets_client,
ssl_config_server_name,
ssl_config_reject_unauthorized,
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 @@ -28,6 +28,7 @@ pub enum AnyPostgresError {
OutOfMemory,
Overflow,
PBKDFD2,
QueryCancelled,
SASL_SIGNATURE_MISMATCH,
SASL_SIGNATURE_INVALID_BASE64,
ShortRead,
Expand Down
27 changes: 22 additions & 5 deletions src/sql/postgres/protocol/BackendKeyData.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,36 @@
use super::new_reader::NewReader;
use crate::postgres::AnyPostgresError;

pub struct BackendKeyData {}
/// CancelRequest's stand-in for the protocol version: `(1234 << 16) | 5678`.
const CANCEL_REQUEST_CODE: u32 = 80877102;

pub struct BackendKeyData {
pub process_id: u32,
pub secret_key: u32,
}

impl BackendKeyData {
/// `Int32(16) Int32(80877102) Int32(pid) Int32(secret)`: no type byte, it
/// is the only message on a connection opened just to carry it.
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> {
if !reader.expect_int::<u32>(12)? {
return Err(AnyPostgresError::InvalidBackendKeyData);
}

// process_id, secret_key
reader.int4()?;
reader.int4()?;
Ok(Self {})
Ok(Self {
process_id: reader.int4()?,
secret_key: reader.int4()?,
})
}
}
7 changes: 7 additions & 0 deletions src/sql/postgres/protocol/ErrorResponse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ impl ErrorResponse {
}
Ok(Self::default())
}

/// SQLSTATE 57014: a cancel request or a timeout stopped the query.
pub fn is_query_canceled(&self) -> bool {
self.messages
.iter()
.any(|message| matches!(message, FieldMessage::Code(code) if code.eq_ascii(b"57014")))
}
}

// `to_js` lives on an extension trait in the `bun_sql_jsc` crate.
2 changes: 2 additions & 0 deletions src/sql/shared/ConnectionFlags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ bitflags! {
const HAS_BACKPRESSURE = 1 << 4;
/// `ref()` was called; `on_data` must not unref the idle connection.
const KEEP_ALIVE_REQUESTED = 1 << 5;
/// Postgres: exists only to deliver a CancelRequest in place of the StartupMessage.
const IS_CANCEL_REQUEST = 1 << 6;
}
}

Expand Down
12 changes: 12 additions & 0 deletions src/sql_jsc/jsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,8 @@ pub struct SqlRuntimeHooks {
pub ssl_config_from_js: unsafe fn(&JSGlobalObject, JSValue) -> *mut c_void,
/// Drop a boxed `SSLConfig` returned by `ssl_config_from_js`.
pub ssl_config_free: unsafe fn(*mut c_void),
/// Copy a boxed `SSLConfig` (caller frees via `ssl_config_free`).
pub ssl_config_clone: unsafe fn(*const c_void) -> *mut c_void,
/// `SSLConfig::asUSocketsForClientVerification`.
pub ssl_config_as_usockets_client:
unsafe fn(*const c_void) -> bun_uws::us_bun_socket_context_options_t,
Expand Down Expand Up @@ -477,6 +479,15 @@ pub mod api {
}
}

impl Clone for SSLConfig {
fn clone(&self) -> Self {
Self(self.0.and_then(|p| {
// SAFETY: `p` is a live boxed SSLConfig; the hook returns a fresh box.
NonNull::new(unsafe { (hooks().ssl_config_clone)(p.as_ptr()) })
}))
}
}

impl SSLConfig {
/// `SSLConfig.server_name` — the SNI hostname C string, or null
/// when unset / default.
Expand Down Expand Up @@ -660,6 +671,7 @@ pub mod codegen {
impl_js_class {
binding,
columns,
connection,
pendingValue,
target
}
Expand Down
72 changes: 42 additions & 30 deletions src/sql_jsc/postgres/PostgresRequest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,40 +454,52 @@ pub(crate) enum EncodeRequest<'a> {
}

impl PostgresSQLConnection {
/// The only caller of the batch writers above.
/// The only caller of the batch writers above. Nothing stays in the buffer for a `request` that its own parameter got rejected.
pub(crate) fn encode_request(
&self,
global: &JSGlobalObject,
request: EncodeRequest<'_>,
request: &PostgresSQLQuery,
batch: EncodeRequest<'_>,
) -> Result<(), AnyPostgresError> {
let writer = self.writer();
match request {
EncodeRequest::BindAndExecute {
statement,
binding_value,
columns_value,
} => bind_and_execute(global, statement, binding_value, columns_value, writer),
EncodeRequest::ParseBindAndExecute {
query,
statement,
binding_value,
columns_value,
include_describe,
} => parse_and_bind_and_execute(
global,
query,
statement,
binding_value,
columns_value,
include_describe,
writer,
),
EncodeRequest::PrepareAndQuery {
query,
signature,
binding_value,
} => prepare_and_query_with_signature(global, query, binding_value, writer, signature),
}
self.writer().atomically(|writer| {
match batch {
EncodeRequest::BindAndExecute {
statement,
binding_value,
columns_value,
} => bind_and_execute(global, statement, binding_value, columns_value, writer),
EncodeRequest::ParseBindAndExecute {
query,
statement,
binding_value,
columns_value,
include_describe,
} => parse_and_bind_and_execute(
global,
query,
statement,
binding_value,
columns_value,
include_describe,
writer,
),
EncodeRequest::PrepareAndQuery {
query,
signature,
binding_value,
} => prepare_and_query_with_signature(
global,
query,
binding_value,
writer,
signature,
),
}?;
if request.is_rejected() {
return Err(AnyPostgresError::QueryCancelled);
}
Ok(())
})
}
}

Expand Down
Loading
Loading