oysteini
87e0cdda9d
This is a hack to avoid a problem with using %(foo)d in a query with a NULL value.
100 lines
2.2 KiB
Python
100 lines
2.2 KiB
Python
import os
|
|
import tempfile
|
|
|
|
def execute_query(cursor, query, bindings):
|
|
for (key, val) in bindings.items():
|
|
if val == None:
|
|
query = query.replace('%(' + key + ')d', 'NULL')
|
|
cursor.execute(query, bindings)
|
|
|
|
def make_result_dict(cursor, row):
|
|
d = {}
|
|
for i in xrange(len(row)):
|
|
d[cursor.description[i][0]] = row[i]
|
|
return d
|
|
|
|
def fetchone_dict(cursor):
|
|
row = cursor.fetchone()
|
|
if row != None:
|
|
return make_result_dict(cursor, row)
|
|
return None
|
|
|
|
def fetchall_dict(cursor):
|
|
return map(lambda r: make_result_dict(cursor, r),
|
|
cursor.fetchall())
|
|
|
|
def first(lst):
|
|
return lst[0]
|
|
|
|
def second(lst):
|
|
return lst[1]
|
|
|
|
def count(predicate, lst):
|
|
c = 0
|
|
for elem in lst:
|
|
if predicate(elem):
|
|
c = c+1
|
|
return c
|
|
|
|
def find(predicate, lst):
|
|
for elem in lst:
|
|
if predicate(elem):
|
|
return elem
|
|
return None
|
|
|
|
def unique(lst):
|
|
newlst = []
|
|
for elem in lst:
|
|
if elem not in newlst:
|
|
newlst.append(elem)
|
|
return newlst
|
|
|
|
def mapcond(fun, predicate, lst):
|
|
def mapfun(x):
|
|
if predicate(x):
|
|
return fun(x)
|
|
return x
|
|
return map(mapfun, lst)
|
|
|
|
def maptup(fun, lst):
|
|
return tuple(map(fun, lst))
|
|
|
|
def translate(value, translations):
|
|
return translations.get(value, value)
|
|
|
|
def str_or_empty(value):
|
|
if value:
|
|
return str(value)
|
|
return ''
|
|
|
|
def p(s):
|
|
encoded = s
|
|
if isinstance(s, unicode):
|
|
encoded = s.encode('utf8')
|
|
print encoded
|
|
|
|
def cut_str(string, length, ellipsis='...'):
|
|
if len(string) < length:
|
|
return string
|
|
return string[0:length-len(ellipsis)]+ellipsis
|
|
|
|
def combine_dicts(*dicts):
|
|
res = {}
|
|
for d in dicts:
|
|
res.update(d)
|
|
return res
|
|
|
|
def run_editor(filename):
|
|
if os.path.exists(filename):
|
|
os.system("%s %s || /usr/bin/env vi %s" %
|
|
(os.getenv("EDITOR"), filename, filename))
|
|
else:
|
|
exit("Error: %s: File does not exist!" % filename)
|
|
|
|
def write_tmpfile(pfix, content, encoding='utf8'):
|
|
file = tempfile.NamedTemporaryFile(prefix=pfix+'-', dir='/tmp', delete=False)
|
|
file.write(content.encode(encoding))
|
|
name = file.name
|
|
file.close()
|
|
return name
|