API Reference
async_atomic

dbzero.async_atomic()

dbzero-procommercial edition

async with dbzero.async_atomic() as atomic_context:

The async_atomic() method provides an asyncio-aware context manager for grouping dbzero mutations into a single atomic operation. It is the supported atomic API for code running inside asyncio tasks.

Like dbzero.atomic(), successful exit stages all changes together, while exceptions or explicit cancellation roll the changes back. Unlike synchronous atomic(), concurrent async atomic blocks wait cooperatively instead of blocking the event loop.


Parameters

This method takes no parameters.


Yields

  • atomic_context (optional): An object with .cancel(), which discards all changes made within the current async atomic block.

Side Effects

  • Groups Mutations: Temporarily holds creations, updates, deletions, tag changes, and collection mutations made inside the async with block.
  • Serializes Async Tasks: Concurrent async_atomic() blocks in the same event loop wait for each other with an asyncio lock.
  • Rolls Back on Failure: Reverts all changes if an exception is raised or .cancel() is called.
  • Protects the Event Loop: Unguarded dbzero mutations from another async task may raise while an async atomic block is active.

Errors

  • Raises RuntimeError if called without a running asyncio task.
  • Regular dbzero.atomic() raises RuntimeError when entered from an asyncio task; use dbzero.async_atomic() instead.

Examples

Grouping Successful Async Operations

async def approve(document, audit_log):
    async with db0.async_atomic():
        document.status = "approved"
        audit_log.append(("approved", document.id))
        await notify_reviewers(document)
        document.review_notified = True

Automatic Rollback on Exception

async def update_with_validation(obj):
    try:
        async with db0.async_atomic():
            obj.value = 200
            await validate_remote_state(obj)
            raise ValueError("rollback")
    except ValueError:
        pass
 
    # The object's value is unchanged.
    assert obj.value != 200

Manual Rollback with cancel()

async def reserve_inventory(item, quantity):
    async with db0.async_atomic() as atomic:
        item.reserved += quantity
        await check_payment_hold()
 
        if item.reserved > item.available:
            atomic.cancel()
            return False
 
    return True

Nested Async Atomic Blocks

Nested async_atomic() blocks in the same task are allowed. Cancelling an inner block rolls back only the inner changes.

async with db0.async_atomic():
    order.status = "processing"
 
    async with db0.async_atomic() as inner:
        order.status = "failed"
        inner.cancel()
 
    assert order.status == "processing"

Use dbzero.atomic() for synchronous code and dbzero.async_atomic() for asyncio task code. Both APIs stage successful changes into the surrounding transaction, which is then committed manually with dbzero.commit() or by autocommit.