Skip to main content

pakem/database/
facade.rs

1use crate::database::connection::DatabasePool;
2use crate::database::transaction::Transaction;
3
4/// Facade `DB` bergaya Laravel untuk akses database dan transaksi cepat tanpa repot.
5pub struct DB;
6
7impl DB {
8    /// Mulai transaksi database baru (ACID Transaction) menggunakan pool yang diberikan.
9    /// Contoh: `let tx = DB::begin(req.db()).await?;`
10    pub async fn begin(pool: &DatabasePool) -> Result<Transaction, sqlx::Error> {
11        pool.begin().await
12    }
13
14    /// Alias untuk `begin()`
15    pub async fn begin_transaction(pool: &DatabasePool) -> Result<Transaction, sqlx::Error> {
16        pool.begin_transaction().await
17    }
18
19    /// Jalankan blok transaksi otomatis (Commit jika Ok, Rollback otomatis jika Err).
20    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