Skip to content

Commit

Permalink
Change Case class to inherit from Criterion
Browse files Browse the repository at this point in the history
* This allows CASE statements to be used in where clauses when the where clause contains a Case instance and subsequent instances derived from Criterion
  • Loading branch information
mikeengland committed Mar 17, 2021
1 parent d8ed544 commit b0b577e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pypika/terms.py
Expand Up @@ -1050,7 +1050,7 @@ def get_sql(self, with_alias: bool = False, **kwargs: Any) -> str:
return arithmetic_sql


class Case(Term):
class Case(Criterion):
def __init__(self, alias: Optional[str] = None) -> None:
super().__init__(alias=alias)
self._cases = []
Expand Down
28 changes: 28 additions & 0 deletions pypika/tests/test_selects.py
Expand Up @@ -473,6 +473,34 @@ def test_select_with_force_index_and_where(self):

self.assertEqual('SELECT "foo" FROM "abc" FORCE INDEX ("egg") WHERE "foo"="bar"', str(q))

def test_where_with_multiple_wheres_using_and_case(self):
case_stmt = Case().when(self.t.foo == 'bar', 1).else_(0)
query = (
Query.from_(self.t)
.select(case_stmt)
.where(case_stmt & self.t.blah.isin(['test']))
)

self.assertEqual(
'SELECT CASE WHEN "foo"=\'bar\' THEN 1 ELSE 0 END FROM "abc" WHERE CASE WHEN "foo"=\'bar\' THEN 1 ELSE 0 '
'END AND "blah" IN (\'test\')',
str(query)
)

def test_where_with_multiple_wheres_using_or_case(self):
case_stmt = Case().when(self.t.foo == 'bar', 1).else_(0)
query = (
Query.from_(self.t)
.select(case_stmt)
.where(case_stmt | self.t.blah.isin(['test']))
)

self.assertEqual(
'SELECT CASE WHEN "foo"=\'bar\' THEN 1 ELSE 0 END FROM "abc" WHERE CASE WHEN "foo"=\'bar\' THEN 1 ELSE 0 '
'END OR "blah" IN (\'test\')',
str(query)
)


class PreWhereTests(WhereTests):
t = Table("abc")
Expand Down

0 comments on commit b0b577e

Please sign in to comment.