datastructures.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. """
  2. Useful auxiliary data structures for query construction. Not useful outside
  3. the SQL domain.
  4. """
  5. from django.core.exceptions import FullResultSet
  6. from django.db.models.sql.constants import INNER, LOUTER
  7. class MultiJoin(Exception):
  8. """
  9. Used by join construction code to indicate the point at which a
  10. multi-valued join was attempted (if the caller wants to treat that
  11. exceptionally).
  12. """
  13. def __init__(self, names_pos, path_with_names):
  14. self.level = names_pos
  15. # The path travelled, this includes the path to the multijoin.
  16. self.names_with_path = path_with_names
  17. class Empty:
  18. pass
  19. class Join:
  20. """
  21. Used by sql.Query and sql.SQLCompiler to generate JOIN clauses into the
  22. FROM entry. For example, the SQL generated could be
  23. LEFT OUTER JOIN "sometable" T1
  24. ON ("othertable"."sometable_id" = "sometable"."id")
  25. This class is primarily used in Query.alias_map. All entries in alias_map
  26. must be Join compatible by providing the following attributes and methods:
  27. - table_name (string)
  28. - table_alias (possible alias for the table, can be None)
  29. - join_type (can be None for those entries that aren't joined from
  30. anything)
  31. - parent_alias (which table is this join's parent, can be None similarly
  32. to join_type)
  33. - as_sql()
  34. - relabeled_clone()
  35. """
  36. def __init__(
  37. self,
  38. table_name,
  39. parent_alias,
  40. table_alias,
  41. join_type,
  42. join_field,
  43. nullable,
  44. filtered_relation=None,
  45. ):
  46. # Join table
  47. self.table_name = table_name
  48. self.parent_alias = parent_alias
  49. # Note: table_alias is not necessarily known at instantiation time.
  50. self.table_alias = table_alias
  51. # LOUTER or INNER
  52. self.join_type = join_type
  53. # A list of 2-tuples to use in the ON clause of the JOIN.
  54. # Each 2-tuple will create one join condition in the ON clause.
  55. self.join_cols = join_field.get_joining_columns()
  56. # Along which field (or ForeignObjectRel in the reverse join case)
  57. self.join_field = join_field
  58. # Is this join nullabled?
  59. self.nullable = nullable
  60. self.filtered_relation = filtered_relation
  61. def as_sql(self, compiler, connection):
  62. """
  63. Generate the full
  64. LEFT OUTER JOIN sometable ON sometable.somecol = othertable.othercol, params
  65. clause for this join.
  66. """
  67. join_conditions = []
  68. params = []
  69. qn = compiler.quote_name_unless_alias
  70. qn2 = connection.ops.quote_name
  71. # Add a join condition for each pair of joining columns.
  72. for lhs_col, rhs_col in self.join_cols:
  73. join_conditions.append(
  74. "%s.%s = %s.%s"
  75. % (
  76. qn(self.parent_alias),
  77. qn2(lhs_col),
  78. qn(self.table_alias),
  79. qn2(rhs_col),
  80. )
  81. )
  82. # Add a single condition inside parentheses for whatever
  83. # get_extra_restriction() returns.
  84. extra_cond = self.join_field.get_extra_restriction(
  85. self.table_alias, self.parent_alias
  86. )
  87. if extra_cond:
  88. extra_sql, extra_params = compiler.compile(extra_cond)
  89. join_conditions.append("(%s)" % extra_sql)
  90. params.extend(extra_params)
  91. if self.filtered_relation:
  92. try:
  93. extra_sql, extra_params = compiler.compile(self.filtered_relation)
  94. except FullResultSet:
  95. pass
  96. else:
  97. join_conditions.append("(%s)" % extra_sql)
  98. params.extend(extra_params)
  99. if not join_conditions:
  100. # This might be a rel on the other end of an actual declared field.
  101. declared_field = getattr(self.join_field, "field", self.join_field)
  102. raise ValueError(
  103. "Join generated an empty ON clause. %s did not yield either "
  104. "joining columns or extra restrictions." % declared_field.__class__
  105. )
  106. on_clause_sql = " AND ".join(join_conditions)
  107. alias_str = (
  108. "" if self.table_alias == self.table_name else (" %s" % self.table_alias)
  109. )
  110. sql = "%s %s%s ON (%s)" % (
  111. self.join_type,
  112. qn(self.table_name),
  113. alias_str,
  114. on_clause_sql,
  115. )
  116. return sql, params
  117. def relabeled_clone(self, change_map):
  118. new_parent_alias = change_map.get(self.parent_alias, self.parent_alias)
  119. new_table_alias = change_map.get(self.table_alias, self.table_alias)
  120. if self.filtered_relation is not None:
  121. filtered_relation = self.filtered_relation.clone()
  122. filtered_relation.path = [
  123. change_map.get(p, p) for p in self.filtered_relation.path
  124. ]
  125. else:
  126. filtered_relation = None
  127. return self.__class__(
  128. self.table_name,
  129. new_parent_alias,
  130. new_table_alias,
  131. self.join_type,
  132. self.join_field,
  133. self.nullable,
  134. filtered_relation=filtered_relation,
  135. )
  136. @property
  137. def identity(self):
  138. return (
  139. self.__class__,
  140. self.table_name,
  141. self.parent_alias,
  142. self.join_field,
  143. self.filtered_relation,
  144. )
  145. def __eq__(self, other):
  146. if not isinstance(other, Join):
  147. return NotImplemented
  148. return self.identity == other.identity
  149. def __hash__(self):
  150. return hash(self.identity)
  151. def equals(self, other):
  152. # Ignore filtered_relation in equality check.
  153. return self.identity[:-1] == other.identity[:-1]
  154. def demote(self):
  155. new = self.relabeled_clone({})
  156. new.join_type = INNER
  157. return new
  158. def promote(self):
  159. new = self.relabeled_clone({})
  160. new.join_type = LOUTER
  161. return new
  162. class BaseTable:
  163. """
  164. The BaseTable class is used for base table references in FROM clause. For
  165. example, the SQL "foo" in
  166. SELECT * FROM "foo" WHERE somecond
  167. could be generated by this class.
  168. """
  169. join_type = None
  170. parent_alias = None
  171. filtered_relation = None
  172. def __init__(self, table_name, alias):
  173. self.table_name = table_name
  174. self.table_alias = alias
  175. def as_sql(self, compiler, connection):
  176. alias_str = (
  177. "" if self.table_alias == self.table_name else (" %s" % self.table_alias)
  178. )
  179. base_sql = compiler.quote_name_unless_alias(self.table_name)
  180. return base_sql + alias_str, []
  181. def relabeled_clone(self, change_map):
  182. return self.__class__(
  183. self.table_name, change_map.get(self.table_alias, self.table_alias)
  184. )
  185. @property
  186. def identity(self):
  187. return self.__class__, self.table_name, self.table_alias
  188. def __eq__(self, other):
  189. if not isinstance(other, BaseTable):
  190. return NotImplemented
  191. return self.identity == other.identity
  192. def __hash__(self):
  193. return hash(self.identity)
  194. def equals(self, other):
  195. return self.identity == other.identity