Project

General

Profile

1 11 aaronmk
# Database access
2
3
import random
4
import re
5
import sys
6
7 46 aaronmk
import ex
8 11 aaronmk
9 46 aaronmk
def _add_cursor_info(e, cur): ex.add_msg(e, 'query: '+cur.query)
10 14 aaronmk
11 11 aaronmk
class NameException(Exception): pass
12
13 46 aaronmk
class DbException(ex.ExceptionWithCause):
14 14 aaronmk
    def __init__(self, msg, cause=None, cur=None):
15 46 aaronmk
        ex.ExceptionWithCause.__init__(self, msg, cause)
16 14 aaronmk
        if cur != None: _add_cursor_info(self, cur)
17
18
class ExceptionWithColumn(DbException):
19 13 aaronmk
    def __init__(self, col, cause=None):
20 14 aaronmk
        DbException.__init__(self, 'column: '+col, cause)
21 13 aaronmk
        self.col = col
22 11 aaronmk
23 13 aaronmk
class DuplicateKeyException(ExceptionWithColumn): pass
24
25
class NullValueException(ExceptionWithColumn): pass
26
27 89 aaronmk
class EmptyRowException(DbException): pass
28
29 11 aaronmk
def check_name(name):
30
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
31
        +'" may contain only alphanumeric characters and _')
32
33
def run_query(db, query, params=None):
34
    cur = db.cursor()
35
    try: cur.execute(query, params)
36 46 aaronmk
    except Exception, e:
37
        _add_cursor_info(e, cur)
38 11 aaronmk
        raise
39
    return cur
40
41 15 aaronmk
def col(cur, idx): return cur.description[idx][0]
42
43 14 aaronmk
def row(cur): return iter(lambda: cur.fetchone(), None).next()
44 11 aaronmk
45
def value(cur): return row(cur)[0]
46
47
def with_savepoint(db, func):
48
    savepoint = 'savepoint_'+str(random.randint(0, sys.maxint)) # must be unique
49
    run_query(db, 'SAVEPOINT '+savepoint)
50
    try: return_val = func()
51
    except:
52
        run_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
53
        raise
54
    else:
55
        run_query(db, 'RELEASE SAVEPOINT '+savepoint)
56
        return return_val
57
58
def select(db, table, fields, conds):
59 15 aaronmk
    check_name(table)
60
    map(check_name, fields)
61
    map(check_name, conds.keys())
62 11 aaronmk
    def cond(entry):
63 13 aaronmk
        col, value = entry
64
        cond_ = col+' '
65 11 aaronmk
        if value == None: cond_ += 'IS'
66
        else: cond_ += '='
67
        cond_ += ' %s'
68
        return cond_
69 89 aaronmk
    query = 'SELECT '+', '.join(fields)+' FROM '+table
70
    if conds != {}:
71
        query += ' WHERE '+' AND '.join(map(cond, conds.iteritems()))
72
    return run_query(db, query, conds.values())
73 11 aaronmk
74 13 aaronmk
def insert(db, table, row):
75 11 aaronmk
    check_name(table)
76 13 aaronmk
    cols = row.keys()
77 15 aaronmk
    map(check_name, cols)
78 89 aaronmk
    query = 'INSERT INTO '+table
79
    if row != {}: query += ' ('+', '.join(cols)+') VALUES ('\
80
        +', '.join(['%s']*len(cols))+')'
81
    else: query += ' DEFAULT VALUES'
82
    return run_query(db, query, row.values())
83 11 aaronmk
84 13 aaronmk
def last_insert_id(db): return value(run_query(db, 'SELECT lastval()'))
85
86 14 aaronmk
def try_insert(db, table, row):
87 13 aaronmk
    try: return with_savepoint(db, lambda: insert(db, table, row))
88 46 aaronmk
    except Exception, e:
89
        msg = str(e)
90 11 aaronmk
        match = re.search(r'duplicate key value violates unique constraint "'
91 13 aaronmk
            +table+'_(\w+)_index"', msg)
92 46 aaronmk
        if match: raise DuplicateKeyException(match.group(1), e)
93 13 aaronmk
        match = re.search(r'null value in column "(\w+)" violates not-null '
94
            'constraint', msg)
95 46 aaronmk
        if match: raise NullValueException(match.group(1), e)
96 13 aaronmk
        raise # no specific exception raised
97 11 aaronmk
98 15 aaronmk
def pkey(db, table): # Assumed to be first column in table
99
    check_name(table)
100
    return col(run_query(db, 'SELECT * FROM '+table+' LIMIT 0'), 0)
101
102 40 aaronmk
def get(db, table, row, pkey, create=False, row_ct_ref=None):
103 89 aaronmk
    if row == []: raise EmptyRowException(table) # nothing to insert/filter by
104 14 aaronmk
    try: return value(select(db, table, [pkey], row))
105
    except StopIteration:
106 40 aaronmk
        if not create: raise
107
        # Insert new row
108 14 aaronmk
        try:
109
            row_ct = try_insert(db, table, row).rowcount
110
            if row_ct_ref != None and row_ct >= 0: row_ct_ref[0] += row_ct
111
            return last_insert_id(db)
112 46 aaronmk
        except DuplicateKeyException, e:
113
            return value(select(db, table, [pkey], {e.col: row[e.col]}))