Transactions

an5 ORM supports transactions to ensure data consistency when performing multiple related operations.

Sqlite note: SQLite uses file-level locking with BEGIN IMMEDIATE to avoid write deadlocks. In-memory databases support transactions within the connection lifetime.

Asynchronous Transaction in Rust

The Rust adapter runtime executes closures within an isolated transaction scope:

use an5_adapters::An5Adapter;
use anyhow::Result;

async fn execute_atomic_flow(adapter: &An5Adapter) -> Result<()> {
    adapter.transaction(|conn| async move {
        // Operations executed on the transaction connection
        sqlx::query("UPDATE accounts SET balance = balance - ? WHERE id = ?")
            .bind(100)
            .bind("acc-1")
            .execute(&mut *conn)
            .await?;

        sqlx::query("UPDATE accounts SET balance = balance + ? WHERE id = ?")
            .bind(100)
            .bind("acc-2")
            .execute(&mut *conn)
            .await?;

        Ok(()) // Commits on Ok(()), rolls back on Err
    }).await?;

    Ok(())
}

Best Practices

  1. Keep transactions short - Minimize the time table rows are locked to avoid blocking concurrent queries.
  2. Handle errors properly - Always handle potential deadlock or timeout exceptions in application code.
  3. Consistent ordering - Always update tables and records in a deterministic order across all endpoints to prevent database deadlocks.
  4. Choose the appropriate isolation level - Tailor the transaction isolation according to concurrency and consistency requirements.

Next Steps