Skip to main content

Pool

Struct Pool 

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

Connections to one server, for the tasks of one worker thread.

Make one pool per worker, inside giong::Runtime::run: nothing is shared between threads, so nothing is locked.

use giong_postgres::{Config, Pool};

fn main() -> std::io::Result<()> {
    let config = Config::from_url("postgres://app:secret@db.internal/shop")?;
    giong::Builder::new().build()?.run(move |_worker| {
        let pool = Pool::new(config.clone(), 4);
        async move {
            let row = pool.query_one("SELECT count(*) FROM orders", &[]).await.unwrap();
            let n: i64 = row.get(0).unwrap();
            println!("{n} orders");
        }
    })
}

query and the other statement methods do not take a connection for themselves: they run on the least busy connection, beside statements from other tasks (pipelining), and the pool opens another connection, up to its maximum, when every open one is busy. That is the fast path for statements that stand alone. On one connection the server answers in order, so a statement waits for those sent before it; the pool steers new statements away from a connection whose oldest statement has been running for more than 5 ms. Run statements known to be slow (reports, migrations) on a connection of their own, from get.

How many connections. Because statements pipeline, a few connections keep the server busy: start with the server’s cores, shared among the workers’ pools. More than that adds no throughput and raises tail latency, since a backend waiting for a core holds up every statement queued on its connection. Statements that wait on disk or on locks need more.

get takes a connection for one task alone, for a transaction or for session settings. While it is out, no shared statement runs on it. It comes back when the PooledClient is dropped; if a transaction was left open, it is rolled back first.

Connections the server closed, or that broke, are left behind as soon as that is noticed, which is when it happens: each connection is read continuously.

Implementations§

Source§

impl Pool

Source

pub fn new(config: Config, max_size: usize) -> Self

A pool of at most max_size connections to the server in config. Connections are opened when needed, not here.

Size it from the server’s max_connections: the pools of all workers of all processes together must stay below it.

§Panics

Panics if max_size is 0.

Source

pub fn wait_timeout(self, timeout: Duration) -> Self

The longest a task waits for a connection when all max_size are taken: 5 seconds by default. A longer wait fails with ErrorKind::PoolTimeout.

§Panics

Panics if other clones of this pool exist; set it right after new.

Source

pub async fn query( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<Vec<Row>, Error>

Runs a statement on a shared connection and returns its rows; see Client::query.

Source

pub async fn query_one( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<Row, Error>

Runs a statement that returns exactly one row; see Client::query_one.

Source

pub async fn query_opt( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<Option<Row>, Error>

Runs a statement that returns at most one row; see Client::query_opt.

Source

pub async fn execute( &self, sql: &str, params: &[&dyn ToSql], ) -> Result<u64, Error>

Runs a statement and returns the number of rows it changed; see Client::execute.

Source

pub async fn batch_execute(&self, sql: &str) -> Result<(), Error>

Runs several statements without parameters; see Client::batch_execute.

Source

pub async fn get(&self) -> Result<PooledClient, Error>

Takes a connection for this task alone, for a transaction or session settings:

let mut conn = pool.get().await?;
let tx = conn.transaction().await?;
tx.execute("INSERT INTO audit (what) VALUES ($1)", &[&"signup"]).await?;
tx.commit().await?;

Waits up to the wait timeout when every connection is taken or busy and the pool is full.

Source

pub fn stats(&self) -> PoolStats

The pool’s current state and counters.

Trait Implementations§

Source§

impl Clone for Pool

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · 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

Auto Trait Implementations§

§

impl !RefUnwindSafe for Pool

§

impl !Send for Pool

§

impl !Sync for Pool

§

impl !UnwindSafe for Pool

§

impl Forget for Pool

§

impl Freeze for Pool

§

impl Move for Pool

§

impl Unpin for Pool

§

impl UnsafeUnpin 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> 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 = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

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.