pub struct PgConnection { /* private fields */ }Expand description
A synchronous PostgreSQL connection with poll-based non-blocking I/O.
The socket is set to non-blocking mode at connect time. I/O methods internally poll with a configurable timeout so they can be adapted to an event-loop’s readiness notifications.
Implementations§
Source§impl PgConnection
impl PgConnection
Sourcepub fn connect(config: &PgConfig) -> Result<PgConnection, PgError>
pub fn connect(config: &PgConfig) -> Result<PgConnection, PgError>
Connect to PostgreSQL (blocking during handshake, then switches to non-blocking mode once authentication completes).
Sourcepub fn connect_with_timeout(
config: &PgConfig,
timeout: Duration,
) -> Result<PgConnection, PgError>
pub fn connect_with_timeout( config: &PgConfig, timeout: Duration, ) -> Result<PgConnection, PgError>
Connect with a custom I/O timeout.
Sourcepub fn set_io_timeout(&mut self, timeout: Duration)
pub fn set_io_timeout(&mut self, timeout: Duration)
Set the application-level I/O timeout.
Sourcepub fn io_timeout(&self) -> Duration
pub fn io_timeout(&self) -> Duration
Get the current I/O timeout.
Sourcepub fn set_notice_handler<F>(&mut self, handler: F)
pub fn set_notice_handler<F>(&mut self, handler: F)
Set a callback that is invoked when the server sends a NoticeResponse.
The callback receives (severity, code, message). This is useful for
logging warnings, deprecation notices, etc.
§Example
conn.set_notice_handler(|severity, code, message| {
eprintln!("PG {}: {} ({})", severity, message, code);
});Sourcepub fn clear_notice_handler(&mut self)
pub fn clear_notice_handler(&mut self)
Remove the notice handler.
Sourcepub fn set_statement_cache_capacity(&mut self, capacity: usize)
pub fn set_statement_cache_capacity(&mut self, capacity: usize)
Set the maximum number of statements to cache before LRU eviction.
Sourcepub fn raw_fd(&self) -> i32
pub fn raw_fd(&self) -> i32
Return the raw file descriptor for event-loop registration (epoll / kqueue).
Sourcepub fn is_nonblocking(&self) -> bool
pub fn is_nonblocking(&self) -> bool
Check if the socket is in non-blocking mode.
Sourcepub fn set_nonblocking(&mut self, nonblocking: bool) -> Result<(), PgError>
pub fn set_nonblocking(&mut self, nonblocking: bool) -> Result<(), PgError>
Set non-blocking mode on the socket.
Sourcepub fn query_simple(&mut self, sql: &str) -> Result<Vec<Row>, PgError>
pub fn query_simple(&mut self, sql: &str) -> Result<Vec<Row>, PgError>
Execute a simple query (no parameters). Returns all result rows.
Sourcepub fn query(
&mut self,
sql: &str,
params: &[&dyn ToSql],
) -> Result<Vec<Row>, PgError>
pub fn query( &mut self, sql: &str, params: &[&dyn ToSql], ) -> Result<Vec<Row>, PgError>
Execute a parameterized query using the Extended Query Protocol. Uses implicit statement caching for performance.
Sourcepub fn query_one(
&mut self,
sql: &str,
params: &[&dyn ToSql],
) -> Result<Row, PgError>
pub fn query_one( &mut self, sql: &str, params: &[&dyn ToSql], ) -> Result<Row, PgError>
Execute a query expecting exactly one row.
Optimised path: reads the Extended Query Protocol response stream and
returns the first DataRow directly, without collecting into a
Vec<Row>. Subsequent rows (if any) are still drained so the
connection is left in a clean state.
Sourcepub fn query_opt(
&mut self,
sql: &str,
params: &[&dyn ToSql],
) -> Result<Option<Row>, PgError>
pub fn query_opt( &mut self, sql: &str, params: &[&dyn ToSql], ) -> Result<Option<Row>, PgError>
Execute a query expecting zero or one row. Returns Ok(None) when
the query returns no rows, avoiding the PgError::NoRows error path.
Sourcepub fn execute(
&mut self,
sql: &str,
params: &[&dyn ToSql],
) -> Result<u64, PgError>
pub fn execute( &mut self, sql: &str, params: &[&dyn ToSql], ) -> Result<u64, PgError>
Execute a statement that returns no rows (INSERT, UPDATE, DELETE). Returns the number of affected rows as reported by the server.
Sourcepub fn transaction<F, T>(&mut self, f: F) -> Result<T, PgError>
pub fn transaction<F, T>(&mut self, f: F) -> Result<T, PgError>
Execute a closure within a transaction.
Automatically BEGINs before calling f, COMMITs on success,
and ROLLBACKs on error. This ensures the transaction is always
finalized, even if the closure panics (via Drop).
§Example
conn.transaction(|tx| {
tx.execute("INSERT INTO users (name) VALUES ($1)", &[&"Alice"])?;
tx.execute("INSERT INTO logs (msg) VALUES ($1)", &[&"User created"])?;
Ok(())
})?;Sourcepub fn copy_in(&mut self, sql: &str) -> Result<CopyWriter<'_>, PgError>
pub fn copy_in(&mut self, sql: &str) -> Result<CopyWriter<'_>, PgError>
Start a COPY FROM STDIN operation.
Sourcepub fn copy_out(&mut self, sql: &str) -> Result<CopyReader<'_>, PgError>
pub fn copy_out(&mut self, sql: &str) -> Result<CopyReader<'_>, PgError>
Start a COPY TO STDOUT operation. Returns a CopyReader that yields data chunks.
Sourcepub fn listen(&mut self, channel: &str) -> Result<(), PgError>
pub fn listen(&mut self, channel: &str) -> Result<(), PgError>
Subscribe to a notification channel.
Sourcepub fn notify(&mut self, channel: &str, payload: &str) -> Result<(), PgError>
pub fn notify(&mut self, channel: &str, payload: &str) -> Result<(), PgError>
Send a notification.
Sourcepub fn unlisten(&mut self, channel: &str) -> Result<(), PgError>
pub fn unlisten(&mut self, channel: &str) -> Result<(), PgError>
Unsubscribe from a notification channel.
Sourcepub fn unlisten_all(&mut self) -> Result<(), PgError>
pub fn unlisten_all(&mut self) -> Result<(), PgError>
Unsubscribe from all notification channels.
Sourcepub fn drain_notifications(&mut self) -> Vec<Notification>
pub fn drain_notifications(&mut self) -> Vec<Notification>
Drain and return all buffered notifications.
Sourcepub fn has_notifications(&self) -> bool
pub fn has_notifications(&self) -> bool
Check if there are buffered notifications.
Sourcepub fn notification_count(&self) -> usize
pub fn notification_count(&self) -> usize
Get the number of buffered notifications.
Sourcepub fn poll_notification(&mut self) -> Result<Option<Notification>, PgError>
pub fn poll_notification(&mut self) -> Result<Option<Notification>, PgError>
Poll for a notification (always non-blocking). Reads from the socket and returns the first notification found, or None if no notification is immediately available.
Sourcepub fn transaction_status(&self) -> TransactionStatus
pub fn transaction_status(&self) -> TransactionStatus
Get the current transaction status.
Sourcepub fn cached_statements(&self) -> usize
pub fn cached_statements(&self) -> usize
Get the number of cached statements.
Sourcepub fn last_affected_rows(&self) -> u64
pub fn last_affected_rows(&self) -> u64
Get the number of rows affected by the last command.
Sourcepub fn last_command_tag(&self) -> &str
pub fn last_command_tag(&self) -> &str
Get the last CommandComplete tag string.
Sourcepub fn process_id(&self) -> i32
pub fn process_id(&self) -> i32
Get the backend process ID.
Sourcepub fn secret_key(&self) -> i32
pub fn secret_key(&self) -> i32
Get the backend secret key (used for cancel requests).
Sourcepub fn server_params(&self) -> &[(String, String)]
pub fn server_params(&self) -> &[(String, String)]
Get server parameters received during startup.
Sourcepub fn server_param(&self, name: &str) -> Option<&str>
pub fn server_param(&self, name: &str) -> Option<&str>
Get a specific server parameter by name.
Sourcepub fn in_transaction(&self) -> bool
pub fn in_transaction(&self) -> bool
Check if the connection is in a transaction.
Sourcepub fn clear_statement_cache(&mut self)
pub fn clear_statement_cache(&mut self)
Clear the statement cache and deallocate all server-side prepared statements.
Sends DEALLOCATE ALL to the server before clearing the client-side
cache. The statement name counter is preserved to prevent name
collisions with any stale server-side references.
Sourcepub fn is_broken(&self) -> bool
pub fn is_broken(&self) -> bool
Returns true if the connection has been marked as broken due to a
fatal I/O error. A broken connection should be discarded (not
returned to the pool).
Sourcepub fn reset(&mut self) -> Result<(), PgError>
pub fn reset(&mut self) -> Result<(), PgError>
Reset the connection to a clean state for pool reuse.
Sends DISCARD ALL which resets session state, deallocates prepared
statements, closes cursors, drops temps, releases advisory locks.
Then clears the client-side statement cache.
Sourcepub fn execute_batch(&mut self, sql: &str) -> Result<u64, PgError>
pub fn execute_batch(&mut self, sql: &str) -> Result<u64, PgError>
Execute one or more SQL statements separated by semicolons, using the Simple Query Protocol. Returns the number of affected rows from the last command.
This is useful for running DDL migrations, multi-statement scripts, or any sequence of commands that don’t require parameters.
§Example
conn.execute_batch("CREATE TABLE t(id INT); INSERT INTO t VALUES (1); INSERT INTO t VALUES (2);")?;Sourcepub fn try_fill_read_buf(&mut self) -> Result<usize, PgError>
pub fn try_fill_read_buf(&mut self) -> Result<usize, PgError>
Try to read data into the read buffer without blocking.
Returns Ok(n) with bytes read, or Err(PgError::WouldBlock) if no
data is available, or another error on failure.
Sourcepub fn try_write(&mut self, data: &[u8]) -> Result<usize, PgError>
pub fn try_write(&mut self, data: &[u8]) -> Result<usize, PgError>
Try to write a buffer to the socket without blocking.
Returns Ok(n) with bytes written, or Err(PgError::WouldBlock) if the
socket is not writable.