Revision 1135
Added by Aaron Marcuse-Kubitza almost 13 years ago
lib/sql.py | ||
---|---|---|
88 | 88 |
|
89 | 89 |
##### Result retrieval |
90 | 90 |
|
91 |
def col(cur, idx): return cur.description[idx][0]
|
|
91 |
def col_names(cur): return (col[0] for col in cur.description)
|
|
92 | 92 |
|
93 | 93 |
def rows(cur): return iter(lambda: cur.fetchone(), None) |
94 | 94 |
|
... | ... | |
104 | 104 |
|
105 | 105 |
##### Basic queries |
106 | 106 |
|
107 |
def select(db, table, fields, conds, limit=None, start=None, recover=None): |
|
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 = {} |
|
108 | 111 |
assert limit == None or type(limit) == int |
109 | 112 |
assert start == None or type(start) == int |
110 | 113 |
check_name(table) |
111 |
map(check_name, fields) |
|
114 |
if fields != None: map(check_name, fields)
|
|
112 | 115 |
map(check_name, conds.keys()) |
113 | 116 |
|
114 | 117 |
def cond(entry): |
... | ... | |
118 | 121 |
else: cond_ += '=' |
119 | 122 |
cond_ += ' %s' |
120 | 123 |
return cond_ |
121 |
query = ('SELECT ' + ', '.join([esc_name(db, field) for field in fields]) |
|
122 |
+ ' FROM '+esc_name(db, table)) |
|
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) |
|
123 | 128 |
|
124 | 129 |
missing = True |
125 | 130 |
if conds != {}: |
... | ... | |
160 | 165 |
'''Assumed to be first column in table''' |
161 | 166 |
check_name(table) |
162 | 167 |
if table not in cache: |
163 |
cache[table] = col(run_query(db, 'SELECT * FROM '+table+' LIMIT 0',
|
|
164 |
recover=recover), 0)
|
|
168 |
cache[table] = col_names(run_query(db,
|
|
169 |
'SELECT * FROM '+table+' LIMIT 0', recover=recover)).next()
|
|
165 | 170 |
return cache[table] |
166 | 171 |
|
167 | 172 |
def index_cols(db, table, index): |
Also available in: Unified diff
sql.py: select(): Select all fields if fields == None. Replaced col(cur, idx) with col_names(cur) because an iterator is easier to use than getting by index.