Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

aggregates.py 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. """
  2. Classes to represent the definitions of aggregate functions.
  3. """
  4. from django.core.exceptions import FieldError
  5. from django.db.models.expressions import Case, Func, Star, When
  6. from django.db.models.fields import IntegerField
  7. from django.db.models.functions.comparison import Coalesce
  8. from django.db.models.functions.mixins import (
  9. FixDurationInputMixin,
  10. NumericOutputFieldMixin,
  11. )
  12. __all__ = [
  13. "Aggregate",
  14. "Avg",
  15. "Count",
  16. "Max",
  17. "Min",
  18. "StdDev",
  19. "Sum",
  20. "Variance",
  21. ]
  22. class Aggregate(Func):
  23. template = "%(function)s(%(distinct)s%(expressions)s)"
  24. contains_aggregate = True
  25. name = None
  26. filter_template = "%s FILTER (WHERE %%(filter)s)"
  27. window_compatible = True
  28. allow_distinct = False
  29. empty_result_set_value = None
  30. def __init__(
  31. self, *expressions, distinct=False, filter=None, default=None, **extra
  32. ):
  33. if distinct and not self.allow_distinct:
  34. raise TypeError("%s does not allow distinct." % self.__class__.__name__)
  35. if default is not None and self.empty_result_set_value is not None:
  36. raise TypeError(f"{self.__class__.__name__} does not allow default.")
  37. self.distinct = distinct
  38. self.filter = filter
  39. self.default = default
  40. super().__init__(*expressions, **extra)
  41. def get_source_fields(self):
  42. # Don't return the filter expression since it's not a source field.
  43. return [e._output_field_or_none for e in super().get_source_expressions()]
  44. def get_source_expressions(self):
  45. source_expressions = super().get_source_expressions()
  46. if self.filter:
  47. return source_expressions + [self.filter]
  48. return source_expressions
  49. def set_source_expressions(self, exprs):
  50. self.filter = self.filter and exprs.pop()
  51. return super().set_source_expressions(exprs)
  52. def resolve_expression(
  53. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  54. ):
  55. # Aggregates are not allowed in UPDATE queries, so ignore for_save
  56. c = super().resolve_expression(query, allow_joins, reuse, summarize)
  57. c.filter = c.filter and c.filter.resolve_expression(
  58. query, allow_joins, reuse, summarize
  59. )
  60. if not summarize:
  61. # Call Aggregate.get_source_expressions() to avoid
  62. # returning self.filter and including that in this loop.
  63. expressions = super(Aggregate, c).get_source_expressions()
  64. for index, expr in enumerate(expressions):
  65. if expr.contains_aggregate:
  66. before_resolved = self.get_source_expressions()[index]
  67. name = (
  68. before_resolved.name
  69. if hasattr(before_resolved, "name")
  70. else repr(before_resolved)
  71. )
  72. raise FieldError(
  73. "Cannot compute %s('%s'): '%s' is an aggregate"
  74. % (c.name, name, name)
  75. )
  76. if (default := c.default) is None:
  77. return c
  78. if hasattr(default, "resolve_expression"):
  79. default = default.resolve_expression(query, allow_joins, reuse, summarize)
  80. c.default = None # Reset the default argument before wrapping.
  81. coalesce = Coalesce(c, default, output_field=c._output_field_or_none)
  82. coalesce.is_summary = c.is_summary
  83. return coalesce
  84. @property
  85. def default_alias(self):
  86. expressions = self.get_source_expressions()
  87. if len(expressions) == 1 and hasattr(expressions[0], "name"):
  88. return "%s__%s" % (expressions[0].name, self.name.lower())
  89. raise TypeError("Complex expressions require an alias")
  90. def get_group_by_cols(self, alias=None):
  91. return []
  92. def as_sql(self, compiler, connection, **extra_context):
  93. extra_context["distinct"] = "DISTINCT " if self.distinct else ""
  94. if self.filter:
  95. if connection.features.supports_aggregate_filter_clause:
  96. filter_sql, filter_params = self.filter.as_sql(compiler, connection)
  97. template = self.filter_template % extra_context.get(
  98. "template", self.template
  99. )
  100. sql, params = super().as_sql(
  101. compiler,
  102. connection,
  103. template=template,
  104. filter=filter_sql,
  105. **extra_context,
  106. )
  107. return sql, (*params, *filter_params)
  108. else:
  109. copy = self.copy()
  110. copy.filter = None
  111. source_expressions = copy.get_source_expressions()
  112. condition = When(self.filter, then=source_expressions[0])
  113. copy.set_source_expressions([Case(condition)] + source_expressions[1:])
  114. return super(Aggregate, copy).as_sql(
  115. compiler, connection, **extra_context
  116. )
  117. return super().as_sql(compiler, connection, **extra_context)
  118. def _get_repr_options(self):
  119. options = super()._get_repr_options()
  120. if self.distinct:
  121. options["distinct"] = self.distinct
  122. if self.filter:
  123. options["filter"] = self.filter
  124. return options
  125. class Avg(FixDurationInputMixin, NumericOutputFieldMixin, Aggregate):
  126. function = "AVG"
  127. name = "Avg"
  128. allow_distinct = True
  129. class Count(Aggregate):
  130. function = "COUNT"
  131. name = "Count"
  132. output_field = IntegerField()
  133. allow_distinct = True
  134. empty_result_set_value = 0
  135. def __init__(self, expression, filter=None, **extra):
  136. if expression == "*":
  137. expression = Star()
  138. if isinstance(expression, Star) and filter is not None:
  139. raise ValueError("Star cannot be used with filter. Please specify a field.")
  140. super().__init__(expression, filter=filter, **extra)
  141. class Max(Aggregate):
  142. function = "MAX"
  143. name = "Max"
  144. class Min(Aggregate):
  145. function = "MIN"
  146. name = "Min"
  147. class StdDev(NumericOutputFieldMixin, Aggregate):
  148. name = "StdDev"
  149. def __init__(self, expression, sample=False, **extra):
  150. self.function = "STDDEV_SAMP" if sample else "STDDEV_POP"
  151. super().__init__(expression, **extra)
  152. def _get_repr_options(self):
  153. return {**super()._get_repr_options(), "sample": self.function == "STDDEV_SAMP"}
  154. class Sum(FixDurationInputMixin, Aggregate):
  155. function = "SUM"
  156. name = "Sum"
  157. allow_distinct = True
  158. class Variance(NumericOutputFieldMixin, Aggregate):
  159. name = "Variance"
  160. def __init__(self, expression, sample=False, **extra):
  161. self.function = "VAR_SAMP" if sample else "VAR_POP"
  162. super().__init__(expression, **extra)
  163. def _get_repr_options(self):
  164. return {**super()._get_repr_options(), "sample": self.function == "VAR_SAMP"}