Commits

Ants Aasma  committed 8fe8ed4

The case() function now also takes a dictionary as its whens parameter. But beware that it doesn't escape literals, use the literal construct for that.

  • Participants
  • Parent commits 3167602

Comments (0)

Files changed (3)

       queries with lots of eager loads might have seen this
       symptom.
 
+    - The case() function now also takes a dictionary as its whens
+      parameter. But beware that it doesn't escape literals, use
+      the literal construct for that.
+
 - declarative extension
     - The "synonym" function is now directly usable with
       "declarative".  Pass in the decorated property using the

File lib/sqlalchemy/sql/expression.py

     """Produce a ``CASE`` statement.
 
     whens
-      A sequence of pairs to be translated into "when / then" clauses.
+      A sequence of pairs or a dict to be translated into "when / then" clauses.
 
     value
       Optional for simple case statements.
       Optional as well, for case defaults.
     """
 
+    try:
+        whens = util.dictlike_iteritems(whens)
+    except TypeError:
+        pass
+
     whenlist = [ClauseList('WHEN', c, 'THEN', r, operator=None)
                 for (c,r) in whens]
     if not else_ is None:

File test/sql/case_statement.py

 import sys
 from sqlalchemy import *
 from testlib import *
+from sqlalchemy import util
 
 
 class CaseTest(TestBase):
             (0, 6, 'pk_6_data')
         ]
 
+    @testing.fails_on('maxdb')
+    def testcase_with_dict(self):
+        query = select([case({
+                    info_table.c.pk < 3: literal('lessthan3'),
+                    info_table.c.pk >= 3: literal('gt3'),
+                }, else_=literal('other')),
+                info_table.c.pk, info_table.c.info
+            ],
+            from_obj=[info_table])
+        assert query.execute().fetchall() == [
+            ('lessthan3', 1, 'pk_1_data'),
+            ('lessthan3', 2, 'pk_2_data'),
+            ('gt3', 3, 'pk_3_data'),
+            ('gt3', 4, 'pk_4_data'),
+            ('gt3', 5, 'pk_5_data'),
+            ('gt3', 6, 'pk_6_data')
+        ]
+
+        simple_query = select([case({
+                    1: literal('one'),
+                    2: literal('two'),
+                }, value=info_table.c.pk, else_=literal('other')),
+                info_table.c.pk
+            ],
+            whereclause=info_table.c.pk < 4,
+            from_obj=[info_table])
+        assert simple_query.execute().fetchall() == [
+            ('one', 1),
+            ('two', 2),
+            ('other', 3),
+        ]
+
 if __name__ == "__main__":
     testenv.main()