-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuowed.py
74 lines (57 loc) · 1.98 KB
/
uowed.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from typing import Protocol, TypeVar
ModelT = TypeVar('ModelT')
class DataMapper(Protocol[ModelT]):
"""Class used by a UoW to flush changes to a database"""
def insert(self, model: ModelT):
raise NotImplementedError
def delete(self, model: ModelT):
raise NotImplementedError
def update(self, model: ModelT):
raise NotImplementedError
class UnitOfWork:
def __init__(self):
self.dirty = {}
self.new = {}
self.deleted = {}
self.mappers = {}
def register_dirty(self, model):
model_id = id(model)
if model_id in self.new:
return
self.dirty[model_id] = model
def register_deleted(self, model):
if isinstance(model, UoWModel):
model = model._model
model_id = id(model)
if model_id in self.new:
self.new.pop(model_id)
return
if model_id in self.dirty:
self.dirty.pop(model_id)
self.deleted[model_id] = model
def register_new(self, model):
model_id = id(model)
self.new[model_id] = model
return UoWModel(model, self)
def commit(self):
# here we can add optimizations like request batching
# but it will also require extending of Mapper protocol
for model in self.new.values():
self.mappers[type(model)].insert(model)
for model in self.dirty.values():
self.mappers[type(model)].update(model)
for model in self.deleted.values():
self.mappers[type(model)].delete(model)
class UoWModel:
"""
Model wrapper which allows to implicitly mark model
as modified on attribute assignment.
"""
def __init__(self, model, uow):
self.__dict__["_model"] = model
self.__dict__["_uow"] = uow
def __getattr__(self, key):
return getattr(self._model, key)
def __setattr__(self, key, value):
setattr(self._model, key, value)
self._uow.register_dirty(self._model)