1 import threading, pickle
2 from . import db, index, cache
5 class environment(object):
6 def __init__(self, *, path=None, getpath=None, recover=False):
12 self.getpath = getpath
13 self.recover = recover
14 self.lk = threading.Lock()
21 self.path = self.getpath()
22 self.bk = db.environment(self.path, recover=self.recover)
27 if self.bk is not None:
31 class storedesc(object):
36 ret = getattr(t, "__didex_attr", None)
39 for nm, val in t.__dict__.items():
40 if isinstance(val, storedesc):
46 def __init__(self, name, *, env=None, path=".", ncache=None):
48 self.lk = threading.Lock()
52 self.env = environment(path=path)
55 ncache = cache.cache()
57 self.cache.load = self._load
62 self._db = self.env().db(self.name)
67 return pickle.loads(self.db().get(id))
69 raise KeyError(id, "could not unpickle data")
71 def _encode(self, obj):
72 return pickle.dumps(obj)
74 def get(self, id, *, load=True):
75 return self.cache.get(id, load=load)
77 @txnfun(lambda self: self.db().env.env)
78 def register(self, obj, *, tx):
79 id = self.db().add(self._encode(obj), tx=tx)
80 for nm, attr in storedescs(obj):
81 attr.register(id, obj, tx)
82 self.cache.put(id, obj)
85 @txnfun(lambda self: self.db().env.env)
86 def unregister(self, id, *, tx):
88 for nm, attr in storedescs(obj):
89 attr.unregister(id, obj, tx)
90 self.db().remove(id, tx=tx)
93 @txnfun(lambda self: self.db().env.env)
94 def update(self, id, *, tx):
95 obj = self.get(id, load=False)
96 for nm, attr, in storedescs(obj):
97 attr.update(id, obj, tx)
98 self.db().replace(id, self._encode(obj), tx=tx)