1
|
# Database access
|
2
|
|
3
|
import random
|
4
|
import re
|
5
|
import sys
|
6
|
|
7
|
import exc
|
8
|
import util
|
9
|
|
10
|
def get_cur_query(cur):
|
11
|
if hasattr(cur, 'query'): return cur.query
|
12
|
elif hasattr(cur, '_last_executed'): return cur._last_executed
|
13
|
else: return None
|
14
|
|
15
|
def _add_cursor_info(e, cur): exc.add_msg(e, 'query: '+get_cur_query(cur))
|
16
|
|
17
|
class DbException(exc.ExceptionWithCause):
|
18
|
def __init__(self, msg, cause=None, cur=None):
|
19
|
exc.ExceptionWithCause.__init__(self, msg, cause)
|
20
|
if cur != None: _add_cursor_info(self, cur)
|
21
|
|
22
|
class NameException(DbException): pass
|
23
|
|
24
|
class ExceptionWithColumns(DbException):
|
25
|
def __init__(self, cols, cause=None):
|
26
|
DbException.__init__(self, 'columns: ' + ', '.join(cols), cause)
|
27
|
self.cols = cols
|
28
|
|
29
|
class DuplicateKeyException(ExceptionWithColumns): pass
|
30
|
|
31
|
class NullValueException(ExceptionWithColumns): pass
|
32
|
|
33
|
class EmptyRowException(DbException): pass
|
34
|
|
35
|
def check_name(name):
|
36
|
if re.search(r'\W', name) != None: raise NameException('Name "'+name
|
37
|
+'" may contain only alphanumeric characters and _')
|
38
|
|
39
|
def esc_name(db, name):
|
40
|
module = util.root_module(db)
|
41
|
if module == 'psycopg2': quote = '"'
|
42
|
elif module == 'MySQLdb': quote = '`'
|
43
|
else: raise NotImplementedError("Can't escape names for "+module+
|
44
|
' database')
|
45
|
return quote + name.replace(quote, '') + quote
|
46
|
|
47
|
def run_query(db, query, params=None):
|
48
|
cur = db.cursor()
|
49
|
try: cur.execute(query, params)
|
50
|
except Exception, e:
|
51
|
_add_cursor_info(e, cur)
|
52
|
raise
|
53
|
return cur
|
54
|
|
55
|
def col(cur, idx): return cur.description[idx][0]
|
56
|
|
57
|
def rows(cur): return iter(lambda: cur.fetchone(), None)
|
58
|
|
59
|
def row(cur): return rows(cur).next()
|
60
|
|
61
|
def value(cur): return row(cur)[0]
|
62
|
|
63
|
def values(cur): return iter(lambda: value(cur), None)
|
64
|
|
65
|
def value_or_none(cur):
|
66
|
try: return value(cur)
|
67
|
except StopIteration: return None
|
68
|
|
69
|
def with_savepoint(db, func):
|
70
|
savepoint = 'savepoint_'+str(random.randint(0, sys.maxint)) # must be unique
|
71
|
run_query(db, 'SAVEPOINT '+savepoint)
|
72
|
try: return_val = func()
|
73
|
except:
|
74
|
run_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
|
75
|
raise
|
76
|
else:
|
77
|
run_query(db, 'RELEASE SAVEPOINT '+savepoint)
|
78
|
return return_val
|
79
|
|
80
|
def select(db, table, fields, conds, limit=None):
|
81
|
assert limit == None or type(limit) == int
|
82
|
check_name(table)
|
83
|
map(check_name, fields)
|
84
|
map(check_name, conds.keys())
|
85
|
def cond(entry):
|
86
|
col, value = entry
|
87
|
cond_ = col+' '
|
88
|
if value == None: cond_ += 'IS'
|
89
|
else: cond_ += '='
|
90
|
cond_ += ' %s'
|
91
|
return cond_
|
92
|
query = 'SELECT '+', '.join(fields)+' FROM '+table
|
93
|
if conds != {}:
|
94
|
query += ' WHERE '+' AND '.join(map(cond, conds.iteritems()))
|
95
|
if limit != None: query += ' LIMIT '+str(limit)
|
96
|
return run_query(db, query, conds.values())
|
97
|
|
98
|
def insert(db, table, row):
|
99
|
check_name(table)
|
100
|
cols = row.keys()
|
101
|
map(check_name, cols)
|
102
|
query = 'INSERT INTO '+table
|
103
|
if row != {}: query += ' ('+', '.join(cols)+') VALUES ('\
|
104
|
+', '.join(['%s']*len(cols))+')'
|
105
|
else: query += ' DEFAULT VALUES'
|
106
|
return run_query(db, query, row.values())
|
107
|
|
108
|
def last_insert_id(db):
|
109
|
module = util.root_module(db)
|
110
|
if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
|
111
|
elif module == 'MySQLdb': return db.insert_id()
|
112
|
else: return None
|
113
|
|
114
|
def constraint_cols(db, table, constraint):
|
115
|
check_name(table)
|
116
|
check_name(constraint)
|
117
|
module = util.root_module(db)
|
118
|
if module == 'psycopg2':
|
119
|
return list(values(run_query(db, '''\
|
120
|
SELECT attname
|
121
|
FROM pg_constraint
|
122
|
JOIN pg_class ON pg_class.oid = conrelid
|
123
|
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
|
124
|
WHERE
|
125
|
relname = %(table)s
|
126
|
AND conname = %(constraint)s
|
127
|
ORDER BY attnum
|
128
|
''',
|
129
|
{'table': table, 'constraint': constraint})))
|
130
|
else: raise NotImplementedError("Can't list constraint columns for "+module+
|
131
|
' database')
|
132
|
|
133
|
def try_insert(db, table, row):
|
134
|
try: return with_savepoint(db, lambda: insert(db, table, row))
|
135
|
except Exception, e:
|
136
|
msg = str(e)
|
137
|
match = re.search(r'duplicate key value violates unique constraint '
|
138
|
r'"(([^\W_]+)_[^"]+)"', msg)
|
139
|
if match:
|
140
|
constraint, table = match.groups()
|
141
|
try: cols = constraint_cols(db, table, constraint)
|
142
|
except NotImplementedError: raise e
|
143
|
else: raise DuplicateKeyException(cols[0], e)
|
144
|
match = re.search(r'null value in column "(\w+)" violates not-null '
|
145
|
'constraint', msg)
|
146
|
if match: raise NullValueException([match.group(1)], e)
|
147
|
raise # no specific exception raised
|
148
|
|
149
|
def pkey(db, cache, table): # Assumed to be first column in table
|
150
|
check_name(table)
|
151
|
if table not in cache:
|
152
|
cache[table] = col(run_query(db, 'SELECT * FROM '+table+' LIMIT 0'), 0)
|
153
|
return cache[table]
|
154
|
|
155
|
def put(db, table, row, pkey, row_ct_ref=None):
|
156
|
try:
|
157
|
row_ct = try_insert(db, table, row).rowcount
|
158
|
if row_ct_ref != None and row_ct >= 0: row_ct_ref[0] += row_ct
|
159
|
return last_insert_id(db)
|
160
|
except DuplicateKeyException, e:
|
161
|
return value(select(db, table, [pkey], util.dict_subset(row, e.cols)))
|
162
|
|
163
|
def get(db, table, row, pkey, row_ct_ref=None, create=False):
|
164
|
try: return value(select(db, table, [pkey], row, 1))
|
165
|
except StopIteration:
|
166
|
if not create: raise
|
167
|
return put(db, table, row, pkey, row_ct_ref) # insert new row
|
168
|
|
169
|
|
170
|
def truncate(db, table):
|
171
|
check_name(table)
|
172
|
return run_query(db, 'TRUNCATE '+table+' CASCADE')
|
173
|
|
174
|
def tables(db):
|
175
|
module = util.root_module(db)
|
176
|
if module == 'psycopg2':
|
177
|
return values(run_query(db, "SELECT tablename from pg_tables "
|
178
|
"WHERE schemaname = 'public' ORDER BY tablename"))
|
179
|
elif module == 'MySQLdb': return values(run_query(db, 'SHOW TABLES'))
|
180
|
else: raise NotImplementedError("Can't list tables for "+module+' database')
|
181
|
|
182
|
def empty_db(db):
|
183
|
for table in tables(db): truncate(db, table)
|
184
|
|
185
|
db_engines = {
|
186
|
'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
|
187
|
'PostgreSQL': ('psycopg2', {}),
|
188
|
}
|
189
|
|
190
|
DatabaseErrors_set = set([DbException])
|
191
|
DatabaseErrors = tuple(DatabaseErrors_set)
|
192
|
|
193
|
def _add_module(module):
|
194
|
DatabaseErrors_set.add(module.DatabaseError)
|
195
|
global DatabaseErrors
|
196
|
DatabaseErrors = tuple(DatabaseErrors_set)
|
197
|
|
198
|
def connect(db_config):
|
199
|
db_config = db_config.copy() # don't modify input!
|
200
|
module_name, mappings = db_engines[db_config.pop('engine')]
|
201
|
module = __import__(module_name)
|
202
|
_add_module(module)
|
203
|
for orig, new in mappings.iteritems():
|
204
|
try: util.rename_key(db_config, orig, new)
|
205
|
except KeyError: pass
|
206
|
return module.connect(**db_config)
|