Skip to content

Commit 73f1119

Browse files
committed
The where clause in db queries can be a dict now.
When the where clause is a dict, each key-value pair is make a condition and joined with AND. For example: >>> db.select("post", where={"category": "popular", "published": True}, >>> limit=5, _test=True) <sql: "SELECT * FROM post WHERE category = 'popular' AND published = 't' LIMIT 5">
1 parent 44e48a4 commit 73f1119

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

web/db.py

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -617,11 +617,22 @@ def _where(self, where, vars):
617617
#@@@ for backward-compatibility
618618
elif isinstance(where, (list, tuple)) and len(where) == 2:
619619
where = SQLQuery(where[0], where[1])
620+
elif isinstance(where, dict):
621+
where = self._where_dict(where)
620622
elif isinstance(where, SQLQuery):
621623
pass
622624
else:
623625
where = reparam(where, vars)
624626
return where
627+
628+
def _where_dict(self, where):
629+
where_clauses = []
630+
for k, v in where.iteritems():
631+
where_clauses.append(k + ' = ' + sqlquote(v))
632+
if where_clauses:
633+
return SQLQuery.join(where_clauses, " AND ")
634+
else:
635+
return None
625636

626637
def query(self, sql_query, vars=None, processed=False, _test=False):
627638
"""
@@ -677,6 +688,8 @@ def select(self, tables, vars=None, what='*', where=None, order=None, group=None
677688
<sql: 'SELECT * FROM foo'>
678689
>>> db.select(['foo', 'bar'], where="foo.bar_id = bar.id", limit=5, _test=True)
679690
<sql: 'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5'>
691+
>>> db.select('foo', where={'id': 5}, _test=True)
692+
<sql: 'SELECT * FROM foo WHERE id = 5'>
680693
"""
681694
if vars is None: vars = {}
682695
sql_clauses = self.sql_clauses(what, tables, where, group, order, limit, offset)
@@ -698,15 +711,7 @@ def where(self, table, what='*', order=None, group=None, limit=None,
698711
>>> db.where('foo', _test=True)
699712
<sql: 'SELECT * FROM foo'>
700713
"""
701-
where_clauses = []
702-
for k, v in kwargs.iteritems():
703-
where_clauses.append(k + ' = ' + sqlquote(v))
704-
705-
if where_clauses:
706-
where = SQLQuery.join(where_clauses, " AND ")
707-
else:
708-
where = None
709-
714+
where = self._where_dict(kwargs)
710715
return self.select(table, what=what, order=order,
711716
group=group, limit=limit, offset=offset, _test=_test,
712717
where=where)
@@ -730,6 +735,8 @@ def gen_clause(self, sql, val, vars):
730735
#@@@
731736
elif isinstance(val, (list, tuple)) and len(val) == 2:
732737
nout = SQLQuery(val[0], val[1]) # backwards-compatibility
738+
elif sql == 'WHERE' and isinstance(val, dict):
739+
nout = self._where_dict(val)
733740
elif isinstance(val, SQLQuery):
734741
nout = val
735742
else:

0 commit comments

Comments
 (0)