Skip to content

Commit

Permalink
fix(terms): fixed EmptyCriterion bug with ComplexCriterion (#732)
Browse files Browse the repository at this point in the history
issue: #327
  • Loading branch information
GeorgiySurkov authored Sep 22, 2023
1 parent ea9cc5b commit 12a8f33
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pypika/terms.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,12 +486,18 @@ def __init__(self, alias: Optional[str] = None) -> None:

class Criterion(Term):
def __and__(self, other: Any) -> "ComplexCriterion":
if isinstance(other, EmptyCriterion):
return self
return ComplexCriterion(Boolean.and_, self, other)

def __or__(self, other: Any) -> "ComplexCriterion":
if isinstance(other, EmptyCriterion):
return self
return ComplexCriterion(Boolean.or_, self, other)

def __xor__(self, other: Any) -> "ComplexCriterion":
if isinstance(other, EmptyCriterion):
return self
return ComplexCriterion(Boolean.xor_, self, other)

@staticmethod
Expand Down Expand Up @@ -532,6 +538,9 @@ def __or__(self, other: Any) -> Any:
def __xor__(self, other: Any) -> Any:
return other

def __invert__(self) -> Any:
return self


class Field(Criterion, JSON):
def __init__(
Expand Down
56 changes: 56 additions & 0 deletions pypika/tests/test_criterions.py
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,62 @@ def test_fields_(self):

self.assertEqual(len(empty_criterion.fields_()), 0)

def test_empty_criterion_on_the_left(self):
t = Table("test1")
q = EmptyCriterion() & t.f1 == "v1"

self.assertEqual(
'"test1"."f1"=\'v1\'',
q.get_sql(with_namespace=True),
)

def test_empty_criterion_on_the_right(self):
t = Table("test1")
q = (t.f1 == "v1") & EmptyCriterion()

self.assertEqual(
'"test1"."f1"=\'v1\'',
q.get_sql(with_namespace=True),
)

def test_invertion_of_the_empty_criterion(self):
t = Table("test1")
q = (t.f1 == "v1") & ~EmptyCriterion()

self.assertEqual(
'"test1"."f1"=\'v1\'',
q.get_sql(with_namespace=True),
)

def test_different_operations_with_empty_criterion(self):
t = Table("test1")
q1 = (t.f1 == "v1") & EmptyCriterion()
q2 = (t.f1 == "v1") | EmptyCriterion()
q3 = (t.f1 == "v1") ^ EmptyCriterion()

expected_sql = '"test1"."f1"=\'v1\''
self.assertEqual(
expected_sql,
q1.get_sql(with_namespace=True),
)
self.assertEqual(
expected_sql,
q2.get_sql(with_namespace=True),
)
self.assertEqual(
expected_sql,
q3.get_sql(with_namespace=True),
)

def test_more_than_one_empty_criterions(self):
t = Table("test1")
q = EmptyCriterion() & ~(EmptyCriterion() | EmptyCriterion()) & (t.f1 == "v1") & ~EmptyCriterion()

self.assertEqual(
'"test1"."f1"=\'v1\'',
q.get_sql(with_namespace=True),
)


class AllTests(unittest.TestCase):
def test_zero_args_returns_empty_criterion(self):
Expand Down

0 comments on commit 12a8f33

Please sign in to comment.