1 import threading, pickle, inspect
2 from . import db, index, cache
5 __all__ = ["environment", "datastore", "autostore"]
7 class environment(object):
8 def __init__(self, *, path=None, getpath=None, recover=False):
14 self.getpath = getpath
15 self.recover = recover
16 self.lk = threading.Lock()
23 self.path = self.getpath()
24 self.bk = db.environment(self.path, recover=self.recover)
29 if self.bk is not None:
33 class storedesc(object):
38 ret = t.__dict__.get("__didex_attr")
41 for st in inspect.getmro(t):
42 for nm, val in st.__dict__.items():
43 if isinstance(val, storedesc):
48 class datastore(object):
49 def __init__(self, name, *, env=None, path=".", ncache=None):
51 self.lk = threading.Lock()
55 self.env = environment(path=path)
58 ncache = cache.cache()
60 self.cache.load = self._load
65 self._db = self.env().db(self.name)
70 return pickle.loads(self.db().get(id))
72 raise KeyError(id, "could not unpickle data")
74 def _encode(self, obj):
75 return pickle.dumps(obj)
77 def get(self, id, *, load=True):
78 return self.cache.get(id, load=load)
80 @txnfun(lambda self: self.db().env.env)
81 def register(self, obj, *, tx):
82 id = self.db().add(self._encode(obj), tx=tx)
83 for nm, attr in storedescs(obj):
84 attr.register(id, obj, tx)
85 self.cache.put(id, obj)
88 @txnfun(lambda self: self.db().env.env)
89 def unregister(self, id, *, vfy=None, tx):
91 if vfy is not None and obj is not vfy:
92 raise RuntimeError("object identity crisis: " + str(vfy) + " is not cached object " + obj)
93 for nm, attr in storedescs(obj):
94 attr.unregister(id, obj, tx)
95 self.db().remove(id, tx=tx)
98 @txnfun(lambda self: self.db().env.env)
99 def update(self, id, *, vfy=None, tx):
100 obj = self.get(id, load=False)
101 if vfy is not None and obj is not vfy:
102 raise RuntimeError("object identity crisis: " + str(vfy) + " is not cached object " + obj)
103 for nm, attr, in storedescs(obj):
104 attr.update(id, obj, tx)
105 self.db().replace(id, self._encode(obj), tx=tx)
107 class autotype(type):
108 def __call__(self, *args, **kwargs):
109 new = super().__call__(*args, **kwargs)
110 new.id = self.store.register(new)
111 self.store.update(new.id, vfy=new) # This doesn't feel too nice.
114 class autostore(object, metaclass=autotype):
119 self.store.update(self.id, vfy=self)
122 self.store.unregister(self.id, vfy=self)