Search code examples
rustrust-sqlx

Why does mutably borrowing fix an expected trait implementation?


I am using rust sqlx and I am getting a connection from my DB pool for my query:

POOL: OnceCell<Pool<Postgres>> = OnceCell::new();

pub async fn get_connection() -> PoolConnection<Postgres> {
    POOL.get().unwrap().acquire().await.unwrap()
}

pub async fn fetch_users() -> Result<Vec<User>> {
    let result = sqlx::query_as!(User,
        r#"SELECT * FROM users"#)
        .fetch_all(get_connection().await).await?;
        Ok(result)
}

But get_connection().await is giving me an error:

the trait bound `sqlx::pool::PoolConnection<sqlx::Postgres>: sqlx::Executor<'_>` is not satisfied expected an implementor of trait `sqlx::Executor<'_>`

The compiler is telling me to fix by using consider mutably borrowing here: `&mut` which works fine when I change to &mut get_connection().await.

I don't understand why this fixes the issue. Can anyone explain?


Solution

  • Looking at the implementations for sqlx::Executor, all of them are on some &mut T type. It is implemented for &mut PoolConnection<Postgres> but not PoolConnection<Postgres>.

    Adding &mut changes it from passing a PoolConnection<Postgres> into a &mut PoolConnection<Postgres>. This is required since Rust does not auto-borrow function parameters.