Skip to content

Commit 61e84a9

Browse files
committed
handle the empty group by.
1 parent 8d37bc8 commit 61e84a9

File tree

2 files changed

+91
-51
lines changed

2 files changed

+91
-51
lines changed

django_mongodb/compiler.py

Lines changed: 90 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
from django.db.models import Count, Expression
44
from django.db.models.aggregates import Aggregate
55
from django.db.models.constants import LOOKUP_SEP
6-
from django.db.models.expressions import Value
6+
from django.db.models.expressions import Col, Value
77
from django.db.models.sql import compiler
8-
from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, MULTI
8+
from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, MULTI, SINGLE
99
from django.utils.functional import cached_property
1010

1111
from .base import Cursor
@@ -17,6 +17,62 @@ class SQLCompiler(compiler.SQLCompiler):
1717

1818
query_class = MongoQuery
1919

20+
def pre_sql_setup(self):
21+
super().pre_sql_setup()
22+
self.annotations = {}
23+
group = {}
24+
group_expressions = set()
25+
aggregation_idx = 1
26+
for target, expr in self.query.annotation_select.items():
27+
if not expr.contains_aggregate:
28+
result_expr = expr
29+
else:
30+
replacements = {}
31+
for sub_expr in self._get_aggregate_expressions(expr):
32+
alias = f"__aggregation{aggregation_idx}"
33+
group[alias] = sub_expr.as_mql(self, self.connection)
34+
aggregation_idx += 1
35+
column_target = expr.output_field.__class__()
36+
column_target.set_attributes_from_name(alias)
37+
replacements[sub_expr] = Col(self.collection_name, column_target)
38+
result_expr = expr.replace_expressions(replacements)
39+
40+
self.annotations[target] = result_expr
41+
if group:
42+
"""
43+
order_by = self.get_order_by()
44+
for expr, (_, _, is_ref) in order_by:
45+
# Skip references to the SELECT clause, as all expressions in
46+
# the SELECT clause are already part of the GROUP BY.
47+
if not is_ref:
48+
group_expressions |= set(expr.get_group_by_cols())
49+
having_group_by = self.having.get_group_by_cols() if self.having else ()
50+
for expr in having_group_by:
51+
group_expressions.add(expr)
52+
"""
53+
54+
ids = (
55+
None
56+
if not group_expressions
57+
else {
58+
col.target.column: col.as_mql(self, self.connection)
59+
for col in group_expressions
60+
}
61+
)
62+
group["_id"] = ids
63+
64+
pipeline = [{"$group": group}]
65+
if ids:
66+
pipeline.append(
67+
{"$addFields": {key: f"$_id.{value[1:]}" for key, value in ids.items()}}
68+
)
69+
if "_id" not in ids:
70+
pipeline.append({"$unSet": "$_id"})
71+
72+
self._group_pipeline = pipeline
73+
else:
74+
self._group_pipeline = None
75+
2076
def execute_sql(
2177
self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE
2278
):
@@ -34,11 +90,13 @@ def execute_sql(
3490
except EmptyResultSet:
3591
return iter([]) if result_type == MULTI else None
3692

37-
return (
38-
(self._make_result(row, columns) for row in query.fetch())
39-
if result_type == MULTI
40-
else self._make_result(next(query.fetch()), columns)
41-
)
93+
if result_type == MULTI:
94+
return (self._make_result(row, columns) for row in query.fetch())
95+
96+
try:
97+
return self._make_result(next(query.fetch()), columns)
98+
except StopIteration:
99+
return None
42100

43101
def results_iter(
44102
self,
@@ -65,7 +123,7 @@ def results_iter(
65123
return rows
66124

67125
def has_results(self):
68-
return bool(self.get_count(check_exists=True))
126+
return bool(self.execute_sql(SINGLE))
69127

70128
def _make_result(self, entity, columns):
71129
"""
@@ -138,9 +196,9 @@ def build_query(self, columns=None):
138196
"""Check if the query is supported and prepare a MongoQuery."""
139197
self.check_query()
140198
query = self.query_class(self)
141-
query.project_fields = self.get_project_fields(columns)
142-
query.lookup_pipeline = self.get_lookup_pipeline()
143199
query.aggregation_stage = self.get_aggregation_pipeline()
200+
query.lookup_pipeline = self.get_lookup_pipeline()
201+
query.project_fields = self.get_project_fields(columns)
144202
try:
145203
query.mongo_query = {"$expr": self.query.where.as_mql(self, self.connection)}
146204
except FullResultSet:
@@ -180,7 +238,7 @@ def project_field(column):
180238

181239
return (
182240
tuple(map(project_field, columns))
183-
+ tuple(self.query.annotation_select.items())
241+
+ tuple(self.annotations.items())
184242
+ tuple(map(project_field, related_columns))
185243
)
186244

@@ -239,52 +297,34 @@ def get_lookup_pipeline(self):
239297
result += self.query.alias_map[alias].as_mql(self, self.connection)
240298
return result
241299

242-
def get_aggregation_pipeline(self):
243-
pipeline = None
244-
if any(isinstance(a, Aggregate) for a in self.query.annotations.values()):
245-
result = {}
246-
# self.get_group_by(self.select, [])
247-
for alias, annotation in self.query.annotation_select.items():
248-
value = annotation.as_mql(self, self.connection)
249-
if isinstance(value, list):
250-
value = value[0]
251-
result[alias] = value
252-
253-
expressions = set()
254-
for expr, *_ in self.select:
255-
expressions |= set(expr.get_group_by_cols())
256-
order_by = self.get_order_by()
257-
for expr, (_, _, is_ref) in order_by:
258-
# Skip references to the SELECT clause, as all expressions in
259-
# the SELECT clause are already part of the GROUP BY.
260-
if not is_ref:
261-
expressions |= set(expr.get_group_by_cols())
262-
having_group_by = self.having.get_group_by_cols() if self.having else ()
263-
for expr in having_group_by:
264-
expressions.add(expr)
265-
266-
ids = (
267-
None
268-
if not expressions
269-
else {col.target.column: col.as_mql(self, self.connection) for col in expressions}
270-
)
271-
result["_id"] = ids
272-
273-
pipeline = [{"$group": result}]
274-
if ids:
275-
pipeline.append(
276-
{"$addFields": {key: f"$_id.{value[1:]}" for key, value in ids.items()}}
300+
def _get_aggregate_expressions2(self, expr):
301+
stack = [(None, expr)]
302+
while stack:
303+
parent, expr = stack.pop()
304+
if isinstance(expr, Aggregate):
305+
yield parent
306+
elif hasattr(expr, "get_source_expressions"):
307+
stack.extend(
308+
[((expr, idx), se) for idx, se in enumerate(expr.get_source_expressions())]
277309
)
278-
if "_id" not in ids:
279-
pipeline.append({"$unSet": "$_id"})
280310

281-
return pipeline
311+
def _get_aggregate_expressions(self, expr):
312+
stack = [expr]
313+
while stack:
314+
expr = stack.pop()
315+
if isinstance(expr, Aggregate):
316+
yield expr
317+
elif hasattr(expr, "get_source_expressions"):
318+
stack.extend(expr.get_source_expressions())
319+
320+
def get_aggregation_pipeline(self):
321+
return self._group_pipeline
282322

283323
def get_project_fields(self, columns=None):
284324
fields = {}
285325
for name, expr in columns or []:
286326
try:
287-
column = name if isinstance(expr, Aggregate) else expr.target.column
327+
column = expr.target.column
288328
except AttributeError:
289329
# Generate the MQL for an annotation.
290330
try:

django_mongodb/functions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
Count: "sum",
4040
Max: "max",
4141
Min: "min",
42-
StdDev: "stddev",
42+
StdDev: "stdDevPop",
4343
Sum: "sum",
4444
Variance: "stdDevPop",
4545
}

0 commit comments

Comments
 (0)