Skip to content

Chapter 6 Excercise for the Reader: Separate UoW and Context Manager #47

Description

@chrisgrf

experiment with separating the UoW (whose responsibilities are
commit() , rollback() , and providing the .batches repository) from the
context manager, whose job is to initialize things, and then do the commit
or rollback on exit.

Could someone give a solution for this exercise?

Following is my code example. Would there be a point in splitting FakeUnitOfWork?

src/allocation/service_layer/unit_of_work.py

class AbstractUnitOfWork(abc.ABC):
    batches: repository.AbstractRepository
    
    @abc.abstractmethod
    def commit(self):
        raise NotImplementedError

    @abc.abstractmethod
    def rollback(self):
        raise NotImplementedError


DEFAULT_SESSION_FACTORY = sessionmaker(
    bind=create_engine(
        config.get_postgres_uri(),
    )
)


class SQLAlchemyUoWContextManager:
    def __init__(self, session_factory=DEFAULT_SESSION_FACTORY):
        self.session_factory = session_factory

    def __enter__(self):
        self.session: Session = self.session_factory()
        self.uow = SqlAlchemyUnitOfWork(session=self.session)
        return self.uow

    def __exit__(self, *args):
        self.uow.rollback()
        self.session.close()


class SqlAlchemyUnitOfWork(AbstractUnitOfWork):
    def __init__(self, session: Session):
        self.session = session
        self.batches = repository.SqlAlchemyRepository(self.session)

    def commit(self):
        self.session.commit()

    def rollback(self):
        self.session.rollback()

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions