ATLAS Offline Software
dbsqlite.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration
2 
3 # @file PyUtils/python/dbsqlite.py
4 # reaped off: http://svn.python.org/view/sandbox/trunk/dbm_sqlite
5 """Dbm based on sqlite -- Needed to support shelves
6 
7 Issues:
8 
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
13 
14 """
15 
16 from __future__ import print_function
17 
18 __all__ = ['error', 'open']
19 
20 import sqlite3
21 import pickle
22 from collections.abc import MutableMapping
23 from operator import itemgetter
24 import shelve
25 
26 error = sqlite3.DatabaseError
27 
28 class SQLhash(MutableMapping):
29  def __init__(self, filename=':memory:', flags='r', mode=None):
30  # XXX add flag/mode handling
31  # c -- create if it doesn't exist
32  # n -- new empty
33  # w -- open existing
34  # r -- readonly
35  if 'n' in flags:
36  import os
37  if os.path.exists(filename):
38  os.remove(filename)
39 
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:':
44  self.conn.execute(MAKE_SHELF)
45  self.conn.commit()
46 
47  def __len__(self):
48  GET_LEN = 'SELECT COUNT(*) FROM shelf'
49  return self.conn.execute(GET_LEN).fetchone()[0]
50 
51  def __bool__(self):
52  # returns None if count is zero
53  GET_BOOL = 'SELECT MAX(ROWID) FROM shelf'
54  return self.conn.execute(GET_BOOL).fetchone()[0] is not None
55 
56  def keys(self):
57  return list(self.iterkeys())
58 
59  def values(self):
60  return list(self.itervalues())
61 
62  def items(self):
63  return list(self.iteritems())
64 
65  def __iter__(self):
66  return self.iterkeys()
67 
68  def iterkeys(self):
69  GET_KEYS = 'SELECT key FROM shelf ORDER BY ROWID'
70  return SQLHashKeyIterator(self.conn, GET_KEYS, (0,))
71 
72  def itervalues(self):
73  GET_VALUES = 'SELECT value FROM shelf ORDER BY ROWID'
74  return SQLHashValueIterator(self.conn, GET_VALUES, (0,))
75 
76  def iteritems(self):
77  GET_ITEMS = 'SELECT key, value FROM shelf ORDER BY ROWID'
78  return SQLHashItemIterator(self.conn, GET_ITEMS, (0, 1))
79 
80  def __contains__(self, key):
81  HAS_ITEM = 'SELECT 1 FROM shelf WHERE key = ?'
82  return self.conn.execute(HAS_ITEM, (key,)).fetchone() is not None
83 
84  def __getitem__(self, key):
85  GET_ITEM = 'SELECT value FROM shelf WHERE key = ?'
86  item = self.conn.execute(GET_ITEM, (key,)).fetchone()
87  if item is None:
88  raise KeyError(key)
89 
90  return pickle.loads(item[0])
91 
92  def __setitem__(self, key, value):
93  ADD_ITEM = 'REPLACE INTO shelf (key, value) VALUES (?,?)'
94  value = pickle.dumps(value)
95  self.conn.execute(ADD_ITEM, (key, value))
96  #self.conn.commit()
97 
98  def __delitem__(self, key):
99  if key not in self:
100  raise KeyError(key)
101  DEL_ITEM = 'DELETE FROM shelf WHERE key = ?'
102  self.conn.execute(DEL_ITEM, (key,))
103  #self.conn.commit()
104 
105  def update(self, items=(), **kwds):
106  try:
107  items = items.items()
108  items = [(k,pickle.dumps(v)) for k,v in items]
109  except AttributeError:
110  pass
111 
112  UPDATE_ITEMS = 'REPLACE INTO shelf (key, value) VALUES (?, ?)'
113  self.conn.executemany(UPDATE_ITEMS, items)
114  self.conn.commit()
115  if kwds:
116  self.update(kwds)
117 
118  def clear(self):
119  CLEAR_ALL = 'DELETE FROM shelf; VACUUM;'
120  self.conn.executescript(CLEAR_ALL)
121  self.conn.commit()
122 
123  def sync(self):
124  if self.conn is not None:
125  self.conn.commit()
126 
127  def close(self):
128  if self.conn is not None:
129  self.conn.commit()
130  self.conn.close()
131  self.conn = None
132 
133  def __del__(self):
134  self.close()
135 
136 def open(file=None, *args, **kw):
137  if file is not None:
138  return SQLhash(file, *args, **kw)
139  return SQLhash()
140 
141 def open_shelf(file=None, *args, **kw):
142  _db = open(file, *args, **kw)
143  return shelve.Shelf(_db)
144 
146  def __init__(self, conn, stmt, indices):
147  c = conn.cursor()
148  c.execute(stmt)
149 
150  self.iter = iter(c)
151  self.getter = itemgetter(*indices)
152 
153  def __iter__(self):
154  return self
155 
156  def next(self): #py2
157  return self.getter(self.iter.next())
158  def __next__(self): #py3
159  return self.getter(self.iter.__next__())
160 
162  def __init__(self, conn, stmt, indices):
163  c = conn.cursor()
164  c.execute(stmt)
165 
166  self.iter = iter(c)
167  self.getter = itemgetter(*indices)
168 
169  def __iter__(self):
170  return self
171 
172  def next(self): #py2
173  o = self.getter(self.iter.next())
174  return pickle.loads(o)
175  def __next__(self): #py3
176  o = self.getter(self.iter.__next__())
177  return pickle.loads(o)
178 
180  def __init__(self, conn, stmt, indices):
181  c = conn.cursor()
182  c.execute(stmt)
183 
184  self.iter = iter(c)
185  self.getter = itemgetter(*indices)
186 
187  def __iter__(self):
188  return self
189 
190  def next(self): #py2
191  o = self.getter(self.iter.next())
192  k = o[0]
193  v = pickle.loads(o[1])
194  return (k,v)
195  def __next__(self): #py3
196  o = self.getter(self.iter.__next__())
197  k = o[0]
198  v = pickle.loads(o[1])
199  return (k,v)
200 
201 if __name__ in '__main___':
202  for d in SQLhash(flags='n'), SQLhash('example',flags='n'):
203  list(d)
204  print(list(d), "start")
205  d['abc'] = 'lmno'
206  print(d['abc'])
207  d['abc'] = 'rsvp'
208  d['xyz'] = 'pdq'
209  print(d.items())
210  print(d.values())
211  print('***', d.keys())
212  print(list(d), 'list')
213  d.update(p='x', q='y', r='z')
214  print(d.items())
215 
216  del d['abc']
217  try:
218  print(d['abc'])
219  except KeyError:
220  pass
221  else:
222  raise Exception('oh noooo!')
223 
224  try:
225  del d['abc']
226  except KeyError:
227  pass
228  else:
229  raise Exception('drat!')
230 
231  print(list(d))
232  print(bool(d), True)
233  d.clear()
234  print(bool(d), False)
235  print(list(d))
236  d.update(p='x', q='y', r='z')
237  print(list(d))
238  d['xyz'] = 'pdq'
239 
240  d['a_list'] = range(5)
241  print(d['a_list'])
242 
243  d['a_dict'] = {1:'one',2:'two'}
244  print(d['a_dict'])
245 
246  d['a_tuple'] = (1,2,3,4)
247  print(d['a_tuple'])
248 
249  print()
250  d.close()
python.dbsqlite.SQLHashKeyIterator.next
def next(self)
Definition: dbsqlite.py:156
python.dbsqlite.SQLHashKeyIterator.getter
getter
Definition: dbsqlite.py:151
python.dbsqlite.SQLhash.__contains__
def __contains__(self, key)
Definition: dbsqlite.py:80
python.dbsqlite.SQLHashItemIterator.iter
iter
Definition: dbsqlite.py:184
python.dbsqlite.SQLHashItemIterator.getter
getter
Definition: dbsqlite.py:185
python.dbsqlite.SQLHashValueIterator.next
def next(self)
Definition: dbsqlite.py:172
python.dbsqlite.SQLhash.__bool__
def __bool__(self)
Definition: dbsqlite.py:51
python.dbsqlite.SQLhash.clear
def clear(self)
Definition: dbsqlite.py:118
python.dbsqlite.SQLhash.iteritems
def iteritems(self)
Definition: dbsqlite.py:76
python.dbsqlite.SQLhash.__len__
def __len__(self)
Definition: dbsqlite.py:47
python.dbsqlite.SQLhash.__init__
def __init__(self, filename=':memory:', flags='r', mode=None)
Definition: dbsqlite.py:29
python.dbsqlite.SQLhash.__iter__
def __iter__(self)
Definition: dbsqlite.py:65
python.dbsqlite.SQLHashValueIterator.getter
getter
Definition: dbsqlite.py:167
python.dbsqlite.SQLhash.__getitem__
def __getitem__(self, key)
Definition: dbsqlite.py:84
python.dbsqlite.SQLHashValueIterator
Definition: dbsqlite.py:161
python.dbsqlite.SQLhash.sync
def sync(self)
Definition: dbsqlite.py:123
LArG4FSStartPointFilterLegacy.execute
execute
Definition: LArG4FSStartPointFilterLegacy.py:20
python.dbsqlite.open_shelf
def open_shelf(file=None, *args, **kw)
Definition: dbsqlite.py:141
python.dbsqlite.open
def open(file=None, *args, **kw)
Definition: dbsqlite.py:136
python.dbsqlite.SQLhash.itervalues
def itervalues(self)
Definition: dbsqlite.py:72
python.dbsqlite.SQLhash.__del__
def __del__(self)
Definition: dbsqlite.py:133
python.dbsqlite.SQLhash.update
def update(self, items=(), **kwds)
Definition: dbsqlite.py:105
python.dbsqlite.SQLhash.__delitem__
def __delitem__(self, key)
Definition: dbsqlite.py:98
python.dbsqlite.SQLHashKeyIterator.__init__
def __init__(self, conn, stmt, indices)
Definition: dbsqlite.py:146
python.dbsqlite.SQLhash
Definition: dbsqlite.py:28
python.dbsqlite.SQLhash.values
def values(self)
Definition: dbsqlite.py:59
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:195
python.dbsqlite.SQLHashItemIterator.__init__
def __init__(self, conn, stmt, indices)
Definition: dbsqlite.py:180
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
python.dbsqlite.SQLhash.keys
def keys(self)
Definition: dbsqlite.py:56
python.dbsqlite.SQLhash.items
def items(self)
Definition: dbsqlite.py:62
python.dbsqlite.SQLHashItemIterator
Definition: dbsqlite.py:179
python.dbsqlite.SQLHashValueIterator.iter
iter
Definition: dbsqlite.py:166
python.dbsqlite.SQLHashItemIterator.next
def next(self)
Definition: dbsqlite.py:190
python.dbsqlite.SQLHashItemIterator.__next__
def __next__(self)
Definition: dbsqlite.py:195
python.dbsqlite.SQLHashKeyIterator.__iter__
def __iter__(self)
Definition: dbsqlite.py:153
python.dbsqlite.SQLHashKeyIterator
Definition: dbsqlite.py:145
python.dbsqlite.SQLHashValueIterator.__next__
def __next__(self)
Definition: dbsqlite.py:175
python.dbsqlite.SQLHashKeyIterator.__next__
def __next__(self)
Definition: dbsqlite.py:158
python.dbsqlite.SQLHashItemIterator.__iter__
def __iter__(self)
Definition: dbsqlite.py:187
python.dbsqlite.SQLHashValueIterator.__iter__
def __iter__(self)
Definition: dbsqlite.py:169
python.dbsqlite.SQLhash.iterkeys
def iterkeys(self)
Definition: dbsqlite.py:68
python.dbsqlite.SQLhash.conn
conn
Definition: dbsqlite.py:41
python.dbsqlite.SQLHashValueIterator.__init__
def __init__(self, conn, stmt, indices)
Definition: dbsqlite.py:162
pickleTool.object
object
Definition: pickleTool.py:30
dbg::print
void print(std::FILE *stream, std::format_string< Args... > fmt, Args &&... args)
Definition: SGImplSvc.cxx:70
calibdata.commit
bool commit
Definition: calibdata.py:832
python.dbsqlite.SQLHashKeyIterator.iter
iter
Definition: dbsqlite.py:150
xAOD::bool
setBGCode setTAP setLVL2ErrorBits bool
Definition: TrigDecision_v1.cxx:60
python.dbsqlite.SQLhash.close
def close(self)
Definition: dbsqlite.py:127
python.dbsqlite.SQLhash.__setitem__
def __setitem__(self, key, value)
Definition: dbsqlite.py:92