1 import threading, pickle
2 from . import db, index, cache
5 class environment(object):
6 def __init__(self, path):
8 self.lk = threading.Lock()
14 self.bk = db.environment(self.path)
19 if self.bk is not None:
23 class storedesc(object):
28 ret = getattr(t, "__didex_attr", None)
31 for nm, val in t.__dict__.items():
32 if isinstance(val, storedesc):
38 def __init__(self, name, *, env=None, path=".", ncache=None):
40 self.lk = threading.Lock()
44 self.env = environment(path)
47 ncache = cache.cache()
49 self.cache.load = self._load
54 self._db = self.env().db(self.name)
59 return pickle.loads(self.db().get(id))
61 raise KeyError(id, "could not unpickle data")
63 def _encode(self, obj):
64 return pickle.dumps(obj)
66 def get(self, id, *, load=True):
67 return self.cache.get(id, load=load)
69 @txnfun(lambda self: self.db().env.env)
70 def register(self, obj, *, tx):
71 id = self.db().add(self._encode(obj), tx=tx)
72 for nm, attr in storedescs(obj):
73 attr.register(id, obj, tx)
74 self.cache.put(id, obj)
77 @txnfun(lambda self: self.db().env.env)
78 def unregister(self, id, *, tx):
80 for nm, attr in storedescs(obj):
81 attr.unregister(id, obj, tx)
82 self.db().remove(id, tx=tx)
85 @txnfun(lambda self: self.db().env.env)
86 def update(self, id, *, tx):
87 obj = self.get(id, load=False)
88 for nm, attr, in storedescs(obj):
89 attr.update(id, obj, tx)
90 self.db().replace(id, self._encode(obj), tx=tx)