Project

General

Profile

1
# Database access
2

    
3
import copy
4
import re
5
import warnings
6

    
7
import exc
8
import dicts
9
import iters
10
from Proxy import Proxy
11
import rand
12
import strings
13
import util
14

    
15
##### Exceptions
16

    
17
def get_cur_query(cur):
18
    if hasattr(cur, 'query'): return cur.query
19
    elif hasattr(cur, '_last_executed'): return cur._last_executed
20
    else: return None
21

    
22
def _add_cursor_info(e, cur): exc.add_msg(e, 'query: '+get_cur_query(cur))
23

    
24
class DbException(exc.ExceptionWithCause):
25
    def __init__(self, msg, cause=None, cur=None):
26
        exc.ExceptionWithCause.__init__(self, msg, cause)
27
        if cur != None: _add_cursor_info(self, cur)
28

    
29
class NameException(DbException): pass
30

    
31
class ExceptionWithColumns(DbException):
32
    def __init__(self, cols, cause=None):
33
        DbException.__init__(self, 'columns: ' + ', '.join(cols), cause)
34
        self.cols = cols
35

    
36
class DuplicateKeyException(ExceptionWithColumns): pass
37

    
38
class NullValueException(ExceptionWithColumns): pass
39

    
40
class EmptyRowException(DbException): pass
41

    
42
##### Warnings
43

    
44
class DbWarning(UserWarning): pass
45

    
46
##### Input validation
47

    
48
def check_name(name):
49
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
50
        +'" may contain only alphanumeric characters and _')
51

    
52
def esc_name(db, name):
53
    module = util.root_module(db.db)
54
    if module == 'psycopg2': return name
55
        # Don't enclose in quotes because this disables case-insensitivity
56
    elif module == 'MySQLdb': quote = '`'
57
    else: raise NotImplementedError("Can't escape name for "+module+' database')
58
    return quote + name.replace(quote, '') + quote
59

    
60
##### Database connections
61

    
62
db_engines = {
63
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
64
    'PostgreSQL': ('psycopg2', {}),
65
}
66

    
67
DatabaseErrors_set = set([DbException])
68
DatabaseErrors = tuple(DatabaseErrors_set)
69

    
70
def _add_module(module):
71
    DatabaseErrors_set.add(module.DatabaseError)
72
    global DatabaseErrors
73
    DatabaseErrors = tuple(DatabaseErrors_set)
74

    
75
def db_config_str(db_config):
76
    return db_config['engine']+' database '+db_config['database']
77

    
78
def _query_lookup(query, params): return (query, dicts.make_hashable(params))
79

    
80
log_debug_none = lambda msg: None
81

    
82
class DbConn:
83
    def __init__(self, db_config, serializable=True, log_debug=log_debug_none):
84
        self.db_config = db_config
85
        self.serializable = serializable
86
        self.log_debug = log_debug
87
        
88
        self.__db = None
89
        self.pkeys = {}
90
        self.query_results = {}
91
    
92
    def __getattr__(self, name):
93
        if name == '__dict__': raise Exception('getting __dict__')
94
        if name == 'db': return self._db()
95
        else: raise AttributeError()
96
    
97
    def __getstate__(self):
98
        state = copy.copy(self.__dict__) # shallow copy
99
        state['_DbConn__db'] = None # don't pickle the connection
100
        return state
101
    
102
    def _db(self):
103
        if self.__db == None:
104
            # Process db_config
105
            db_config = self.db_config.copy() # don't modify input!
106
            module_name, mappings = db_engines[db_config.pop('engine')]
107
            module = __import__(module_name)
108
            _add_module(module)
109
            for orig, new in mappings.iteritems():
110
                try: util.rename_key(db_config, orig, new)
111
                except KeyError: pass
112
            
113
            # Connect
114
            self.__db = module.connect(**db_config)
115
            
116
            # Configure connection
117
            if self.serializable: run_raw_query(self,
118
                'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
119
        
120
        return self.__db
121
    
122
    class DbCursor(Proxy):
123
        def __init__(self, outer, cache_results):
124
            Proxy.__init__(self, outer.db.cursor())
125
            if cache_results: self.query_results = outer.query_results
126
            else: self.query_results = None
127
            self.query_lookup = None
128
            self.result = []
129
        
130
        def execute(self, query, params=None):
131
            self.query_lookup = _query_lookup(query, params)
132
            try: return_value = self.inner.execute(query, params)
133
            except Exception, e:
134
                self.result = e # cache the exception as the result
135
                self._cache_result()
136
                raise
137
            finally: self.query = get_cur_query(self.inner)
138
            return return_value
139
        
140
        def fetchone(self):
141
            row = self.inner.fetchone()
142
            if row != None: self.result.append(row)
143
            # otherwise, fetched all rows
144
            else: self._cache_result()
145
            return row
146
        
147
        def _cache_result(self):
148
            is_insert = self._is_insert()
149
            # For inserts, only cache exceptions since inserts are not
150
            # idempotent, but an invalid insert will always be invalid
151
            if self.query_results != None and (not is_insert
152
                or isinstance(self.result, Exception)):
153
                
154
                assert self.query_lookup != None
155
                self.query_results[self.query_lookup] = util.dict_subset(
156
                    dicts.AttrsDictView(self),
157
                    ['query', 'result', 'rowcount', 'description'])
158
        
159
        def _is_insert(self): return self.query.upper().find('INSERT') >= 0
160
    
161
    class CacheCursor:
162
        def __init__(self, cached_result): self.__dict__ = cached_result
163
        
164
        def execute(self):
165
            if isinstance(self.result, Exception): raise self.result
166
            # otherwise, result is a rows list
167
            self.iter = iter(self.result)
168
        
169
        def fetchone(self):
170
            try: return self.iter.next()
171
            except StopIteration: return None
172
    
173
    def run_query(self, query, params=None, cacheable=False):
174
        query_lookup = _query_lookup(query, params)
175
        used_cache = False
176
        try:
177
            try:
178
                if not cacheable: raise KeyError
179
                cached_result = self.query_results[query_lookup]
180
                used_cache = True
181
            except KeyError:
182
                cur = self.DbCursor(self, cacheable)
183
                try: cur.execute(query, params)
184
                except Exception, e:
185
                    _add_cursor_info(e, cur)
186
                    raise
187
            else:
188
                cur = self.CacheCursor(cached_result)
189
                cur.execute()
190
        finally:
191
            if self.log_debug != log_debug_none: # only compute msg if needed
192
                if used_cache: cache_status = 'Cache hit'
193
                elif cacheable: cache_status = 'Cache miss'
194
                else: cache_status = 'Non-cacheable'
195
                self.log_debug(cache_status+': '+strings.one_line(cur.query))
196
        
197
        return cur
198
    
199
    def is_cached(self, query, params=None):
200
        return _query_lookup(query, params) in self.query_results
201

    
202
connect = DbConn
203

    
204
##### Querying
205

    
206
def run_raw_query(db, *args, **kw_args):
207
    '''For args, see DbConn.run_query()'''
208
    return db.run_query(*args, **kw_args)
209

    
210
##### Recoverable querying
211

    
212
def with_savepoint(db, func):
213
    savepoint = 'savepoint_'+str(rand.rand_int()) # must be unique
214
    run_raw_query(db, 'SAVEPOINT '+savepoint)
215
    try: return_val = func()
216
    except:
217
        run_raw_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
218
        raise
219
    else:
220
        run_raw_query(db, 'RELEASE SAVEPOINT '+savepoint)
221
        return return_val
222

    
223
def run_query(db, query, params=None, recover=None, cacheable=False):
224
    if recover == None: recover = False
225
    
226
    def run(): return run_raw_query(db, query, params, cacheable)
227
    if recover and not db.is_cached(query, params):
228
        return with_savepoint(db, run)
229
    else: return run() # don't need savepoint if cached
230

    
231
##### Result retrieval
232

    
233
def col_names(cur): return (col[0] for col in cur.description)
234

    
235
def rows(cur): return iter(lambda: cur.fetchone(), None)
236

    
237
def next_row(cur): return rows(cur).next()
238

    
239
def row(cur):
240
    row_iter = rows(cur)
241
    row_ = row_iter.next()
242
    iters.consume_iter(row_iter) # fetch all rows so result will be cached
243
    return row_
244

    
245
def next_value(cur): return next_row(cur)[0]
246

    
247
def value(cur): return row(cur)[0]
248

    
249
def values(cur): return iters.func_iter(lambda: next_value(cur))
250

    
251
def value_or_none(cur):
252
    try: return value(cur)
253
    except StopIteration: return None
254

    
255
##### Basic queries
256

    
257
def select(db, table, fields=None, conds=None, limit=None, start=None,
258
    recover=None, cacheable=True):
259
    '''@param fields Use None to select all fields in the table'''
260
    if conds == None: conds = {}
261
    assert limit == None or type(limit) == int
262
    assert start == None or type(start) == int
263
    check_name(table)
264
    if fields != None: map(check_name, fields)
265
    map(check_name, conds.keys())
266
    
267
    def cond(entry):
268
        col, value = entry
269
        cond_ = esc_name(db, col)+' '
270
        if value == None: cond_ += 'IS'
271
        else: cond_ += '='
272
        cond_ += ' %s'
273
        return cond_
274
    query = 'SELECT '
275
    if fields == None: query += '*'
276
    else: query += ', '.join([esc_name(db, field) for field in fields])
277
    query += ' FROM '+esc_name(db, table)
278
    
279
    missing = True
280
    if conds != {}:
281
        query += ' WHERE '+' AND '.join(map(cond, conds.iteritems()))
282
        missing = False
283
    if limit != None: query += ' LIMIT '+str(limit); missing = False
284
    if start != None:
285
        if start != 0: query += ' OFFSET '+str(start)
286
        missing = False
287
    if missing: warnings.warn(DbWarning(
288
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
289
    
290
    return run_query(db, query, conds.values(), recover, cacheable)
291

    
292
def insert(db, table, row, returning=None, recover=None, cacheable=True):
293
    '''@param returning str|None An inserted column (such as pkey) to return'''
294
    check_name(table)
295
    cols = row.keys()
296
    map(check_name, cols)
297
    query = 'INSERT INTO '+table
298
    
299
    if row != {}: query += ' ('+', '.join(cols)+') VALUES ('\
300
        +', '.join(['%s']*len(cols))+')'
301
    else: query += ' DEFAULT VALUES'
302
    
303
    if returning != None:
304
        check_name(returning)
305
        query += ' RETURNING '+returning
306
    
307
    return run_query(db, query, row.values(), recover, cacheable)
308

    
309
def last_insert_id(db):
310
    module = util.root_module(db.db)
311
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
312
    elif module == 'MySQLdb': return db.insert_id()
313
    else: return None
314

    
315
def truncate(db, table):
316
    check_name(table)
317
    return run_raw_query(db, 'TRUNCATE '+table+' CASCADE')
318

    
319
##### Database structure queries
320

    
321
def pkey(db, table, recover=None):
322
    '''Assumed to be first column in table'''
323
    check_name(table)
324
    if table not in db.pkeys:
325
        db.pkeys[table] = col_names(run_query(db,
326
            'SELECT * FROM '+table+' LIMIT 0', recover=recover)).next()
327
    return db.pkeys[table]
328

    
329
def index_cols(db, table, index):
330
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
331
    automatically created. When you don't know whether something is a UNIQUE
332
    constraint or a UNIQUE index, use this function.'''
333
    check_name(table)
334
    check_name(index)
335
    module = util.root_module(db.db)
336
    if module == 'psycopg2':
337
        return list(values(run_query(db, '''\
338
SELECT attname
339
FROM
340
(
341
        SELECT attnum, attname
342
        FROM pg_index
343
        JOIN pg_class index ON index.oid = indexrelid
344
        JOIN pg_class table_ ON table_.oid = indrelid
345
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
346
        WHERE
347
            table_.relname = %(table)s
348
            AND index.relname = %(index)s
349
    UNION
350
        SELECT attnum, attname
351
        FROM
352
        (
353
            SELECT
354
                indrelid
355
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
356
                    AS indkey
357
            FROM pg_index
358
            JOIN pg_class index ON index.oid = indexrelid
359
            JOIN pg_class table_ ON table_.oid = indrelid
360
            WHERE
361
                table_.relname = %(table)s
362
                AND index.relname = %(index)s
363
        ) s
364
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
365
) s
366
ORDER BY attnum
367
''',
368
            {'table': table, 'index': index}, cacheable=True)))
369
    else: raise NotImplementedError("Can't list index columns for "+module+
370
        ' database')
371

    
372
def constraint_cols(db, table, constraint):
373
    check_name(table)
374
    check_name(constraint)
375
    module = util.root_module(db.db)
376
    if module == 'psycopg2':
377
        return list(values(run_query(db, '''\
378
SELECT attname
379
FROM pg_constraint
380
JOIN pg_class ON pg_class.oid = conrelid
381
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
382
WHERE
383
    relname = %(table)s
384
    AND conname = %(constraint)s
385
ORDER BY attnum
386
''',
387
            {'table': table, 'constraint': constraint})))
388
    else: raise NotImplementedError("Can't list constraint columns for "+module+
389
        ' database')
390

    
391
def tables(db):
392
    module = util.root_module(db.db)
393
    if module == 'psycopg2':
394
        return values(run_query(db, "SELECT tablename from pg_tables "
395
            "WHERE schemaname = 'public' ORDER BY tablename"))
396
    elif module == 'MySQLdb': return values(run_query(db, 'SHOW TABLES'))
397
    else: raise NotImplementedError("Can't list tables for "+module+' database')
398

    
399
##### Database management
400

    
401
def empty_db(db):
402
    for table in tables(db): truncate(db, table)
403

    
404
##### Heuristic queries
405

    
406
def try_insert(db, table, row, returning=None):
407
    '''Recovers from errors'''
408
    try: return insert(db, table, row, returning, recover=True)
409
    except Exception, e:
410
        msg = str(e)
411
        match = re.search(r'duplicate key value violates unique constraint '
412
            r'"(([^\W_]+)_[^"]+)"', msg)
413
        if match:
414
            constraint, table = match.groups()
415
            try: cols = index_cols(db, table, constraint)
416
            except NotImplementedError: raise e
417
            else: raise DuplicateKeyException(cols, e)
418
        match = re.search(r'null value in column "(\w+)" violates not-null '
419
            'constraint', msg)
420
        if match: raise NullValueException([match.group(1)], e)
421
        raise # no specific exception raised
422

    
423
def put(db, table, row, pkey, row_ct_ref=None):
424
    '''Recovers from errors.
425
    Only works under PostgreSQL (uses `INSERT ... RETURNING`)'''
426
    try:
427
        cur = try_insert(db, table, row, pkey)
428
        if row_ct_ref != None and cur.rowcount >= 0:
429
            row_ct_ref[0] += cur.rowcount
430
        return value(cur)
431
    except DuplicateKeyException, e:
432
        return value(select(db, table, [pkey],
433
            util.dict_subset_right_join(row, e.cols), recover=True))
434

    
435
def get(db, table, row, pkey, row_ct_ref=None, create=False):
436
    '''Recovers from errors'''
437
    try: return value(select(db, table, [pkey], row, 1, recover=True))
438
    except StopIteration:
439
        if not create: raise
440
        return put(db, table, row, pkey, row_ct_ref) # insert new row
(22-22/33)