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

    
198
connect = DbConn
199

    
200
##### Querying
201

    
202
def run_raw_query(db, *args, **kw_args):
203
    '''For args, see DbConn.run_query()'''
204
    return db.run_query(*args, **kw_args)
205

    
206
##### Recoverable querying
207

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

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

    
226
##### Result retrieval
227

    
228
def col_names(cur): return (col[0] for col in cur.description)
229

    
230
def rows(cur): return iter(lambda: cur.fetchone(), None)
231

    
232
def next_row(cur): return rows(cur).next()
233

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

    
240
def next_value(cur): return next_row(cur)[0]
241

    
242
def value(cur): return row(cur)[0]
243

    
244
def values(cur): return iters.func_iter(lambda: next_value(cur))
245

    
246
def value_or_none(cur):
247
    try: return value(cur)
248
    except StopIteration: return None
249

    
250
##### Basic queries
251

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

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

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

    
310
def truncate(db, table):
311
    check_name(table)
312
    return run_raw_query(db, 'TRUNCATE '+table+' CASCADE')
313

    
314
##### Database structure queries
315

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

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

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

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

    
394
##### Database management
395

    
396
def empty_db(db):
397
    for table in tables(db): truncate(db, table)
398

    
399
##### Heuristic queries
400

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

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

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