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', 'schemas']
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
            schemas = db_config.pop('schemas', None)
125
            module_name, mappings = db_engines[db_config.pop('engine')]
126
            module = __import__(module_name)
127
            _add_module(module)
128
            for orig, new in mappings.iteritems():
129
                try: util.rename_key(db_config, orig, new)
130
                except KeyError: pass
131
            
132
            # Connect
133
            self.__db = module.connect(**db_config)
134
            
135
            # Configure connection
136
            if schemas != None:
137
                schemas = schemas[:] # don't modify input!
138
                schemas.append('current_setting(search_path)')
139
                run_raw_query(self, 'SET search_path = '+(', '.join(schemas)))
140
            if self.serializable: run_raw_query(self,
141
                'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
142
        
143
        return self.__db
144
    
145
    class DbCursor(Proxy):
146
        def __init__(self, outer):
147
            Proxy.__init__(self, outer.db.cursor())
148
            self.query_results = outer.query_results
149
            self.query_lookup = None
150
            self.result = []
151
        
152
        def execute(self, query, params=None):
153
            self._is_insert = query.upper().find('INSERT') >= 0
154
            self.query_lookup = _query_lookup(query, params)
155
            try: return_value = self.inner.execute(query, params)
156
            except Exception, e:
157
                self.result = e # cache the exception as the result
158
                self._cache_result()
159
                raise
160
            finally: self.query = get_cur_query(self.inner)
161
            # Fetch all rows so result will be cached
162
            if self.rowcount == 0 and not self._is_insert: consume_rows(self)
163
            return return_value
164
        
165
        def fetchone(self):
166
            row = self.inner.fetchone()
167
            if row != None: self.result.append(row)
168
            # otherwise, fetched all rows
169
            else: self._cache_result()
170
            return row
171
        
172
        def _cache_result(self):
173
            # For inserts, only cache exceptions since inserts are not
174
            # idempotent, but an invalid insert will always be invalid
175
            if self.query_results != None and (not self._is_insert
176
                or isinstance(self.result, Exception)):
177
                
178
                assert self.query_lookup != None
179
                self.query_results[self.query_lookup] = self.CacheCursor(
180
                    util.dict_subset(dicts.AttrsDictView(self),
181
                    ['query', 'result', 'rowcount', 'description']))
182
        
183
        class CacheCursor:
184
            def __init__(self, cached_result): self.__dict__ = cached_result
185
            
186
            def execute(self, *args, **kw_args):
187
                if isinstance(self.result, Exception): raise self.result
188
                # otherwise, result is a rows list
189
                self.iter = iter(self.result)
190
            
191
            def fetchone(self):
192
                try: return self.iter.next()
193
                except StopIteration: return None
194
    
195
    def run_query(self, query, params=None, cacheable=False):
196
        if not self.caching: cacheable = False
197
        used_cache = False
198
        try:
199
            # Get cursor
200
            if cacheable:
201
                query_lookup = _query_lookup(query, params)
202
                try:
203
                    cur = self.query_results[query_lookup]
204
                    used_cache = True
205
                except KeyError: cur = self.DbCursor(self)
206
            else: cur = self.db.cursor()
207
            
208
            # Run query
209
            try: cur.execute(query, params)
210
            except Exception, e:
211
                _add_cursor_info(e, cur)
212
                raise
213
        finally:
214
            if self.log_debug != log_debug_none: # only compute msg if needed
215
                if used_cache: cache_status = 'Cache hit'
216
                elif cacheable: cache_status = 'Cache miss'
217
                else: cache_status = 'Non-cacheable'
218
                self.log_debug(cache_status+': '
219
                    +strings.one_line(get_cur_query(cur)))
220
        
221
        return cur
222
    
223
    def is_cached(self, query, params=None):
224
        return _query_lookup(query, params) in self.query_results
225

    
226
connect = DbConn
227

    
228
##### Input validation
229

    
230
def clean_name(name): return re.sub(r'\W', r'', name)
231

    
232
def check_name(name):
233
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
234
        +'" may contain only alphanumeric characters and _')
235

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

    
247
def esc_name_by_engine(engine, name, **kw_args):
248
    return esc_name_by_module(db_engines[engine][0], name, **kw_args)
249

    
250
def esc_name(db, name, **kw_args):
251
    return esc_name_by_module(util.root_module(db.db), name, **kw_args)
252

    
253
def qual_name(db, schema, table):
254
    def esc_name_(name): return esc_name(db, name)
255
    table = esc_name_(table)
256
    if schema != None: return esc_name_(schema)+'.'+table
257
    else: return table
258

    
259
##### Querying
260

    
261
def run_raw_query(db, *args, **kw_args):
262
    '''For params, see DbConn.run_query()'''
263
    return db.run_query(*args, **kw_args)
264

    
265
def mogrify(db, query, params):
266
    module = util.root_module(db.db)
267
    if module == 'psycopg2': return db.db.cursor().mogrify(query, params)
268
    else: raise NotImplementedError("Can't mogrify query for "+module+
269
        ' database')
270

    
271
##### Recoverable querying
272

    
273
def with_savepoint(db, func):
274
    savepoint = 'savepoint_'+str(rand.rand_int()) # must be unique
275
    run_raw_query(db, 'SAVEPOINT '+savepoint)
276
    try: return_val = func()
277
    except:
278
        run_raw_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
279
        raise
280
    else:
281
        run_raw_query(db, 'RELEASE SAVEPOINT '+savepoint)
282
        return return_val
283

    
284
def run_query(db, query, params=None, recover=None, cacheable=False):
285
    if recover == None: recover = False
286
    
287
    def run(): return run_raw_query(db, query, params, cacheable)
288
    if recover and not db.is_cached(query, params):
289
        return with_savepoint(db, run)
290
    else: return run() # don't need savepoint if cached
291

    
292
##### Basic queries
293

    
294
def run_query_into(db, query, params, into=None, *args, **kw_args):
295
    '''Outputs a query to a temp table.
296
    For params, see run_query().
297
    '''
298
    if into == None: return run_query(db, query, params, *args, **kw_args)
299
    else: # place rows in temp table
300
        check_name(into)
301
        
302
        run_query(db, 'DROP TABLE IF EXISTS '+into+' CASCADE', *args, **kw_args)
303
        return run_query(db, 'CREATE TEMP TABLE '+into+' AS '+query, params,
304
            *args, **kw_args) # CREATE TABLE sets rowcount to # rows in query
305

    
306
def mk_select(db, table, fields=None, conds=None, limit=None, start=None,
307
    table_is_esc=False):
308
    '''
309
    @param fields Use None to select all fields in the table
310
    @param table_is_esc Whether the table name has already been escaped
311
    @return tuple(query, params)
312
    '''
313
    def esc_name_(name): return esc_name(db, name)
314
    
315
    if conds == None: conds = {}
316
    assert limit == None or type(limit) == int
317
    assert start == None or type(start) == int
318
    if not table_is_esc: table = esc_name_(table)
319
    
320
    params = []
321
    
322
    def parse_col(field):
323
        '''Parses fields'''
324
        if isinstance(field, tuple): # field is literal values
325
            value, col = field
326
            sql_ = '%s'
327
            params.append(value)
328
            if col != None: sql_ += ' AS '+esc_name_(col)
329
        else: sql_ = esc_name_(field) # field is col name
330
        return sql_
331
    def cond(entry):
332
        '''Parses conditions'''
333
        col, value = entry
334
        cond_ = esc_name_(col)+' '
335
        if value == None: cond_ += 'IS'
336
        else: cond_ += '='
337
        cond_ += ' %s'
338
        return cond_
339
    
340
    query = 'SELECT '
341
    if fields == None: query += '*'
342
    else: query += ', '.join(map(parse_col, fields))
343
    query += ' FROM '+table
344
    
345
    missing = True
346
    if conds != {}:
347
        query += ' WHERE '+' AND '.join(map(cond, conds.iteritems()))
348
        params += conds.values()
349
        missing = False
350
    if limit != None: query += ' LIMIT '+str(limit); missing = False
351
    if start != None:
352
        if start != 0: query += ' OFFSET '+str(start)
353
        missing = False
354
    if missing: warnings.warn(DbWarning(
355
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
356
    
357
    return (query, params)
358

    
359
def select(db, *args, **kw_args):
360
    '''For params, see mk_select() and run_query()'''
361
    recover = kw_args.pop('recover', None)
362
    cacheable = kw_args.pop('cacheable', True)
363
    
364
    query, params = mk_select(db, *args, **kw_args)
365
    return run_query(db, query, params, recover, cacheable)
366

    
367
def mk_insert_select(db, table, cols=None, select_query=None, params=None,
368
    returning=None, embeddable=False, table_is_esc=False):
369
    '''
370
    @param returning str|None An inserted column (such as pkey) to return
371
    @param embeddable Whether the query should be embeddable as a nested SELECT.
372
        Warning: If you set this and cacheable=True when the query is run, the
373
        query will be fully cached, not just if it raises an exception.
374
    @param table_is_esc Whether the table name has already been escaped
375
    '''
376
    if select_query == None: select_query = 'DEFAULT VALUES'
377
    if cols == []: cols = None # no cols (all defaults) = unknown col names
378
    if not table_is_esc: check_name(table)
379
    
380
    # Build query
381
    query = 'INSERT INTO '+table
382
    if cols != None:
383
        map(check_name, cols)
384
        query += ' ('+', '.join(cols)+')'
385
    query += ' '+select_query
386
    
387
    if returning != None:
388
        check_name(returning)
389
        query += ' RETURNING '+returning
390
    
391
    if embeddable:
392
        # Create function
393
        function = 'pg_temp.'+('_'.join(map(clean_name,
394
            ['insert', table] + cols)))
395
        return_type = 'SETOF '+table+'.'+returning+'%TYPE'
396
        function_query = '''\
397
CREATE OR REPLACE FUNCTION '''+function+'''() RETURNS '''+return_type+'''
398
    LANGUAGE sql
399
    AS $$'''+mogrify(db, query, params)+''';$$;
400
'''
401
        run_query(db, function_query, cacheable=True)
402
        
403
        # Return query that uses function
404
        return mk_select(db, function+'() AS f ('+returning+')',
405
            table_is_esc=True) # function alias is required in AS clause
406
    
407
    return (query, params)
408

    
409
def insert_select(db, *args, **kw_args):
410
    '''For params, see mk_insert_select() and run_query_into()
411
    @param into Name of temp table to place RETURNING values in
412
    '''
413
    into = kw_args.pop('into', None)
414
    if into != None: kw_args['embeddable'] = True
415
    recover = kw_args.pop('recover', None)
416
    cacheable = kw_args.pop('cacheable', True)
417
    
418
    query, params = mk_insert_select(db, *args, **kw_args)
419
    return run_query_into(db, query, params, into, recover, cacheable)
420

    
421
default = object() # tells insert() to use the default value for a column
422

    
423
def insert(db, table, row, *args, **kw_args):
424
    '''For params, see insert_select()'''
425
    if lists.is_seq(row): cols = None
426
    else:
427
        cols = row.keys()
428
        row = row.values()
429
    row = list(row) # ensure that "!= []" works
430
    
431
    # Check for special values
432
    labels = []
433
    values = []
434
    for value in row:
435
        if value == default: labels.append('DEFAULT')
436
        else:
437
            labels.append('%s')
438
            values.append(value)
439
    
440
    # Build query
441
    if values != []: query = ' VALUES ('+(', '.join(labels))+')'
442
    else: query = None
443
    
444
    return insert_select(db, table, cols, query, values, *args, **kw_args)
445

    
446
def last_insert_id(db):
447
    module = util.root_module(db.db)
448
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
449
    elif module == 'MySQLdb': return db.insert_id()
450
    else: return None
451

    
452
def truncate(db, table, schema='public'):
453
    return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
454

    
455
##### Database structure queries
456

    
457
def pkey(db, table, recover=None, table_is_esc=False):
458
    '''Assumed to be first column in table'''
459
    return col_names(select(db, table, limit=0, recover=recover,
460
        table_is_esc=table_is_esc)).next()
461

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

    
505
def constraint_cols(db, table, constraint):
506
    check_name(table)
507
    check_name(constraint)
508
    module = util.root_module(db.db)
509
    if module == 'psycopg2':
510
        return list(values(run_query(db, '''\
511
SELECT attname
512
FROM pg_constraint
513
JOIN pg_class ON pg_class.oid = conrelid
514
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
515
WHERE
516
    relname = %(table)s
517
    AND conname = %(constraint)s
518
ORDER BY attnum
519
''',
520
            {'table': table, 'constraint': constraint})))
521
    else: raise NotImplementedError("Can't list constraint columns for "+module+
522
        ' database')
523

    
524
row_num_col = '_row_num'
525

    
526
def add_row_num(db, table):
527
    '''Adds a row number column to a table. Its name is in row_num_col.'''
528
    check_name(table)
529
    run_query(db, 'ALTER TABLE '+table+' ADD COLUMN '+row_num_col
530
        +' serial NOT NULL')
531

    
532
def tables(db, schema='public', table_like='%'):
533
    module = util.root_module(db.db)
534
    params = {'schema': schema, 'table_like': table_like}
535
    if module == 'psycopg2':
536
        return values(run_query(db, '''\
537
SELECT tablename
538
FROM pg_tables
539
WHERE
540
    schemaname = %(schema)s
541
    AND tablename LIKE %(table_like)s
542
ORDER BY tablename
543
''',
544
            params, cacheable=True))
545
    elif module == 'MySQLdb':
546
        return values(run_query(db, 'SHOW TABLES LIKE %(table_like)s', params,
547
            cacheable=True))
548
    else: raise NotImplementedError("Can't list tables for "+module+' database')
549

    
550
##### Database management
551

    
552
def empty_db(db, schema='public', **kw_args):
553
    '''For kw_args, see tables()'''
554
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
555

    
556
##### Heuristic queries
557

    
558
def with_parsed_errors(db, func):
559
    '''Translates known DB errors to typed exceptions'''
560
    try: return func()
561
    except Exception, e:
562
        msg = str(e)
563
        match = re.search(r'duplicate key value violates unique constraint '
564
            r'"(([^\W_]+)_[^"]+)"', msg)
565
        if match:
566
            constraint, table = match.groups()
567
            try: cols = index_cols(db, table, constraint)
568
            except NotImplementedError: raise e
569
            else: raise DuplicateKeyException(cols, e)
570
        match = re.search(r'null value in column "(\w+)" violates not-null '
571
            'constraint', msg)
572
        if match: raise NullValueException([match.group(1)], e)
573
        raise # no specific exception raised
574

    
575
def try_insert(db, table, row, returning=None):
576
    '''Recovers from errors'''
577
    return with_parsed_errors(db, lambda: insert(db, table, row, returning,
578
        recover=True))
579

    
580
def put(db, table, row, pkey, row_ct_ref=None):
581
    '''Recovers from errors.
582
    Only works under PostgreSQL (uses INSERT RETURNING).
583
    '''
584
    try:
585
        cur = try_insert(db, table, row, pkey)
586
        if row_ct_ref != None and cur.rowcount >= 0:
587
            row_ct_ref[0] += cur.rowcount
588
        return value(cur)
589
    except DuplicateKeyException, e:
590
        return value(select(db, table, [pkey],
591
            util.dict_subset_right_join(row, e.cols), recover=True))
592

    
593
def get(db, table, row, pkey, row_ct_ref=None, create=False):
594
    '''Recovers from errors'''
595
    try: return value(select(db, table, [pkey], row, 1, recover=True))
596
    except StopIteration:
597
        if not create: raise
598
        return put(db, table, row, pkey, row_ct_ref) # insert new row
599

    
600
def put_table(db, out_table, out_cols, in_tables, in_cols, pkey,
601
    row_ct_ref=None, table_is_esc=False):
602
    '''Recovers from errors.
603
    Only works under PostgreSQL (uses INSERT RETURNING).
604
    @return Name of the table where the pkeys (from INSERT RETURNING) are made
605
        available
606
    '''
607
    pkeys_table = clean_name(out_table)+'_pkeys'
608
    def insert_():
609
        return insert_select(db, out_table, out_cols,
610
            *mk_select(db, in_tables[0], in_cols, table_is_esc=table_is_esc),
611
            returning=pkey, into=pkeys_table, recover=True,
612
            table_is_esc=table_is_esc)
613
    try:
614
        cur = with_parsed_errors(db, insert_)
615
        if row_ct_ref != None and cur.rowcount >= 0:
616
            row_ct_ref[0] += cur.rowcount
617
        
618
        # Add row_num to pkeys_table, so it can be joined with in_table's pkeys
619
        add_row_num(db, pkeys_table)
620
        
621
        return pkeys_table
622
    except DuplicateKeyException, e: raise
(22-22/33)