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

    fn acquire(self) -> BoxFuture<'c, Result<Self::Connection, Error>>;
    fn begin(
        self
    ) -> BoxFuture<'c, Result<Transaction<'c, Self::Database>, Error>>; }
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