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)
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
##### Querying
58

    
59
def run_raw_query(db, query, params=None):
60
    cur = db.cursor()
61
    try: cur.execute(query, params)
62
    except Exception, e:
63
        _add_cursor_info(e, cur)
64
        raise
65
    if run_raw_query.debug:
66
        sys.stderr.write(strings.one_line(get_cur_query(cur))+'\n')
67
    return cur
68

    
69
##### Recoverable querying
70

    
71
def with_savepoint(db, func):
72
    savepoint = 'savepoint_'+str(random.randint(0, sys.maxint)) # must be unique
73
    run_raw_query(db, 'SAVEPOINT '+savepoint)
74
    try: return_val = func()
75
    except:
76
        run_raw_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
77
        raise
78
    else:
79
        run_raw_query(db, 'RELEASE SAVEPOINT '+savepoint)
80
        return return_val
81

    
82
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
##### Result retrieval
90

    
91
def col_names(cur): return (col[0] for col in cur.description)
92

    
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
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
    assert limit == None or type(limit) == int
112
    assert start == None or type(start) == int
113
    check_name(table)
114
    if fields != None: map(check_name, fields)
115
    map(check_name, conds.keys())
116
    
117
    def cond(entry):
118
        col, value = entry
119
        cond_ = esc_name(db, col)+' '
120
        if value == None: cond_ += 'IS'
121
        else: cond_ += '='
122
        cond_ += ' %s'
123
        return cond_
124
    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
    
129
    missing = True
130
    if conds != {}:
131
        query += ' WHERE '+' AND '.join(map(cond, conds.iteritems()))
132
        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
    return run_query(db, query, conds.values(), recover)
141

    
142
def insert(db, table, row, recover=None):
143
    check_name(table)
144
    cols = row.keys()
145
    map(check_name, cols)
146
    query = 'INSERT INTO '+table
147
    if row != {}: query += ' ('+', '.join(cols)+') VALUES ('\
148
        +', '.join(['%s']*len(cols))+')'
149
    else: query += ' DEFAULT VALUES'
150
    return run_query(db, query, row.values(), recover)
151

    
152
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

    
158
def truncate(db, table):
159
    check_name(table)
160
    return run_raw_query(db, 'TRUNCATE '+table+' CASCADE')
161

    
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
        cache[table] = col_names(run_query(db,
169
            'SELECT * FROM '+table+' LIMIT 0', recover=recover)).next()
170
    return cache[table]
171

    
172
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
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
ORDER BY attnum
210
''',
211
            {'table': table, 'index': index})))
212
    else: raise NotImplementedError("Can't list index columns for "+module+
213
        ' database')
214

    
215
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
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

    
242
##### Database management
243

    
244
def empty_db(db):
245
    for table in tables(db): truncate(db, table)
246

    
247
##### Heuristic queries
248

    
249
def try_insert(db, table, row):
250
    '''Recovers from errors'''
251
    try: return insert(db, table, row, recover=True)
252
    except Exception, e:
253
        msg = str(e)
254
        match = re.search(r'duplicate key value violates unique constraint '
255
            r'"(([^\W_]+)_[^"]+)"', msg)
256
        if match:
257
            constraint, table = match.groups()
258
            try: cols = index_cols(db, table, constraint)
259
            except NotImplementedError: raise e
260
            else: raise DuplicateKeyException(cols, e)
261
        match = re.search(r'null value in column "(\w+)" violates not-null '
262
            'constraint', msg)
263
        if match: raise NullValueException([match.group(1)], e)
264
        raise # no specific exception raised
265

    
266
def put(db, table, row, pkey, row_ct_ref=None):
267
    '''Recovers from errors'''
268
    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
        return value(select(db, table, [pkey],
274
            util.dict_subset_right_join(row, e.cols), recover=True))
275

    
276
def get(db, table, row, pkey, row_ct_ref=None, create=False):
277
    '''Recovers from errors'''
278
    try: return value(select(db, table, [pkey], row, 1, recover=True))
279
    except StopIteration:
280
        if not create: raise
281
        return put(db, table, row, pkey, row_ct_ref) # insert new row
282

    
283
##### Database connections
284

    
285
db_engines = {
286
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
287
    'PostgreSQL': ('psycopg2', {}),
288
}
289

    
290
DatabaseErrors_set = set([DbException])
291
DatabaseErrors = tuple(DatabaseErrors_set)
292

    
293
def _add_module(module):
294
    DatabaseErrors_set.add(module.DatabaseError)
295
    global DatabaseErrors
296
    DatabaseErrors = tuple(DatabaseErrors_set)
297

    
298
def connect(db_config, serializable=True):
299
    db_config = db_config.copy() # don't modify input!
300
    module_name, mappings = db_engines[db_config.pop('engine')]
301
    module = __import__(module_name)
302
    _add_module(module)
303
    for orig, new in mappings.iteritems():
304
        try: util.rename_key(db_config, orig, new)
305
        except KeyError: pass
306
    db = module.connect(**db_config)
307
    if serializable:
308
        run_raw_query(db, 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
309
    return db
310

    
311
def db_config_str(db_config):
312
    return db_config['engine']+' database '+db_config['database']
(11-11/18)