axum_webtools/db/
sqlx.rs

1use scoped_futures::ScopedBoxFuture;
2use sqlx::{Database, Pool, Transaction};
3
4pub async fn with_tx<'a, F, R, E, DB>(pool: &Pool<DB>, callback: F) -> Result<R, E>
5where
6    F: for<'r> FnOnce(&'r mut Transaction<DB>) -> ScopedBoxFuture<'a, 'r, Result<R, E>>
7        + Send
8        + 'a + 'static,
9    E: From<sqlx::Error> + Send + 'a,
10    R: Send + 'a,
11    DB: Database,
12{
13    let mut tx = pool.begin().await?;
14    let res = callback(&mut tx).await;
15    match res {
16        Ok(response) => {
17            tx.commit().await?;
18            Ok(response)
19        }
20        Err(e) => {
21            tx.rollback().await?;
22            Err(e)
23        }
24    }
25}