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
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 clean_name(name): return re.sub(r'\W', r'', name)
226

    
227
def check_name(name):
228
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
229
        +'" may contain only alphanumeric characters and _')
230

    
231
def esc_name_by_module(module, name, ignore_case=False):
232
    if module == 'psycopg2':
233
        if ignore_case:
234
            # Don't enclose in quotes because this disables case-insensitivity
235
            check_name(name)
236
            return name
237
        else: quote = '"'
238
    elif module == 'MySQLdb': quote = '`'
239
    else: raise NotImplementedError("Can't escape name for "+module+' database')
240
    return quote + name.replace(quote, '') + quote
241

    
242
def esc_name_by_engine(engine, name, **kw_args):
243
    return esc_name_by_module(db_engines[engine][0], name, **kw_args)
244

    
245
def esc_name(db, name, **kw_args):
246
    return esc_name_by_module(util.root_module(db.db), name, **kw_args)
247

    
248
def qual_name(db, schema, table):
249
    def esc_name_(name): return esc_name(db, name)
250
    table = esc_name_(table)
251
    if schema != None: return esc_name_(schema)+'.'+table
252
    else: return table
253

    
254
##### Querying
255

    
256
def run_raw_query(db, *args, **kw_args):
257
    '''For args, see DbConn.run_query()'''
258
    return db.run_query(*args, **kw_args)
259

    
260
def mogrify(db, query, params):
261
    module = util.root_module(db.db)
262
    if module == 'psycopg2': return db.db.cursor().mogrify(query, params)
263
    else: raise NotImplementedError("Can't mogrify query for "+module+
264
        ' database')
265

    
266
##### Recoverable querying
267

    
268
def with_savepoint(db, func):
269
    savepoint = 'savepoint_'+str(rand.rand_int()) # must be unique
270
    run_raw_query(db, 'SAVEPOINT '+savepoint)
271
    try: return_val = func()
272
    except:
273
        run_raw_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
274
        raise
275
    else:
276
        run_raw_query(db, 'RELEASE SAVEPOINT '+savepoint)
277
        return return_val
278

    
279
def run_query(db, query, params=None, recover=None, cacheable=False):
280
    if recover == None: recover = False
281
    
282
    def run(): return run_raw_query(db, query, params, cacheable)
283
    if recover and not db.is_cached(query, params):
284
        return with_savepoint(db, run)
285
    else: return run() # don't need savepoint if cached
286

    
287
##### Basic queries
288

    
289
def mk_select(db, table, fields=None, conds=None, limit=None, start=None,
290
    table_is_esc=False):
291
    '''
292
    @param fields Use None to select all fields in the table
293
    @param table_is_esc Whether the table name has already been escaped
294
    @return tuple(query, params)
295
    '''
296
    def esc_name_(name): return esc_name(db, name)
297
    
298
    if conds == None: conds = {}
299
    assert limit == None or type(limit) == int
300
    assert start == None or type(start) == int
301
    if not table_is_esc: table = esc_name_(table)
302
    
303
    params = []
304
    
305
    def parse_col(field):
306
        '''Parses fields'''
307
        if isinstance(field, tuple): # field is literal values
308
            value, col = field
309
            sql_ = '%s'
310
            params.append(value)
311
            if col != None: sql_ += ' AS '+esc_name_(col)
312
        else: sql_ = esc_name_(field) # field is col name
313
        return sql_
314
    def cond(entry):
315
        '''Parses conditions'''
316
        col, value = entry
317
        cond_ = esc_name_(col)+' '
318
        if value == None: cond_ += 'IS'
319
        else: cond_ += '='
320
        cond_ += ' %s'
321
        return cond_
322
    
323
    query = 'SELECT '
324
    if fields == None: query += '*'
325
    else: query += ', '.join(map(parse_col, fields))
326
    query += ' FROM '+table
327
    
328
    missing = True
329
    if conds != {}:
330
        query += ' WHERE '+' AND '.join(map(cond, conds.iteritems()))
331
        params += conds.values()
332
        missing = False
333
    if limit != None: query += ' LIMIT '+str(limit); missing = False
334
    if start != None:
335
        if start != 0: query += ' OFFSET '+str(start)
336
        missing = False
337
    if missing: warnings.warn(DbWarning(
338
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
339
    
340
    return (query, params)
341

    
342
def select(db, *args, **kw_args):
343
    '''For params, see mk_select() and run_query()'''
344
    recover = kw_args.pop('recover', None)
345
    cacheable = kw_args.pop('cacheable', True)
346
    
347
    query, params = mk_select(db, *args, **kw_args)
348
    return run_query(db, query, params, recover, cacheable)
349

    
350
def mk_insert_select(db, table, cols=None, select_query=None, params=None,
351
    returning=None, embeddable=False, table_is_esc=False):
352
    '''
353
    @param returning str|None An inserted column (such as pkey) to return
354
    @param embeddable Whether the query should be embeddable as a nested SELECT.
355
        Warning: If you set this and cacheable=True when the query is run, the
356
        query will be fully cached, not just if it raises an exception.
357
    @param table_is_esc Whether the table name has already been escaped
358
    '''
359
    if select_query == None: select_query = 'DEFAULT VALUES'
360
    if cols == []: cols = None # no cols (all defaults) = unknown col names
361
    if not table_is_esc: check_name(table)
362
    
363
    # Build query
364
    query = 'INSERT INTO '+table
365
    if cols != None:
366
        map(check_name, cols)
367
        query += ' ('+', '.join(cols)+')'
368
    query += ' '+select_query
369
    
370
    if returning != None:
371
        check_name(returning)
372
        query += ' RETURNING '+returning
373
    
374
    if embeddable:
375
        # Create function
376
        function = '_'.join(map(clean_name, ['insert', table] + cols))
377
        qual_function = 'pg_temp.'+function
378
        return_type = 'SETOF '+table+'.'+returning+'%TYPE'
379
        function_query = '''\
380
CREATE OR REPLACE FUNCTION '''+qual_function+'''() RETURNS '''+return_type+'''
381
    LANGUAGE sql
382
    AS $$'''+mogrify(db, query, params)+''';$$;
383
'''
384
        run_query(db, function_query, cacheable=True)
385
        
386
        # Return query that uses function
387
        return mk_select(db, qual_function+'() AS '+function+' ('+returning+')',
388
            table_is_esc=True) # function alias is required in AS clause
389
    
390
    return (query, params)
391

    
392
def insert_select(db, *args, **kw_args):
393
    '''For params, see mk_insert_select() and run_query()
394
    @param into Name of temp table to place RETURNING values in
395
    '''
396
    into = kw_args.pop('into', None)
397
    if into != None: kw_args['embeddable'] = True
398
    recover = kw_args.pop('recover', None)
399
    cacheable = kw_args.pop('cacheable', True)
400
    
401
    query, params = mk_insert_select(db, *args, **kw_args)
402
    if into == None: # return RETURNING values
403
        return run_query(db, query, params, recover, cacheable)
404
    else: # place RETURNING values in temp table
405
        run_query(db, 'DROP TABLE IF EXISTS '+into+' CASCADE', recover,
406
            cacheable)
407
        return run_query(db, 'CREATE TEMP TABLE '+into+' AS '+query, params,
408
            recover, cacheable) # CREATE TABLE sets rowcount to # inserts
409

    
410
default = object() # tells insert() to use the default value for a column
411

    
412
def insert(db, table, row, *args, **kw_args):
413
    '''For args, see insert_select()'''
414
    if lists.is_seq(row): cols = None
415
    else:
416
        cols = row.keys()
417
        row = row.values()
418
    row = list(row) # ensure that "!= []" works
419
    
420
    # Check for special values
421
    labels = []
422
    values = []
423
    for value in row:
424
        if value == default: labels.append('DEFAULT')
425
        else:
426
            labels.append('%s')
427
            values.append(value)
428
    
429
    # Build query
430
    if values != []: query = ' VALUES ('+(', '.join(labels))+')'
431
    else: query = None
432
    
433
    return insert_select(db, table, cols, query, values, *args, **kw_args)
434

    
435
def last_insert_id(db):
436
    module = util.root_module(db.db)
437
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
438
    elif module == 'MySQLdb': return db.insert_id()
439
    else: return None
440

    
441
def truncate(db, table, schema='public'):
442
    return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
443

    
444
##### Database structure queries
445

    
446
def pkey(db, table, recover=None):
447
    '''Assumed to be first column in table'''
448
    check_name(table)
449
    return col_names(select(db, table, limit=0, recover=recover)).next()
450

    
451
def index_cols(db, table, index):
452
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
453
    automatically created. When you don't know whether something is a UNIQUE
454
    constraint or a UNIQUE index, use this function.'''
455
    check_name(table)
456
    check_name(index)
457
    module = util.root_module(db.db)
458
    if module == 'psycopg2':
459
        return list(values(run_query(db, '''\
460
SELECT attname
461
FROM
462
(
463
        SELECT attnum, attname
464
        FROM pg_index
465
        JOIN pg_class index ON index.oid = indexrelid
466
        JOIN pg_class table_ ON table_.oid = indrelid
467
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
468
        WHERE
469
            table_.relname = %(table)s
470
            AND index.relname = %(index)s
471
    UNION
472
        SELECT attnum, attname
473
        FROM
474
        (
475
            SELECT
476
                indrelid
477
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
478
                    AS indkey
479
            FROM pg_index
480
            JOIN pg_class index ON index.oid = indexrelid
481
            JOIN pg_class table_ ON table_.oid = indrelid
482
            WHERE
483
                table_.relname = %(table)s
484
                AND index.relname = %(index)s
485
        ) s
486
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
487
) s
488
ORDER BY attnum
489
''',
490
            {'table': table, 'index': index}, cacheable=True)))
491
    else: raise NotImplementedError("Can't list index columns for "+module+
492
        ' database')
493

    
494
def constraint_cols(db, table, constraint):
495
    check_name(table)
496
    check_name(constraint)
497
    module = util.root_module(db.db)
498
    if module == 'psycopg2':
499
        return list(values(run_query(db, '''\
500
SELECT attname
501
FROM pg_constraint
502
JOIN pg_class ON pg_class.oid = conrelid
503
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
504
WHERE
505
    relname = %(table)s
506
    AND conname = %(constraint)s
507
ORDER BY attnum
508
''',
509
            {'table': table, 'constraint': constraint})))
510
    else: raise NotImplementedError("Can't list constraint columns for "+module+
511
        ' database')
512

    
513
def tables(db, schema='public', table_like='%'):
514
    module = util.root_module(db.db)
515
    params = {'schema': schema, 'table_like': table_like}
516
    if module == 'psycopg2':
517
        return values(run_query(db, '''\
518
SELECT tablename
519
FROM pg_tables
520
WHERE
521
    schemaname = %(schema)s
522
    AND tablename LIKE %(table_like)s
523
ORDER BY tablename
524
''',
525
            params, cacheable=True))
526
    elif module == 'MySQLdb':
527
        return values(run_query(db, 'SHOW TABLES LIKE %(table_like)s', params,
528
            cacheable=True))
529
    else: raise NotImplementedError("Can't list tables for "+module+' database')
530

    
531
##### Database management
532

    
533
def empty_db(db, schema='public', **kw_args):
534
    '''For kw_args, see tables()'''
535
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
536

    
537
##### Heuristic queries
538

    
539
def with_parsed_errors(db, func):
540
    '''Translates known DB errors to typed exceptions'''
541
    try: return func()
542
    except Exception, e:
543
        msg = str(e)
544
        match = re.search(r'duplicate key value violates unique constraint '
545
            r'"(([^\W_]+)_[^"]+)"', msg)
546
        if match:
547
            constraint, table = match.groups()
548
            try: cols = index_cols(db, table, constraint)
549
            except NotImplementedError: raise e
550
            else: raise DuplicateKeyException(cols, e)
551
        match = re.search(r'null value in column "(\w+)" violates not-null '
552
            'constraint', msg)
553
        if match: raise NullValueException([match.group(1)], e)
554
        raise # no specific exception raised
555

    
556
def try_insert(db, table, row, returning=None):
557
    '''Recovers from errors'''
558
    return with_parsed_errors(db, lambda: insert(db, table, row, returning,
559
        recover=True))
560

    
561
def put(db, table, row, pkey, row_ct_ref=None):
562
    '''Recovers from errors.
563
    Only works under PostgreSQL (uses INSERT RETURNING).
564
    '''
565
    try:
566
        cur = try_insert(db, table, row, pkey)
567
        if row_ct_ref != None and cur.rowcount >= 0:
568
            row_ct_ref[0] += cur.rowcount
569
        return value(cur)
570
    except DuplicateKeyException, e:
571
        return value(select(db, table, [pkey],
572
            util.dict_subset_right_join(row, e.cols), recover=True))
573

    
574
def get(db, table, row, pkey, row_ct_ref=None, create=False):
575
    '''Recovers from errors'''
576
    try: return value(select(db, table, [pkey], row, 1, recover=True))
577
    except StopIteration:
578
        if not create: raise
579
        return put(db, table, row, pkey, row_ct_ref) # insert new row
580

    
581
def put_table(db, out_table, out_cols, in_table, in_cols, pkey, row_ct_ref=None,
582
    table_is_esc=False):
583
    '''Recovers from errors.
584
    Only works under PostgreSQL (uses INSERT RETURNING).
585
    @return tuple(table, col) Where the pkeys (from INSERT RETURNING) are made
586
        available
587
    '''
588
    pkeys_table = clean_name(out_table)+'_pkeys'
589
    def insert_():
590
        return insert_select(db, out_table, out_cols,
591
            *mk_select(db, in_table, in_cols, table_is_esc=table_is_esc),
592
            returning=pkey, into=pkeys_table, recover=True,
593
            table_is_esc=table_is_esc)
594
    try:
595
        cur = with_parsed_errors(db, insert_)
596
        if row_ct_ref != None and cur.rowcount >= 0:
597
            row_ct_ref[0] += cur.rowcount
598
        return (pkeys_table, None)
599
    except DuplicateKeyException, e: raise
(22-22/33)