From: Fredrik Tolf Date: Fri, 20 Mar 2015 05:15:35 +0000 (+0100) Subject: Added autostore convenience type. X-Git-Url: http://dolda2000.com/gitweb/?p=didex.git;a=commitdiff_plain;h=ca180faa157589645754310971bd0af22597f992 Added autostore convenience type. --- diff --git a/didex/store.py b/didex/store.py index 450a9fe..fb5f2c6 100644 --- a/didex/store.py +++ b/didex/store.py @@ -83,16 +83,37 @@ 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) + 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