Skip to content

Commit

Permalink
Merge 3ca9990 into f9960d4
Browse files Browse the repository at this point in the history
  • Loading branch information
cpinamtz committed Apr 7, 2021
2 parents f9960d4 + 3ca9990 commit 1f29849
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"python.pythonPath": "/home/cpinamtz/.virtualenvs/pypika-fork/bin/python"
}
17 changes: 17 additions & 0 deletions pypika/terms.py
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,23 @@ def negate(self) -> "ContainsCriterion":
self._is_negated = True


class ExistsCriterion(Criterion):
def __init__(self, container, alias=None):
super(ExistsCriterion, self).__init__(alias)
self.container = container
self._is_negated = False

def get_sql(self, **kwargs):
# FIXME escape
return "{not_}EXISTS {container}".format(
container=self.container.get_sql(**kwargs),
not_='NOT ' if self._is_negated else ''
)

def negate(self):
self._is_negated = True
return self

class RangeCriterion(Criterion):
def __init__(self, term: Term, start: Any, end: Any, alias: Optional[str] = None) -> str:
super().__init__(alias)
Expand Down
23 changes: 22 additions & 1 deletion pypika/tests/test_criterions.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
functions as fn,
)
from pypika.queries import QueryBuilder
from pypika.terms import Mod
from pypika.terms import ExistsCriterion, Mod

__author__ = "Timothy Heys"
__email__ = "theys@kayak.com"
Expand Down Expand Up @@ -590,6 +590,27 @@ def test_glob_single_chars_and_various_chars(self):
self.assertEqual('"like"."foo" GLOB \'a_b*\'', str(c2))


class ExistsCriterionTests(unittest.TestCase):
t2 = Table("abc", alias="t2")
q2 = QueryBuilder().from_(t2).select(t2.field2)

def test_exists(self):
t1 = Table("def", alias="t1")
q1 = QueryBuilder().from_(t1).where(ExistsCriterion(self.q2)).select(t1.field1)

self.assertEqual(
'SELECT "t1"."field1" FROM "def" "t1" WHERE EXISTS (SELECT "t2"."field2" FROM "abc" "t2")', str(q1)
)

def test_not_exists(self):
t1 = Table("def", alias="t1")
q1 = QueryBuilder().from_(t1).where(ExistsCriterion(self.q2).negate()).select(t1.field1)

self.assertEqual(
'SELECT "t1"."field1" FROM "def" "t1" WHERE NOT EXISTS (SELECT "t2"."field2" FROM "abc" "t2")', str(q1)
)


class ComplexCriterionTests(unittest.TestCase):
table_abc, table_efg = Table("abc", alias="cx0"), Table("efg", alias="cx1")

Expand Down

0 comments on commit 1f29849

Please sign in to comment.