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 (Scoped)

let user = try db.transaction {
    let created = try db.user.create(User(email: "john@example.com", name: "John"))
    try db.order.create(Order(userId: created.id, total: 100))
    return created
}

The closure returns the transaction’s value and commits when it returns; a thrown error rolls it back first. It is handed the adapter for raw SQL, but the typed handles on db share the same connection, so they are part of the transaction too. Nested transaction calls are rejected rather than flattened.

Error Handling and Rollback

import Foundation

do {
    try db.transaction { (_: An5Adapter) throws -> Void in
        _ = try db.user.create(User(email: "john@example.com", name: "First"))
        throw NSError(domain: "example.rollback", code: 1)
    }
} catch {
    // the insert above was discarded with the transaction
}

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