pub trait Acquire<'c> {
    type Database: Database;
    type Connection: Deref + DerefMut + Send
   where
        <Self::Connection as Deref>::Target == <Self::Database as Database>::Connection
; fn acquire(
        self
    ) -> Pin<Box<dyn Future<Output = Result<Self::Connection, Error>> + Send + 'c, Global>>; fn begin(
        self
    ) -> Pin<Box<dyn Future<Output = Result<Transaction<'c, Self::Database>, Error>> + Send + 'c, Global>>; }
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

Implementors