Skip to content

Commit 686aafa

Browse files
committed
support for lists in db queries
1 parent 23248e3 commit 686aafa

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

web/db.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -227,21 +227,37 @@ def __repr__(self):
227227

228228
sqlliteral = SQLLiteral
229229

230+
def _sqllist(values):
231+
"""
232+
>>> _sqllist([1, 2, 3])
233+
<sql: '(1, 2, 3)'>
234+
"""
235+
items = []
236+
items.append('(')
237+
for i, v in enumerate(values):
238+
if i != 0:
239+
items.append(', ')
240+
items.append(sqlparam(v))
241+
items.append(')')
242+
return SQLQuery(items)
243+
230244
def reparam(string_, dictionary):
231245
"""
232246
Takes a string and a dictionary and interpolates the string
233247
using values from the dictionary. Returns an `SQLQuery` for the result.
234248
235249
>>> reparam("s = $s", dict(s=True))
236250
<sql: "s = 't'">
251+
>>> reparam("s IN $s", dict(s=[1, 2]))
252+
<sql: 's IN (1, 2)'>
237253
"""
238254
dictionary = dictionary.copy() # eval mucks with it
239255
vals = []
240256
result = []
241257
for live, chunk in _interpolate(string_):
242258
if live:
243259
v = eval(chunk, dictionary)
244-
result.append(sqlparam(v))
260+
result.append(sqlquote(v))
245261
else:
246262
result.append(chunk)
247263
return SQLQuery.join(result, '')
@@ -338,8 +354,13 @@ def sqlquote(a):
338354
339355
>>> 'WHERE x = ' + sqlquote(True) + ' AND y = ' + sqlquote(3)
340356
<sql: "WHERE x = 't' AND y = 3">
357+
>>> 'WHERE x = ' + sqlquote(True) + ' AND y IN ' + sqlquote([2, 3])
358+
<sql: "WHERE x = 't' AND y IN (2, 3)">
341359
"""
342-
return sqlparam(a).sqlquery()
360+
if isinstance(a, list):
361+
return _sqllist(a)
362+
else:
363+
return sqlparam(a).sqlquery()
343364

344365
class Transaction:
345366
"""Database transaction."""

0 commit comments

Comments
 (0)