rusttransactionsrust-sqlx

How can I commit() this transaction?


In the below code I'm getting this error:

error[E0599]: no method named `commit` found for mutable reference `&mut sqlx::PgConnection` in the current scope
   --> src/main.rs:103:12
    |
103 |         db.commit().await?;
    |            ^^^^^^ method not found in `&mut PgConnection`

I need to commit if the db is None since I'm starting a new transaction with: &mut self.pool.begin().await?.

It's ok to use db: Option<&mut sqlx::PgConnection> as argument type or should I use something else, like Acquire trait?

Code on Rust Playground

pub async fn find_player_id(
    &self,
    db: Option<&mut sqlx::PgConnection>,
    id: &str,
    team_id: &str,
) -> Result<String, Error> {
    let db = match db {
        Some(db) => db,
        None => &mut self.pool.begin().await?,
    };

    let _ = self.team_service.find_team_id(Some(db), team_id).await?;

    let player_id = self.repo.find_player_id(Some(db), id).await?;

    db.commit().await?;

    Ok(player_id)
}

UPDATE:

Someone on SO closed the question because they think is a duplicate of Why do I need to import a trait to use the methods it defines for a type?.

This is not, I think. Please read the question before taking action.


Solution

  • It is true that a trait must be in scope for its methods to be available. The trait that provides commit is AnyConnectionBackend. However, this trait requires the any feature to be enabled, which you disabled with default-features = false. So simply add feature any to sqlx and then use sqlx::postgres::any::AnyConnectionBackend;. (With any disabled, rust-analyzer could not even find AnyConnectionBackend in order to suggest importing it.)