Transactions
an5 ORM supports transactions to ensure data consistency when performing multiple related operations.
Mysql note: MySQL (InnoDB engine) enforces full ACID compliance and row-level locking during active transactions.
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
- Keep transactions short - Minimize the time table rows are locked to avoid blocking concurrent queries.
- Handle errors properly - Always handle potential deadlock or timeout exceptions in application code.
- Consistent ordering - Always update tables and records in a deterministic order across all endpoints to prevent database deadlocks.
- Choose the appropriate isolation level - Tailor the transaction isolation according to concurrency and consistency requirements.
Next Steps
- Advanced Queries - Filter, sort, and paginate data
- Relations & Joins - Model relational data integrity