where.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. """
  2. Code to manage the creation and SQL rendering of 'where' constraints.
  3. """
  4. import operator
  5. from functools import reduce
  6. from django.core.exceptions import EmptyResultSet, FullResultSet
  7. from django.db.models.expressions import Case, When
  8. from django.db.models.lookups import Exact
  9. from django.utils import tree
  10. from django.utils.functional import cached_property
  11. # Connection types
  12. AND = "AND"
  13. OR = "OR"
  14. XOR = "XOR"
  15. class WhereNode(tree.Node):
  16. """
  17. An SQL WHERE clause.
  18. The class is tied to the Query class that created it (in order to create
  19. the correct SQL).
  20. A child is usually an expression producing boolean values. Most likely the
  21. expression is a Lookup instance.
  22. However, a child could also be any class with as_sql() and either
  23. relabeled_clone() method or relabel_aliases() and clone() methods and
  24. contains_aggregate attribute.
  25. """
  26. default = AND
  27. resolved = False
  28. conditional = True
  29. def split_having_qualify(self, negated=False, must_group_by=False):
  30. """
  31. Return three possibly None nodes: one for those parts of self that
  32. should be included in the WHERE clause, one for those parts of self
  33. that must be included in the HAVING clause, and one for those parts
  34. that refer to window functions.
  35. """
  36. if not self.contains_aggregate and not self.contains_over_clause:
  37. return self, None, None
  38. in_negated = negated ^ self.negated
  39. # Whether or not children must be connected in the same filtering
  40. # clause (WHERE > HAVING > QUALIFY) to maintain logical semantic.
  41. must_remain_connected = (
  42. (in_negated and self.connector == AND)
  43. or (not in_negated and self.connector == OR)
  44. or self.connector == XOR
  45. )
  46. if (
  47. must_remain_connected
  48. and self.contains_aggregate
  49. and not self.contains_over_clause
  50. ):
  51. # It's must cheaper to short-circuit and stash everything in the
  52. # HAVING clause than split children if possible.
  53. return None, self, None
  54. where_parts = []
  55. having_parts = []
  56. qualify_parts = []
  57. for c in self.children:
  58. if hasattr(c, "split_having_qualify"):
  59. where_part, having_part, qualify_part = c.split_having_qualify(
  60. in_negated, must_group_by
  61. )
  62. if where_part is not None:
  63. where_parts.append(where_part)
  64. if having_part is not None:
  65. having_parts.append(having_part)
  66. if qualify_part is not None:
  67. qualify_parts.append(qualify_part)
  68. elif c.contains_over_clause:
  69. qualify_parts.append(c)
  70. elif c.contains_aggregate:
  71. having_parts.append(c)
  72. else:
  73. where_parts.append(c)
  74. if must_remain_connected and qualify_parts:
  75. # Disjunctive heterogeneous predicates can be pushed down to
  76. # qualify as long as no conditional aggregation is involved.
  77. if not where_parts or (where_parts and not must_group_by):
  78. return None, None, self
  79. elif where_parts:
  80. # In theory this should only be enforced when dealing with
  81. # where_parts containing predicates against multi-valued
  82. # relationships that could affect aggregation results but this
  83. # is complex to infer properly.
  84. raise NotImplementedError(
  85. "Heterogeneous disjunctive predicates against window functions are "
  86. "not implemented when performing conditional aggregation."
  87. )
  88. where_node = (
  89. self.create(where_parts, self.connector, self.negated)
  90. if where_parts
  91. else None
  92. )
  93. having_node = (
  94. self.create(having_parts, self.connector, self.negated)
  95. if having_parts
  96. else None
  97. )
  98. qualify_node = (
  99. self.create(qualify_parts, self.connector, self.negated)
  100. if qualify_parts
  101. else None
  102. )
  103. return where_node, having_node, qualify_node
  104. def as_sql(self, compiler, connection):
  105. """
  106. Return the SQL version of the where clause and the value to be
  107. substituted in. Return '', [] if this node matches everything,
  108. None, [] if this node is empty, and raise EmptyResultSet if this
  109. node can't match anything.
  110. """
  111. result = []
  112. result_params = []
  113. if self.connector == AND:
  114. full_needed, empty_needed = len(self.children), 1
  115. else:
  116. full_needed, empty_needed = 1, len(self.children)
  117. if self.connector == XOR and not connection.features.supports_logical_xor:
  118. # Convert if the database doesn't support XOR:
  119. # a XOR b XOR c XOR ...
  120. # to:
  121. # (a OR b OR c OR ...) AND (a + b + c + ...) == 1
  122. lhs = self.__class__(self.children, OR)
  123. rhs_sum = reduce(
  124. operator.add,
  125. (Case(When(c, then=1), default=0) for c in self.children),
  126. )
  127. rhs = Exact(1, rhs_sum)
  128. return self.__class__([lhs, rhs], AND, self.negated).as_sql(
  129. compiler, connection
  130. )
  131. for child in self.children:
  132. try:
  133. sql, params = compiler.compile(child)
  134. except EmptyResultSet:
  135. empty_needed -= 1
  136. except FullResultSet:
  137. full_needed -= 1
  138. else:
  139. if sql:
  140. result.append(sql)
  141. result_params.extend(params)
  142. else:
  143. full_needed -= 1
  144. # Check if this node matches nothing or everything.
  145. # First check the amount of full nodes and empty nodes
  146. # to make this node empty/full.
  147. # Now, check if this node is full/empty using the
  148. # counts.
  149. if empty_needed == 0:
  150. if self.negated:
  151. raise FullResultSet
  152. else:
  153. raise EmptyResultSet
  154. if full_needed == 0:
  155. if self.negated:
  156. raise EmptyResultSet
  157. else:
  158. raise FullResultSet
  159. conn = " %s " % self.connector
  160. sql_string = conn.join(result)
  161. if not sql_string:
  162. raise FullResultSet
  163. if self.negated:
  164. # Some backends (Oracle at least) need parentheses around the inner
  165. # SQL in the negated case, even if the inner SQL contains just a
  166. # single expression.
  167. sql_string = "NOT (%s)" % sql_string
  168. elif len(result) > 1 or self.resolved:
  169. sql_string = "(%s)" % sql_string
  170. return sql_string, result_params
  171. def get_group_by_cols(self):
  172. cols = []
  173. for child in self.children:
  174. cols.extend(child.get_group_by_cols())
  175. return cols
  176. def get_source_expressions(self):
  177. return self.children[:]
  178. def set_source_expressions(self, children):
  179. assert len(children) == len(self.children)
  180. self.children = children
  181. def relabel_aliases(self, change_map):
  182. """
  183. Relabel the alias values of any children. 'change_map' is a dictionary
  184. mapping old (current) alias values to the new values.
  185. """
  186. for pos, child in enumerate(self.children):
  187. if hasattr(child, "relabel_aliases"):
  188. # For example another WhereNode
  189. child.relabel_aliases(change_map)
  190. elif hasattr(child, "relabeled_clone"):
  191. self.children[pos] = child.relabeled_clone(change_map)
  192. def clone(self):
  193. clone = self.create(connector=self.connector, negated=self.negated)
  194. for child in self.children:
  195. if hasattr(child, "clone"):
  196. child = child.clone()
  197. clone.children.append(child)
  198. return clone
  199. def relabeled_clone(self, change_map):
  200. clone = self.clone()
  201. clone.relabel_aliases(change_map)
  202. return clone
  203. def replace_expressions(self, replacements):
  204. if replacement := replacements.get(self):
  205. return replacement
  206. clone = self.create(connector=self.connector, negated=self.negated)
  207. for child in self.children:
  208. clone.children.append(child.replace_expressions(replacements))
  209. return clone
  210. def get_refs(self):
  211. refs = set()
  212. for child in self.children:
  213. refs |= child.get_refs()
  214. return refs
  215. @classmethod
  216. def _contains_aggregate(cls, obj):
  217. if isinstance(obj, tree.Node):
  218. return any(cls._contains_aggregate(c) for c in obj.children)
  219. return obj.contains_aggregate
  220. @cached_property
  221. def contains_aggregate(self):
  222. return self._contains_aggregate(self)
  223. @classmethod
  224. def _contains_over_clause(cls, obj):
  225. if isinstance(obj, tree.Node):
  226. return any(cls._contains_over_clause(c) for c in obj.children)
  227. return obj.contains_over_clause
  228. @cached_property
  229. def contains_over_clause(self):
  230. return self._contains_over_clause(self)
  231. @property
  232. def is_summary(self):
  233. return any(child.is_summary for child in self.children)
  234. @staticmethod
  235. def _resolve_leaf(expr, query, *args, **kwargs):
  236. if hasattr(expr, "resolve_expression"):
  237. expr = expr.resolve_expression(query, *args, **kwargs)
  238. return expr
  239. @classmethod
  240. def _resolve_node(cls, node, query, *args, **kwargs):
  241. if hasattr(node, "children"):
  242. for child in node.children:
  243. cls._resolve_node(child, query, *args, **kwargs)
  244. if hasattr(node, "lhs"):
  245. node.lhs = cls._resolve_leaf(node.lhs, query, *args, **kwargs)
  246. if hasattr(node, "rhs"):
  247. node.rhs = cls._resolve_leaf(node.rhs, query, *args, **kwargs)
  248. def resolve_expression(self, *args, **kwargs):
  249. clone = self.clone()
  250. clone._resolve_node(clone, *args, **kwargs)
  251. clone.resolved = True
  252. return clone
  253. @cached_property
  254. def output_field(self):
  255. from django.db.models import BooleanField
  256. return BooleanField()
  257. @property
  258. def _output_field_or_none(self):
  259. return self.output_field
  260. def select_format(self, compiler, sql, params):
  261. # Wrap filters with a CASE WHEN expression if a database backend
  262. # (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP
  263. # BY list.
  264. if not compiler.connection.features.supports_boolean_expr_in_select_clause:
  265. sql = f"CASE WHEN {sql} THEN 1 ELSE 0 END"
  266. return sql, params
  267. def get_db_converters(self, connection):
  268. return self.output_field.get_db_converters(connection)
  269. def get_lookup(self, lookup):
  270. return self.output_field.get_lookup(lookup)
  271. def leaves(self):
  272. for child in self.children:
  273. if isinstance(child, WhereNode):
  274. yield from child.leaves()
  275. else:
  276. yield child
  277. class NothingNode:
  278. """A node that matches nothing."""
  279. contains_aggregate = False
  280. contains_over_clause = False
  281. def as_sql(self, compiler=None, connection=None):
  282. raise EmptyResultSet
  283. class ExtraWhere:
  284. # The contents are a black box - assume no aggregates or windows are used.
  285. contains_aggregate = False
  286. contains_over_clause = False
  287. def __init__(self, sqls, params):
  288. self.sqls = sqls
  289. self.params = params
  290. def as_sql(self, compiler=None, connection=None):
  291. sqls = ["(%s)" % sql for sql in self.sqls]
  292. return " AND ".join(sqls), list(self.params or ())
  293. class SubqueryConstraint:
  294. # Even if aggregates or windows would be used in a subquery,
  295. # the outer query isn't interested about those.
  296. contains_aggregate = False
  297. contains_over_clause = False
  298. def __init__(self, alias, columns, targets, query_object):
  299. self.alias = alias
  300. self.columns = columns
  301. self.targets = targets
  302. query_object.clear_ordering(clear_default=True)
  303. self.query_object = query_object
  304. def as_sql(self, compiler, connection):
  305. query = self.query_object
  306. query.set_values(self.targets)
  307. query_compiler = query.get_compiler(connection=connection)
  308. return query_compiler.as_subquery_condition(self.alias, self.columns, compiler)