kegani 0.1.1

A developer-friendly, ergonomic, production-ready Rust web framework
Documentation
//! Transaction wrapper for Kegani
//!
//! Provides automatic commit/rollback for database transactions.

use sqlx::{PgPool, postgres::PgTransaction};

/// Transaction wrapper with automatic management
pub struct Transaction {
    inner: Option<PgTransaction<'static>>,
}

impl Transaction {
    /// Commit the transaction
    pub async fn commit(mut self) -> Result<(), sqlx::Error> {
        if let Some(tx) = self.inner.take() {
            tx.commit().await?;
        }
        Ok(())
    }

    /// Rollback the transaction
    pub async fn rollback(mut self) -> Result<(), sqlx::Error> {
        if let Some(tx) = self.inner.take() {
            tx.rollback().await?;
        }
        Ok(())
    }

    /// Get the transaction reference
    pub fn inner_mut(&mut self) -> Option<&mut PgTransaction<'static>> {
        self.inner.as_mut()
    }
}

impl Drop for Transaction {
    fn drop(&mut self) {
        // If not explicitly committed/rolled back, rollback by default
        if self.inner.is_some() {
            tracing::warn!("Transaction dropped without explicit commit/rollback");
        }
    }
}

/// Transaction helper for automatic commit on success
pub async fn with_transaction<F, T>(pool: &PgPool, f: F) -> Result<T, sqlx::Error>
where
    F: FnOnce(&mut PgTransaction<'_>) -> Result<T, sqlx::Error>,
{
    let mut tx = pool.begin().await?;

    match f(&mut tx) {
        Ok(result) => {
            tx.commit().await?;
            Ok(result)
        }
        Err(e) => {
            tx.rollback().await?;
            Err(e)
        }
    }
}