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] = (self.query,
156
                    self.result, self.rowcount)
157
        
158
        def _is_insert(self): return self.query.upper().find('INSERT') >= 0
159
    
160
    class CacheCursor:
161
        def __init__(self, query, result, rowcount):
162
            self.query = query
163
            self.result = result
164
            self.rowcount = rowcount
165
        
166
        def execute(self):
167
            if isinstance(self.result, Exception): raise self.result
168
            # otherwise, result is a rows list
169
            self.iter = iter(self.result)
170
        
171
        def fetchone(self):
172
            try: return self.iter.next()
173
            except StopIteration: return None
174
    
175
    def run_query(self, query, params=None, cacheable=False):
176
        query_lookup = _query_lookup(query, params)
177
        used_cache = False
178
        try:
179
            try:
180
                if not cacheable: raise KeyError
181
                cached_result = self.query_results[query_lookup]
182
                used_cache = True
183
            except KeyError:
184
                cur = self.DbCursor(self, cacheable)
185
                try: cur.execute(query, params)
186
                except Exception, e:
187
                    _add_cursor_info(e, cur)
188
                    raise
189
            else:
190
                cur = self.CacheCursor(*cached_result)
191
                cur.execute()
192
        finally:
193
            if self.log_debug != log_debug_none: # only compute msg if needed
194
                if used_cache: cache_status = 'Cache hit'
195
                elif cacheable: cache_status = 'Cache miss'
196
                else: cache_status = 'Non-cacheable'
197
                self.log_debug(cache_status+': '+strings.one_line(cur.query))
198
        
199
        return cur
200

    
201
connect = DbConn
202

    
203
##### Querying
204

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

    
209
##### Recoverable querying
210

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

    
222
def run_query(db, query, params=None, recover=None, cacheable=False):
223
    if recover == None: recover = False
224
    
225
    def run(): return run_raw_query(db, query, params, cacheable)
226
    if recover: return with_savepoint(db, run)
227
    else: return run()
228

    
229
##### Result retrieval
230

    
231
def col_names(cur): return (col[0] for col in cur.description)
232

    
233
def rows(cur): return iter(lambda: cur.fetchone(), None)
234

    
235
def next_row(cur): return rows(cur).next()
236

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

    
243
def next_value(cur): return next_row(cur)[0]
244

    
245
def value(cur): return row(cur)[0]
246

    
247
def values(cur): return iters.func_iter(lambda: next_value(cur))
248

    
249
def value_or_none(cur):
250
    try: return value(cur)
251
    except StopIteration: return None
252

    
253
##### Basic queries
254

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

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

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

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

    
317
##### Database structure queries
318

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

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

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

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

    
397
##### Database management
398

    
399
def empty_db(db):
400
    for table in tables(db): truncate(db, table)
401

    
402
##### Heuristic queries
403

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

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

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