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
##### Input validation
75

    
76
def clean_name(name): return re.sub(r'\W', r'', name)
77

    
78
def check_name(name):
79
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
80
        +'" may contain only alphanumeric characters and _')
81

    
82
def esc_name_by_module(module, name, ignore_case=False):
83
    if module == 'psycopg2':
84
        if ignore_case:
85
            # Don't enclose in quotes because this disables case-insensitivity
86
            check_name(name)
87
            return name
88
        else: quote = '"'
89
    elif module == 'MySQLdb': quote = '`'
90
    else: raise NotImplementedError("Can't escape name for "+module+' database')
91
    return quote + name.replace(quote, '') + quote
92

    
93
def esc_name_by_engine(engine, name, **kw_args):
94
    return esc_name_by_module(db_engines[engine][0], name, **kw_args)
95

    
96
def esc_name(db, name, **kw_args):
97
    return esc_name_by_module(util.root_module(db.db), name, **kw_args)
98

    
99
def qual_name(db, schema, table):
100
    def esc_name_(name): return esc_name(db, name)
101
    table = esc_name_(table)
102
    if schema != None: return esc_name_(schema)+'.'+table
103
    else: return table
104

    
105
##### Database connections
106

    
107
db_config_names = ['engine', 'host', 'user', 'password', 'database', 'schemas']
108

    
109
db_engines = {
110
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
111
    'PostgreSQL': ('psycopg2', {}),
112
}
113

    
114
DatabaseErrors_set = set([DbException])
115
DatabaseErrors = tuple(DatabaseErrors_set)
116

    
117
def _add_module(module):
118
    DatabaseErrors_set.add(module.DatabaseError)
119
    global DatabaseErrors
120
    DatabaseErrors = tuple(DatabaseErrors_set)
121

    
122
def db_config_str(db_config):
123
    return db_config['engine']+' database '+db_config['database']
124

    
125
def _query_lookup(query, params): return (query, dicts.make_hashable(params))
126

    
127
log_debug_none = lambda msg: None
128

    
129
class DbConn:
130
    def __init__(self, db_config, serializable=True, log_debug=log_debug_none,
131
        caching=True):
132
        self.db_config = db_config
133
        self.serializable = serializable
134
        self.log_debug = log_debug
135
        self.caching = caching
136
        
137
        self.__db = None
138
        self.query_results = {}
139
    
140
    def __getattr__(self, name):
141
        if name == '__dict__': raise Exception('getting __dict__')
142
        if name == 'db': return self._db()
143
        else: raise AttributeError()
144
    
145
    def __getstate__(self):
146
        state = copy.copy(self.__dict__) # shallow copy
147
        state['log_debug'] = None # don't pickle the debug callback
148
        state['_DbConn__db'] = None # don't pickle the connection
149
        return state
150
    
151
    def _db(self):
152
        if self.__db == None:
153
            # Process db_config
154
            db_config = self.db_config.copy() # don't modify input!
155
            schemas = db_config.pop('schemas', None)
156
            module_name, mappings = db_engines[db_config.pop('engine')]
157
            module = __import__(module_name)
158
            _add_module(module)
159
            for orig, new in mappings.iteritems():
160
                try: util.rename_key(db_config, orig, new)
161
                except KeyError: pass
162
            
163
            # Connect
164
            self.__db = module.connect(**db_config)
165
            
166
            # Configure connection
167
            if self.serializable: run_raw_query(self,
168
                'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
169
            if schemas != None:
170
                schemas_ = ''.join((esc_name(self, s)+', '
171
                    for s in schemas.split(',')))
172
                run_raw_query(self, "SELECT set_config('search_path', \
173
%s || current_setting('search_path'), false)", [schemas_])
174
        
175
        return self.__db
176
    
177
    class DbCursor(Proxy):
178
        def __init__(self, outer):
179
            Proxy.__init__(self, outer.db.cursor())
180
            self.query_results = outer.query_results
181
            self.query_lookup = None
182
            self.result = []
183
        
184
        def execute(self, query, params=None):
185
            self._is_insert = query.upper().find('INSERT') >= 0
186
            self.query_lookup = _query_lookup(query, params)
187
            try: return_value = self.inner.execute(query, params)
188
            except Exception, e:
189
                self.result = e # cache the exception as the result
190
                self._cache_result()
191
                raise
192
            finally: self.query = get_cur_query(self.inner)
193
            # Fetch all rows so result will be cached
194
            if self.rowcount == 0 and not self._is_insert: consume_rows(self)
195
            return return_value
196
        
197
        def fetchone(self):
198
            row = self.inner.fetchone()
199
            if row != None: self.result.append(row)
200
            # otherwise, fetched all rows
201
            else: self._cache_result()
202
            return row
203
        
204
        def _cache_result(self):
205
            # For inserts, only cache exceptions since inserts are not
206
            # idempotent, but an invalid insert will always be invalid
207
            if self.query_results != None and (not self._is_insert
208
                or isinstance(self.result, Exception)):
209
                
210
                assert self.query_lookup != None
211
                self.query_results[self.query_lookup] = self.CacheCursor(
212
                    util.dict_subset(dicts.AttrsDictView(self),
213
                    ['query', 'result', 'rowcount', 'description']))
214
        
215
        class CacheCursor:
216
            def __init__(self, cached_result): self.__dict__ = cached_result
217
            
218
            def execute(self, *args, **kw_args):
219
                if isinstance(self.result, Exception): raise self.result
220
                # otherwise, result is a rows list
221
                self.iter = iter(self.result)
222
            
223
            def fetchone(self):
224
                try: return self.iter.next()
225
                except StopIteration: return None
226
    
227
    def run_query(self, query, params=None, cacheable=False):
228
        if not self.caching: cacheable = False
229
        used_cache = False
230
        try:
231
            # Get cursor
232
            if cacheable:
233
                query_lookup = _query_lookup(query, params)
234
                try:
235
                    cur = self.query_results[query_lookup]
236
                    used_cache = True
237
                except KeyError: cur = self.DbCursor(self)
238
            else: cur = self.db.cursor()
239
            
240
            # Run query
241
            try: cur.execute(query, params)
242
            except Exception, e:
243
                _add_cursor_info(e, cur)
244
                raise
245
        finally:
246
            if self.log_debug != log_debug_none: # only compute msg if needed
247
                if used_cache: cache_status = 'Cache hit'
248
                elif cacheable: cache_status = 'Cache miss'
249
                else: cache_status = 'Non-cacheable'
250
                self.log_debug(cache_status+': '
251
                    +strings.one_line(get_cur_query(cur)))
252
        
253
        return cur
254
    
255
    def is_cached(self, query, params=None):
256
        return _query_lookup(query, params) in self.query_results
257

    
258
connect = DbConn
259

    
260
##### Querying
261

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

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

    
272
##### Recoverable querying
273

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

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

    
293
##### Basic queries
294

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

    
307
order_by_pkey = object() # tells mk_select() to order by the pkey
308

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

    
365
def select(db, *args, **kw_args):
366
    '''For params, see mk_select() and run_query()'''
367
    recover = kw_args.pop('recover', None)
368
    cacheable = kw_args.pop('cacheable', True)
369
    
370
    query, params = mk_select(db, *args, **kw_args)
371
    return run_query(db, query, params, recover, cacheable)
372

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

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

    
427
default = object() # tells insert() to use the default value for a column
428

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

    
452
def last_insert_id(db):
453
    module = util.root_module(db.db)
454
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
455
    elif module == 'MySQLdb': return db.insert_id()
456
    else: return None
457

    
458
def truncate(db, table, schema='public'):
459
    return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
460

    
461
##### Database structure queries
462

    
463
def pkey(db, table, recover=None, table_is_esc=False):
464
    '''Assumed to be first column in table'''
465
    return col_names(select(db, table, limit=0, order_by=None, recover=recover,
466
        table_is_esc=table_is_esc)).next()
467

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

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

    
530
row_num_col = '_row_num'
531

    
532
def add_row_num(db, table):
533
    '''Adds a row number column to a table. Its name is in row_num_col. It will
534
    be the primary key.'''
535
    check_name(table)
536
    run_query(db, 'ALTER TABLE '+table+' ADD COLUMN '+row_num_col
537
        +' serial NOT NULL PRIMARY KEY')
538

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

    
557
##### Database management
558

    
559
def empty_db(db, schema='public', **kw_args):
560
    '''For kw_args, see tables()'''
561
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
562

    
563
##### Heuristic queries
564

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

    
582
def try_insert(db, table, row, returning=None):
583
    '''Recovers from errors'''
584
    return with_parsed_errors(db, lambda: insert(db, table, row, returning,
585
        recover=True))
586

    
587
def put(db, table, row, pkey_=None, row_ct_ref=None):
588
    '''Recovers from errors.
589
    Only works under PostgreSQL (uses INSERT RETURNING).
590
    '''
591
    if pkey_ == None: pkey_ = pkey(db, table, recover=True)
592
    
593
    try:
594
        cur = try_insert(db, table, row, pkey_)
595
        if row_ct_ref != None and cur.rowcount >= 0:
596
            row_ct_ref[0] += cur.rowcount
597
        return value(cur)
598
    except DuplicateKeyException, e:
599
        return value(select(db, table, [pkey_],
600
            util.dict_subset_right_join(row, e.cols), recover=True))
601

    
602
def get(db, table, row, pkey, row_ct_ref=None, create=False):
603
    '''Recovers from errors'''
604
    try: return value(select(db, table, [pkey], row, 1, recover=True))
605
    except StopIteration:
606
        if not create: raise
607
        return put(db, table, row, pkey, row_ct_ref) # insert new row
608

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

    
633
##### Data cleanup
634

    
635
def cleanup_table(db, table, cols, table_is_esc=False):
636
    def esc_name_(name): return esc_name(db, name)
637
    
638
    if not table_is_esc: check_name(table)
639
    cols = map(esc_name_, cols)
640
    
641
    run_query(db, 'UPDATE '+table+' SET\n'+(',\n'.join(('\n'+col
642
        +' = nullif(nullif(trim(both from '+col+"), %(null0)s), %(null1)s)"
643
            for col in cols))),
644
        dict(null0='', null1=r'\N'))
(22-22/33)