Skip to main content

Pool

Struct Pool 

Source
pub struct Pool { /* private fields */ }
Expand description

A PostgreSQL connection pool.

Created via Pool::connect or Pool::builder. The pool manages a set of connections, automatically acquires/releases them for each query, and supports optional read/write splitting with a replica.

§Example

use bsql::Pool;

let pool = Pool::connect("postgres://user:pass@localhost/mydb")?;

// Or configure via builder:
let pool = Pool::builder()
    .url("postgres://user:pass@localhost/mydb")
    .lifetime_secs(900)
    .timeout_secs(5)
    .build()?;

Implementations§

Source§

impl Pool

Source

pub async fn connect(url: &str) -> BsqlResult<Self>

Connect to PostgreSQL using a connection URL.

Creates the pool (parses URL, allocates pool structures). Actual TCP/UDS connections are established lazily on first acquire().

Format: postgres://user:password@host:port/dbname

Source

pub fn builder() -> PoolBuilder

Create a pool builder for fine-grained configuration.

Source

pub async fn acquire(&self) -> BsqlResult<PoolConnection>

Acquire a connection from the pool.

Fail-fast: returns BsqlError::Pool immediately if no connections are available (unless acquire_timeout is configured).

Source

pub async fn begin(&self) -> BsqlResult<Transaction>

Begin a new transaction.

Acquires a connection and sends BEGIN immediately.

Source

pub async fn query_stream( &self, sql: &str, sql_hash: u64, params: &[&(dyn Encode + Sync)], ) -> BsqlResult<QueryStream>

Execute a query and return a stream of rows.

Acquires a connection from the pool and returns a QueryStream that holds the connection alive until the stream is consumed or dropped.

Uses true PG-level streaming via Execute(max_rows=64). Only 64 rows are in memory at a time. The stream fetches additional chunks on demand via the PortalSuspended / re-Execute protocol.

Source

pub fn set_warmup_sqls<S: Into<Box<str>>>( &self, sqls: impl IntoIterator<Item = S>, )

Set the SQL statements to pre-PREPARE on new connections.

Each SQL string is PREPAREd on new connections before they are returned from acquire(). This eliminates first-use Parse overhead for hot queries.

Warmup errors are silently ignored — a bad warmup SQL does not prevent the connection from being usable.

Source

pub async fn raw_query(&self, sql: &str) -> BsqlResult<Vec<RawRow>>

Execute arbitrary SQL and return text rows.

Uses PostgreSQL’s simple query protocol — all values returned as strings. This bypasses bsql’s compile-time SQL validation entirely.

Use for DDL, ad-hoc queries, migrations, or the rare dynamic SQL that cannot be expressed via query!. For type-safe queries, use query!.

Source

pub async fn raw_execute(&self, sql: &str) -> BsqlResult<()>

Execute arbitrary SQL without returning rows.

Uses PostgreSQL’s simple query protocol. Useful for DDL (CREATE TABLE, ALTER, DROP), SET commands, or any statement where you don’t need results.

Source

pub async fn copy_in<'a, I>( &self, table: &str, columns: &[&str], rows: I, ) -> BsqlResult<u64>
where I: IntoIterator<Item = &'a str>,

Bulk copy data INTO a table from an iterator of text rows.

Each row is a tab-separated string (TSV format, matching PostgreSQL’s default COPY text format). Returns the number of rows copied.

This is 10-100x faster than individual INSERTs for bulk data loading.

§Example
let rows = vec!["alice\talice@example.com", "bob\tbob@example.com"];
let count = pool.copy_in("users", &["name", "email"], rows.iter().map(|s| s.as_str())).await?;
Source

pub async fn copy_out<W: Write>( &self, query: &str, writer: &mut W, ) -> BsqlResult<u64>

Bulk copy data OUT of a table or query result to a writer.

Data is written in PostgreSQL’s text format (tab-separated columns, newline-terminated rows). Returns the number of rows copied.

§Example
let mut buf = Vec::new();
let count = pool.copy_out("SELECT name, email FROM users", &mut buf).await?;
Source

pub fn status(&self) -> PoolStatus

Pool status metrics: idle, active, open, and max_size.

Returns detailed pool utilization metrics from the driver.

Source

pub fn close(&self)

Gracefully close the pool (and replica pool if configured).

No new connections can be acquired after this call. All idle connections are closed immediately. Active connections are closed when returned to the pool.

Source

pub fn is_closed(&self) -> bool

Whether the pool has been closed.

Source

pub fn has_replica(&self) -> bool

Whether a read replica pool is configured.

Source

pub fn is_uds(&self) -> bool

Whether this pool uses sync connections via Unix domain sockets.

When true, the pool automatically uses SyncConnection (blocking I/O) internally, eliminating async overhead for sub-microsecond UDS I/O. The user API is identical — this is purely a performance optimization.

Source

pub async fn for_each_raw<F>( &self, sql: &str, sql_hash: u64, params: &[&(dyn Encode + Sync)], readonly: bool, f: F, ) -> BsqlResult<()>
where F: FnMut(PgDataRow<'_>) -> BsqlResult<()>,

Process each row directly from the wire buffer via a closure.

Acquires a connection, calls Connection::for_each, and releases. Zero arena allocation — the closure reads columns directly from the DataRow message bytes.

When readonly is true and a replica pool is configured, routes to the replica pool; otherwise uses the primary.

Trait Implementations§

Source§

impl Clone for Pool

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Pool

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a> From<&'a Pool> for QueryTarget<'a>

Source§

fn from(pool: &'a Pool) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for Pool

§

impl RefUnwindSafe for Pool

§

impl Send for Pool

§

impl Sync for Pool

§

impl Unpin for Pool

§

impl UnsafeUnpin for Pool

§

impl UnwindSafe for Pool

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.