summaryrefslogtreecommitdiff
path: root/Zettelkast/Notes/290220241458 - Unit of Work pattern.md
diff options
context:
space:
mode:
Diffstat (limited to 'Zettelkast/Notes/290220241458 - Unit of Work pattern.md')
-rw-r--r--Zettelkast/Notes/290220241458 - Unit of Work pattern.md40
1 files changed, 40 insertions, 0 deletions
diff --git a/Zettelkast/Notes/290220241458 - Unit of Work pattern.md b/Zettelkast/Notes/290220241458 - Unit of Work pattern.md
new file mode 100644
index 0000000..3ba00cb
--- /dev/null
+++ b/Zettelkast/Notes/290220241458 - Unit of Work pattern.md
@@ -0,0 +1,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()
+```
+