Project

General

Profile

1
# Database access
2

    
3
import copy
4
import re
5
import sys
6
import warnings
7

    
8
import exc
9
from Proxy import Proxy
10
import rand
11
import strings
12
import util
13

    
14
##### Exceptions
15

    
16
def get_cur_query(cur):
17
    if hasattr(cur, 'query'): return cur.query
18
    elif hasattr(cur, '_last_executed'): return cur._last_executed
19
    else: return None
20

    
21
def _add_cursor_info(e, cur): exc.add_msg(e, 'query: '+get_cur_query(cur))
22

    
23
class DbException(exc.ExceptionWithCause):
24
    def __init__(self, msg, cause=None, cur=None):
25
        exc.ExceptionWithCause.__init__(self, msg, cause)
26
        if cur != None: _add_cursor_info(self, cur)
27

    
28
class NameException(DbException): pass
29

    
30
class ExceptionWithColumns(DbException):
31
    def __init__(self, cols, cause=None):
32
        DbException.__init__(self, 'columns: ' + ', '.join(cols), cause)
33
        self.cols = cols
34

    
35
class DuplicateKeyException(ExceptionWithColumns): pass
36

    
37
class NullValueException(ExceptionWithColumns): pass
38

    
39
class EmptyRowException(DbException): pass
40

    
41
##### Warnings
42

    
43
class DbWarning(UserWarning): pass
44

    
45
##### Input validation
46

    
47
def check_name(name):
48
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
49
        +'" may contain only alphanumeric characters and _')
50

    
51
def esc_name(db, name):
52
    module = util.root_module(db.db)
53
    if module == 'psycopg2': return name
54
        # Don't enclose in quotes because this disables case-insensitivity
55
    elif module == 'MySQLdb': quote = '`'
56
    else: raise NotImplementedError("Can't escape name for "+module+' database')
57
    return quote + name.replace(quote, '') + quote
58

    
59
##### Database connections
60

    
61
db_engines = {
62
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
63
    'PostgreSQL': ('psycopg2', {}),
64
}
65

    
66
DatabaseErrors_set = set([DbException])
67
DatabaseErrors = tuple(DatabaseErrors_set)
68

    
69
def _add_module(module):
70
    DatabaseErrors_set.add(module.DatabaseError)
71
    global DatabaseErrors
72
    DatabaseErrors = tuple(DatabaseErrors_set)
73

    
74
def db_config_str(db_config):
75
    return db_config['engine']+' database '+db_config['database']
76

    
77
class DbConn:
78
    def __init__(self, db_config, serializable=True, debug=False):
79
        self.db_config = db_config
80
        self.serializable = serializable
81
        self.debug = debug
82
        
83
        self.__db = None
84
        self.pkeys = {}
85
        self.index_cols = {}
86
        self.query_results = {}
87
    
88
    def __getattr__(self, name):
89
        if name == '__dict__': raise Exception('getting __dict__')
90
        if name == 'db': return self._db()
91
        else: raise AttributeError()
92
    
93
    def __getstate__(self):
94
        state = copy.copy(self.__dict__) # shallow copy
95
        state['_DbConn__db'] = None # don't pickle the connection
96
        return state
97
    
98
    def _db(self):
99
        if self.__db == None:
100
            # Process db_config
101
            db_config = self.db_config.copy() # don't modify input!
102
            module_name, mappings = db_engines[db_config.pop('engine')]
103
            module = __import__(module_name)
104
            _add_module(module)
105
            for orig, new in mappings.iteritems():
106
                try: util.rename_key(db_config, orig, new)
107
                except KeyError: pass
108
            
109
            # Connect
110
            self.__db = module.connect(**db_config)
111
            
112
            # Configure connection
113
            if self.serializable: run_raw_query(self,
114
                'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
115
        
116
        return self.__db
117
    
118
    class Cursor(Proxy):
119
        def __init__(self, inner):
120
            Proxy.__init__(self, inner)
121
            self.result = None
122
        
123
        def rows(cur): return iter(lambda: cur.fetchone(), None)
124
    
125
    def run_query(self, query, params=None):
126
        cur = self.db.cursor()
127
        try: cur.execute(query, params)
128
        except Exception, e:
129
            _add_cursor_info(e, cur)
130
            raise
131
        if self.debug:
132
            sys.stderr.write(strings.one_line(get_cur_query(cur))+'\n')
133
        return cur
134

    
135
connect = DbConn
136

    
137
##### Querying
138

    
139
def run_raw_query(db, query, params=None): return db.run_query(query, params)
140

    
141
##### Recoverable querying
142

    
143
def with_savepoint(db, func):
144
    savepoint = 'savepoint_'+str(rand.rand_int()) # must be unique
145
    run_raw_query(db, 'SAVEPOINT '+savepoint)
146
    try: return_val = func()
147
    except:
148
        run_raw_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
149
        raise
150
    else:
151
        run_raw_query(db, 'RELEASE SAVEPOINT '+savepoint)
152
        return return_val
153

    
154
def run_query(db, query, params=None, recover=None):
155
    if recover == None: recover = False
156
    
157
    def run(): return run_raw_query(db, query, params)
158
    if recover: return with_savepoint(db, run)
159
    else: return run()
160

    
161
##### Result retrieval
162

    
163
def col_names(cur): return (col[0] for col in cur.description)
164

    
165
def rows(cur): return iter(lambda: cur.fetchone(), None)
166

    
167
def row(cur): return rows(cur).next()
168

    
169
def value(cur): return row(cur)[0]
170

    
171
def values(cur): return iter(lambda: value(cur), None)
172

    
173
def value_or_none(cur):
174
    try: return value(cur)
175
    except StopIteration: return None
176

    
177
##### Basic queries
178

    
179
def select(db, table, fields=None, conds=None, limit=None, start=None,
180
    recover=None):
181
    '''@param fields Use None to select all fields in the table'''
182
    if conds == None: conds = {}
183
    assert limit == None or type(limit) == int
184
    assert start == None or type(start) == int
185
    check_name(table)
186
    if fields != None: map(check_name, fields)
187
    map(check_name, conds.keys())
188
    
189
    def cond(entry):
190
        col, value = entry
191
        cond_ = esc_name(db, col)+' '
192
        if value == None: cond_ += 'IS'
193
        else: cond_ += '='
194
        cond_ += ' %s'
195
        return cond_
196
    query = 'SELECT '
197
    if fields == None: query += '*'
198
    else: query += ', '.join([esc_name(db, field) for field in fields])
199
    query += ' FROM '+esc_name(db, table)
200
    
201
    missing = True
202
    if conds != {}:
203
        query += ' WHERE '+' AND '.join(map(cond, conds.iteritems()))
204
        missing = False
205
    if limit != None: query += ' LIMIT '+str(limit); missing = False
206
    if start != None:
207
        if start != 0: query += ' OFFSET '+str(start)
208
        missing = False
209
    if missing: warnings.warn(DbWarning(
210
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
211
    
212
    return run_query(db, query, conds.values(), recover)
213

    
214
def insert(db, table, row, returning=None, recover=None):
215
    '''@param returning str|None An inserted column (such as pkey) to return'''
216
    check_name(table)
217
    cols = row.keys()
218
    map(check_name, cols)
219
    query = 'INSERT INTO '+table
220
    
221
    if row != {}: query += ' ('+', '.join(cols)+') VALUES ('\
222
        +', '.join(['%s']*len(cols))+')'
223
    else: query += ' DEFAULT VALUES'
224
    
225
    if returning != None:
226
        check_name(returning)
227
        query += ' RETURNING '+returning
228
    
229
    return run_query(db, query, row.values(), recover)
230

    
231
def last_insert_id(db):
232
    module = util.root_module(db.db)
233
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
234
    elif module == 'MySQLdb': return db.insert_id()
235
    else: return None
236

    
237
def truncate(db, table):
238
    check_name(table)
239
    return run_raw_query(db, 'TRUNCATE '+table+' CASCADE')
240

    
241
##### Database structure queries
242

    
243
def pkey(db, table, recover=None):
244
    '''Assumed to be first column in table'''
245
    check_name(table)
246
    if table not in db.pkeys:
247
        db.pkeys[table] = col_names(run_query(db,
248
            'SELECT * FROM '+table+' LIMIT 0', recover=recover)).next()
249
    return db.pkeys[table]
250

    
251
def index_cols(db, table, index):
252
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
253
    automatically created. When you don't know whether something is a UNIQUE
254
    constraint or a UNIQUE index, use this function.'''
255
    check_name(table)
256
    check_name(index)
257
    lookup = (table, index)
258
    if lookup not in db.index_cols:
259
        module = util.root_module(db.db)
260
        if module == 'psycopg2':
261
            db.index_cols[lookup] = list(values(run_query(db, '''\
262
SELECT attname
263
FROM
264
(
265
        SELECT attnum, attname
266
        FROM pg_index
267
        JOIN pg_class index ON index.oid = indexrelid
268
        JOIN pg_class table_ ON table_.oid = indrelid
269
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
270
        WHERE
271
            table_.relname = %(table)s
272
            AND index.relname = %(index)s
273
    UNION
274
        SELECT attnum, attname
275
        FROM
276
        (
277
            SELECT
278
                indrelid
279
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
280
                    AS indkey
281
            FROM pg_index
282
            JOIN pg_class index ON index.oid = indexrelid
283
            JOIN pg_class table_ ON table_.oid = indrelid
284
            WHERE
285
                table_.relname = %(table)s
286
                AND index.relname = %(index)s
287
        ) s
288
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
289
) s
290
ORDER BY attnum
291
''',
292
                {'table': table, 'index': index})))
293
        else: raise NotImplementedError("Can't list index columns for "+module+
294
            ' database')
295
    return db.index_cols[lookup]
296

    
297
def constraint_cols(db, table, constraint):
298
    check_name(table)
299
    check_name(constraint)
300
    module = util.root_module(db.db)
301
    if module == 'psycopg2':
302
        return list(values(run_query(db, '''\
303
SELECT attname
304
FROM pg_constraint
305
JOIN pg_class ON pg_class.oid = conrelid
306
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
307
WHERE
308
    relname = %(table)s
309
    AND conname = %(constraint)s
310
ORDER BY attnum
311
''',
312
            {'table': table, 'constraint': constraint})))
313
    else: raise NotImplementedError("Can't list constraint columns for "+module+
314
        ' database')
315

    
316
def tables(db):
317
    module = util.root_module(db.db)
318
    if module == 'psycopg2':
319
        return values(run_query(db, "SELECT tablename from pg_tables "
320
            "WHERE schemaname = 'public' ORDER BY tablename"))
321
    elif module == 'MySQLdb': return values(run_query(db, 'SHOW TABLES'))
322
    else: raise NotImplementedError("Can't list tables for "+module+' database')
323

    
324
##### Database management
325

    
326
def empty_db(db):
327
    for table in tables(db): truncate(db, table)
328

    
329
##### Heuristic queries
330

    
331
def try_insert(db, table, row, returning=None):
332
    '''Recovers from errors'''
333
    try: return insert(db, table, row, returning, recover=True)
334
    except Exception, e:
335
        msg = str(e)
336
        match = re.search(r'duplicate key value violates unique constraint '
337
            r'"(([^\W_]+)_[^"]+)"', msg)
338
        if match:
339
            constraint, table = match.groups()
340
            try: cols = index_cols(db, table, constraint)
341
            except NotImplementedError: raise e
342
            else: raise DuplicateKeyException(cols, e)
343
        match = re.search(r'null value in column "(\w+)" violates not-null '
344
            'constraint', msg)
345
        if match: raise NullValueException([match.group(1)], e)
346
        raise # no specific exception raised
347

    
348
def put(db, table, row, pkey, row_ct_ref=None):
349
    '''Recovers from errors.
350
    Only works under PostgreSQL (uses `INSERT ... RETURNING`)'''
351
    try:
352
        cur = try_insert(db, table, row, pkey)
353
        if row_ct_ref != None and cur.rowcount >= 0:
354
            row_ct_ref[0] += cur.rowcount
355
        return value(cur)
356
    except DuplicateKeyException, e:
357
        return value(select(db, table, [pkey],
358
            util.dict_subset_right_join(row, e.cols), recover=True))
359

    
360
def get(db, table, row, pkey, row_ct_ref=None, create=False):
361
    '''Recovers from errors'''
362
    try: return value(select(db, table, [pkey], row, 1, recover=True))
363
    except StopIteration:
364
        if not create: raise
365
        return put(db, table, row, pkey, row_ct_ref) # insert new row
(22-22/33)