Project

General

Profile

1
# Database access
2

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

    
8
import exc
9
import strings
10
import util
11

    
12
##### Exceptions
13

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

    
19
def _add_cursor_info(e, cur): exc.add_msg(e, 'query: '+get_cur_query(cur))
20

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

    
26
class NameException(DbException): pass
27

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

    
33
class DuplicateKeyException(ExceptionWithColumns): pass
34

    
35
class NullValueException(ExceptionWithColumns): pass
36

    
37
class EmptyRowException(DbException): pass
38

    
39
##### Warnings
40

    
41
class DbWarning(UserWarning): pass
42

    
43
##### Input validation
44

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

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

    
57
##### Connection object
58

    
59
class DbConn:
60
    def __init__(self, db):
61
        self.db = db
62
        self.pkeys = {}
63
        self.index_cols = {}
64

    
65
##### Querying
66

    
67
def run_raw_query(db, query, params=None):
68
    cur = db.db.cursor()
69
    try: cur.execute(query, params)
70
    except Exception, e:
71
        _add_cursor_info(e, cur)
72
        raise
73
    if run_raw_query.debug:
74
        sys.stderr.write(strings.one_line(get_cur_query(cur))+'\n')
75
    return cur
76

    
77
##### Recoverable querying
78

    
79
def with_savepoint(db, func):
80
    savepoint = 'savepoint_'+str(random.randint(0, sys.maxint)) # must be unique
81
    run_raw_query(db, 'SAVEPOINT '+savepoint)
82
    try: return_val = func()
83
    except:
84
        run_raw_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
85
        raise
86
    else:
87
        run_raw_query(db, 'RELEASE SAVEPOINT '+savepoint)
88
        return return_val
89

    
90
def run_query(db, query, params=None, recover=None):
91
    if recover == None: recover = False
92
    
93
    def run(): return run_raw_query(db, query, params)
94
    if recover: return with_savepoint(db, run)
95
    else: return run()
96

    
97
##### Result retrieval
98

    
99
def col_names(cur): return (col[0] for col in cur.description)
100

    
101
def rows(cur): return iter(lambda: cur.fetchone(), None)
102

    
103
def row(cur): return rows(cur).next()
104

    
105
def value(cur): return row(cur)[0]
106

    
107
def values(cur): return iter(lambda: value(cur), None)
108

    
109
def value_or_none(cur):
110
    try: return value(cur)
111
    except StopIteration: return None
112

    
113
##### Basic queries
114

    
115
def select(db, table, fields=None, conds=None, limit=None, start=None,
116
    recover=None):
117
    '''@param fields Use None to select all fields in the table'''
118
    if conds == None: conds = {}
119
    assert limit == None or type(limit) == int
120
    assert start == None or type(start) == int
121
    check_name(table)
122
    if fields != None: map(check_name, fields)
123
    map(check_name, conds.keys())
124
    
125
    def cond(entry):
126
        col, value = entry
127
        cond_ = esc_name(db, col)+' '
128
        if value == None: cond_ += 'IS'
129
        else: cond_ += '='
130
        cond_ += ' %s'
131
        return cond_
132
    query = 'SELECT '
133
    if fields == None: query += '*'
134
    else: query += ', '.join([esc_name(db, field) for field in fields])
135
    query += ' FROM '+esc_name(db, table)
136
    
137
    missing = True
138
    if conds != {}:
139
        query += ' WHERE '+' AND '.join(map(cond, conds.iteritems()))
140
        missing = False
141
    if limit != None: query += ' LIMIT '+str(limit); missing = False
142
    if start != None:
143
        if start != 0: query += ' OFFSET '+str(start)
144
        missing = False
145
    if missing: warnings.warn(DbWarning(
146
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
147
    
148
    return run_query(db, query, conds.values(), recover)
149

    
150
def insert(db, table, row, returning=None, recover=None):
151
    '''@param returning str|None An inserted column (such as pkey) to return'''
152
    check_name(table)
153
    cols = row.keys()
154
    map(check_name, cols)
155
    query = 'INSERT INTO '+table
156
    
157
    if row != {}: query += ' ('+', '.join(cols)+') VALUES ('\
158
        +', '.join(['%s']*len(cols))+')'
159
    else: query += ' DEFAULT VALUES'
160
    
161
    if returning != None:
162
        check_name(returning)
163
        query += ' RETURNING '+returning
164
    
165
    return run_query(db, query, row.values(), recover)
166

    
167
def last_insert_id(db):
168
    module = util.root_module(db.db)
169
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
170
    elif module == 'MySQLdb': return db.insert_id()
171
    else: return None
172

    
173
def truncate(db, table):
174
    check_name(table)
175
    return run_raw_query(db, 'TRUNCATE '+table+' CASCADE')
176

    
177
##### Database structure queries
178

    
179
def pkey(db, table, recover=None):
180
    '''Assumed to be first column in table'''
181
    check_name(table)
182
    if table not in db.pkeys:
183
        db.pkeys[table] = col_names(run_query(db,
184
            'SELECT * FROM '+table+' LIMIT 0', recover=recover)).next()
185
    return db.pkeys[table]
186

    
187
def index_cols(db, table, index):
188
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
189
    automatically created. When you don't know whether something is a UNIQUE
190
    constraint or a UNIQUE index, use this function.'''
191
    check_name(table)
192
    check_name(index)
193
    module = util.root_module(db.db)
194
    if module == 'psycopg2':
195
        return list(values(run_query(db, '''\
196
SELECT attname
197
FROM
198
(
199
        SELECT attnum, attname
200
        FROM pg_index
201
        JOIN pg_class index ON index.oid = indexrelid
202
        JOIN pg_class table_ ON table_.oid = indrelid
203
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
204
        WHERE
205
            table_.relname = %(table)s
206
            AND index.relname = %(index)s
207
    UNION
208
        SELECT attnum, attname
209
        FROM
210
        (
211
            SELECT
212
                indrelid
213
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
214
                    AS indkey
215
            FROM pg_index
216
            JOIN pg_class index ON index.oid = indexrelid
217
            JOIN pg_class table_ ON table_.oid = indrelid
218
            WHERE
219
                table_.relname = %(table)s
220
                AND index.relname = %(index)s
221
        ) s
222
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
223
) s
224
ORDER BY attnum
225
''',
226
            {'table': table, 'index': index})))
227
    else: raise NotImplementedError("Can't list index columns for "+module+
228
        ' database')
229

    
230
def constraint_cols(db, table, constraint):
231
    check_name(table)
232
    check_name(constraint)
233
    module = util.root_module(db.db)
234
    if module == 'psycopg2':
235
        return list(values(run_query(db, '''\
236
SELECT attname
237
FROM pg_constraint
238
JOIN pg_class ON pg_class.oid = conrelid
239
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
240
WHERE
241
    relname = %(table)s
242
    AND conname = %(constraint)s
243
ORDER BY attnum
244
''',
245
            {'table': table, 'constraint': constraint})))
246
    else: raise NotImplementedError("Can't list constraint columns for "+module+
247
        ' database')
248

    
249
def tables(db):
250
    module = util.root_module(db.db)
251
    if module == 'psycopg2':
252
        return values(run_query(db, "SELECT tablename from pg_tables "
253
            "WHERE schemaname = 'public' ORDER BY tablename"))
254
    elif module == 'MySQLdb': return values(run_query(db, 'SHOW TABLES'))
255
    else: raise NotImplementedError("Can't list tables for "+module+' database')
256

    
257
##### Database management
258

    
259
def empty_db(db):
260
    for table in tables(db): truncate(db, table)
261

    
262
##### Heuristic queries
263

    
264
def try_insert(db, table, row, returning=None):
265
    '''Recovers from errors'''
266
    try: return insert(db, table, row, returning, recover=True)
267
    except Exception, e:
268
        msg = str(e)
269
        match = re.search(r'duplicate key value violates unique constraint '
270
            r'"(([^\W_]+)_[^"]+)"', msg)
271
        if match:
272
            constraint, table = match.groups()
273
            try: cols = index_cols(db, table, constraint)
274
            except NotImplementedError: raise e
275
            else: raise DuplicateKeyException(cols, e)
276
        match = re.search(r'null value in column "(\w+)" violates not-null '
277
            'constraint', msg)
278
        if match: raise NullValueException([match.group(1)], e)
279
        raise # no specific exception raised
280

    
281
def put(db, table, row, pkey, row_ct_ref=None):
282
    '''Recovers from errors.
283
    Only works under PostgreSQL (uses `INSERT ... RETURNING`)'''
284
    try:
285
        cur = try_insert(db, table, row, pkey)
286
        if row_ct_ref != None and cur.rowcount >= 0:
287
            row_ct_ref[0] += cur.rowcount
288
        return value(cur)
289
    except DuplicateKeyException, e:
290
        return value(select(db, table, [pkey],
291
            util.dict_subset_right_join(row, e.cols), recover=True))
292

    
293
def get(db, table, row, pkey, row_ct_ref=None, create=False):
294
    '''Recovers from errors'''
295
    try: return value(select(db, table, [pkey], row, 1, recover=True))
296
    except StopIteration:
297
        if not create: raise
298
        return put(db, table, row, pkey, row_ct_ref) # insert new row
299

    
300
##### Database connections
301

    
302
db_engines = {
303
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
304
    'PostgreSQL': ('psycopg2', {}),
305
}
306

    
307
DatabaseErrors_set = set([DbException])
308
DatabaseErrors = tuple(DatabaseErrors_set)
309

    
310
def _add_module(module):
311
    DatabaseErrors_set.add(module.DatabaseError)
312
    global DatabaseErrors
313
    DatabaseErrors = tuple(DatabaseErrors_set)
314

    
315
def connect(db_config, serializable=True):
316
    db_config = db_config.copy() # don't modify input!
317
    module_name, mappings = db_engines[db_config.pop('engine')]
318
    module = __import__(module_name)
319
    _add_module(module)
320
    for orig, new in mappings.iteritems():
321
        try: util.rename_key(db_config, orig, new)
322
        except KeyError: pass
323
    db = DbConn(module.connect(**db_config))
324
    if serializable:
325
        run_raw_query(db, 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
326
    return db
327

    
328
def db_config_str(db_config):
329
    return db_config['engine']+' database '+db_config['database']
(14-14/25)