Skip to content

Commit

Permalink
fix count for query with group by and no agg
Browse files Browse the repository at this point in the history
  • Loading branch information
snopoke committed Jun 19, 2020
1 parent f7dfb8d commit 9b46208
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion sqlagg/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def count(self, connection, filter_values):
query = self._build_query_generic(self.columns, group_by=self.group_by, filters=self.filters,
distinct_on=self.distinct_on)

if any(col.aggregate_fn for col in self.columns):
if self.group_by or any(col.aggregate_fn for col in self.columns):
query = sqlalchemy.select([sqlalchemy.func.count()]).select_from(query.alias())
else:
query = query.with_only_columns([sqlalchemy.func.count()]).order_by(None)
Expand Down
16 changes: 16 additions & 0 deletions tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,22 @@ def test_count_no_grouping(self):
vc.append_column(SimpleColumn('indicator_a'))
self.assertEqual(2, vc.count(self.session.connection(), {'username': 'user1'},))

def test_count_group_no_agg(self):
# due to past idiosyncrasy of sqlagg CommCare was adding a group by on
# primary keys as follows:
#
# SELECT username_ea02198f AS column_0, doc_id AS doc_id FROM ucr_table_x GROUP BY doc_id
#
# When doing a count of this query we have to do a subquery

vc = QueryContext(
"user_table",
group_by=['indicator_a']
)

vc.append_column(SimpleColumn('indicator_a'))
self.assertEqual(4, vc.count(self.session.connection(),))

def test_count_with_nulls(self):
vc = QueryContext(
"user_table",
Expand Down

0 comments on commit 9b46208

Please sign in to comment.