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
71 72 73 74 75 76 77 | |
start
start() -> None
Begin the transaction and push this UnitOfWork onto the context stack.
Source code in src/protean/core/unit_of_work.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
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
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | |
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
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 | |
get_session
get_session(provider_name: str) -> SessionProtocol
Get session for provider, initializing one if it doesn't exist
Source code in src/protean/core/unit_of_work.py
482 483 484 485 486 487 | |