Permalink
Browse files

support for lists in db queries

  • Loading branch information...
anandology committed Feb 2, 2009
1 parent 23248e3 commit 686aafab4c1c5d0e438b4b36fab3d14d121ef99f
Showing with 23 additions and 2 deletions.
  1. +23 −2 web/db.py
View
@@ -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, '')
@@ -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."""

0 comments on commit 686aafa

Please sign in to comment.