Skip to content

Instantly share code, notes, and snippets.

@maedoc
Created August 30, 2013 16:44
Show Gist options
  • Save maedoc/6391891 to your computer and use it in GitHub Desktop.
Save maedoc/6391891 to your computer and use it in GitHub Desktop.
import sqlite3
import json
def queued(f):
return f
class TableStore(object):
def __init__(self, db, name):
self.db = db
self.name = '[%s]' % (name,)
@queued
def create(self):
self.db.execute('create table %s (k, v)' % (self.name,))
return self
@queued
def __setitem__(self, k, v):
self.db.execute("insert into %s values (?, ?)" % (self.name,), (k, v))
def __getitem__(self, k):
q = "select v from %s where k='%s'" % (self.name, k)
ret = [r for r, in self.db.execute(q)]
if len(ret) == 0:
raise AttributeError('key %r does not exist in %r'% (k, self))
return ret
@queued
def __delitem__(self, k):
q = "delete from %s where k='%s'" % (self.name, k)
self.db.execute(q)
def __contains__(self, k):
q = "select exists(select * from %s where k='%s')" % (self.name, k)
return True if next(self.db.execute(q))[0] else False
def iterkeys(self):
q = "select k from %s" % (self.name, )
for r, in self.db.execute(q):
yield r
def keys(self):
return list(self.iterkeys())
def itervalues(self):
q = "select v from %s" % (self.name, )
for r, in self.db.execute(q):
yield r
def iteritems(self):
ks, vs = self.iterkeys(), self.itervalues()
while True:
yield next(ks), next(vs)
@queued
def drop(self):
self.db.execute('drop table %s' % (self.name,))
def __repr__(self):
return '<%s %r>' % (self.__class__.__name__, self.name)
class UniqueKeys(object):
"""
Uses a table constraint to ensure *keys* are unique, and updates
to existing key just changes the value.
"""
def create(self):
q = 'create table %s (k, v, unique(k) on conflict replace)' % (self.name, )
self.db.execute(q)
return self
def __getitem__(self, k):
return super(UniqueKeys, self).__getitem__(k)[0]
class JSONValues(object):
"""
Data descriptor to map *values* to and from JSON.
"""
def __getitem__(self, k):
sup = super(JSONValues, self).__getitem__(k)
try:
return json.loads(sup)
except:
return sup
def __setitem__(self, k, v):
js = json.dumps(v)
print 'storing as %r'% (js,)
super(JSONValues, self).__setitem__(k, v)
class Store(UniqueKeys, TableStore):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment