Closed tgy3300 closed 1 month ago
the lifetime issue that I am hitting after fixing the dereferencing issue (.execute(&mut *txn)
) in your example is a bit tricky and I have not really found a way to tell the borrow checker that the lifetimes are actually fine.
The following would be how I could get around this
#[cfg(test)]
mod tests {
use sqlx::MySql;
use sqlx::MySqlPool;
use sqlx::Transaction;
use std::future::Future;
use sqlx::Error;
async fn execute_transaction<'a,'tx:'a,F, Fut>(
conn: MySqlPool,
f: F,
) -> Result<(), Error>
where
F: FnOnce(Transaction<'tx, MySql>) -> Fut,
Fut: Future<Output = Result<(), Error>> {
let txn = conn.begin().await?;
f(txn).await
}
#[tokio::test]
async fn test_fn() -> anyhow::Result<()> {
let conn = MySqlPool::connect("url").await?;
execute_transaction(conn, |mut txn| async move {
let _r1 = sqlx::query("DELETE FROM blog WHERE id = ?")
.bind("aaa")
.execute(&mut *txn)
.await?
.rows_affected();
txn.commit().await
})
.await?;
Ok(())
}
}
Because the API with the closures is not really better without explicite support, I think you might be better off by just doing it explcitely https://github.com/launchbadge/sqlx/blob/19f40d87a669e41081a629a469359d341c9223d6/examples/postgres/transaction/src/main.rs#L52-L63
Issues are not for asking for support with your own code. Please use Discussions or Discord.
Report an error: