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, *, vfy=None, tx):
88 if vfy is not None and obj is not vfy:
89 raise RuntimeError("object identity crisis: " + str(vfy) + " is not cached object " + obj)
90 for nm, attr in storedescs(obj):
91 attr.unregister(id, obj, tx)
92 self.db().remove(id, tx=tx)
95 @txnfun(lambda self: self.db().env.env)
96 def update(self, id, *, vfy=None, tx):
97 obj = self.get(id, load=False)
98 if vfy is not None and obj is not vfy:
99 raise RuntimeError("object identity crisis: " + str(vfy) + " is not cached object " + obj)
100 for nm, attr, in storedescs(obj):
101 attr.update(id, obj, tx)
102 self.db().replace(id, self._encode(obj), tx=tx)
104 class autotype(type):
105 def __call__(self, *args, **kwargs):
106 new = super().__call__(*args, **kwargs)
107 new.id = self.store.register(new)
110 class autostore(object, metaclass=autotype):
115 self.store.update(self.id, vfy=self)
118 self.store.unregister(self.id, vfy=self)