Skip to content

Commit

Permalink
support for lists in db queries
Browse files Browse the repository at this point in the history
  • Loading branch information
anandology committed Feb 2, 2009
1 parent 23248e3 commit 686aafa
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions web/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,21 +227,37 @@ def __repr__(self):

sqlliteral = SQLLiteral

def _sqllist(values):
"""
>>> _sqllist([1, 2, 3])
<sql: '(1, 2, 3)'>
"""
items = []
items.append('(')
for i, v in enumerate(values):
if i != 0:
items.append(', ')
items.append(sqlparam(v))
items.append(')')
return SQLQuery(items)

def reparam(string_, dictionary):
"""
Takes a string and a dictionary and interpolates the string
using values from the dictionary. Returns an `SQLQuery` for the result.
>>> reparam("s = $s", dict(s=True))
<sql: "s = 't'">
>>> reparam("s IN $s", dict(s=[1, 2]))
<sql: 's IN (1, 2)'>
"""
dictionary = dictionary.copy() # eval mucks with it
vals = []
result = []
for live, chunk in _interpolate(string_):
if live:
v = eval(chunk, dictionary)
result.append(sqlparam(v))
result.append(sqlquote(v))
else:
result.append(chunk)
return SQLQuery.join(result, '')
Expand Down Expand Up @@ -338,8 +354,13 @@ def sqlquote(a):
>>> 'WHERE x = ' + sqlquote(True) + ' AND y = ' + sqlquote(3)
<sql: "WHERE x = 't' AND y = 3">
>>> 'WHERE x = ' + sqlquote(True) + ' AND y IN ' + sqlquote([2, 3])
<sql: "WHERE x = 't' AND y IN (2, 3)">
"""
return sqlparam(a).sqlquery()
if isinstance(a, list):
return _sqllist(a)
else:
return sqlparam(a).sqlquery()

class Transaction:
"""Database transaction."""
Expand Down

0 comments on commit 686aafa

Please sign in to comment.