Skip to main content

transaction

Function transaction 

Source
pub async fn transaction<'a, T, F, Fut>(
    pool: &PgPool,
    f: F,
) -> TransactionResult<T>
where F: FnOnce(&mut Transaction) -> Fut, Fut: Future<Output = Result<T, TransactionError>> + 'a,
Expand description

Execute a function within a transaction

This helper function automatically begins a transaction, executes the provided function, and commits the transaction if it returns Ok, or rolls back if it returns Err.

§Arguments

  • pool - The database connection pool
  • f - The async function to execute within the transaction

§Returns

The result of the function, or a transaction error

§Example

use ormkit::transaction::transaction;

let result = transaction(pool, |tx| async move {
    sqlx::query("INSERT INTO users (name) VALUES ($1)")
        .bind("John")
        .execute(&mut *tx)
        .await?;

    Ok(42)
}).await?;

assert_eq!(result, 42);