Project

General

Profile

1
# Database access
2

    
3
import random
4
import re
5
import sys
6

    
7
import exc
8
import strings
9
import util
10

    
11
##### Exceptions
12

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

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

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

    
25
class NameException(DbException): pass
26

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

    
32
class DuplicateKeyException(ExceptionWithColumns): pass
33

    
34
class NullValueException(ExceptionWithColumns): pass
35

    
36
class EmptyRowException(DbException): pass
37

    
38
##### Input validation
39

    
40
def check_name(name):
41
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
42
        +'" may contain only alphanumeric characters and _')
43

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

    
52
##### Querying
53

    
54
def run_raw_query(db, query, params=None):
55
    if run_raw_query.debug: sys.stderr.write(strings.one_line(query)+'\n')
56
    cur = db.cursor()
57
    try: cur.execute(query, params)
58
    except Exception, e:
59
        _add_cursor_info(e, cur)
60
        raise
61
    return cur
62

    
63
##### Recoverable querying
64

    
65
def with_savepoint(db, func):
66
    savepoint = 'savepoint_'+str(random.randint(0, sys.maxint)) # must be unique
67
    run_raw_query(db, 'SAVEPOINT '+savepoint)
68
    try: return_val = func()
69
    except:
70
        run_raw_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
71
        raise
72
    else:
73
        run_raw_query(db, 'RELEASE SAVEPOINT '+savepoint)
74
        return return_val
75

    
76
def run_query(db, query, params=None, recover=None):
77
    if recover == None: recover = False
78
    
79
    def run(): return run_raw_query(db, query, params)
80
    if recover: return with_savepoint(db, run)
81
    else: return run()
82

    
83
##### Result retrieval
84

    
85
def col(cur, idx): return cur.description[idx][0]
86

    
87
def rows(cur): return iter(lambda: cur.fetchone(), None)
88

    
89
def row(cur): return rows(cur).next()
90

    
91
def value(cur): return row(cur)[0]
92

    
93
def values(cur): return iter(lambda: value(cur), None)
94

    
95
def value_or_none(cur):
96
    try: return value(cur)
97
    except StopIteration: return None
98

    
99
##### Basic queries
100

    
101
def select(db, table, fields, conds, limit=None, recover=None):
102
    assert limit == None or type(limit) == int
103
    check_name(table)
104
    map(check_name, fields)
105
    map(check_name, conds.keys())
106
    def cond(entry):
107
        col, value = entry
108
        cond_ = esc_name(db, col)+' '
109
        if value == None: cond_ += 'IS'
110
        else: cond_ += '='
111
        cond_ += ' %s'
112
        return cond_
113
    query = ('SELECT ' + ', '.join([esc_name(db, field) for field in fields])
114
        + ' FROM '+esc_name(db, table))
115
    if conds != {}:
116
        query += ' WHERE '+' AND '.join(map(cond, conds.iteritems()))
117
    if limit != None: query += ' LIMIT '+str(limit)
118
    return run_query(db, query, conds.values(), recover)
119

    
120
def insert(db, table, row, recover=None):
121
    check_name(table)
122
    cols = row.keys()
123
    map(check_name, cols)
124
    query = 'INSERT INTO '+table
125
    if row != {}: query += ' ('+', '.join(cols)+') VALUES ('\
126
        +', '.join(['%s']*len(cols))+')'
127
    else: query += ' DEFAULT VALUES'
128
    return run_query(db, query, row.values(), recover)
129

    
130
def last_insert_id(db):
131
    module = util.root_module(db)
132
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
133
    elif module == 'MySQLdb': return db.insert_id()
134
    else: return None
135

    
136
def truncate(db, table):
137
    check_name(table)
138
    return run_query(db, 'TRUNCATE '+table+' CASCADE')
139

    
140
##### Database structure queries
141

    
142
def pkey(db, cache, table, recover=None):
143
    '''Assumed to be first column in table'''
144
    check_name(table)
145
    if table not in cache:
146
        cache[table] = col(run_query(db, 'SELECT * FROM '+table+' LIMIT 0',
147
            recover=recover), 0)
148
    return cache[table]
149

    
150
def index_cols(db, table, index):
151
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
152
    automatically created. When you don't know whether something is a UNIQUE
153
    constraint or a UNIQUE index, use this function.'''
154
    check_name(table)
155
    check_name(index)
156
    module = util.root_module(db)
157
    if module == 'psycopg2':
158
        return list(values(run_query(db, '''\
159
SELECT attname
160
FROM pg_index
161
JOIN pg_class index ON index.oid = indexrelid
162
JOIN pg_class table_ ON table_.oid = indrelid
163
JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
164
WHERE
165
    table_.relname = %(table)s
166
    AND index.relname = %(index)s
167
ORDER BY attnum
168
''',
169
            {'table': table, 'index': index})))
170
    else: raise NotImplementedError("Can't list index columns for "+module+
171
        ' database')
172

    
173
def constraint_cols(db, table, constraint):
174
    check_name(table)
175
    check_name(constraint)
176
    module = util.root_module(db)
177
    if module == 'psycopg2':
178
        return list(values(run_query(db, '''\
179
SELECT attname
180
FROM pg_constraint
181
JOIN pg_class ON pg_class.oid = conrelid
182
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
183
WHERE
184
    relname = %(table)s
185
    AND conname = %(constraint)s
186
ORDER BY attnum
187
''',
188
            {'table': table, 'constraint': constraint})))
189
    else: raise NotImplementedError("Can't list constraint columns for "+module+
190
        ' database')
191

    
192
def tables(db):
193
    module = util.root_module(db)
194
    if module == 'psycopg2':
195
        return values(run_query(db, "SELECT tablename from pg_tables "
196
            "WHERE schemaname = 'public' ORDER BY tablename"))
197
    elif module == 'MySQLdb': return values(run_query(db, 'SHOW TABLES'))
198
    else: raise NotImplementedError("Can't list tables for "+module+' database')
199

    
200
##### Database management
201

    
202
def empty_db(db):
203
    for table in tables(db): truncate(db, table)
204

    
205
##### Heuristic queries
206

    
207
def try_insert(db, table, row):
208
    '''Recovers from errors'''
209
    try: return insert(db, table, row, recover=True)
210
    except Exception, e:
211
        msg = str(e)
212
        match = re.search(r'duplicate key value violates unique constraint '
213
            r'"(([^\W_]+)_[^"]+)"', msg)
214
        if match:
215
            constraint, table = match.groups()
216
            try: cols = index_cols(db, table, constraint)
217
            except NotImplementedError: raise e
218
            else: raise DuplicateKeyException(cols, e)
219
        match = re.search(r'null value in column "(\w+)" violates not-null '
220
            'constraint', msg)
221
        if match: raise NullValueException([match.group(1)], e)
222
        raise # no specific exception raised
223

    
224
def put(db, table, row, pkey, row_ct_ref=None):
225
    '''Recovers from errors'''
226
    try:
227
        row_ct = try_insert(db, table, row).rowcount
228
        if row_ct_ref != None and row_ct >= 0: row_ct_ref[0] += row_ct
229
        return last_insert_id(db)
230
    except DuplicateKeyException, e:
231
        return value(select(db, table, [pkey], util.dict_subset(row, e.cols),
232
            recover=True))
233

    
234
def get(db, table, row, pkey, row_ct_ref=None, create=False):
235
    '''Recovers from errors'''
236
    try: return value(select(db, table, [pkey], row, 1, recover=True))
237
    except StopIteration:
238
        if not create: raise
239
        return put(db, table, row, pkey, row_ct_ref) # insert new row
240

    
241
##### Database connections
242

    
243
db_engines = {
244
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
245
    'PostgreSQL': ('psycopg2', {}),
246
}
247

    
248
DatabaseErrors_set = set([DbException])
249
DatabaseErrors = tuple(DatabaseErrors_set)
250

    
251
def _add_module(module):
252
    DatabaseErrors_set.add(module.DatabaseError)
253
    global DatabaseErrors
254
    DatabaseErrors = tuple(DatabaseErrors_set)
255

    
256
def connect(db_config, serializable=True):
257
    db_config = db_config.copy() # don't modify input!
258
    module_name, mappings = db_engines[db_config.pop('engine')]
259
    module = __import__(module_name)
260
    _add_module(module)
261
    for orig, new in mappings.iteritems():
262
        try: util.rename_key(db_config, orig, new)
263
        except KeyError: pass
264
    db = module.connect(**db_config)
265
    if serializable:
266
        run_raw_query(db, 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
267
    return db
268

    
269
def db_config_str(db_config):
270
    return db_config['engine']+' database '+db_config['database']
(8-8/14)