Skip to main content

PgConnection

Struct PgConnection 

Source
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

Source

pub fn connect(config: &PgConfig) -> Result<PgConnection, PgError>

Connect to PostgreSQL (blocking during handshake, then switches to non-blocking mode once authentication completes).

Source

pub fn connect_with_timeout( config: &PgConfig, timeout: Duration, ) -> Result<PgConnection, PgError>

Connect with a custom I/O timeout.

Source

pub fn set_io_timeout(&mut self, timeout: Duration)

Set the application-level I/O timeout.

Source

pub fn io_timeout(&self) -> Duration

Get the current I/O timeout.

Source

pub fn set_notice_handler<F>(&mut self, handler: F)
where F: Fn(&str, &str, &str) + Send + Sync + 'static,

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);
});
Source

pub fn clear_notice_handler(&mut self)

Remove the notice handler.

Source

pub fn set_statement_cache_capacity(&mut self, capacity: usize)

Set the maximum number of statements to cache before LRU eviction.

Source

pub fn raw_fd(&self) -> i32

Return the raw file descriptor for event-loop registration (epoll / kqueue).

Source

pub fn is_nonblocking(&self) -> bool

Check if the socket is in non-blocking mode.

Source

pub fn set_nonblocking(&mut self, nonblocking: bool) -> Result<(), PgError>

Set non-blocking mode on the socket.

Source

pub fn query_simple(&mut self, sql: &str) -> Result<Vec<Row>, PgError>

Execute a simple query (no parameters). Returns all result rows.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn begin(&mut self) -> Result<(), PgError>

Begin a transaction.

Source

pub fn commit(&mut self) -> Result<(), PgError>

Commit the current transaction.

Source

pub fn rollback(&mut self) -> Result<(), PgError>

Rollback the current transaction.

Source

pub fn savepoint(&mut self, name: &str) -> Result<(), PgError>

Create a savepoint.

Source

pub fn rollback_to(&mut self, name: &str) -> Result<(), PgError>

Rollback to a savepoint.

Source

pub fn release_savepoint(&mut self, name: &str) -> Result<(), PgError>

Release a savepoint.

Source

pub fn transaction<F, T>(&mut self, f: F) -> Result<T, PgError>
where F: FnOnce(&mut Transaction<'_>) -> 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(())
})?;
Source

pub fn copy_in(&mut self, sql: &str) -> Result<CopyWriter<'_>, PgError>

Start a COPY FROM STDIN operation.

Source

pub fn copy_out(&mut self, sql: &str) -> Result<CopyReader<'_>, PgError>

Start a COPY TO STDOUT operation. Returns a CopyReader that yields data chunks.

Source

pub fn listen(&mut self, channel: &str) -> Result<(), PgError>

Subscribe to a notification channel.

Source

pub fn notify(&mut self, channel: &str, payload: &str) -> Result<(), PgError>

Send a notification.

Source

pub fn unlisten(&mut self, channel: &str) -> Result<(), PgError>

Unsubscribe from a notification channel.

Source

pub fn unlisten_all(&mut self) -> Result<(), PgError>

Unsubscribe from all notification channels.

Source

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

Drain and return all buffered notifications.

Source

pub fn has_notifications(&self) -> bool

Check if there are buffered notifications.

Source

pub fn notification_count(&self) -> usize

Get the number of buffered notifications.

Source

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.

Source

pub fn transaction_status(&self) -> TransactionStatus

Get the current transaction status.

Source

pub fn cached_statements(&self) -> usize

Get the number of cached statements.

Source

pub fn last_affected_rows(&self) -> u64

Get the number of rows affected by the last command.

Source

pub fn last_command_tag(&self) -> &str

Get the last CommandComplete tag string.

Source

pub fn process_id(&self) -> i32

Get the backend process ID.

Source

pub fn secret_key(&self) -> i32

Get the backend secret key (used for cancel requests).

Source

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

Get server parameters received during startup.

Source

pub fn server_param(&self, name: &str) -> Option<&str>

Get a specific server parameter by name.

Source

pub fn in_transaction(&self) -> bool

Check if the connection is in a transaction.

Source

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.

Source

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).

Source

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.

Source

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);")?;
Source

pub fn is_alive(&mut self) -> bool

Check if the connection is alive by sending a simple query.

Source

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.

Source

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.

Source

pub fn poll_read(&mut self, timeout: Duration) -> Result<usize, PgError>

Poll the socket for readability with a timeout.

Uses the OS poll(2) syscall for efficient, zero-waste waiting. The thread sleeps in the kernel until data arrives or the timeout expires — no busy-loop, no thread::sleep.

Source

pub fn poll_write( &mut self, data: &[u8], timeout: Duration, ) -> Result<(), PgError>

Poll the socket for writability with a timeout. Writes all of data or times out.

Trait Implementations§

Source§

impl Drop for PgConnection

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Executor for PgConnection

Source§

fn execute(&mut self, query: &str, params: &[&dyn ToSql]) -> OrmResult<u64>

Executes a command (e.g., INSERT, UPDATE, DELETE) and returns the number of affected rows.
Source§

fn query(&mut self, query: &str, params: &[&dyn ToSql]) -> OrmResult<Vec<Row>>

Executes a query and returns the resulting rows.

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<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.