X-Git-Url: http://dolda2000.com/gitweb/?p=didex.git;a=blobdiff_plain;f=didex%2Fstore.py;h=a9bf0cdc6c34db06434b90c6b5d042b9d66480c1;hp=450a9fe02def89bfeee0c5b34baab96f14199bba;hb=a19ad473ae0a534f454dadacb01d8252ab51c21f;hpb=eca9b3be30f697c14e43e1ad717bf29ca13c6408 diff --git a/didex/store.py b/didex/store.py index 450a9fe..a9bf0cd 100644 --- a/didex/store.py +++ b/didex/store.py @@ -1,7 +1,9 @@ -import threading, pickle +import threading, pickle, inspect, atexit from . import db, index, cache from .db import txnfun +__all__ = ["environment", "datastore", "autostore"] + class environment(object): def __init__(self, *, path=None, getpath=None, recover=False): if path is not None: @@ -20,11 +22,13 @@ class environment(object): if self.path is None: self.path = self.getpath() self.bk = db.environment(self.path, recover=self.recover) + atexit.register(self.close) return self.bk def close(self): with self.lk: if self.bk is not None: + atexit.unregister(self.close) self.bk.close() self.bk = None @@ -33,16 +37,17 @@ class storedesc(object): def storedescs(obj): t = type(obj) - ret = getattr(t, "__didex_attr", None) + ret = t.__dict__.get("__didex_attr") if ret is None: ret = [] - for nm, val in t.__dict__.items(): - if isinstance(val, storedesc): - ret.append((nm, val)) + for st in inspect.getmro(t): + for nm, val in st.__dict__.items(): + if isinstance(val, storedesc): + ret.append((nm, val)) t.__didex_attr = ret return ret -class store(object): +class datastore(object): def __init__(self, name, *, env=None, path=".", ncache=None): self.name = name self.lk = threading.Lock() @@ -83,16 +88,38 @@ class store(object): return id @txnfun(lambda self: self.db().env.env) - def unregister(self, id, *, tx): + def unregister(self, id, *, vfy=None, tx): obj = self.get(id) + if vfy is not None and obj is not vfy: + raise RuntimeError("object identity crisis: " + str(vfy) + " is not cached object " + obj) for nm, attr in storedescs(obj): attr.unregister(id, obj, tx) self.db().remove(id, tx=tx) self.cache.remove(id) @txnfun(lambda self: self.db().env.env) - def update(self, id, *, tx): + def update(self, id, *, vfy=None, tx): obj = self.get(id, load=False) + if vfy is not None and obj is not vfy: + raise RuntimeError("object identity crisis: " + str(vfy) + " is not cached object " + obj) for nm, attr, in storedescs(obj): attr.update(id, obj, tx) self.db().replace(id, self._encode(obj), tx=tx) + +class autotype(type): + def __call__(self, *args, **kwargs): + new = super().__call__(*args, **kwargs) + new.id = self.store.register(new) + self.store.update(new.id, vfy=new) # This doesn't feel too nice. + return new + +class autostore(object, metaclass=autotype): + def __init__(self): + self.id = None + + def save(self): + self.store.update(self.id, vfy=self) + + def remove(self): + self.store.unregister(self.id, vfy=self) + self.id = None