1use crate::database::connection::DatabasePool;
2use crate::database::transaction::Transaction;
3
4pub struct DB;
6
7impl DB {
8 pub async fn begin(pool: &DatabasePool) -> Result<Transaction, sqlx::Error> {
11 pool.begin().await
12 }
13
14 pub async fn begin_transaction(pool: &DatabasePool) -> Result<Transaction, sqlx::Error> {
16 pool.begin_transaction().await
17 }
18
19 pub async fn transaction<F, Fut, R, E>(pool: &DatabasePool, callback: F) -> Result<R, E>
21 where
22 F: FnOnce(Transaction) -> Fut,
23 Fut: std::future::Future<Output = Result<R, E>>,
24 E: From<sqlx::Error>,
25 {
26 let tx = pool.begin().await?;
27 let res = callback(tx.clone()).await;
28 match res {
29 Ok(val) => {
30 tx.commit().await?;
31 Ok(val)
32 }
33 Err(err) => {
34 let _ = tx.rollback().await;
35 Err(err)
36 }
37 }
38 }
39}
40