1
|
# Database access
|
2
|
|
3
|
import copy
|
4
|
import re
|
5
|
import warnings
|
6
|
|
7
|
import exc
|
8
|
import dicts
|
9
|
import iters
|
10
|
import lists
|
11
|
from Proxy import Proxy
|
12
|
import rand
|
13
|
import strings
|
14
|
import util
|
15
|
|
16
|
##### Exceptions
|
17
|
|
18
|
def get_cur_query(cur):
|
19
|
if hasattr(cur, 'query'): return cur.query
|
20
|
elif hasattr(cur, '_last_executed'): return cur._last_executed
|
21
|
else: return None
|
22
|
|
23
|
def _add_cursor_info(e, cur): exc.add_msg(e, 'query: '+get_cur_query(cur))
|
24
|
|
25
|
class DbException(exc.ExceptionWithCause):
|
26
|
def __init__(self, msg, cause=None, cur=None):
|
27
|
exc.ExceptionWithCause.__init__(self, msg, cause)
|
28
|
if cur != None: _add_cursor_info(self, cur)
|
29
|
|
30
|
class NameException(DbException): pass
|
31
|
|
32
|
class ExceptionWithColumns(DbException):
|
33
|
def __init__(self, cols, cause=None):
|
34
|
DbException.__init__(self, 'columns: ' + ', '.join(cols), cause)
|
35
|
self.cols = cols
|
36
|
|
37
|
class DuplicateKeyException(ExceptionWithColumns): pass
|
38
|
|
39
|
class NullValueException(ExceptionWithColumns): pass
|
40
|
|
41
|
class EmptyRowException(DbException): pass
|
42
|
|
43
|
##### Warnings
|
44
|
|
45
|
class DbWarning(UserWarning): pass
|
46
|
|
47
|
##### Result retrieval
|
48
|
|
49
|
def col_names(cur): return (col[0] for col in cur.description)
|
50
|
|
51
|
def rows(cur): return iter(lambda: cur.fetchone(), None)
|
52
|
|
53
|
def consume_rows(cur):
|
54
|
'''Used to fetch all rows so result will be cached'''
|
55
|
iters.consume_iter(rows(cur))
|
56
|
|
57
|
def next_row(cur): return rows(cur).next()
|
58
|
|
59
|
def row(cur):
|
60
|
row_ = next_row(cur)
|
61
|
consume_rows(cur)
|
62
|
return row_
|
63
|
|
64
|
def next_value(cur): return next_row(cur)[0]
|
65
|
|
66
|
def value(cur): return row(cur)[0]
|
67
|
|
68
|
def values(cur): return iters.func_iter(lambda: next_value(cur))
|
69
|
|
70
|
def value_or_none(cur):
|
71
|
try: return value(cur)
|
72
|
except StopIteration: return None
|
73
|
|
74
|
##### Database connections
|
75
|
|
76
|
db_config_names = ['engine', 'host', 'user', 'password', 'database']
|
77
|
|
78
|
db_engines = {
|
79
|
'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
|
80
|
'PostgreSQL': ('psycopg2', {}),
|
81
|
}
|
82
|
|
83
|
DatabaseErrors_set = set([DbException])
|
84
|
DatabaseErrors = tuple(DatabaseErrors_set)
|
85
|
|
86
|
def _add_module(module):
|
87
|
DatabaseErrors_set.add(module.DatabaseError)
|
88
|
global DatabaseErrors
|
89
|
DatabaseErrors = tuple(DatabaseErrors_set)
|
90
|
|
91
|
def db_config_str(db_config):
|
92
|
return db_config['engine']+' database '+db_config['database']
|
93
|
|
94
|
def _query_lookup(query, params): return (query, dicts.make_hashable(params))
|
95
|
|
96
|
log_debug_none = lambda msg: None
|
97
|
|
98
|
class DbConn:
|
99
|
def __init__(self, db_config, serializable=True, log_debug=log_debug_none,
|
100
|
caching=True):
|
101
|
self.db_config = db_config
|
102
|
self.serializable = serializable
|
103
|
self.log_debug = log_debug
|
104
|
self.caching = caching
|
105
|
|
106
|
self.__db = None
|
107
|
self.query_results = {}
|
108
|
|
109
|
def __getattr__(self, name):
|
110
|
if name == '__dict__': raise Exception('getting __dict__')
|
111
|
if name == 'db': return self._db()
|
112
|
else: raise AttributeError()
|
113
|
|
114
|
def __getstate__(self):
|
115
|
state = copy.copy(self.__dict__) # shallow copy
|
116
|
state['log_debug'] = None # don't pickle the debug callback
|
117
|
state['_DbConn__db'] = None # don't pickle the connection
|
118
|
return state
|
119
|
|
120
|
def _db(self):
|
121
|
if self.__db == None:
|
122
|
# Process db_config
|
123
|
db_config = self.db_config.copy() # don't modify input!
|
124
|
module_name, mappings = db_engines[db_config.pop('engine')]
|
125
|
module = __import__(module_name)
|
126
|
_add_module(module)
|
127
|
for orig, new in mappings.iteritems():
|
128
|
try: util.rename_key(db_config, orig, new)
|
129
|
except KeyError: pass
|
130
|
|
131
|
# Connect
|
132
|
self.__db = module.connect(**db_config)
|
133
|
|
134
|
# Configure connection
|
135
|
if self.serializable: run_raw_query(self,
|
136
|
'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
|
137
|
|
138
|
return self.__db
|
139
|
|
140
|
class DbCursor(Proxy):
|
141
|
def __init__(self, outer):
|
142
|
Proxy.__init__(self, outer.db.cursor())
|
143
|
self.query_results = outer.query_results
|
144
|
self.query_lookup = None
|
145
|
self.result = []
|
146
|
|
147
|
def execute(self, query, params=None):
|
148
|
self._is_insert = query.upper().find('INSERT') >= 0
|
149
|
self.query_lookup = _query_lookup(query, params)
|
150
|
try: return_value = self.inner.execute(query, params)
|
151
|
except Exception, e:
|
152
|
self.result = e # cache the exception as the result
|
153
|
self._cache_result()
|
154
|
raise
|
155
|
finally: self.query = get_cur_query(self.inner)
|
156
|
# Fetch all rows so result will be cached
|
157
|
if self.rowcount == 0 and not self._is_insert: consume_rows(self)
|
158
|
return return_value
|
159
|
|
160
|
def fetchone(self):
|
161
|
row = self.inner.fetchone()
|
162
|
if row != None: self.result.append(row)
|
163
|
# otherwise, fetched all rows
|
164
|
else: self._cache_result()
|
165
|
return row
|
166
|
|
167
|
def _cache_result(self):
|
168
|
# For inserts, only cache exceptions since inserts are not
|
169
|
# idempotent, but an invalid insert will always be invalid
|
170
|
if self.query_results != None and (not self._is_insert
|
171
|
or isinstance(self.result, Exception)):
|
172
|
|
173
|
assert self.query_lookup != None
|
174
|
self.query_results[self.query_lookup] = self.CacheCursor(
|
175
|
util.dict_subset(dicts.AttrsDictView(self),
|
176
|
['query', 'result', 'rowcount', 'description']))
|
177
|
|
178
|
class CacheCursor:
|
179
|
def __init__(self, cached_result): self.__dict__ = cached_result
|
180
|
|
181
|
def execute(self, *args, **kw_args):
|
182
|
if isinstance(self.result, Exception): raise self.result
|
183
|
# otherwise, result is a rows list
|
184
|
self.iter = iter(self.result)
|
185
|
|
186
|
def fetchone(self):
|
187
|
try: return self.iter.next()
|
188
|
except StopIteration: return None
|
189
|
|
190
|
def run_query(self, query, params=None, cacheable=False):
|
191
|
if not self.caching: cacheable = False
|
192
|
used_cache = False
|
193
|
try:
|
194
|
# Get cursor
|
195
|
if cacheable:
|
196
|
query_lookup = _query_lookup(query, params)
|
197
|
try:
|
198
|
cur = self.query_results[query_lookup]
|
199
|
used_cache = True
|
200
|
except KeyError: cur = self.DbCursor(self)
|
201
|
else: cur = self.db.cursor()
|
202
|
|
203
|
# Run query
|
204
|
try: cur.execute(query, params)
|
205
|
except Exception, e:
|
206
|
_add_cursor_info(e, cur)
|
207
|
raise
|
208
|
finally:
|
209
|
if self.log_debug != log_debug_none: # only compute msg if needed
|
210
|
if used_cache: cache_status = 'Cache hit'
|
211
|
elif cacheable: cache_status = 'Cache miss'
|
212
|
else: cache_status = 'Non-cacheable'
|
213
|
self.log_debug(cache_status+': '
|
214
|
+strings.one_line(get_cur_query(cur)))
|
215
|
|
216
|
return cur
|
217
|
|
218
|
def is_cached(self, query, params=None):
|
219
|
return _query_lookup(query, params) in self.query_results
|
220
|
|
221
|
connect = DbConn
|
222
|
|
223
|
##### Input validation
|
224
|
|
225
|
def check_name(name):
|
226
|
if re.search(r'\W', name) != None: raise NameException('Name "'+name
|
227
|
+'" may contain only alphanumeric characters and _')
|
228
|
|
229
|
def esc_name_by_module(module, name, preserve_case=False):
|
230
|
if module == 'psycopg2':
|
231
|
if preserve_case: quote = '"'
|
232
|
# Don't enclose in quotes because this disables case-insensitivity
|
233
|
else: return name
|
234
|
elif module == 'MySQLdb': quote = '`'
|
235
|
else: raise NotImplementedError("Can't escape name for "+module+' database')
|
236
|
return quote + name.replace(quote, '') + quote
|
237
|
|
238
|
def esc_name_by_engine(engine, name, **kw_args):
|
239
|
return esc_name_by_module(db_engines[engine][0], name, **kw_args)
|
240
|
|
241
|
def esc_name(db, name, **kw_args):
|
242
|
return esc_name_by_module(util.root_module(db.db), name, **kw_args)
|
243
|
|
244
|
def qual_name(db, schema, table):
|
245
|
def esc_name_(name): return esc_name(db, name, preserve_case=True)
|
246
|
table = esc_name_(table)
|
247
|
if schema != None: return esc_name_(schema)+'.'+table
|
248
|
else: return table
|
249
|
|
250
|
##### Querying
|
251
|
|
252
|
def run_raw_query(db, *args, **kw_args):
|
253
|
'''For args, see DbConn.run_query()'''
|
254
|
return db.run_query(*args, **kw_args)
|
255
|
|
256
|
##### Recoverable querying
|
257
|
|
258
|
def with_savepoint(db, func):
|
259
|
savepoint = 'savepoint_'+str(rand.rand_int()) # must be unique
|
260
|
run_raw_query(db, 'SAVEPOINT '+savepoint)
|
261
|
try: return_val = func()
|
262
|
except:
|
263
|
run_raw_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
|
264
|
raise
|
265
|
else:
|
266
|
run_raw_query(db, 'RELEASE SAVEPOINT '+savepoint)
|
267
|
return return_val
|
268
|
|
269
|
def run_query(db, query, params=None, recover=None, cacheable=False):
|
270
|
if recover == None: recover = False
|
271
|
|
272
|
def run(): return run_raw_query(db, query, params, cacheable)
|
273
|
if recover and not db.is_cached(query, params):
|
274
|
return with_savepoint(db, run)
|
275
|
else: return run() # don't need savepoint if cached
|
276
|
|
277
|
##### Basic queries
|
278
|
|
279
|
def mk_select(db, table, fields=None, conds=None, limit=None, start=None,
|
280
|
table_is_esc=False):
|
281
|
'''
|
282
|
@param fields Use None to select all fields in the table
|
283
|
@param table_is_esc Whether the table name has already been escaped
|
284
|
@return tuple(query, params)
|
285
|
'''
|
286
|
if conds == None: conds = {}
|
287
|
assert limit == None or type(limit) == int
|
288
|
assert start == None or type(start) == int
|
289
|
if not table_is_esc: check_name(table)
|
290
|
if fields != None: map(check_name, fields)
|
291
|
map(check_name, conds.keys())
|
292
|
|
293
|
def cond(entry):
|
294
|
col, value = entry
|
295
|
cond_ = esc_name(db, col)+' '
|
296
|
if value == None: cond_ += 'IS'
|
297
|
else: cond_ += '='
|
298
|
cond_ += ' %s'
|
299
|
return cond_
|
300
|
query = 'SELECT '
|
301
|
if fields == None: query += '*'
|
302
|
else: query += ', '.join([esc_name(db, field) for field in fields])
|
303
|
query += ' FROM '+esc_name(db, table)
|
304
|
|
305
|
missing = True
|
306
|
if conds != {}:
|
307
|
query += ' WHERE '+' AND '.join(map(cond, conds.iteritems()))
|
308
|
missing = False
|
309
|
if limit != None: query += ' LIMIT '+str(limit); missing = False
|
310
|
if start != None:
|
311
|
if start != 0: query += ' OFFSET '+str(start)
|
312
|
missing = False
|
313
|
if missing: warnings.warn(DbWarning(
|
314
|
'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
|
315
|
|
316
|
return (query, conds.values())
|
317
|
|
318
|
def select(db, *args, **kw_args):
|
319
|
'''For params, see mk_select() and run_query()'''
|
320
|
recover = kw_args.pop('recover', None)
|
321
|
cacheable = kw_args.pop('cacheable', True)
|
322
|
|
323
|
query, params = mk_select(db, *args, **kw_args)
|
324
|
return run_query(db, query, params, recover, cacheable)
|
325
|
|
326
|
default = object() # tells insert() to use the default value for a column
|
327
|
|
328
|
def insert(db, table, row, returning=None, recover=None, cacheable=True,
|
329
|
table_is_esc=False):
|
330
|
'''
|
331
|
@param returning str|None An inserted column (such as pkey) to return
|
332
|
@param table_is_esc Whether the table name has already been escaped
|
333
|
'''
|
334
|
if not table_is_esc: check_name(table)
|
335
|
if lists.is_seq(row): cols = None
|
336
|
else:
|
337
|
cols = row.keys()
|
338
|
row = row.values()
|
339
|
map(check_name, cols)
|
340
|
row = list(row) # ensure that "!= []" works
|
341
|
|
342
|
# Check for special values
|
343
|
labels = []
|
344
|
values = []
|
345
|
for value in row:
|
346
|
if value == default: labels.append('DEFAULT')
|
347
|
else:
|
348
|
labels.append('%s')
|
349
|
values.append(value)
|
350
|
|
351
|
# Build query
|
352
|
query = 'INSERT INTO '+table
|
353
|
if values != []:
|
354
|
if cols != None: query += ' ('+', '.join(cols)+')'
|
355
|
query += ' VALUES ('+(', '.join(labels))+')'
|
356
|
else: query += ' DEFAULT VALUES'
|
357
|
|
358
|
if returning != None:
|
359
|
check_name(returning)
|
360
|
query += ' RETURNING '+returning
|
361
|
|
362
|
return run_query(db, query, values, recover, cacheable)
|
363
|
|
364
|
def last_insert_id(db):
|
365
|
module = util.root_module(db.db)
|
366
|
if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
|
367
|
elif module == 'MySQLdb': return db.insert_id()
|
368
|
else: return None
|
369
|
|
370
|
def truncate(db, table, schema='public'):
|
371
|
return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
|
372
|
|
373
|
##### Database structure queries
|
374
|
|
375
|
def pkey(db, table, recover=None):
|
376
|
'''Assumed to be first column in table'''
|
377
|
check_name(table)
|
378
|
return col_names(select(db, table, limit=0, recover=recover)).next()
|
379
|
|
380
|
def index_cols(db, table, index):
|
381
|
'''Can also use this for UNIQUE constraints, because a UNIQUE index is
|
382
|
automatically created. When you don't know whether something is a UNIQUE
|
383
|
constraint or a UNIQUE index, use this function.'''
|
384
|
check_name(table)
|
385
|
check_name(index)
|
386
|
module = util.root_module(db.db)
|
387
|
if module == 'psycopg2':
|
388
|
return list(values(run_query(db, '''\
|
389
|
SELECT attname
|
390
|
FROM
|
391
|
(
|
392
|
SELECT attnum, attname
|
393
|
FROM pg_index
|
394
|
JOIN pg_class index ON index.oid = indexrelid
|
395
|
JOIN pg_class table_ ON table_.oid = indrelid
|
396
|
JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
|
397
|
WHERE
|
398
|
table_.relname = %(table)s
|
399
|
AND index.relname = %(index)s
|
400
|
UNION
|
401
|
SELECT attnum, attname
|
402
|
FROM
|
403
|
(
|
404
|
SELECT
|
405
|
indrelid
|
406
|
, (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
|
407
|
AS indkey
|
408
|
FROM pg_index
|
409
|
JOIN pg_class index ON index.oid = indexrelid
|
410
|
JOIN pg_class table_ ON table_.oid = indrelid
|
411
|
WHERE
|
412
|
table_.relname = %(table)s
|
413
|
AND index.relname = %(index)s
|
414
|
) s
|
415
|
JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
|
416
|
) s
|
417
|
ORDER BY attnum
|
418
|
''',
|
419
|
{'table': table, 'index': index}, cacheable=True)))
|
420
|
else: raise NotImplementedError("Can't list index columns for "+module+
|
421
|
' database')
|
422
|
|
423
|
def constraint_cols(db, table, constraint):
|
424
|
check_name(table)
|
425
|
check_name(constraint)
|
426
|
module = util.root_module(db.db)
|
427
|
if module == 'psycopg2':
|
428
|
return list(values(run_query(db, '''\
|
429
|
SELECT attname
|
430
|
FROM pg_constraint
|
431
|
JOIN pg_class ON pg_class.oid = conrelid
|
432
|
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
|
433
|
WHERE
|
434
|
relname = %(table)s
|
435
|
AND conname = %(constraint)s
|
436
|
ORDER BY attnum
|
437
|
''',
|
438
|
{'table': table, 'constraint': constraint})))
|
439
|
else: raise NotImplementedError("Can't list constraint columns for "+module+
|
440
|
' database')
|
441
|
|
442
|
def tables(db, schema='public', table_like='%'):
|
443
|
module = util.root_module(db.db)
|
444
|
params = {'schema': schema, 'table_like': table_like}
|
445
|
if module == 'psycopg2':
|
446
|
return values(run_query(db, '''\
|
447
|
SELECT tablename
|
448
|
FROM pg_tables
|
449
|
WHERE
|
450
|
schemaname = %(schema)s
|
451
|
AND tablename LIKE %(table_like)s
|
452
|
ORDER BY tablename
|
453
|
''',
|
454
|
params, cacheable=True))
|
455
|
elif module == 'MySQLdb':
|
456
|
return values(run_query(db, 'SHOW TABLES LIKE %(table_like)s', params,
|
457
|
cacheable=True))
|
458
|
else: raise NotImplementedError("Can't list tables for "+module+' database')
|
459
|
|
460
|
##### Database management
|
461
|
|
462
|
def empty_db(db, schema='public', **kw_args):
|
463
|
'''For kw_args, see tables()'''
|
464
|
for table in tables(db, schema, **kw_args): truncate(db, table, schema)
|
465
|
|
466
|
##### Heuristic queries
|
467
|
|
468
|
def try_insert(db, table, row, returning=None):
|
469
|
'''Recovers from errors'''
|
470
|
try: return insert(db, table, row, returning, recover=True)
|
471
|
except Exception, e:
|
472
|
msg = str(e)
|
473
|
match = re.search(r'duplicate key value violates unique constraint '
|
474
|
r'"(([^\W_]+)_[^"]+)"', msg)
|
475
|
if match:
|
476
|
constraint, table = match.groups()
|
477
|
try: cols = index_cols(db, table, constraint)
|
478
|
except NotImplementedError: raise e
|
479
|
else: raise DuplicateKeyException(cols, e)
|
480
|
match = re.search(r'null value in column "(\w+)" violates not-null '
|
481
|
'constraint', msg)
|
482
|
if match: raise NullValueException([match.group(1)], e)
|
483
|
raise # no specific exception raised
|
484
|
|
485
|
def put(db, table, row, pkey, row_ct_ref=None):
|
486
|
'''Recovers from errors.
|
487
|
Only works under PostgreSQL (uses `INSERT ... RETURNING`)'''
|
488
|
try:
|
489
|
cur = try_insert(db, table, row, pkey)
|
490
|
if row_ct_ref != None and cur.rowcount >= 0:
|
491
|
row_ct_ref[0] += cur.rowcount
|
492
|
return value(cur)
|
493
|
except DuplicateKeyException, e:
|
494
|
return value(select(db, table, [pkey],
|
495
|
util.dict_subset_right_join(row, e.cols), recover=True))
|
496
|
|
497
|
def get(db, table, row, pkey, row_ct_ref=None, create=False):
|
498
|
'''Recovers from errors'''
|
499
|
try: return value(select(db, table, [pkey], row, 1, recover=True))
|
500
|
except StopIteration:
|
501
|
if not create: raise
|
502
|
return put(db, table, row, pkey, row_ct_ref) # insert new row
|