3
3
from django .db .models import Count , Expression
4
4
from django .db .models .aggregates import Aggregate
5
5
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
7
7
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
9
9
from django .utils .functional import cached_property
10
10
11
11
from .base import Cursor
@@ -17,6 +17,62 @@ class SQLCompiler(compiler.SQLCompiler):
17
17
18
18
query_class = MongoQuery
19
19
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
+
20
76
def execute_sql (
21
77
self , result_type = MULTI , chunked_fetch = False , chunk_size = GET_ITERATOR_CHUNK_SIZE
22
78
):
@@ -34,11 +90,13 @@ def execute_sql(
34
90
except EmptyResultSet :
35
91
return iter ([]) if result_type == MULTI else None
36
92
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
42
100
43
101
def results_iter (
44
102
self ,
@@ -65,7 +123,7 @@ def results_iter(
65
123
return rows
66
124
67
125
def has_results (self ):
68
- return bool (self .get_count ( check_exists = True ))
126
+ return bool (self .execute_sql ( SINGLE ))
69
127
70
128
def _make_result (self , entity , columns ):
71
129
"""
@@ -139,9 +197,9 @@ def build_query(self, columns=None):
139
197
self .check_query ()
140
198
self .setup_query ()
141
199
query = self .query_class (self )
142
- query .project_fields = self .get_project_fields (columns )
143
- query .lookup_pipeline = self .get_lookup_pipeline ()
144
200
query .aggregation_stage = self .get_aggregation_pipeline ()
201
+ query .lookup_pipeline = self .get_lookup_pipeline ()
202
+ query .project_fields = self .get_project_fields (columns )
145
203
try :
146
204
query .mongo_query = {"$expr" : self .query .where .as_mql (self , self .connection )}
147
205
except FullResultSet :
@@ -181,7 +239,7 @@ def project_field(column):
181
239
182
240
return (
183
241
tuple (map (project_field , columns ))
184
- + tuple (self .query . annotation_select .items ())
242
+ + tuple (self .annotations .items ())
185
243
+ tuple (map (project_field , related_columns ))
186
244
)
187
245
@@ -240,52 +298,34 @@ def get_lookup_pipeline(self):
240
298
result += self .query .alias_map [alias ].as_mql (self , self .connection )
241
299
return result
242
300
243
- def get_aggregation_pipeline (self ):
244
- pipeline = None
245
- if any (isinstance (a , Aggregate ) for a in self .query .annotations .values ()):
246
- result = {}
247
- # self.get_group_by(self.select, [])
248
- for alias , annotation in self .query .annotation_select .items ():
249
- value = annotation .as_mql (self , self .connection )
250
- if isinstance (value , list ):
251
- value = value [0 ]
252
- result [alias ] = value
253
-
254
- expressions = set ()
255
- for expr , * _ in self .select :
256
- expressions |= set (expr .get_group_by_cols ())
257
- order_by = self .get_order_by ()
258
- for expr , (_ , _ , is_ref ) in order_by :
259
- # Skip references to the SELECT clause, as all expressions in
260
- # the SELECT clause are already part of the GROUP BY.
261
- if not is_ref :
262
- expressions |= set (expr .get_group_by_cols ())
263
- having_group_by = self .having .get_group_by_cols () if self .having else ()
264
- for expr in having_group_by :
265
- expressions .add (expr )
266
-
267
- ids = (
268
- None
269
- if not expressions
270
- else {col .target .column : col .as_mql (self , self .connection ) for col in expressions }
271
- )
272
- result ["_id" ] = ids
273
-
274
- pipeline = [{"$group" : result }]
275
- if ids :
276
- pipeline .append (
277
- {"$addFields" : {key : f"$_id.{ value [1 :]} " for key , value in ids .items ()}}
301
+ def _get_aggregate_expressions2 (self , expr ):
302
+ stack = [(None , expr )]
303
+ while stack :
304
+ parent , expr = stack .pop ()
305
+ if isinstance (expr , Aggregate ):
306
+ yield parent
307
+ elif hasattr (expr , "get_source_expressions" ):
308
+ stack .extend (
309
+ [((expr , idx ), se ) for idx , se in enumerate (expr .get_source_expressions ())]
278
310
)
279
- if "_id" not in ids :
280
- pipeline .append ({"$unSet" : "$_id" })
281
311
282
- return pipeline
312
+ def _get_aggregate_expressions (self , expr ):
313
+ stack = [expr ]
314
+ while stack :
315
+ expr = stack .pop ()
316
+ if isinstance (expr , Aggregate ):
317
+ yield expr
318
+ elif hasattr (expr , "get_source_expressions" ):
319
+ stack .extend (expr .get_source_expressions ())
320
+
321
+ def get_aggregation_pipeline (self ):
322
+ return self ._group_pipeline
283
323
284
324
def get_project_fields (self , columns = None ):
285
325
fields = {}
286
326
for name , expr in columns or []:
287
327
try :
288
- column = name if isinstance ( expr , Aggregate ) else expr .target .column
328
+ column = expr .target .column
289
329
except AttributeError :
290
330
# Generate the MQL for an annotation.
291
331
try :
0 commit comments