Project

General

Profile

1 11 aaronmk
# Database access
2
3
import random
4
import re
5
import sys
6 865 aaronmk
import warnings
7 11 aaronmk
8 300 aaronmk
import exc
9 862 aaronmk
import strings
10 131 aaronmk
import util
11 11 aaronmk
12 832 aaronmk
##### Exceptions
13
14 135 aaronmk
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 14 aaronmk
19 300 aaronmk
def _add_cursor_info(e, cur): exc.add_msg(e, 'query: '+get_cur_query(cur))
20 135 aaronmk
21 300 aaronmk
class DbException(exc.ExceptionWithCause):
22 14 aaronmk
    def __init__(self, msg, cause=None, cur=None):
23 300 aaronmk
        exc.ExceptionWithCause.__init__(self, msg, cause)
24 14 aaronmk
        if cur != None: _add_cursor_info(self, cur)
25
26 360 aaronmk
class NameException(DbException): pass
27
28 468 aaronmk
class ExceptionWithColumns(DbException):
29
    def __init__(self, cols, cause=None):
30
        DbException.__init__(self, 'columns: ' + ', '.join(cols), cause)
31
        self.cols = cols
32 11 aaronmk
33 468 aaronmk
class DuplicateKeyException(ExceptionWithColumns): pass
34 13 aaronmk
35 468 aaronmk
class NullValueException(ExceptionWithColumns): pass
36 13 aaronmk
37 89 aaronmk
class EmptyRowException(DbException): pass
38
39 865 aaronmk
##### Warnings
40
41
class DbWarning(UserWarning): pass
42
43 832 aaronmk
##### Input validation
44
45 11 aaronmk
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 643 aaronmk
def esc_name(db, name):
50
    module = util.root_module(db)
51 645 aaronmk
    if module == 'psycopg2': return name
52
        # Don't enclose in quotes because this disables case-insensitivity
53 643 aaronmk
    elif module == 'MySQLdb': quote = '`'
54 645 aaronmk
    else: raise NotImplementedError("Can't escape name for "+module+' database')
55 643 aaronmk
    return quote + name.replace(quote, '') + quote
56
57 832 aaronmk
##### Querying
58
59 830 aaronmk
def run_raw_query(db, query, params=None):
60 11 aaronmk
    cur = db.cursor()
61
    try: cur.execute(query, params)
62 46 aaronmk
    except Exception, e:
63
        _add_cursor_info(e, cur)
64 11 aaronmk
        raise
65 867 aaronmk
    if run_raw_query.debug:
66
        sys.stderr.write(strings.one_line(get_cur_query(cur))+'\n')
67 11 aaronmk
    return cur
68
69 832 aaronmk
##### Recoverable querying
70 15 aaronmk
71 11 aaronmk
def with_savepoint(db, func):
72
    savepoint = 'savepoint_'+str(random.randint(0, sys.maxint)) # must be unique
73 830 aaronmk
    run_raw_query(db, 'SAVEPOINT '+savepoint)
74 11 aaronmk
    try: return_val = func()
75
    except:
76 830 aaronmk
        run_raw_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
77 11 aaronmk
        raise
78
    else:
79 830 aaronmk
        run_raw_query(db, 'RELEASE SAVEPOINT '+savepoint)
80 11 aaronmk
        return return_val
81
82 830 aaronmk
def run_query(db, query, params=None, recover=None):
83
    if recover == None: recover = False
84
85
    def run(): return run_raw_query(db, query, params)
86
    if recover: return with_savepoint(db, run)
87
    else: return run()
88
89 832 aaronmk
##### Result retrieval
90
91 1135 aaronmk
def col_names(cur): return (col[0] for col in cur.description)
92 832 aaronmk
93
def rows(cur): return iter(lambda: cur.fetchone(), None)
94
95
def row(cur): return rows(cur).next()
96
97
def value(cur): return row(cur)[0]
98
99
def values(cur): return iter(lambda: value(cur), None)
100
101
def value_or_none(cur):
102
    try: return value(cur)
103
    except StopIteration: return None
104
105
##### Basic queries
106
107 1135 aaronmk
def select(db, table, fields=None, conds=None, limit=None, start=None,
108
    recover=None):
109
    '''@param fields Use None to select all fields in the table'''
110
    if conds == None: conds = {}
111 135 aaronmk
    assert limit == None or type(limit) == int
112 865 aaronmk
    assert start == None or type(start) == int
113 15 aaronmk
    check_name(table)
114 1135 aaronmk
    if fields != None: map(check_name, fields)
115 15 aaronmk
    map(check_name, conds.keys())
116 865 aaronmk
117 11 aaronmk
    def cond(entry):
118 13 aaronmk
        col, value = entry
119 644 aaronmk
        cond_ = esc_name(db, col)+' '
120 11 aaronmk
        if value == None: cond_ += 'IS'
121
        else: cond_ += '='
122
        cond_ += ' %s'
123
        return cond_
124 1135 aaronmk
    query = 'SELECT '
125
    if fields == None: query += '*'
126
    else: query += ', '.join([esc_name(db, field) for field in fields])
127
    query += ' FROM '+esc_name(db, table)
128 865 aaronmk
129
    missing = True
130 89 aaronmk
    if conds != {}:
131
        query += ' WHERE '+' AND '.join(map(cond, conds.iteritems()))
132 865 aaronmk
        missing = False
133
    if limit != None: query += ' LIMIT '+str(limit); missing = False
134
    if start != None:
135
        if start != 0: query += ' OFFSET '+str(start)
136
        missing = False
137
    if missing: warnings.warn(DbWarning(
138
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
139
140 830 aaronmk
    return run_query(db, query, conds.values(), recover)
141 11 aaronmk
142 830 aaronmk
def insert(db, table, row, recover=None):
143 11 aaronmk
    check_name(table)
144 13 aaronmk
    cols = row.keys()
145 15 aaronmk
    map(check_name, cols)
146 89 aaronmk
    query = 'INSERT INTO '+table
147
    if row != {}: query += ' ('+', '.join(cols)+') VALUES ('\
148
        +', '.join(['%s']*len(cols))+')'
149
    else: query += ' DEFAULT VALUES'
150 830 aaronmk
    return run_query(db, query, row.values(), recover)
151 11 aaronmk
152 135 aaronmk
def last_insert_id(db):
153
    module = util.root_module(db)
154
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
155
    elif module == 'MySQLdb': return db.insert_id()
156
    else: return None
157 13 aaronmk
158 832 aaronmk
def truncate(db, table):
159
    check_name(table)
160 869 aaronmk
    return run_raw_query(db, 'TRUNCATE '+table+' CASCADE')
161 832 aaronmk
162
##### Database structure queries
163
164
def pkey(db, cache, table, recover=None):
165
    '''Assumed to be first column in table'''
166
    check_name(table)
167
    if table not in cache:
168 1135 aaronmk
        cache[table] = col_names(run_query(db,
169
            'SELECT * FROM '+table+' LIMIT 0', recover=recover)).next()
170 832 aaronmk
    return cache[table]
171
172 853 aaronmk
def index_cols(db, table, index):
173
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
174
    automatically created. When you don't know whether something is a UNIQUE
175
    constraint or a UNIQUE index, use this function.'''
176
    check_name(table)
177
    check_name(index)
178
    module = util.root_module(db)
179
    if module == 'psycopg2':
180
        return list(values(run_query(db, '''\
181
SELECT attname
182 866 aaronmk
FROM
183
(
184
        SELECT attnum, attname
185
        FROM pg_index
186
        JOIN pg_class index ON index.oid = indexrelid
187
        JOIN pg_class table_ ON table_.oid = indrelid
188
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
189
        WHERE
190
            table_.relname = %(table)s
191
            AND index.relname = %(index)s
192
    UNION
193
        SELECT attnum, attname
194
        FROM
195
        (
196
            SELECT
197
                indrelid
198
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
199
                    AS indkey
200
            FROM pg_index
201
            JOIN pg_class index ON index.oid = indexrelid
202
            JOIN pg_class table_ ON table_.oid = indrelid
203
            WHERE
204
                table_.relname = %(table)s
205
                AND index.relname = %(index)s
206
        ) s
207
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
208
) s
209 853 aaronmk
ORDER BY attnum
210
''',
211
            {'table': table, 'index': index})))
212
    else: raise NotImplementedError("Can't list index columns for "+module+
213
        ' database')
214
215 464 aaronmk
def constraint_cols(db, table, constraint):
216
    check_name(table)
217
    check_name(constraint)
218
    module = util.root_module(db)
219
    if module == 'psycopg2':
220
        return list(values(run_query(db, '''\
221
SELECT attname
222
FROM pg_constraint
223
JOIN pg_class ON pg_class.oid = conrelid
224
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
225
WHERE
226
    relname = %(table)s
227
    AND conname = %(constraint)s
228
ORDER BY attnum
229
''',
230
            {'table': table, 'constraint': constraint})))
231
    else: raise NotImplementedError("Can't list constraint columns for "+module+
232
        ' database')
233
234 832 aaronmk
def tables(db):
235
    module = util.root_module(db)
236
    if module == 'psycopg2':
237
        return values(run_query(db, "SELECT tablename from pg_tables "
238
            "WHERE schemaname = 'public' ORDER BY tablename"))
239
    elif module == 'MySQLdb': return values(run_query(db, 'SHOW TABLES'))
240
    else: raise NotImplementedError("Can't list tables for "+module+' database')
241 830 aaronmk
242 833 aaronmk
##### Database management
243
244
def empty_db(db):
245
    for table in tables(db): truncate(db, table)
246
247 832 aaronmk
##### Heuristic queries
248
249 14 aaronmk
def try_insert(db, table, row):
250 830 aaronmk
    '''Recovers from errors'''
251
    try: return insert(db, table, row, recover=True)
252 46 aaronmk
    except Exception, e:
253
        msg = str(e)
254 465 aaronmk
        match = re.search(r'duplicate key value violates unique constraint '
255
            r'"(([^\W_]+)_[^"]+)"', msg)
256
        if match:
257
            constraint, table = match.groups()
258 854 aaronmk
            try: cols = index_cols(db, table, constraint)
259 465 aaronmk
            except NotImplementedError: raise e
260 851 aaronmk
            else: raise DuplicateKeyException(cols, e)
261 13 aaronmk
        match = re.search(r'null value in column "(\w+)" violates not-null '
262
            'constraint', msg)
263 470 aaronmk
        if match: raise NullValueException([match.group(1)], e)
264 13 aaronmk
        raise # no specific exception raised
265 11 aaronmk
266 471 aaronmk
def put(db, table, row, pkey, row_ct_ref=None):
267 830 aaronmk
    '''Recovers from errors'''
268 471 aaronmk
    try:
269
        row_ct = try_insert(db, table, row).rowcount
270
        if row_ct_ref != None and row_ct >= 0: row_ct_ref[0] += row_ct
271
        return last_insert_id(db)
272
    except DuplicateKeyException, e:
273 1069 aaronmk
        return value(select(db, table, [pkey],
274
            util.dict_subset_right_join(row, e.cols), recover=True))
275 471 aaronmk
276 473 aaronmk
def get(db, table, row, pkey, row_ct_ref=None, create=False):
277 830 aaronmk
    '''Recovers from errors'''
278
    try: return value(select(db, table, [pkey], row, 1, recover=True))
279 14 aaronmk
    except StopIteration:
280 40 aaronmk
        if not create: raise
281 471 aaronmk
        return put(db, table, row, pkey, row_ct_ref) # insert new row
282 131 aaronmk
283 832 aaronmk
##### Database connections
284
285 131 aaronmk
db_engines = {
286
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
287
    'PostgreSQL': ('psycopg2', {}),
288
}
289
290 360 aaronmk
DatabaseErrors_set = set([DbException])
291
DatabaseErrors = tuple(DatabaseErrors_set)
292 342 aaronmk
293
def _add_module(module):
294
    DatabaseErrors_set.add(module.DatabaseError)
295
    global DatabaseErrors
296
    DatabaseErrors = tuple(DatabaseErrors_set)
297
298 646 aaronmk
def connect(db_config, serializable=True):
299 131 aaronmk
    db_config = db_config.copy() # don't modify input!
300 342 aaronmk
    module_name, mappings = db_engines[db_config.pop('engine')]
301
    module = __import__(module_name)
302
    _add_module(module)
303 330 aaronmk
    for orig, new in mappings.iteritems():
304
        try: util.rename_key(db_config, orig, new)
305
        except KeyError: pass
306 646 aaronmk
    db = module.connect(**db_config)
307
    if serializable:
308 830 aaronmk
        run_raw_query(db, 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
309 646 aaronmk
    return db
310
311
def db_config_str(db_config):
312
    return db_config['engine']+' database '+db_config['database']