Project

General

Profile

1
# Database access
2

    
3
import random
4
import re
5
import sys
6

    
7
import ex
8

    
9
def _add_cursor_info(e, cur): ex.add_msg(e, 'query: '+cur.query)
10

    
11
class NameException(Exception): pass
12

    
13
class DbException(ex.ExceptionWithCause):
14
    def __init__(self, msg, cause=None, cur=None):
15
        ex.ExceptionWithCause.__init__(self, msg, cause)
16
        if cur != None: _add_cursor_info(self, cur)
17

    
18
class ExceptionWithColumn(DbException):
19
    def __init__(self, col, cause=None):
20
        DbException.__init__(self, 'column: '+col, cause)
21
        self.col = col
22

    
23
class DuplicateKeyException(ExceptionWithColumn): pass
24

    
25
class NullValueException(ExceptionWithColumn): pass
26

    
27
class EmptyRowException(DbException): pass
28

    
29
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
    except Exception, e:
37
        _add_cursor_info(e, cur)
38
        raise
39
    return cur
40

    
41
def col(cur, idx): return cur.description[idx][0]
42

    
43
def row(cur): return iter(lambda: cur.fetchone(), None).next()
44

    
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
    check_name(table)
60
    map(check_name, fields)
61
    map(check_name, conds.keys())
62
    def cond(entry):
63
        col, value = entry
64
        cond_ = col+' '
65
        if value == None: cond_ += 'IS'
66
        else: cond_ += '='
67
        cond_ += ' %s'
68
        return cond_
69
    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

    
74
def insert(db, table, row):
75
    check_name(table)
76
    cols = row.keys()
77
    map(check_name, cols)
78
    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

    
84
def last_insert_id(db): return value(run_query(db, 'SELECT lastval()'))
85

    
86
def try_insert(db, table, row):
87
    try: return with_savepoint(db, lambda: insert(db, table, row))
88
    except Exception, e:
89
        msg = str(e)
90
        match = re.search(r'duplicate key value violates unique constraint "'
91
            +table+'_(\w+)_index"', msg)
92
        if match: raise DuplicateKeyException(match.group(1), e)
93
        match = re.search(r'null value in column "(\w+)" violates not-null '
94
            'constraint', msg)
95
        if match: raise NullValueException(match.group(1), e)
96
        raise # no specific exception raised
97

    
98
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
def get(db, table, row, pkey, create=False, row_ct_ref=None):
103
    if row == []: raise EmptyRowException(table) # nothing to insert/filter by
104
    try: return value(select(db, table, [pkey], row))
105
    except StopIteration:
106
        if not create: raise
107
        # Insert new row
108
        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
        except DuplicateKeyException, e:
113
            return value(select(db, table, [pkey], {e.col: row[e.col]}))
(5-5/10)