1 import threading, pickle
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 = getattr(t, "__didex_attr", None)
41 for nm, val in t.__dict__.items():
42 if isinstance(val, storedesc):
47 class datastore(object):
48 def __init__(self, name, *, env=None, path=".", ncache=None):
50 self.lk = threading.Lock()
54 self.env = environment(path=path)
57 ncache = cache.cache()
59 self.cache.load = self._load
64 self._db = self.env().db(self.name)
69 return pickle.loads(self.db().get(id))
71 raise KeyError(id, "could not unpickle data")
73 def _encode(self, obj):
74 return pickle.dumps(obj)
76 def get(self, id, *, load=True):
77 return self.cache.get(id, load=load)
79 @txnfun(lambda self: self.db().env.env)
80 def register(self, obj, *, tx):
81 id = self.db().add(self._encode(obj), tx=tx)
82 for nm, attr in storedescs(obj):
83 attr.register(id, obj, tx)
84 self.cache.put(id, obj)
87 @txnfun(lambda self: self.db().env.env)
88 def unregister(self, id, *, vfy=None, tx):
90 if vfy is not None and obj is not vfy:
91 raise RuntimeError("object identity crisis: " + str(vfy) + " is not cached object " + obj)
92 for nm, attr in storedescs(obj):
93 attr.unregister(id, obj, tx)
94 self.db().remove(id, tx=tx)
97 @txnfun(lambda self: self.db().env.env)
98 def update(self, id, *, vfy=None, tx):
99 obj = self.get(id, load=False)
100 if vfy is not None and obj is not vfy:
101 raise RuntimeError("object identity crisis: " + str(vfy) + " is not cached object " + obj)
102 for nm, attr, in storedescs(obj):
103 attr.update(id, obj, tx)
104 self.db().replace(id, self._encode(obj), tx=tx)
106 class autotype(type):
107 def __call__(self, *args, **kwargs):
108 new = super().__call__(*args, **kwargs)
109 new.id = self.store.register(new)
110 self.store.update(new.id, vfy=new) # This doesn't feel too nice.
113 class autostore(object, metaclass=autotype):
118 self.store.update(self.id, vfy=self)
121 self.store.unregister(self.id, vfy=self)