Transaction¶
Transaction is a context manager that wraps one or more SQL operations
in a single atomic unit: commits on success, rolls back on exception.
Nested with Transaction(model) blocks use PostgreSQL savepoints
automatically — an exception in an inner block rolls back only that scope,
leaving the outer transaction intact.
See Learn halfORM in half an hour for a full walkthrough.
Transaction
¶
Context manager for atomic database operations.
Wraps one or more SQL operations in a single transaction: commits on success, rolls back on exception. Transactions are per-thread and per-model instance.
Nested with Transaction(model) blocks use PostgreSQL savepoints
automatically: an exception in an inner block rolls back only that inner
block, leaving the outer transaction intact.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Model
|
the :class: |
required |
Example
Atomic insert of two related rows:
from half_orm.transaction import Transaction
with Transaction(blog):
alice = Author(
first_name='Alice', last_name='Martin',
email='alice@example.com',
).ho_insert()
Post(
title='First post', content='Hello world',
author_id=alice['id'],
).ho_insert()
# both rows are committed, or neither is
Nested transactions use savepoints:
New in version 0.18.0: nested Transaction blocks use savepoints.