Skip to main content

TransactionManager

Trait TransactionManager 

Source
pub trait TransactionManager: Send + Sync {
    type Context: Send;

    // Required method
    fn transaction<F, Fut, R>(
        &self,
        f: F,
    ) -> BoxFuture<'_, Result<R, RepoError>>
       where F: FnOnce(Self::Context) -> Fut + Send + 'static,
             Fut: Future<Output = Result<R, RepoError>> + Send + 'static,
             R: Send + 'static;
}
Expand description

Trait for managing transactional boundaries across repository operations.

This allows services to coordinate multiple repository calls within a single database transaction without coupling to a specific persistence backend.

Note: TransactionManager is not object-safe because transaction has generic type parameters. Use a concrete type or a trait alias when dynamic dispatch is needed.

§Example

async fn transfer<TM: TransactionManager>(
    tm: &TM,
    amount: u64,
) -> Result<(), RepoError> {
    tm.transaction(|ctx| async move {
        // Obtain transaction-scoped repositories from `ctx` (backend-specific).
        let from_repo = ctx.from_account_repo();
        let to_repo = ctx.to_account_repo();
        let mut from = from_repo.find_by_id(1).await?;
        let mut to = to_repo.find_by_id(2).await?;
        from.balance -= amount;
        to.balance += amount;
        from_repo.update(from).await?;
        to_repo.update(to).await?;
        Ok(())
    }).await
}

Required Associated Types§

Source

type Context: Send

Opaque handle passed to transaction closures.

Implementations expose transaction-scoped repositories or connections through this type so writes inside the closure participate in the open transaction.

Required Methods§

Source

fn transaction<F, Fut, R>(&self, f: F) -> BoxFuture<'_, Result<R, RepoError>>
where F: FnOnce(Self::Context) -> Fut + Send + 'static, Fut: Future<Output = Result<R, RepoError>> + Send + 'static, R: Send + 'static,

Execute the given closure within a transactional boundary.

The closure receives an owned Context. Use it to obtain transaction-scoped repositories so all writes share the same connection and roll back together on error.

If the closure returns Ok, the transaction is committed. If it returns Err or panics, the transaction is rolled back.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§