blob: 3ba00cba42c4f4581ccafe10a95759f169a7a4dc (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
#needs-clarification
The Unit of Work is an abstraction of the concept of atomic operations. We can have a clear boundary on what work is grouped together and should be committed only if everything succeeded.
We can use the UoW to remove dependency on storage layer from entrypoints by having the UoW manage the set-up. This makes tests easier.
For example an SqlAlchemyUoW can wrap an SqlAlchemy Session object and expose only its most thin API: commit and rollback. It can work together as well with a [[022920240901 - Repository Pattern|Repository]]. Using a ContextManager we can make the operations safe by only explicitly having the user of the UoW commit and otherwise when exiting do a rollback:
```py
import abc
class AbstractUnitOfWork(abc.ABC):
products: AbstractRepository
def __init__(self, products: AbstractRepository):
self.products = products
def __exit__(self):
self.rollback()
@abc.abstractmethod
def commit(self):
pass
@abc.abstractmethod
def rollback(self):
pass
class SqlAlchemyUnitOfWork(AbstractUnitOfWork):
def __init__(self, products: AbstractRepository, sessionmaker):
self._session = sessionmaker()
super().__init__(some_repo)
def commit(self):
self._session.commit()
def rollback(self):
self._session.rollback()
```
|