Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support of SAMPLE ClickHouse clause #707

Merged
merged 1 commit into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion pypika/dialects.py
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,16 @@ def drop_view(self, view: str) -> "ClickHouseDropQueryBuilder":
class ClickHouseQueryBuilder(QueryBuilder):
QUERY_CLS = ClickHouseQuery

def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self._sample = None
self._sample_offset = None

@builder
def sample(self, sample: int, offset: Optional[int] = None) -> "ClickHouseQueryBuilder":
self._sample = sample
self._sample_offset = offset

@staticmethod
def _delete_sql(**kwargs: Any) -> str:
return 'ALTER TABLE'
Expand All @@ -792,7 +802,12 @@ def _from_sql(self, with_namespace: bool = False, **kwargs: Any) -> str:
selectable = ",".join(clause.get_sql(subquery=True, with_alias=True, **kwargs) for clause in self._from)
if self._delete_from:
return " {selectable} DELETE".format(selectable=selectable)
return " FROM {selectable}".format(selectable=selectable)
clauses = [selectable]
if self._sample is not None:
clauses.append(f"SAMPLE {self._sample}")
if self._sample_offset is not None:
clauses.append(f"OFFSET {self._sample_offset}")
return " FROM {clauses}".format(clauses=" ".join(clauses))

def _set_sql(self, **kwargs: Any) -> str:
return " UPDATE {set}".format(
Expand Down
10 changes: 10 additions & 0 deletions pypika/tests/dialects/test_clickhouse.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@ def test_use_AS_keyword_for_alias(self):
query = ClickHouseQuery.from_(t).select(t.foo.as_('f1'), t.bar.as_('f2'))
self.assertEqual(str(query), 'SELECT "foo" AS "f1","bar" AS "f2" FROM "abc"')

def test_use_SAMPLE_keyword(self):
t = Table('abc')
query = ClickHouseQuery.from_(t).select(t.foo).sample(10)
self.assertEqual(str(query), 'SELECT "foo" FROM "abc" SAMPLE 10')

def test_use_SAMPLE_with_offset_keyword(self):
t = Table('abc')
query = ClickHouseQuery.from_(t).select(t.foo).sample(10, 5)
self.assertEqual(str(query), 'SELECT "foo" FROM "abc" SAMPLE 10 OFFSET 5')


class ClickHouseDeleteTests(TestCase):
table_abc = Table("abc")
Expand Down
Loading