PooledConn

Struct PooledConn 

Source
pub struct PooledConn { /* private fields */ }

Methods from Deref<Target = Conn>§

Source

pub fn backend_key(&self) -> Option<&BackendKeyData>

Get the backend key data for query cancellation.

Source

pub fn connection_id(&self) -> u32

Get the connection ID (backend process ID).

Returns 0 if the backend key data is not available.

Source

pub fn server_params(&self) -> &[(String, String)]

Get server parameters.

Source

pub fn transaction_status(&self) -> TransactionStatus

Get the current transaction status.

Source

pub fn in_transaction(&self) -> bool

Check if currently in a transaction.

Source

pub fn is_broken(&self) -> bool

Check if the connection is broken.

Source

pub fn set_async_message_handler<H: AsyncMessageHandler + 'static>( &mut self, handler: H, )

Set the async message handler.

The handler is called when the server sends asynchronous messages:

  • Notification - from LISTEN/NOTIFY
  • Notice - warnings and informational messages
  • ParameterChanged - server parameter updates
Source

pub fn clear_async_message_handler(&mut self)

Remove the async message handler.

Source

pub async fn ping(&mut self) -> Result<()>

Ping the server with an empty query to check connection aliveness.

Source

pub async fn query<H: TextHandler>( &mut self, sql: &str, handler: &mut H, ) -> Result<()>

Execute a simple query with a handler.

Source

pub async fn query_drop(&mut self, sql: &str) -> Result<Option<u64>>

Execute a simple query and discard results.

Source

pub async fn query_collect<T: for<'a> FromRow<'a>>( &mut self, sql: &str, ) -> Result<Vec<T>>

Execute a simple query and collect typed rows.

Source

pub async fn query_first<T: for<'a> FromRow<'a>>( &mut self, sql: &str, ) -> Result<Option<T>>

Execute a simple query and return the first typed row.

Source

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

Prepare a statement using the extended query protocol.

Source

pub async fn prepare_typed( &mut self, query: &str, param_oids: &[u32], ) -> Result<PreparedStatement>

Prepare a statement with explicit parameter types.

Source

pub async fn prepare_batch( &mut self, queries: &[&str], ) -> Result<Vec<PreparedStatement>>

Prepare multiple statements in a single round-trip.

This is more efficient than calling prepare() multiple times when you need to prepare several statements, as it batches the network communication.

§Example
let stmts = conn.prepare_batch(&[
    "SELECT id, name FROM users WHERE id = $1",
    "INSERT INTO users (name) VALUES ($1) RETURNING id",
    "UPDATE users SET name = $1 WHERE id = $2",
]).await?;

// Use stmts[0], stmts[1], stmts[2]...
Source

pub async fn exec<S: IntoStatement, P: ToParams, H: BinaryHandler>( &mut self, statement: S, params: P, handler: &mut H, ) -> Result<()>

Execute a statement with a handler.

The statement can be either:

  • A &PreparedStatement returned from prepare()
  • A raw SQL &str for one-shot execution
Source

pub async fn exec_drop<S: IntoStatement, P: ToParams>( &mut self, statement: S, params: P, ) -> Result<Option<u64>>

Execute a statement and discard results.

The statement can be either a &PreparedStatement or a raw SQL &str.

Source

pub async fn exec_collect<T: for<'a> FromRow<'a>, S: IntoStatement, P: ToParams>( &mut self, statement: S, params: P, ) -> Result<Vec<T>>

Execute a statement and collect typed rows.

The statement can be either a &PreparedStatement or a raw SQL &str.

Source

pub async fn exec_batch<S: IntoStatement, P: ToParams>( &mut self, statement: S, params_list: &[P], ) -> Result<()>

Execute a statement with multiple parameter sets in a batch.

This is more efficient than calling exec_drop multiple times as it batches the network communication. The statement is parsed once (if raw SQL) and then bound/executed for each parameter set.

Parameters are processed in chunks (default 1000) to avoid overwhelming the server with too many pending operations.

The statement can be either:

  • A &PreparedStatement returned from prepare()
  • A raw SQL &str for one-shot execution
§Example
// Using prepared statement
let stmt = conn.prepare("INSERT INTO users (name, age) VALUES ($1, $2)").await?;
conn.exec_batch(&stmt, &[
    ("alice", 30),
    ("bob", 25),
    ("charlie", 35),
]).await?;

// Using raw SQL
conn.exec_batch("INSERT INTO users (name, age) VALUES ($1, $2)", &[
    ("alice", 30),
    ("bob", 25),
]).await?;
Source

pub async fn exec_batch_chunked<S: IntoStatement, P: ToParams>( &mut self, statement: S, params_list: &[P], chunk_size: usize, ) -> Result<()>

Execute a statement with multiple parameter sets in a batch with custom chunk size.

Same as exec_batch but allows specifying the chunk size for batching.

Source

pub async fn close_statement(&mut self, stmt: &PreparedStatement) -> Result<()>

Close a prepared statement.

Source

pub async fn lowlevel_flush(&mut self) -> Result<()>

Low-level flush: send FLUSH to force server to send pending responses.

Unlike SYNC, FLUSH does not end the transaction or wait for ReadyForQuery. It just forces the server to send any pending responses without ending the extended query sequence.

Source

pub async fn lowlevel_sync(&mut self) -> Result<()>

Low-level sync: send SYNC and receive ReadyForQuery.

This ends an extended query sequence and:

  • Commits implicit transaction if successful
  • Rolls back implicit transaction if failed
  • Updates transaction status
Source

pub async fn lowlevel_bind<P: ToParams>( &mut self, portal: &str, statement_name: &str, params: P, ) -> Result<()>

Low-level bind: send BIND message and receive BindComplete.

This allows creating named portals. Unlike exec(), this does NOT send EXECUTE or SYNC - the caller controls when to execute and sync.

§Arguments
  • portal: Portal name (empty string “” for unnamed portal)
  • statement_name: Prepared statement name
  • params: Parameter values
Source

pub async fn lowlevel_execute<H: BinaryHandler>( &mut self, portal: &str, max_rows: u32, handler: &mut H, ) -> Result<bool>

Low-level execute: send EXECUTE message and receive results.

Executes a previously bound portal. Does NOT send SYNC.

§Arguments
  • portal: Portal name (empty string “” for unnamed portal)
  • max_rows: Maximum rows to return (0 = unlimited)
  • handler: Handler to receive rows
§Returns
  • Ok(true) if more rows available (PortalSuspended received)
  • Ok(false) if execution completed (CommandComplete received)
Source

pub async fn exec_iter<S: IntoStatement, P, F, Fut, T>( &mut self, statement: S, params: P, f: F, ) -> Result<T>
where P: ToParams, F: FnOnce(&mut UnnamedPortal<'_>) -> Fut, Fut: Future<Output = Result<T>>,

Execute a statement with iterative row fetching.

Creates an unnamed portal and passes it to the closure. The closure can call portal.fetch(n, handler) multiple times to retrieve rows in batches. Sync is called after the closure returns to end the implicit transaction.

The statement can be either:

  • A &PreparedStatement returned from prepare()
  • A raw SQL &str for one-shot execution
§Example
// Using prepared statement
let stmt = conn.prepare("SELECT * FROM users").await?;
conn.exec_iter(&stmt, (), |portal| async move {
    while portal.fetch(100, &mut handler).await? {
        // process handler.into_rows()...
    }
    Ok(())
}).await?;

// Using raw SQL
conn.exec_iter("SELECT * FROM users", (), |portal| async move {
    while portal.fetch(100, &mut handler).await? {
        // process handler.into_rows()...
    }
    Ok(())
}).await?;
Source

pub async fn lowlevel_close_portal(&mut self, portal: &str) -> Result<()>

Low-level close portal: send Close(Portal) and receive CloseComplete.

Source

pub async fn run_pipeline<T, F, Fut>(&mut self, f: F) -> Result<T>
where F: FnOnce(&mut Pipeline<'_>) -> Fut, Fut: Future<Output = Result<T>>,

Run a pipeline of batched queries.

Pipeline mode allows sending multiple queries to the server without waiting for responses, reducing round-trip latency.

§Example
// Prepare statements outside the pipeline
let stmts = conn.prepare_batch(&[
    "SELECT id, name FROM users WHERE active = $1",
    "INSERT INTO users (name) VALUES ($1) RETURNING id",
]).await?;

let (active, inactive, count) = conn.run_pipeline(|p| async move {
    // Queue executions
    let t1 = p.exec(&stmts[0], (true,)).await?;
    let t2 = p.exec(&stmts[0], (false,)).await?;
    let t3 = p.exec("SELECT COUNT(*) FROM users", ()).await?;

    p.sync().await?;

    // Claim results in order with different methods
    let active: Vec<(i32, String)> = p.claim_collect(t1).await?;
    let inactive: Option<(i32, String)> = p.claim_one(t2).await?;
    let count: Vec<(i64,)> = p.claim_collect(t3).await?;

    Ok((active, inactive, count))
}).await?;
Source

pub async fn tx<F, R, Fut>(&mut self, f: F) -> Result<R>
where F: FnOnce(&mut Conn, Transaction) -> Fut, Fut: Future<Output = Result<R>>,

Execute a closure within a transaction.

If the closure returns Ok, the transaction is committed. If the closure returns Err or the transaction is not explicitly committed or rolled back, the transaction is rolled back.

§Errors

Returns Error::InvalidUsage if called while already in a transaction.

Trait Implementations§

Source§

impl Deref for PooledConn

Source§

type Target = Conn

The resulting type after dereferencing.
Source§

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

Dereferences the value.
Source§

impl DerefMut for PooledConn

Source§

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

Mutably dereferences the value.
Source§

impl Drop for PooledConn

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