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.
Basic Transaction (Callback)
Use db.transaction() with a callback function. All operations executed through the transaction client succeed or rollback together:
def transfer_workflow(tx):
tx.account.update(
where={"id": sender_id},
data={"balance": {"decrement": amount}}
)
tx.account.update(
where={"id": receiver_id},
data={"balance": {"increment": amount}}
)
# Automatically commits on return, rolls back if an exception is raised
db.transaction(transfer_workflow)
Lambda Transaction
For concise single- or two-step operations:
db.transaction(lambda tx: tx.user.create({
"data": {"email": "alice@example.com", "name": "Alice"}
}))
Exception Handling and Rollback
try:
def failing_action(tx):
tx.user.create({"data": {"email": "bob@example.com"}})
raise RuntimeError("Validation failure: reverting transaction")
db.transaction(failing_action)
except RuntimeError as err:
print(f"Transaction safely rolled back: {err}")
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