Struct sfo_sql::SqlPool

source ·
pub struct SqlPool<EM: ErrorMap<InError = Error>> { /* private fields */ }

Implementations§

source§

impl<EM: 'static + ErrorMap<InError = Error>> SqlPool<EM>

source

pub fn from_raw_pool(pool: RawSqlPool) -> Self

source

pub async fn open(uri: &str, max_connections: u32) -> Result<Self, EM::OutError>

source

pub async fn raw_pool(&self) -> RawSqlPool

source

pub async fn get_conn(&self) -> Result<SqlConnection<EM>, EM::OutError>

Methods from Deref<Target = RawSqlPool>§

pub fn acquire( &self ) -> impl Future<Output = Result<PoolConnection<DB>, Error>> + 'static

Retrieves a connection from the pool.

Waits for at most the configured connection timeout before returning an error.

pub fn try_acquire(&self) -> Option<PoolConnection<DB>>

Attempts to retrieve a connection from the pool if there is one available.

Returns None immediately if there are no idle connections available in the pool.

pub async fn begin(&self) -> Result<Transaction<'static, DB>, Error>

Retrieves a new connection and immediately begins a new transaction.

pub async fn try_begin(&self) -> Result<Option<Transaction<'static, DB>>, Error>

Attempts to retrieve a new connection and immediately begins a new transaction if there is one available.

pub async fn close(&self)

Shut down the connection pool, waiting for all connections to be gracefully closed.

Upon .awaiting this call, any currently waiting or subsequent calls to [Pool::acquire] and the like will immediately return [Error::PoolClosed] and no new connections will be opened.

Any connections currently idle in the pool will be immediately closed, including sending a graceful shutdown message to the database server, if applicable.

Checked-out connections are unaffected, but will be closed in the same manner when they are returned to the pool.

Does not resolve until all connections are returned to the pool and gracefully closed.

Note: async fn

Because this is an async fn, the pool will not be marked as closed unless the returned future is polled at least once.

If you want to close the pool but don’t want to wait for all connections to be gracefully closed, you can do pool.close().now_or_never(), which polls the future exactly once with a no-op waker.

pub fn is_closed(&self) -> bool

Returns true if [.close()][Pool::close] has been called on the pool, false otherwise.

pub fn close_event(&self) -> CloseEvent

Get a future that resolves when [Pool::close()] is called.

If the pool is already closed, the future resolves immediately.

This can be used to cancel long-running operations that hold onto a [PoolConnection] so they don’t prevent the pool from closing (which would otherwise wait until all connections are returned).

Examples

These examples use Postgres and Tokio, but should suffice to demonstrate the concept.

Do something when the pool is closed:

use sqlx::PgPool;

let pool = PgPool::connect("postgresql://...").await?;

let pool2 = pool.clone();

tokio::spawn(async move {
    // Demonstrates that `CloseEvent` is itself a `Future` you can wait on.
    // This lets you implement any kind of on-close event that you like.
    pool2.close_event().await;

    println!("Pool is closing!");

    // Imagine maybe recording application statistics or logging a report, etc.
});

// The rest of the application executes normally...

// Close the pool before the application exits...
pool.close().await;

Cancel a long-running operation:

use sqlx::{Executor, PgPool};

let pool = PgPool::connect("postgresql://...").await?;

let pool2 = pool.clone();

tokio::spawn(async move {
    pool2.close_event().do_until(async {
        // This statement normally won't return for 30 days!
        // (Assuming the connection doesn't time out first, of course.)
        pool2.execute("SELECT pg_sleep('30 days')").await;

        // If the pool is closed before the statement completes, this won't be printed.
        // This is because `.do_until()` cancels the future it's given if the
        // pool is closed first.
        println!("Waited!");
    }).await;
});

// This normally wouldn't return until the above statement completed and the connection
// was returned to the pool. However, thanks to `.do_until()`, the operation was
// cancelled as soon as we called `.close().await`.
pool.close().await;

pub fn size(&self) -> u32

Returns the number of connections currently active. This includes idle connections.

pub fn num_idle(&self) -> usize

Returns the number of connections active and idle (not in use).

This will block until the number of connections stops changing for at least 2 atomic accesses in a row. If the number of idle connections is changing rapidly, this may run indefinitely.

Trait Implementations§

source§

impl<EM: Clone + ErrorMap<InError = Error>> Clone for SqlPool<EM>

source§

fn clone(&self) -> SqlPool<EM>

Returns a copy 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<EM: ErrorMap<InError = Error>> Deref for SqlPool<EM>

§

type Target = Pool<MySql>

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.

Auto Trait Implementations§

§

impl<EM> !RefUnwindSafe for SqlPool<EM>

§

impl<EM> Send for SqlPool<EM>

§

impl<EM> Sync for SqlPool<EM>

§

impl<EM> Unpin for SqlPool<EM>
where EM: Unpin,

§

impl<EM> !UnwindSafe for SqlPool<EM>

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.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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

§

type Output = T

Should always be Self
source§

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

§

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

§

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

§

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

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more