pub struct Conn { /* private fields */ }Expand description
Synchronous PostgreSQL connection.
Implementations§
Source§impl Conn
impl Conn
Sourcepub fn new_with_stream(stream: Stream, options: Opts) -> Result<Self>
pub 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 fn run_pipeline<T, F>(&mut self, f: F) -> Result<T>
pub fn run_pipeline<T, F>(&mut self, f: F) -> Result<T>
Run a pipeline of batched queries.
This provides automatic cleanup of the pipeline on exit, ensuring the connection is left in a valid state even if the closure fails.
§Example
let stmt = conn.prepare("INSERT INTO users (name) VALUES ($1) RETURNING id")?;
let (id1, id2) = conn.run_pipeline(|p| {
let t1 = p.exec(&stmt, ("alice",))?;
let t2 = p.exec(&stmt, ("bob",))?;
p.sync()?;
let id1: Option<(i32,)> = p.claim_one(t1)?;
let id2: Option<(i32,)> = p.claim_one(t2)?;
Ok((id1, id2))
})?;Sourcepub fn ping(&mut self) -> Result<()>
pub fn ping(&mut self) -> Result<()>
Ping the server with an empty query to check connection aliveness.
Sourcepub fn query<H: TextHandler>(
&mut self,
sql: &str,
handler: &mut H,
) -> Result<()>
pub fn query<H: TextHandler>( &mut self, sql: &str, handler: &mut H, ) -> Result<()>
Execute a simple query with a handler.
Sourcepub fn query_drop(&mut self, sql: &str) -> Result<Option<u64>>
pub fn query_drop(&mut self, sql: &str) -> Result<Option<u64>>
Execute a simple query and discard results.
Sourcepub fn query_first<T: for<'a> FromRow<'a>>(
&mut self,
sql: &str,
) -> Result<Option<T>>
pub 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 fn prepare(&mut self, query: &str) -> Result<PreparedStatement>
pub fn prepare(&mut self, query: &str) -> Result<PreparedStatement>
Prepare a statement using the extended query protocol.
Sourcepub fn prepare_batch(
&mut self,
queries: &[&str],
) -> Result<Vec<PreparedStatement>>
pub 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",
])?;
// Use stmts[0], stmts[1], stmts[2]...Sourcepub fn prepare_typed(
&mut self,
query: &str,
param_oids: &[u32],
) -> Result<PreparedStatement>
pub fn prepare_typed( &mut self, query: &str, param_oids: &[u32], ) -> Result<PreparedStatement>
Prepare a statement with explicit parameter types.
Sourcepub fn exec<S: IntoStatement, P: ToParams, H: BinaryHandler>(
&mut self,
statement: S,
params: P,
handler: &mut H,
) -> Result<()>
pub 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
&PreparedStatementreturned fromprepare() - A raw SQL
&strfor one-shot execution
§Examples
// Using prepared statement
let stmt = conn.prepare("SELECT $1::int")?;
conn.exec(&stmt, (42,), &mut handler)?;
// Using raw SQL
conn.exec("SELECT $1::int", (42,), &mut handler)?;Sourcepub fn exec_drop<S: IntoStatement, P: ToParams>(
&mut self,
statement: S,
params: P,
) -> Result<Option<u64>>
pub 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 fn exec_collect<T: for<'a> FromRow<'a>, S: IntoStatement, P: ToParams>(
&mut self,
statement: S,
params: P,
) -> Result<Vec<T>>
pub 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.
§Example
let stmt = conn.prepare("SELECT id, name FROM users WHERE id = $1")?;
let rows: Vec<(i32, String)> = conn.exec_collect(&stmt, (42,))?;
// Or with raw SQL:
let rows: Vec<(i32, String)> = conn.exec_collect("SELECT id, name FROM users", ())?;Sourcepub fn exec_first<T: for<'a> FromRow<'a>, S: IntoStatement, P: ToParams>(
&mut self,
statement: S,
params: P,
) -> Result<Option<T>>
pub 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.
§Example
let stmt = conn.prepare("SELECT id, name FROM users WHERE id = $1")?;
let row: Option<(i32, String)> = conn.exec_first(&stmt, (42,))?;
// Or with raw SQL:
let row: Option<(i32, String)> = conn.exec_first("SELECT id, name FROM users LIMIT 1", ())?;Sourcepub fn exec_batch<S: IntoStatement, P: ToParams>(
&mut self,
statement: S,
params_list: &[P],
) -> Result<()>
pub 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)")?;
conn.exec_batch(&stmt, &[
("alice", 30),
("bob", 25),
("charlie", 35),
])?;
// Using raw SQL
conn.exec_batch("INSERT INTO users (name, age) VALUES ($1, $2)", &[
("alice", 30),
("bob", 25),
])?;Sourcepub fn exec_batch_chunked<S: IntoStatement, P: ToParams>(
&mut self,
statement: S,
params_list: &[P],
chunk_size: usize,
) -> Result<()>
pub 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 fn close_statement(&mut self, stmt: &PreparedStatement) -> Result<()>
pub fn close_statement(&mut self, stmt: &PreparedStatement) -> Result<()>
Close a prepared statement.
Sourcepub fn transaction<F, R>(&mut self, f: F) -> Result<R>
pub fn transaction<F, R>(&mut self, f: F) -> 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.
Source§impl Conn
impl Conn
Sourcepub fn lowlevel_bind<P: ToParams>(
&mut self,
portal: &str,
statement_name: &str,
params: P,
) -> Result<()>
pub 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 fn lowlevel_execute<H: BinaryHandler>(
&mut self,
portal: &str,
max_rows: u32,
handler: &mut H,
) -> Result<bool>
pub 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)
Sourcepub fn lowlevel_sync(&mut self) -> Result<()>
pub 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 fn lowlevel_flush(&mut self) -> Result<()>
pub 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 (like ParseComplete, BindComplete, RowDescription, DataRow, etc.) without ending the extended query sequence.
Sourcepub fn exec_iter<S: IntoStatement, P, F, T>(
&mut self,
statement: S,
params: P,
f: F,
) -> Result<T>
pub fn exec_iter<S: IntoStatement, P, F, T>( &mut self, statement: S, params: P, f: F, ) -> 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
&PreparedStatementreturned fromprepare() - A raw SQL
&strfor one-shot execution
§Example
// Using prepared statement
let stmt = conn.prepare("SELECT * FROM users")?;
conn.exec_iter(&stmt, (), |portal| {
while portal.fetch(100, &mut handler)? {
// process handler.into_rows()...
}
Ok(())
})?;
// Using raw SQL
conn.exec_iter("SELECT * FROM users", (), |portal| {
while portal.fetch(100, &mut handler)? {
// process handler.into_rows()...
}
Ok(())
})?;Sourcepub fn lowlevel_close_portal(&mut self, portal: &str) -> Result<()>
pub fn lowlevel_close_portal(&mut self, portal: &str) -> Result<()>
Low-level close portal: send Close(Portal) and receive CloseComplete.