UnitOfWork
Transaction boundary for persistence operations. Used as a context manager to group multiple repository operations into a single atomic transaction.
See Unit of Work guide for practical usage.
Transaction boundary for persistence operations.
Groups one or more repository operations into an atomic unit. Use as a context manager to ensure that all changes within the block are committed together or rolled back on error::
with UnitOfWork():
repo = domain.repository_for(Order)
order = repo.get(order_id)
order.confirm()
repo.add(order)
Command handlers and the @use_case decorator wrap their execution in a
UnitOfWork automatically, so explicit usage is typically only needed in
application services or scripts.
The UnitOfWork maintains an identity map to track loaded aggregates and collects domain events raised during the transaction. On commit, events are persisted to the outbox and dispatched to brokers/event store.
Source code in src/protean/core/unit_of_work.py
42 43 44 45 46 47 48 | |
start
start() -> None
Begin the transaction and push this UnitOfWork onto the context stack.
Source code in src/protean/core/unit_of_work.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | |
commit
commit() -> None
Commit all changes, persist outbox messages, and dispatch events.
| RAISES | DESCRIPTION |
|---|---|
InvalidOperationError
|
If the UnitOfWork is not in progress. |
ExpectedVersionError
|
On optimistic concurrency conflict. |
TransactionError
|
If the underlying database commit fails. |
Source code in src/protean/core/unit_of_work.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
rollback
rollback() -> None
Roll back all changes and close sessions.
| RAISES | DESCRIPTION |
|---|---|
InvalidOperationError
|
If the UnitOfWork is not in progress. |
Source code in src/protean/core/unit_of_work.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | |
get_session
get_session(provider_name)
Get session for provider, initializing one if it doesn't exist
Source code in src/protean/core/unit_of_work.py
386 387 388 389 390 391 | |