Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a transaction to a function and do a query

I am attempting to use SQLx with SQLite to:

  1. Begin a transaction.
  2. Pass it to a function.
  3. Execute two queries on it within the function.

I am struggling to determine what the function's transaction argument should be, and how to use the transaction within the function.

The only official example I saw concerned PostgreSQL and adapting it to SQLite did not work.

ChatGPT 4 also failed to give me a working example:

// sqlx = { version = "0.7.4", features = ["runtime-tokio-rustls", "sqlite"] }
// tokio = { version = "1.36.0", features = ["full"] }

use sqlx::sqlite::{SqlitePool, Sqlite};
use sqlx::{Pool, Transaction, Error};

async fn execute_query(tx: &mut Transaction<'_, Sqlite>) -> Result<(), Error> {
    sqlx::query("INSERT INTO users (name) VALUES ('Alice')")
        .execute(tx)
        .await?;
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    let pool: Pool<Sqlite> = SqlitePool::connect("sqlite::memory:").await?;
    let mut tx = pool.begin().await?;
    execute_query(&mut tx).await?;
    tx.commit().await?;
    Ok(())
}

Producing this error:

error[E0277]: the trait bound `&mut Transaction<'_, Sqlite>: Executor<'_>` is not satisfied
   --> src\main.rs:9:18
    |
6   |         .execute(tx)
    |          ------- ^^ the trait `Executor<'_>` is not implemented for `&mut Transaction<'_, Sqlite>`
    |          |
    |          required by a bound introduced by this call
    |
    = help: the following other types implement trait `Executor<'c>`:
              <&'c mut SqliteConnection as Executor<'c>>
              <&'c mut AnyConnection as Executor<'c>>
              <&Pool<DB> as Executor<'p>>
like image 971
Noah McIlraith Avatar asked Oct 26 '25 12:10

Noah McIlraith


1 Answers

a pointer to the underlying connection seems to have fixed the identical error for me:

 .execute(&mut **tx)

I get a different error without passing in the mutable reference as well.

like image 79
CleverPatrick Avatar answered Oct 29 '25 03:10

CleverPatrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!