Debian Codegraph @

django/contrib/postgres/aggregates/mixins.py

raw
1 import warnings
2
3 from django.core.exceptions import FullResultSet
4 from django.db.models.expressions import OrderByList
5 from django.utils.deprecation import RemovedInDjango61Warning
6
7
8 class OrderableAggMixin:
9 # RemovedInDjango61Warning: When the deprecation ends, replace with:
10 # def __init__(self, *expressions, order_by=(), **extra):
11 def __init__(self, *expressions, ordering=(), order_by=(), **extra):
12 # RemovedInDjango61Warning.
13 if ordering:
14 warnings.warn(
15 "The ordering argument is deprecated. Use order_by instead.",
16 category=RemovedInDjango61Warning,
17 stacklevel=2,
18 )
19 if order_by:
20 raise TypeError("Cannot specify both order_by and ordering.")
21 order_by = ordering
22 if not order_by:
23 self.order_by = None
24 elif isinstance(order_by, (list, tuple)):
25 self.order_by = OrderByList(*order_by)
26 else:
27 self.order_by = OrderByList(order_by)
28 super().__init__(*expressions, **extra)
29
30 def get_source_expressions(self):
31 return super().get_source_expressions() + [self.order_by]
32
33 def set_source_expressions(self, exprs):
34 *exprs, self.order_by = exprs
35 return super().set_source_expressions(exprs)
36
37 def as_sql(self, compiler, connection):
38 *source_exprs, filtering_expr, order_by_expr = self.get_source_expressions()
39
40 order_by_sql = ""
41 order_by_params = []
42 if order_by_expr is not None:
43 order_by_sql, order_by_params = compiler.compile(order_by_expr)
44
45 filter_params = []
46 if filtering_expr is not None:
47 try:
48 _, filter_params = compiler.compile(filtering_expr)
49 except FullResultSet:
50 pass
51
52 source_params = []
53 for source_expr in source_exprs:
54 source_params += compiler.compile(source_expr)[1]
55
56 sql, _ = super().as_sql(compiler, connection, order_by=order_by_sql)
57 return sql, (*source_params, *order_by_params, *filter_params)