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.
 
 
 
 

225 lines
7.9 KiB

  1. """
  2. Code to manage the creation and SQL rendering of 'where' constraints.
  3. """
  4. from django.db.models.sql.datastructures import EmptyResultSet
  5. from django.utils import tree
  6. from django.utils.functional import cached_property
  7. # Connection types
  8. AND = 'AND'
  9. OR = 'OR'
  10. class WhereNode(tree.Node):
  11. """
  12. Used to represent the SQL where-clause.
  13. The class is tied to the Query class that created it (in order to create
  14. the correct SQL).
  15. A child is usually an expression producing boolean values. Most likely the
  16. expression is a Lookup instance.
  17. However, a child could also be any class with as_sql() and either
  18. relabeled_clone() method or relabel_aliases() and clone() methods and
  19. contains_aggregate attribute.
  20. """
  21. default = AND
  22. def split_having(self, negated=False):
  23. """
  24. Returns two possibly None nodes: one for those parts of self that
  25. should be included in the WHERE clause and one for those parts of
  26. self that must be included in the HAVING clause.
  27. """
  28. if not self.contains_aggregate:
  29. return self, None
  30. in_negated = negated ^ self.negated
  31. # If the effective connector is OR and this node contains an aggregate,
  32. # then we need to push the whole branch to HAVING clause.
  33. may_need_split = (
  34. (in_negated and self.connector == AND) or
  35. (not in_negated and self.connector == OR))
  36. if may_need_split and self.contains_aggregate:
  37. return None, self
  38. where_parts = []
  39. having_parts = []
  40. for c in self.children:
  41. if hasattr(c, 'split_having'):
  42. where_part, having_part = c.split_having(in_negated)
  43. if where_part is not None:
  44. where_parts.append(where_part)
  45. if having_part is not None:
  46. having_parts.append(having_part)
  47. elif c.contains_aggregate:
  48. having_parts.append(c)
  49. else:
  50. where_parts.append(c)
  51. having_node = self.__class__(having_parts, self.connector, self.negated) if having_parts else None
  52. where_node = self.__class__(where_parts, self.connector, self.negated) if where_parts else None
  53. return where_node, having_node
  54. def as_sql(self, compiler, connection):
  55. """
  56. Returns the SQL version of the where clause and the value to be
  57. substituted in. Returns '', [] if this node matches everything,
  58. None, [] if this node is empty, and raises EmptyResultSet if this
  59. node can't match anything.
  60. """
  61. result = []
  62. result_params = []
  63. if self.connector == AND:
  64. full_needed, empty_needed = len(self.children), 1
  65. else:
  66. full_needed, empty_needed = 1, len(self.children)
  67. for child in self.children:
  68. try:
  69. sql, params = compiler.compile(child)
  70. except EmptyResultSet:
  71. empty_needed -= 1
  72. else:
  73. if sql:
  74. result.append(sql)
  75. result_params.extend(params)
  76. else:
  77. full_needed -= 1
  78. # Check if this node matches nothing or everything.
  79. # First check the amount of full nodes and empty nodes
  80. # to make this node empty/full.
  81. # Now, check if this node is full/empty using the
  82. # counts.
  83. if empty_needed == 0:
  84. if self.negated:
  85. return '', []
  86. else:
  87. raise EmptyResultSet
  88. if full_needed == 0:
  89. if self.negated:
  90. raise EmptyResultSet
  91. else:
  92. return '', []
  93. conn = ' %s ' % self.connector
  94. sql_string = conn.join(result)
  95. if sql_string:
  96. if self.negated:
  97. # Some backends (Oracle at least) need parentheses
  98. # around the inner SQL in the negated case, even if the
  99. # inner SQL contains just a single expression.
  100. sql_string = 'NOT (%s)' % sql_string
  101. elif len(result) > 1:
  102. sql_string = '(%s)' % sql_string
  103. return sql_string, result_params
  104. def get_group_by_cols(self):
  105. cols = []
  106. for child in self.children:
  107. cols.extend(child.get_group_by_cols())
  108. return cols
  109. def relabel_aliases(self, change_map):
  110. """
  111. Relabels the alias values of any children. 'change_map' is a dictionary
  112. mapping old (current) alias values to the new values.
  113. """
  114. for pos, child in enumerate(self.children):
  115. if hasattr(child, 'relabel_aliases'):
  116. # For example another WhereNode
  117. child.relabel_aliases(change_map)
  118. elif hasattr(child, 'relabeled_clone'):
  119. self.children[pos] = child.relabeled_clone(change_map)
  120. def clone(self):
  121. """
  122. Creates a clone of the tree. Must only be called on root nodes (nodes
  123. with empty subtree_parents). Childs must be either (Contraint, lookup,
  124. value) tuples, or objects supporting .clone().
  125. """
  126. clone = self.__class__._new_instance(
  127. children=[], connector=self.connector, negated=self.negated)
  128. for child in self.children:
  129. if hasattr(child, 'clone'):
  130. clone.children.append(child.clone())
  131. else:
  132. clone.children.append(child)
  133. return clone
  134. def relabeled_clone(self, change_map):
  135. clone = self.clone()
  136. clone.relabel_aliases(change_map)
  137. return clone
  138. @classmethod
  139. def _contains_aggregate(cls, obj):
  140. if isinstance(obj, tree.Node):
  141. return any(cls._contains_aggregate(c) for c in obj.children)
  142. return obj.contains_aggregate
  143. @cached_property
  144. def contains_aggregate(self):
  145. return self._contains_aggregate(self)
  146. class NothingNode(object):
  147. """
  148. A node that matches nothing.
  149. """
  150. contains_aggregate = False
  151. def as_sql(self, compiler=None, connection=None):
  152. raise EmptyResultSet
  153. class ExtraWhere(object):
  154. # The contents are a black box - assume no aggregates are used.
  155. contains_aggregate = False
  156. def __init__(self, sqls, params):
  157. self.sqls = sqls
  158. self.params = params
  159. def as_sql(self, compiler=None, connection=None):
  160. sqls = ["(%s)" % sql for sql in self.sqls]
  161. return " AND ".join(sqls), list(self.params or ())
  162. class SubqueryConstraint(object):
  163. # Even if aggregates would be used in a subquery, the outer query isn't
  164. # interested about those.
  165. contains_aggregate = False
  166. def __init__(self, alias, columns, targets, query_object):
  167. self.alias = alias
  168. self.columns = columns
  169. self.targets = targets
  170. self.query_object = query_object
  171. def as_sql(self, compiler, connection):
  172. query = self.query_object
  173. # QuerySet was sent
  174. if hasattr(query, 'values'):
  175. if query._db and connection.alias != query._db:
  176. raise ValueError("Can't do subqueries with queries on different DBs.")
  177. # Do not override already existing values.
  178. if query._fields is None:
  179. query = query.values(*self.targets)
  180. else:
  181. query = query._clone()
  182. query = query.query
  183. if query.can_filter():
  184. # If there is no slicing in use, then we can safely drop all ordering
  185. query.clear_ordering(True)
  186. query_compiler = query.get_compiler(connection=connection)
  187. return query_compiler.as_subquery_condition(self.alias, self.columns, compiler)
  188. def relabel_aliases(self, change_map):
  189. self.alias = change_map.get(self.alias, self.alias)
  190. def clone(self):
  191. return self.__class__(
  192. self.alias, self.columns, self.targets,
  193. self.query_object)