Skip to main content

rs_zero/db/
transaction.rs

1use std::{future::Future, pin::Pin};
2
3use crate::db::{DatabasePool, DatabaseResult};
4
5#[cfg(feature = "db-sqlite")]
6pub type DatabaseConnection = sqlx::SqliteConnection;
7
8#[cfg(all(not(feature = "db-sqlite"), feature = "db-postgres"))]
9pub type DatabaseConnection = sqlx::PgConnection;
10
11#[cfg(all(
12    not(feature = "db-sqlite"),
13    not(feature = "db-postgres"),
14    feature = "db-mysql"
15))]
16pub type DatabaseConnection = sqlx::MySqlConnection;
17
18/// Runs a function inside a database transaction.
19///
20/// The operation receives the transaction connection. Returning `Ok` commits
21/// the transaction; returning `Err` rolls it back and returns the original
22/// error.
23pub async fn run_transaction<F, T>(pool: &DatabasePool, operation: F) -> DatabaseResult<T>
24where
25    F: for<'tx> FnOnce(
26        &'tx mut DatabaseConnection,
27    ) -> Pin<Box<dyn Future<Output = DatabaseResult<T>> + 'tx>>,
28{
29    let mut transaction = pool.begin().await?;
30    let result = operation(&mut transaction).await;
31    match result {
32        Ok(value) => {
33            transaction.commit().await?;
34            Ok(value)
35        }
36        Err(error) => {
37            transaction.rollback().await?;
38            Err(error)
39        }
40    }
41}