Skip to content

Unit of work

AbstractDatabaseUnitOfWork

Bases: UnitOfWorkProtocol, ABC

Abstract unit of work for working with a repository.

  • Changes to the repository should only be committed at the end of the unit of work.
  • Nested units of work share the same context (so that multiple units of work can be combined and all succeed for rollback together).

repository instance-attribute

__aenter__() async

Only enter context once even if multiple async with blocks are used.

This allows for a single uow to be used for multiple operations that would otherwise be their own standalone uows.

Examples:

async def combined_service(schema1, schema2, uow):
    async with uow:
        await create_service(schema1, uow)
        await create_service(schema2, uow)

Only one commit/rollback will be called at the end of the block even though each individual service call also uses an async with block.

__aexit__(exc_type, exc_val, exc_tb) async

__init__()

commit() abstractmethod async

Commit the unit of work.

rollback() abstractmethod async

Rollback any changes during the unit of work context.

SessionDatabaseUnitOfWork

Bases: AbstractDatabaseUnitOfWork, ABC

Abstract class for a repository unit of work that uses a database session.

repository_class abstractmethod property

Note: Can be overridden as ClassVar.

e.g.

    class MyUnitOfWork(SessionDatabaseUnitOfWork):
        repository_class: ClassVar[RepositoryWithSessionInit] = MyRepository

session_factory = session_maker instance-attribute

__init__(session_maker)

commit() async

flush() async

rollback() async