pub struct Conn { /* private fields */ }Expand description
Asynchronous PostgreSQL connection.
Implementations§
Source§impl Conn
impl Conn
Sourcepub async fn new_with_stream(stream: Stream, options: Opts) -> Result<Self>
pub async fn new_with_stream(stream: Stream, options: Opts) -> Result<Self>
Connect using an existing stream.
Sourcepub fn backend_key(&self) -> Option<&BackendKeyData>
pub fn backend_key(&self) -> Option<&BackendKeyData>
Get the backend key data for query cancellation.
Sourcepub fn connection_id(&self) -> u32
pub fn connection_id(&self) -> u32
Get the connection ID (backend process ID).
Returns 0 if the backend key data is not available.
Sourcepub fn server_params(&self) -> &[(String, String)]
pub fn server_params(&self) -> &[(String, String)]
Get server parameters.
Sourcepub fn transaction_status(&self) -> TransactionStatus
pub fn transaction_status(&self) -> TransactionStatus
Get the current transaction status.
Sourcepub fn in_transaction(&self) -> bool
pub fn in_transaction(&self) -> bool
Check if currently in a transaction.
Sourcepub fn set_async_message_handler<H: AsyncMessageHandler + 'static>(
&mut self,
handler: H,
)
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/NOTIFYNotice- warnings and informational messagesParameterChanged- server parameter updates
Sourcepub fn clear_async_message_handler(&mut self)
pub fn clear_async_message_handler(&mut self)
Remove the async message handler.
Sourcepub async fn ping(&mut self) -> Result<()>
pub async fn ping(&mut self) -> Result<()>
Ping the server with an empty query to check connection aliveness.
Sourcepub async fn query<H: SimpleHandler>(
&mut self,
sql: &str,
handler: &mut H,
) -> Result<()>
pub async fn query<H: SimpleHandler>( &mut self, sql: &str, handler: &mut H, ) -> Result<()>
Execute a simple query with a handler.
Sourcepub async fn query_drop(&mut self, sql: &str) -> Result<Option<u64>>
pub async fn query_drop(&mut self, sql: &str) -> Result<Option<u64>>
Execute a simple query and discard results.
Sourcepub async fn query_collect<T: for<'a> FromRow<'a>>(
&mut self,
sql: &str,
) -> Result<Vec<T>>
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.
Sourcepub async fn query_first<T: for<'a> FromRow<'a>>(
&mut self,
sql: &str,
) -> Result<Option<T>>
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.
Sourcepub async fn query_foreach<T: for<'a> FromRow<'a>, F: FnMut(T) -> Result<()>>(
&mut self,
sql: &str,
f: F,
) -> Result<()>
pub async fn query_foreach<T: for<'a> FromRow<'a>, F: FnMut(T) -> Result<()>>( &mut self, sql: &str, f: F, ) -> Result<()>
Sourcepub async fn prepare(&mut self, query: &str) -> Result<PreparedStatement>
pub async fn prepare(&mut self, query: &str) -> Result<PreparedStatement>
Prepare a statement using the extended query protocol.
Sourcepub async fn prepare_typed(
&mut self,
query: &str,
param_oids: &[u32],
) -> Result<PreparedStatement>
pub async fn prepare_typed( &mut self, query: &str, param_oids: &[u32], ) -> Result<PreparedStatement>
Prepare a statement with explicit parameter types.
Sourcepub async fn prepare_batch(
&mut self,
queries: &[&str],
) -> Result<Vec<PreparedStatement>>
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]...Sourcepub async fn exec<S: IntoStatement, P: ToParams, H: ExtendedHandler>(
&mut self,
statement: S,
params: P,
handler: &mut H,
) -> Result<()>
pub async fn exec<S: IntoStatement, P: ToParams, H: ExtendedHandler>( &mut self, statement: S, params: P, handler: &mut H, ) -> Result<()>
Execute a statement with a handler.
The statement can be either:
- A
&PreparedStatementreturned fromprepare() - A raw SQL
&strfor one-shot execution
Sourcepub async fn exec_drop<S: IntoStatement, P: ToParams>(
&mut self,
statement: S,
params: P,
) -> Result<Option<u64>>
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.
Sourcepub async fn exec_collect<T: for<'a> FromRow<'a>, S: IntoStatement, P: ToParams>(
&mut self,
statement: S,
params: P,
) -> Result<Vec<T>>
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.
Sourcepub async fn exec_first<T: for<'a> FromRow<'a>, S: IntoStatement, P: ToParams>(
&mut self,
statement: S,
params: P,
) -> Result<Option<T>>
pub async fn exec_first<T: for<'a> FromRow<'a>, S: IntoStatement, P: ToParams>( &mut self, statement: S, params: P, ) -> Result<Option<T>>
Execute a statement and return the first typed row.
The statement can be either a &PreparedStatement or a raw SQL &str.
Sourcepub async fn exec_foreach<T: for<'a> FromRow<'a>, S: IntoStatement, P: ToParams, F: FnMut(T) -> Result<()>>(
&mut self,
statement: S,
params: P,
f: F,
) -> Result<()>
pub async fn exec_foreach<T: for<'a> FromRow<'a>, S: IntoStatement, P: ToParams, F: FnMut(T) -> Result<()>>( &mut self, statement: S, params: P, f: F, ) -> Result<()>
Execute a statement and call a closure for each row.
The statement can be either a &PreparedStatement or a raw SQL &str.
§Example
let stmt = conn.prepare("SELECT id, name FROM users").await?;
conn.exec_foreach(&stmt, (), |row: (i32, String)| {
println!("{}: {}", row.0, row.1);
Ok(())
}).await?;The closure can return an error to stop iteration early.
Sourcepub async fn exec_batch<S: IntoStatement, P: ToParams>(
&mut self,
statement: S,
params_list: &[P],
) -> Result<()>
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
&PreparedStatementreturned fromprepare() - A raw SQL
&strfor 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?;Sourcepub async fn exec_batch_chunked<S: IntoStatement, P: ToParams>(
&mut self,
statement: S,
params_list: &[P],
chunk_size: usize,
) -> Result<()>
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.
Sourcepub async fn close_statement(&mut self, stmt: &PreparedStatement) -> Result<()>
pub async fn close_statement(&mut self, stmt: &PreparedStatement) -> Result<()>
Close a prepared statement.
Sourcepub async fn lowlevel_flush(&mut self) -> Result<()>
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.
Sourcepub async fn lowlevel_sync(&mut self) -> Result<()>
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
Sourcepub async fn lowlevel_bind<P: ToParams>(
&mut self,
portal: &str,
statement_name: &str,
params: P,
) -> Result<()>
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 nameparams: Parameter values
Sourcepub async fn lowlevel_execute<H: ExtendedHandler>(
&mut self,
portal: &str,
max_rows: u32,
handler: &mut H,
) -> Result<bool>
pub async fn lowlevel_execute<H: ExtendedHandler>( &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)
Sourcepub async fn exec_portal<S: IntoStatement, P, F, T>(
&mut self,
statement: S,
params: P,
f: F,
) -> Result<T>
pub async fn exec_portal<S: IntoStatement, P, F, T>( &mut self, statement: S, params: P, f: F, ) -> Result<T>
Execute a statement with iterative row fetching using a portal.
Creates an unnamed portal and passes it to the closure. The closure can
call portal.exec(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
&PreparedStatementreturned fromprepare() - A raw SQL
&strfor one-shot execution
§Example
// Using prepared statement
let stmt = conn.prepare("SELECT * FROM users").await?;
conn.exec_portal(&stmt, (), |portal| async move {
while portal.exec(100, &mut handler).await? {
// process handler.into_rows()...
}
Ok(())
}).await?;
// Using raw SQL
conn.exec_portal("SELECT * FROM users", (), |portal| async move {
while portal.exec(100, &mut handler).await? {
// process handler.into_rows()...
}
Ok(())
}).await?;Sourcepub async fn lowlevel_close_portal(&mut self, portal: &str) -> Result<()>
pub async fn lowlevel_close_portal(&mut self, portal: &str) -> Result<()>
Low-level close portal: send Close(Portal) and receive CloseComplete.
Sourcepub async fn pipeline<T, F>(&mut self, f: F) -> Result<T>
pub async fn pipeline<T, F>(&mut self, f: F) -> 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.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?;Sourcepub async fn transaction<F, R>(&mut self, f: F) -> Result<R>
pub async fn transaction<F, R>(&mut self, f: F) -> Result<R>
Execute a closure within a transaction.
If no explicit commit or rollback is called:
- If the closure returns
Ok, the transaction is committed. - If the closure returns
Err, the transaction is rolled back.
§Errors
Returns Error::InvalidUsage if called while already in a transaction.