rs-zero 0.2.24

Rust-first microservice framework inspired by go-zero engineering practices
Documentation
use std::{future::Future, pin::Pin};

use crate::db::{DatabasePool, DatabaseResult};

#[cfg(feature = "db-sqlite")]
pub type DatabaseConnection = sqlx::SqliteConnection;

#[cfg(all(not(feature = "db-sqlite"), feature = "db-postgres"))]
pub type DatabaseConnection = sqlx::PgConnection;

#[cfg(all(
    not(feature = "db-sqlite"),
    not(feature = "db-postgres"),
    feature = "db-mysql"
))]
pub type DatabaseConnection = sqlx::MySqlConnection;

/// Runs a function inside a database transaction.
///
/// The operation receives the transaction connection. Returning `Ok` commits
/// the transaction; returning `Err` rolls it back and returns the original
/// error.
pub async fn run_transaction<F, T>(pool: &DatabasePool, operation: F) -> DatabaseResult<T>
where
    F: for<'tx> FnOnce(
        &'tx mut DatabaseConnection,
    ) -> Pin<Box<dyn Future<Output = DatabaseResult<T>> + 'tx>>,
{
    let mut transaction = pool.begin().await?;
    let result = operation(&mut transaction).await;
    match result {
        Ok(value) => {
            transaction.commit().await?;
            Ok(value)
        }
        Err(error) => {
            transaction.rollback().await?;
            Err(error)
        }
    }
}