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.

datastructures.py 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. """
  2. Useful auxiliary data structures for query construction. Not useful outside
  3. the SQL domain.
  4. """
  5. # for backwards-compatibility in Django 1.11
  6. from django.core.exceptions import EmptyResultSet # NOQA: F401
  7. from django.db.models.sql.constants import INNER, LOUTER
  8. class MultiJoin(Exception):
  9. """
  10. Used by join construction code to indicate the point at which a
  11. multi-valued join was attempted (if the caller wants to treat that
  12. exceptionally).
  13. """
  14. def __init__(self, names_pos, path_with_names):
  15. self.level = names_pos
  16. # The path travelled, this includes the path to the multijoin.
  17. self.names_with_path = path_with_names
  18. class Empty:
  19. pass
  20. class Join:
  21. """
  22. Used by sql.Query and sql.SQLCompiler to generate JOIN clauses into the
  23. FROM entry. For example, the SQL generated could be
  24. LEFT OUTER JOIN "sometable" T1 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__(self, table_name, parent_alias, table_alias, join_type,
  37. join_field, nullable, filtered_relation=None):
  38. # Join table
  39. self.table_name = table_name
  40. self.parent_alias = parent_alias
  41. # Note: table_alias is not necessarily known at instantiation time.
  42. self.table_alias = table_alias
  43. # LOUTER or INNER
  44. self.join_type = join_type
  45. # A list of 2-tuples to use in the ON clause of the JOIN.
  46. # Each 2-tuple will create one join condition in the ON clause.
  47. self.join_cols = join_field.get_joining_columns()
  48. # Along which field (or ForeignObjectRel in the reverse join case)
  49. self.join_field = join_field
  50. # Is this join nullabled?
  51. self.nullable = nullable
  52. self.filtered_relation = filtered_relation
  53. def as_sql(self, compiler, connection):
  54. """
  55. Generate the full
  56. LEFT OUTER JOIN sometable ON sometable.somecol = othertable.othercol, params
  57. clause for this join.
  58. """
  59. join_conditions = []
  60. params = []
  61. qn = compiler.quote_name_unless_alias
  62. qn2 = connection.ops.quote_name
  63. # Add a join condition for each pair of joining columns.
  64. for lhs_col, rhs_col in self.join_cols:
  65. join_conditions.append('%s.%s = %s.%s' % (
  66. qn(self.parent_alias),
  67. qn2(lhs_col),
  68. qn(self.table_alias),
  69. qn2(rhs_col),
  70. ))
  71. # Add a single condition inside parentheses for whatever
  72. # get_extra_restriction() returns.
  73. extra_cond = self.join_field.get_extra_restriction(
  74. compiler.query.where_class, self.table_alias, self.parent_alias)
  75. if extra_cond:
  76. extra_sql, extra_params = compiler.compile(extra_cond)
  77. join_conditions.append('(%s)' % extra_sql)
  78. params.extend(extra_params)
  79. if self.filtered_relation:
  80. extra_sql, extra_params = compiler.compile(self.filtered_relation)
  81. if extra_sql:
  82. join_conditions.append('(%s)' % extra_sql)
  83. params.extend(extra_params)
  84. if not join_conditions:
  85. # This might be a rel on the other end of an actual declared field.
  86. declared_field = getattr(self.join_field, 'field', self.join_field)
  87. raise ValueError(
  88. "Join generated an empty ON clause. %s did not yield either "
  89. "joining columns or extra restrictions." % declared_field.__class__
  90. )
  91. on_clause_sql = ' AND '.join(join_conditions)
  92. alias_str = '' if self.table_alias == self.table_name else (' %s' % self.table_alias)
  93. sql = '%s %s%s ON (%s)' % (self.join_type, qn(self.table_name), alias_str, on_clause_sql)
  94. return sql, params
  95. def relabeled_clone(self, change_map):
  96. new_parent_alias = change_map.get(self.parent_alias, self.parent_alias)
  97. new_table_alias = change_map.get(self.table_alias, self.table_alias)
  98. if self.filtered_relation is not None:
  99. filtered_relation = self.filtered_relation.clone()
  100. filtered_relation.path = [change_map.get(p, p) for p in self.filtered_relation.path]
  101. else:
  102. filtered_relation = None
  103. return self.__class__(
  104. self.table_name, new_parent_alias, new_table_alias, self.join_type,
  105. self.join_field, self.nullable, filtered_relation=filtered_relation,
  106. )
  107. def equals(self, other, with_filtered_relation):
  108. return (
  109. isinstance(other, self.__class__) and
  110. self.table_name == other.table_name and
  111. self.parent_alias == other.parent_alias and
  112. self.join_field == other.join_field and
  113. (not with_filtered_relation or self.filtered_relation == other.filtered_relation)
  114. )
  115. def __eq__(self, other):
  116. return self.equals(other, with_filtered_relation=True)
  117. def demote(self):
  118. new = self.relabeled_clone({})
  119. new.join_type = INNER
  120. return new
  121. def promote(self):
  122. new = self.relabeled_clone({})
  123. new.join_type = LOUTER
  124. return new
  125. class BaseTable:
  126. """
  127. The BaseTable class is used for base table references in FROM clause. For
  128. example, the SQL "foo" in
  129. SELECT * FROM "foo" WHERE somecond
  130. could be generated by this class.
  131. """
  132. join_type = None
  133. parent_alias = None
  134. filtered_relation = None
  135. def __init__(self, table_name, alias):
  136. self.table_name = table_name
  137. self.table_alias = alias
  138. def as_sql(self, compiler, connection):
  139. alias_str = '' if self.table_alias == self.table_name else (' %s' % self.table_alias)
  140. base_sql = compiler.quote_name_unless_alias(self.table_name)
  141. return base_sql + alias_str, []
  142. def relabeled_clone(self, change_map):
  143. return self.__class__(self.table_name, change_map.get(self.table_alias, self.table_alias))
  144. def equals(self, other, with_filtered_relation):
  145. return (
  146. isinstance(self, other.__class__) and
  147. self.table_name == other.table_name and
  148. self.table_alias == other.table_alias
  149. )