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.

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

  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