5 """Dbm based on sqlite -- Needed to support shelves
9 # ??? how to coordinate with whichdb
10 # ??? Any difference between blobs and text
11 # ??? does default encoding affect str-->bytes or PySqlite3 always use UTF-8
12 # ??? what is the correct isolation mode
16 from __future__
import print_function
18 __all__ = [
'error',
'open']
22 from collections.abc
import MutableMapping
23 from operator
import itemgetter
26 error = sqlite3.DatabaseError
29 def __init__(self, filename=':memory:
', flags='r', mode=None):
37 if os.path.exists(filename):
40 MAKE_SHELF =
'CREATE TABLE IF NOT EXISTS shelf (key TEXT PRIMARY KEY NOT NULL, value BLOB)'
41 self.
conn = sqlite3.connect(filename)
42 self.
conn.text_factory = str
43 if 'r' not in flags
or filename==
':memory:':
48 GET_LEN =
'SELECT COUNT(*) FROM shelf'
53 GET_BOOL =
'SELECT MAX(ROWID) FROM shelf'
54 return self.
conn.
execute(GET_BOOL).fetchone()[0]
is not None
69 GET_KEYS =
'SELECT key FROM shelf ORDER BY ROWID'
73 GET_VALUES =
'SELECT value FROM shelf ORDER BY ROWID'
77 GET_ITEMS =
'SELECT key, value FROM shelf ORDER BY ROWID'
81 HAS_ITEM =
'SELECT 1 FROM shelf WHERE key = ?'
82 return self.
conn.
execute(HAS_ITEM, (key,)).fetchone()
is not None
85 GET_ITEM =
'SELECT value FROM shelf WHERE key = ?'
86 item = self.
conn.
execute(GET_ITEM, (key,)).fetchone()
90 return pickle.loads(item[0])
93 ADD_ITEM =
'REPLACE INTO shelf (key, value) VALUES (?,?)'
94 value = pickle.dumps(value)
101 DEL_ITEM =
'DELETE FROM shelf WHERE key = ?'
107 items = items.items()
108 items = [(k,pickle.dumps(v))
for k,v
in items]
109 except AttributeError:
112 UPDATE_ITEMS =
'REPLACE INTO shelf (key, value) VALUES (?, ?)'
113 self.
conn.executemany(UPDATE_ITEMS, items)
119 CLEAR_ALL =
'DELETE FROM shelf; VACUUM;'
120 self.
conn.executescript(CLEAR_ALL)
124 if self.
conn is not None:
128 if self.
conn is not None:
136 def open(file=None, *args, **kw):
138 return SQLhash(file, *args, **kw)
142 _db =
open(file, *args, **kw)
143 return shelve.Shelf(_db)
174 return pickle.loads(o)
177 return pickle.loads(o)
193 v = pickle.loads(o[1])
198 v = pickle.loads(o[1])
201 if __name__
in '__main___':
211 print(
'***', d.keys())
213 d.update(p=
'x', q=
'y', r=
'z')
222 raise Exception(
'oh noooo!')
229 raise Exception(
'drat!')
236 d.update(p=
'x', q=
'y', r=
'z')
240 d[
'a_list'] =
range(5)
243 d[
'a_dict'] = {1:
'one',2:
'two'}
246 d[
'a_tuple'] = (1,2,3,4)