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.

subqueries.py 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. """
  2. Query subclasses which provide extra functionality beyond simple data retrieval.
  3. """
  4. from django.core.exceptions import FieldError
  5. from django.db import connections
  6. from django.db.models.query_utils import Q
  7. from django.db.models.sql.constants import (
  8. CURSOR, GET_ITERATOR_CHUNK_SIZE, NO_RESULTS,
  9. )
  10. from django.db.models.sql.query import Query
  11. __all__ = ['DeleteQuery', 'UpdateQuery', 'InsertQuery', 'AggregateQuery']
  12. class DeleteQuery(Query):
  13. """A DELETE SQL query."""
  14. compiler = 'SQLDeleteCompiler'
  15. def do_query(self, table, where, using):
  16. self.alias_map = {table: self.alias_map[table]}
  17. self.where = where
  18. cursor = self.get_compiler(using).execute_sql(CURSOR)
  19. return cursor.rowcount if cursor else 0
  20. def delete_batch(self, pk_list, using):
  21. """
  22. Set up and execute delete queries for all the objects in pk_list.
  23. More than one physical query may be executed if there are a
  24. lot of values in pk_list.
  25. """
  26. # number of objects deleted
  27. num_deleted = 0
  28. field = self.get_meta().pk
  29. for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
  30. self.where = self.where_class()
  31. self.add_q(Q(
  32. **{field.attname + '__in': pk_list[offset:offset + GET_ITERATOR_CHUNK_SIZE]}))
  33. num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using)
  34. return num_deleted
  35. def delete_qs(self, query, using):
  36. """
  37. Delete the queryset in one SQL query (if possible). For simple queries
  38. this is done by copying the query.query.where to self.query, for
  39. complex queries by using subquery.
  40. """
  41. innerq = query.query
  42. # Make sure the inner query has at least one table in use.
  43. innerq.get_initial_alias()
  44. # The same for our new query.
  45. self.get_initial_alias()
  46. innerq_used_tables = tuple([t for t in innerq.alias_map if innerq.alias_refcount[t]])
  47. if not innerq_used_tables or innerq_used_tables == tuple(self.alias_map):
  48. # There is only the base table in use in the query.
  49. self.where = innerq.where
  50. else:
  51. pk = query.model._meta.pk
  52. if not connections[using].features.update_can_self_select:
  53. # We can't do the delete using subquery.
  54. values = list(query.values_list('pk', flat=True))
  55. if not values:
  56. return 0
  57. return self.delete_batch(values, using)
  58. else:
  59. innerq.clear_select_clause()
  60. innerq.select = [
  61. pk.get_col(self.get_initial_alias())
  62. ]
  63. values = innerq
  64. self.where = self.where_class()
  65. self.add_q(Q(pk__in=values))
  66. cursor = self.get_compiler(using).execute_sql(CURSOR)
  67. return cursor.rowcount if cursor else 0
  68. class UpdateQuery(Query):
  69. """An UPDATE SQL query."""
  70. compiler = 'SQLUpdateCompiler'
  71. def __init__(self, *args, **kwargs):
  72. super().__init__(*args, **kwargs)
  73. self._setup_query()
  74. def _setup_query(self):
  75. """
  76. Run on initialization and at the end of chaining. Any attributes that
  77. would normally be set in __init__() should go here instead.
  78. """
  79. self.values = []
  80. self.related_ids = None
  81. self.related_updates = {}
  82. def clone(self):
  83. obj = super().clone()
  84. obj.related_updates = self.related_updates.copy()
  85. return obj
  86. def update_batch(self, pk_list, values, using):
  87. self.add_update_values(values)
  88. for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
  89. self.where = self.where_class()
  90. self.add_q(Q(pk__in=pk_list[offset: offset + GET_ITERATOR_CHUNK_SIZE]))
  91. self.get_compiler(using).execute_sql(NO_RESULTS)
  92. def add_update_values(self, values):
  93. """
  94. Convert a dictionary of field name to value mappings into an update
  95. query. This is the entry point for the public update() method on
  96. querysets.
  97. """
  98. values_seq = []
  99. for name, val in values.items():
  100. field = self.get_meta().get_field(name)
  101. direct = not (field.auto_created and not field.concrete) or not field.concrete
  102. model = field.model._meta.concrete_model
  103. if not direct or (field.is_relation and field.many_to_many):
  104. raise FieldError(
  105. 'Cannot update model field %r (only non-relations and '
  106. 'foreign keys permitted).' % field
  107. )
  108. if model is not self.get_meta().concrete_model:
  109. self.add_related_update(model, field, val)
  110. continue
  111. values_seq.append((field, model, val))
  112. return self.add_update_fields(values_seq)
  113. def add_update_fields(self, values_seq):
  114. """
  115. Append a sequence of (field, model, value) triples to the internal list
  116. that will be used to generate the UPDATE query. Might be more usefully
  117. called add_update_targets() to hint at the extra information here.
  118. """
  119. for field, model, val in values_seq:
  120. if hasattr(val, 'resolve_expression'):
  121. # Resolve expressions here so that annotations are no longer needed
  122. val = val.resolve_expression(self, allow_joins=False, for_save=True)
  123. self.values.append((field, model, val))
  124. def add_related_update(self, model, field, value):
  125. """
  126. Add (name, value) to an update query for an ancestor model.
  127. Update are coalesced so that only one update query per ancestor is run.
  128. """
  129. self.related_updates.setdefault(model, []).append((field, None, value))
  130. def get_related_updates(self):
  131. """
  132. Return a list of query objects: one for each update required to an
  133. ancestor model. Each query will have the same filtering conditions as
  134. the current query but will only update a single table.
  135. """
  136. if not self.related_updates:
  137. return []
  138. result = []
  139. for model, values in self.related_updates.items():
  140. query = UpdateQuery(model)
  141. query.values = values
  142. if self.related_ids is not None:
  143. query.add_filter(('pk__in', self.related_ids))
  144. result.append(query)
  145. return result
  146. class InsertQuery(Query):
  147. compiler = 'SQLInsertCompiler'
  148. def __init__(self, *args, ignore_conflicts=False, **kwargs):
  149. super().__init__(*args, **kwargs)
  150. self.fields = []
  151. self.objs = []
  152. self.ignore_conflicts = ignore_conflicts
  153. def insert_values(self, fields, objs, raw=False):
  154. self.fields = fields
  155. self.objs = objs
  156. self.raw = raw
  157. class AggregateQuery(Query):
  158. """
  159. Take another query as a parameter to the FROM clause and only select the
  160. elements in the provided list.
  161. """
  162. compiler = 'SQLAggregateCompiler'
  163. def add_subquery(self, query, using):
  164. query.subquery = True
  165. self.subquery, self.sub_params = query.get_compiler(using).as_sql(with_col_aliases=True)