datastructures.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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
  32. similarly 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_fields = join_field.get_joining_fields()
  56. self.join_cols = tuple(
  57. (lhs_field.column, rhs_field.column)
  58. for lhs_field, rhs_field in self.join_fields
  59. )
  60. # Along which field (or ForeignObjectRel in the reverse join case)
  61. self.join_field = join_field
  62. # Is this join nullable?
  63. self.nullable = nullable
  64. self.filtered_relation = filtered_relation
  65. def as_sql(self, compiler, connection):
  66. """
  67. Generate the full
  68. LEFT OUTER JOIN sometable
  69. ON sometable.somecol = othertable.othercol, params
  70. clause for this join.
  71. """
  72. join_conditions = []
  73. params = []
  74. qn = compiler.quote_name
  75. # Add a join condition for each pair of joining columns.
  76. for lhs, rhs in self.join_fields:
  77. lhs, rhs = connection.ops.prepare_join_on_clause(
  78. self.parent_alias, lhs, self.table_alias, rhs
  79. )
  80. lhs_sql, lhs_params = compiler.compile(lhs)
  81. lhs_full_name = lhs_sql % lhs_params
  82. rhs_sql, rhs_params = compiler.compile(rhs)
  83. rhs_full_name = rhs_sql % rhs_params
  84. join_conditions.append(f"{lhs_full_name} = {rhs_full_name}")
  85. # Add a single condition inside parentheses for whatever
  86. # get_extra_restriction() returns.
  87. extra_cond = self.join_field.get_extra_restriction(
  88. self.table_alias, self.parent_alias
  89. )
  90. if extra_cond:
  91. extra_sql, extra_params = compiler.compile(extra_cond)
  92. join_conditions.append("(%s)" % extra_sql)
  93. params.extend(extra_params)
  94. if self.filtered_relation:
  95. try:
  96. extra_sql, extra_params = compiler.compile(self.filtered_relation)
  97. except FullResultSet:
  98. pass
  99. else:
  100. join_conditions.append("(%s)" % extra_sql)
  101. params.extend(extra_params)
  102. if not join_conditions:
  103. # This might be a rel on the other end of an actual declared field.
  104. declared_field = getattr(self.join_field, "field", self.join_field)
  105. raise ValueError(
  106. "Join generated an empty ON clause. %s did not yield either "
  107. "joining columns or extra restrictions." % declared_field.__class__
  108. )
  109. on_clause_sql = " AND ".join(join_conditions)
  110. alias_str = (
  111. ""
  112. if self.table_alias == self.table_name
  113. else (" %s" % qn(self.table_alias))
  114. )
  115. sql = "%s %s%s ON (%s)" % (
  116. self.join_type,
  117. qn(self.table_name),
  118. alias_str,
  119. on_clause_sql,
  120. )
  121. return sql, params
  122. def relabeled_clone(self, change_map):
  123. new_parent_alias = change_map.get(self.parent_alias, self.parent_alias)
  124. new_table_alias = change_map.get(self.table_alias, self.table_alias)
  125. if self.filtered_relation is not None:
  126. filtered_relation = self.filtered_relation.relabeled_clone(change_map)
  127. else:
  128. filtered_relation = None
  129. return self.__class__(
  130. self.table_name,
  131. new_parent_alias,
  132. new_table_alias,
  133. self.join_type,
  134. self.join_field,
  135. self.nullable,
  136. filtered_relation=filtered_relation,
  137. )
  138. @property
  139. def identity(self):
  140. return (
  141. self.__class__,
  142. self.table_name,
  143. self.parent_alias,
  144. self.join_field,
  145. self.filtered_relation,
  146. )
  147. def __eq__(self, other):
  148. if not isinstance(other, Join):
  149. return NotImplemented
  150. return self.identity == other.identity
  151. def __hash__(self):
  152. return hash(self.identity)
  153. def demote(self):
  154. new = self.relabeled_clone({})
  155. new.join_type = INNER
  156. return new
  157. def promote(self):
  158. new = self.relabeled_clone({})
  159. new.join_type = LOUTER
  160. return new
  161. class BaseTable:
  162. """
  163. The BaseTable class is used for base table references in FROM clause. For
  164. example, the SQL "foo" in
  165. SELECT * FROM "foo" WHERE somecond
  166. could be generated by this class.
  167. """
  168. join_type = None
  169. parent_alias = None
  170. filtered_relation = None
  171. def __init__(self, table_name, alias):
  172. self.table_name = table_name
  173. self.table_alias = alias
  174. def as_sql(self, compiler, connection):
  175. qn = compiler.quote_name
  176. alias_str = (
  177. ""
  178. if self.table_alias == self.table_name
  179. else (" %s" % qn(self.table_alias))
  180. )
  181. base_sql = qn(self.table_name)
  182. return base_sql + alias_str, []
  183. def relabeled_clone(self, change_map):
  184. return self.__class__(
  185. self.table_name, change_map.get(self.table_alias, self.table_alias)
  186. )
  187. @property
  188. def identity(self):
  189. return self.__class__, self.table_name, self.table_alias
  190. def __eq__(self, other):
  191. if not isinstance(other, BaseTable):
  192. return NotImplemented
  193. return self.identity == other.identity
  194. def __hash__(self):
  195. return hash(self.identity)