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

support having #171

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
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
30 changes: 30 additions & 0 deletions src/infi/clickhouse_orm/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,7 @@ def __init__(self, model_cls, database):
self._model_cls = model_cls
self._database = database
self._order_by = []
self._having = ''
self._where_q = Q()
self._prewhere_q = Q()
self._grouping_fields = []
Expand Down Expand Up @@ -392,6 +393,9 @@ def as_sql(self):
if self._grouping_with_totals:
sql += ' WITH TOTALS'

if self._having:
sql += '\nHAVING ' + self.having_as_sql()

if self._order_by:
sql += '\nORDER BY ' + self.order_by_as_sql()

Expand All @@ -413,6 +417,12 @@ def order_by_as_sql(self):
for field in self._order_by
])

def having_as_sql(self):
"""
Returns the contents of the query's `Having` clause as a string.
"""
return self._having

def conditions_as_sql(self, prewhere=False):
"""
Returns the contents of the query's `WHERE` or `PREWHERE` clause as a string.
Expand Down Expand Up @@ -442,6 +452,26 @@ def order_by(self, *field_names):
qs._order_by = field_names
return qs

def having(self, *q, **kwargs):
"""
Returns a copy of this queryset that includes only rows matching the having conditions.
"""

qs = copy(self)

condition = Q()
for arg in q:
if isinstance(arg, Q):
condition &= arg
else:
raise TypeError('Invalid argument "%r" to queryset filter' % arg)

if kwargs:
condition &= Q(**kwargs)

qs._having = condition.to_sql(self._model_cls)
return qs

def only(self, *field_names):
"""
Returns a copy of this queryset limited to the specified field names.
Expand Down