transaction()

Atomic database operations: group multiple changes into a single, all-or-nothing transaction for data integrity and reliability.

Overview

The transaction() context manager lets you group multiple database operations into a single atomic unit. Either all changes succeed together, or none are applied if something fails. This is essential for keeping your data safe and consistent.

Why Use Transactions?

  • Data Integrity: Prevents partial updates and keeps your database consistent.
  • Automatic Rollback: If any operation fails, all changes are undone automatically.
  • Business Logic: Ensures complex operations (like money transfers, order processing) are atomic.

Example Usage

Transaction Example
1with db.transaction():
2 user_id = db.insert("users", {"name": "Alice"})
3 db.insert("profiles", {"user_id": user_id})
4 # If any step fails, all changes are rolled back!
5

Real-World Scenarios

  • Money Transfer: Deduct from one account, add to another, log the transaction. If any step fails, no money is lost.
  • Order Processing: Charge customer, reduce inventory, create order record. If payment fails, inventory isn't reduced.
  • User Registration: Create account, profile, send email. If any step fails, no partial user is created.

How It Works

  1. Akron starts a transaction when you enter the with db.transaction() block.
  2. If all operations succeed, changes are committed.
  3. If any operation fails, Akron automatically rolls back all changes.

Best Practices

  • Use transactions for any set of operations that must succeed together.
  • Don't use transactions for simple, single-step reads or writes.

Learn More

See the Basic Usage and Insert API for more examples.