Skip to content

Commit 06439da

Browse files
committed
handle the empty group by.
1 parent 613c7ae commit 06439da

File tree

2 files changed

+83
-45
lines changed

2 files changed

+83
-45
lines changed

django_mongodb/compiler.py

Lines changed: 82 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from django.db import DatabaseError, IntegrityError, NotSupportedError
55
from django.db.models import Count, Expression
66
from django.db.models.aggregates import Aggregate
7-
from django.db.models.expressions import OrderBy, Value
7+
from django.db.models.expressions import Col, OrderBy, Value
88
from django.db.models.sql import compiler
99
from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, MULTI, ORDER_DIR, SINGLE
1010
from django.utils.functional import cached_property
@@ -18,6 +18,62 @@ class SQLCompiler(compiler.SQLCompiler):
1818

1919
query_class = MongoQuery
2020

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

87143
def has_results(self):
88-
return bool(self.get_count(check_exists=True))
144+
return bool(self.execute_sql(SINGLE))
89145

90146
def _make_result(self, entity, columns):
91147
"""
@@ -174,9 +230,9 @@ def build_query(self, columns=None):
174230
"""Check if the query is supported and prepare a MongoQuery."""
175231
self.check_query()
176232
query = self.query_class(self)
177-
query.project_fields = self.get_project_fields(columns)
178-
query.lookup_pipeline = self.get_lookup_pipeline()
179233
query.aggregation_stage = self.get_aggregation_pipeline()
234+
query.lookup_pipeline = self.get_lookup_pipeline()
235+
query.project_fields = self.get_project_fields(columns)
180236
try:
181237
query.mongo_query = {"$expr": self.query.where.as_mql(self, self.connection)}
182238
except FullResultSet:
@@ -216,7 +272,7 @@ def project_field(column):
216272

217273
return (
218274
tuple(map(project_field, columns))
219-
+ tuple(self.query.annotation_select.items())
275+
+ tuple(self.annotations.items())
220276
+ tuple(map(project_field, related_columns))
221277
)
222278

@@ -281,52 +337,34 @@ def get_lookup_pipeline(self):
281337
result += self.query.alias_map[alias].as_mql(self, self.connection)
282338
return result
283339

284-
def get_aggregation_pipeline(self):
285-
pipeline = None
286-
if any(isinstance(a, Aggregate) for a in self.query.annotations.values()):
287-
result = {}
288-
# self.get_group_by(self.select, [])
289-
for alias, annotation in self.query.annotation_select.items():
290-
value = annotation.as_mql(self, self.connection)
291-
if isinstance(value, list):
292-
value = value[0]
293-
result[alias] = value
294-
295-
expressions = set()
296-
for expr, *_ in self.select:
297-
expressions |= set(expr.get_group_by_cols())
298-
order_by = self.get_order_by()
299-
for expr, (_, _, is_ref) in order_by:
300-
# Skip references to the SELECT clause, as all expressions in
301-
# the SELECT clause are already part of the GROUP BY.
302-
if not is_ref:
303-
expressions |= set(expr.get_group_by_cols())
304-
having_group_by = self.having.get_group_by_cols() if self.having else ()
305-
for expr in having_group_by:
306-
expressions.add(expr)
307-
308-
ids = (
309-
None
310-
if not expressions
311-
else {col.target.column: col.as_mql(self, self.connection) for col in expressions}
312-
)
313-
result["_id"] = ids
314-
315-
pipeline = [{"$group": result}]
316-
if ids:
317-
pipeline.append(
318-
{"$addFields": {key: f"$_id.{value[1:]}" for key, value in ids.items()}}
340+
def _get_aggregate_expressions2(self, expr):
341+
stack = [(None, expr)]
342+
while stack:
343+
parent, expr = stack.pop()
344+
if isinstance(expr, Aggregate):
345+
yield parent
346+
elif hasattr(expr, "get_source_expressions"):
347+
stack.extend(
348+
[((expr, idx), se) for idx, se in enumerate(expr.get_source_expressions())]
319349
)
320-
if "_id" not in ids:
321-
pipeline.append({"$unSet": "$_id"})
322350

323-
return pipeline
351+
def _get_aggregate_expressions(self, expr):
352+
stack = [expr]
353+
while stack:
354+
expr = stack.pop()
355+
if isinstance(expr, Aggregate):
356+
yield expr
357+
elif hasattr(expr, "get_source_expressions"):
358+
stack.extend(expr.get_source_expressions())
359+
360+
def get_aggregation_pipeline(self):
361+
return self._group_pipeline
324362

325363
def get_project_fields(self, columns=None):
326364
fields = {}
327365
for name, expr in columns or []:
328366
try:
329-
column = name if isinstance(expr, Aggregate) else expr.target.column
367+
column = expr.target.column
330368
except AttributeError:
331369
# Generate the MQL for an annotation.
332370
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)