Trait sqlx::Acquire

source ¡
pub trait Acquire<'c> {
    type Database: Database;
    type Connection: Deref<Target = <Self::Database as Database>::Connection> + DerefMut + Send;

    // Required methods
    fn acquire(
        self
    ) -> Pin<Box<dyn Future<Output = Result<Self::Connection, Error>> + Send + 'c>>;
    fn begin(
        self
    ) -> Pin<Box<dyn Future<Output = Result<Transaction<'c, Self::Database>, Error>> + Send + 'c>>;
}
Expand description

Acquire connections or transactions from a database in a generic way.

If you want to accept generic database connections that implement Acquire which then allows you to acquire a connection or begin a transaction, then you can do it like that:

async fn run_query<'a, A>(conn: A) -> Result<(), BoxDynError>
where
    A: Acquire<'a, Database = Postgres>,
{
    let mut conn = conn.acquire().await?;

    sqlx::query!("SELECT 1 as v").fetch_one(&mut *conn).await?;
    sqlx::query!("SELECT 2 as v").fetch_one(&mut *conn).await?;

    Ok(())
}

If you run into a lifetime error about “implementation of sqlx::Acquire is not general enough”, the workaround looks like this:

fn run_query<'a, 'c, A>(conn: A) -> impl Future<Output = Result<(), BoxDynError>> + Send + 'a
where
    A: Acquire<'c, Database = Postgres> + Send + 'a,
{
    async move {
        let mut conn = conn.acquire().await?;

        sqlx::query!("SELECT 1 as v").fetch_one(&mut *conn).await?;
        sqlx::query!("SELECT 2 as v").fetch_one(&mut *conn).await?;

        Ok(())
    }
}

However, if you really just want to accept both, a transaction or a connection as an argument to a function, then it’s easier to just accept a mutable reference to a database connection like so:

async fn run_query(conn: &mut PgConnection) -> Result<(), BoxDynError> {
    sqlx::query!("SELECT 1 as v").fetch_one(&mut *conn).await?;
    sqlx::query!("SELECT 2 as v").fetch_one(&mut *conn).await?;

    Ok(())
}

The downside of this approach is that you have to acquire a connection from a pool first and can’t directly pass the pool as argument.

Required Associated Types§

Required Methods§

source

fn acquire( self ) -> Pin<Box<dyn Future<Output = Result<Self::Connection, Error>> + Send + 'c>>

source

fn begin( self ) -> Pin<Box<dyn Future<Output = Result<Transaction<'c, Self::Database>, Error>> + Send + 'c>>

Implementors§

source§

impl<'a, DB> Acquire<'a> for &Pool<DB>
where DB: Database,

source§

impl<'c> Acquire<'c> for &'c mut AnyConnection

source§

impl<'c> Acquire<'c> for &'c mut MySqlConnection

source§

impl<'c> Acquire<'c> for &'c mut PgConnection

source§

impl<'c> Acquire<'c> for &'c mut SqliteConnection

source§

impl<'c, 't, DB> Acquire<'t> for &'t mut Transaction<'c, DB>
where DB: Database,

§

type Database = DB

§

type Connection = &'t mut <DB as Database>::Connection

source§

impl<'c, DB> Acquire<'c> for &'c mut PoolConnection<DB>
where DB: Database,

§

type Database = DB

§

type Connection = &'c mut <DB as Database>::Connection