Skip to main content

PooledConnection

Struct PooledConnection 

Source
pub struct PooledConnection { /* private fields */ }
Expand description

A pooled connection that returns to the pool when dropped.

When rls_dirty is true (set by acquire_with_rls), the connection will automatically reset RLS session variables before returning to the pool. This prevents cross-tenant data leakage.

Implementations§

Source§

impl PooledConnection

Source

pub fn get_mut(&mut self) -> &mut PgConnection

Get a mutable reference to the underlying connection.

Source

pub fn cancel_token(&self) -> CancelToken

Get a token to cancel the currently running query.

Source

pub async fn release(self)

Deterministic connection cleanup and pool return.

This is the correct way to return a connection to the pool. COMMITs the transaction (which auto-resets transaction-local RLS session variables) and returns the connection to the pool with prepared statement caches intact.

If cleanup fails, the connection is destroyed (not returned to pool).

§Usage
let mut conn = pool.acquire_with_rls(ctx).await?;
let result = conn.fetch_all_cached(&cmd).await;
conn.release().await; // COMMIT + return to pool
result
Source

pub async fn fetch_all_uncached(&mut self, cmd: &Qail) -> PgResult<Vec<PgRow>>

Execute a QAIL command and fetch all rows (UNCACHED). Returns rows with column metadata for JSON serialization.

Source

pub async fn fetch_all_fast(&mut self, cmd: &Qail) -> PgResult<Vec<PgRow>>

Execute a QAIL command and fetch all rows (FAST VERSION). Uses native AST-to-wire encoding and optimized recv_with_data_fast. Skips column metadata for maximum speed.

Source

pub async fn fetch_all_cached(&mut self, cmd: &Qail) -> PgResult<Vec<PgRow>>

Execute a QAIL command and fetch all rows (CACHED). Uses prepared statement caching: Parse+Describe on first call, then Bind+Execute only on subsequent calls with the same SQL shape. This matches PostgREST’s behavior for fair benchmarks.

Source

pub async fn fetch_all_with_rls( &mut self, cmd: &Qail, rls_sql: &str, ) -> PgResult<Vec<PgRow>>

Execute a QAIL command with RLS context in a SINGLE roundtrip.

Pipelines the RLS setup (BEGIN + set_config) and the query (Parse/Bind/Execute/Sync) into one write_all syscall. PG processes messages in order, so the BEGIN + set_config completes before the query executes — security is preserved.

Wire layout:

[SimpleQuery: "BEGIN; SET LOCAL...; SELECT set_config(...)"]
[Parse (if cache miss)]
[Describe (if cache miss)]
[Bind]
[Execute]
[Sync]

Response processing: consume 2× ReadyForQuery (SimpleQuery + Sync).

Source

pub async fn pipeline_ast( &mut self, cmds: &[Qail], ) -> PgResult<Vec<Vec<Vec<Option<Vec<u8>>>>>>

Execute multiple QAIL commands in a single PG pipeline round-trip.

Sends all queries as Parse+Bind+Execute in one write, receives all responses in one read. Returns raw column data per query per row.

This is the fastest path for batch operations — amortizes TCP overhead across N queries into a single syscall pair.

Source

pub async fn explain_estimate( &mut self, cmd: &Qail, ) -> PgResult<Option<ExplainEstimate>>

Run EXPLAIN (FORMAT JSON) on a Qail command and return cost estimates.

Uses simple_query under the hood — no additional round-trips beyond the single EXPLAIN statement. Returns None if parsing fails or the EXPLAIN output is unexpected.

Methods from Deref<Target = PgConnection>§

Source

pub fn get_cancel_key(&self) -> (i32, i32)

Get the cancel key for this connection.

Source

pub async fn copy_in_raw( &mut self, table: &str, columns: &[String], data: &[u8], ) -> PgResult<u64>

Fastest bulk insert using COPY protocol with pre-encoded data. Accepts raw COPY text format bytes, no encoding needed. Use when caller has already encoded rows to COPY format.

§Format

Data should be tab-separated rows with newlines: 1\thello\t3.14\n2\tworld\t2.71\n

Source

pub async fn copy_export(&mut self, cmd: &Qail) -> PgResult<Vec<Vec<String>>>

Export data using COPY TO STDOUT (AST-native). Takes a Qail::Export and returns rows as Vec<Vec>.

§Example
let cmd = Qail::export("users")
    .columns(["id", "name"])
    .filter("active", true);
let rows = conn.copy_export(&cmd).await?;
Source

pub async fn send(&mut self, msg: FrontendMessage) -> PgResult<()>

Send a frontend message.

Source

pub async fn recv(&mut self) -> PgResult<BackendMessage>

Loops until a complete message is available. Automatically buffers NotificationResponse messages for LISTEN/NOTIFY.

Source

pub async fn send_bytes(&mut self, bytes: &[u8]) -> PgResult<()>

Send raw bytes to the stream. Includes flush for TLS safety — TLS buffers internally and needs flush to push encrypted data to the underlying TCP socket.

Source

pub fn buffer_bytes(&mut self, bytes: &[u8])

Buffer bytes for later flush (NO SYSCALL). Use flush_write_buf() to send all buffered data.

Source

pub async fn flush_write_buf(&mut self) -> PgResult<()>

Flush the write buffer to the stream (single write_all + flush). The flush is critical for TLS connections.

Source

pub async fn query_pipeline( &mut self, queries: &[(&str, &[Option<Vec<u8>>])], ) -> PgResult<Vec<Vec<Vec<Option<Vec<u8>>>>>>

Execute multiple SQL queries in a single network round-trip (PIPELINING).

Source

pub async fn pipeline_ast( &mut self, cmds: &[Qail], ) -> PgResult<Vec<Vec<Vec<Option<Vec<u8>>>>>>

Execute multiple Qail ASTs in a single network round-trip.

Source

pub async fn pipeline_ast_fast(&mut self, cmds: &[Qail]) -> PgResult<usize>

FAST AST pipeline - returns only query count, no result parsing.

Source

pub async fn pipeline_bytes_fast( &mut self, wire_bytes: &[u8], expected_queries: usize, ) -> PgResult<usize>

FASTEST extended query pipeline - takes pre-encoded wire bytes.

Source

pub async fn pipeline_simple_fast(&mut self, cmds: &[Qail]) -> PgResult<usize>

Simple query protocol pipeline - uses ‘Q’ message.

Source

pub async fn pipeline_simple_bytes_fast( &mut self, wire_bytes: &[u8], expected_queries: usize, ) -> PgResult<usize>

FASTEST simple query pipeline - takes pre-encoded bytes.

Source

pub async fn pipeline_ast_cached(&mut self, cmds: &[Qail]) -> PgResult<usize>

CACHED PREPARED STATEMENT pipeline - Parse once, Bind+Execute many.

  1. Generate SQL template with $1, $2, etc. placeholders
  2. Parse template ONCE (cached in PostgreSQL)
  3. Send Bind+Execute for each instance (params differ per query)
Source

pub async fn pipeline_prepared_fast( &mut self, stmt: &PreparedStatement, params_batch: &[Vec<Option<Vec<u8>>>], ) -> PgResult<usize>

ZERO-LOOKUP prepared statement pipeline.

  • Hash computation per query
  • HashMap lookup per query
  • String allocation for stmt_name
§Example
// Prepare once (outside timing loop):
let stmt = PreparedStatement::from_sql("SELECT id, name FROM harbors LIMIT $1");
let params_batch: Vec<Vec<Option<Vec<u8>>>> = (1..=1000)
    .map(|i| vec![Some(i.to_string().into_bytes())])
    .collect();
// Execute many (no hash, no lookup!):
conn.pipeline_prepared_fast(&stmt, &params_batch).await?;
Source

pub async fn prepare(&mut self, sql: &str) -> PgResult<PreparedStatement>

Prepare a statement and return a handle for fast execution. PreparedStatement handle for use with pipeline_prepared_fast.

Source

pub async fn pipeline_prepared_results( &mut self, stmt: &PreparedStatement, params_batch: &[Vec<Option<Vec<u8>>>], ) -> PgResult<Vec<Vec<Vec<Option<Vec<u8>>>>>>

Execute a prepared statement pipeline and return all row data.

Source

pub async fn pipeline_prepared_zerocopy( &mut self, stmt: &PreparedStatement, params_batch: &[Vec<Option<Vec<u8>>>], ) -> PgResult<Vec<Vec<Vec<Option<Bytes>>>>>

ZERO-COPY pipeline execution with Bytes for column data.

Source

pub async fn pipeline_prepared_ultra( &mut self, stmt: &PreparedStatement, params_batch: &[Vec<Option<Vec<u8>>>], ) -> PgResult<Vec<Vec<(Bytes, Bytes)>>>

ULTRA-FAST pipeline for 2-column SELECT queries.

Source

pub async fn query_cached( &mut self, sql: &str, params: &[Option<Vec<u8>>], ) -> PgResult<Vec<Vec<Option<Vec<u8>>>>>

Execute a query with cached prepared statement. Like query(), but reuses prepared statements across calls. The statement name is derived from a hash of the SQL text. OPTIMIZED: Pre-allocated buffer + ultra-fast encoders.

Source

pub async fn execute_simple(&mut self, sql: &str) -> PgResult<()>

Execute a simple SQL statement (no parameters).

Source

pub async fn simple_query(&mut self, sql: &str) -> PgResult<Vec<PgRow>>

Execute a simple SQL query and return rows (Simple Query Protocol).

Unlike execute_simple, this collects and returns data rows. Used for branch management and other administrative queries.

SECURITY: Capped at 10,000 rows to prevent OOM from unbounded results.

Source

pub async fn query_prepared_single( &mut self, stmt: &PreparedStatement, params: &[Option<Vec<u8>>], ) -> PgResult<Vec<Vec<Option<Vec<u8>>>>>

ZERO-HASH sequential query using pre-computed PreparedStatement. This is the FASTEST sequential path because it skips:

  • SQL generation from AST (done once outside loop)
  • Hash computation for statement name (pre-computed in PreparedStatement)
  • HashMap lookup for is_new check (statement already prepared)
§Example
let stmt = conn.prepare("SELECT * FROM users WHERE id = $1").await?;
for id in 1..10000 {
    let rows = conn.query_prepared_single(&stmt, &[Some(id.to_string().into_bytes())]).await?;
}
Source

pub async fn begin_transaction(&mut self) -> PgResult<()>

Begin a new transaction. After calling this, all queries run within the transaction until commit() or rollback() is called.

Source

pub async fn commit(&mut self) -> PgResult<()>

Commit the current transaction. Makes all changes since begin_transaction() permanent.

Source

pub async fn rollback(&mut self) -> PgResult<()>

Rollback the current transaction. Discards all changes since begin_transaction().

Source

pub async fn savepoint(&mut self, name: &str) -> PgResult<()>

Create a named savepoint within the current transaction. Savepoints allow partial rollback within a transaction. Use rollback_to() to return to this savepoint.

Source

pub async fn rollback_to(&mut self, name: &str) -> PgResult<()>

Rollback to a previously created savepoint. Discards all changes since the named savepoint was created, but keeps the transaction open.

Source

pub async fn release_savepoint(&mut self, name: &str) -> PgResult<()>

Release a savepoint (free resources, if no longer needed).

Source

pub async fn listen(&mut self, channel: &str) -> PgResult<()>

Subscribe to a notification channel.

conn.listen("price_calendar_changed").await?;
Source

pub async fn unlisten(&mut self, channel: &str) -> PgResult<()>

Unsubscribe from a notification channel.

Source

pub async fn unlisten_all(&mut self) -> PgResult<()>

Unsubscribe from all notification channels.

Source

pub fn poll_notifications(&mut self) -> Vec<Notification>

Drain all buffered notifications without blocking.

Notifications arrive asynchronously from PostgreSQL and are buffered whenever recv() encounters a NotificationResponse. This method returns all currently buffered notifications.

Source

pub async fn recv_notification(&mut self) -> PgResult<Notification>

Wait for the next notification, blocking until one arrives.

Unlike recv(), this does NOT use the 30-second Slowloris timeout guard. LISTEN connections idle for long periods — that’s normal, not a DoS attack.

Useful for a dedicated LISTEN connection in a background task.

Trait Implementations§

Source§

impl Deref for PooledConnection

Source§

type Target = PgConnection

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for PooledConnection

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl Drop for PooledConnection

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> ColumnValue<Value> for T