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.

deletion.py 14KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. from collections import Counter, OrderedDict
  2. from operator import attrgetter
  3. from django.db import IntegrityError, connections, transaction
  4. from django.db.models import signals, sql
  5. class ProtectedError(IntegrityError):
  6. def __init__(self, msg, protected_objects):
  7. self.protected_objects = protected_objects
  8. super().__init__(msg, protected_objects)
  9. def CASCADE(collector, field, sub_objs, using):
  10. collector.collect(sub_objs, source=field.remote_field.model,
  11. source_attr=field.name, nullable=field.null)
  12. if field.null and not connections[using].features.can_defer_constraint_checks:
  13. collector.add_field_update(field, None, sub_objs)
  14. def PROTECT(collector, field, sub_objs, using):
  15. raise ProtectedError(
  16. "Cannot delete some instances of model '%s' because they are "
  17. "referenced through a protected foreign key: '%s.%s'" % (
  18. field.remote_field.model.__name__, sub_objs[0].__class__.__name__, field.name
  19. ),
  20. sub_objs
  21. )
  22. def SET(value):
  23. if callable(value):
  24. def set_on_delete(collector, field, sub_objs, using):
  25. collector.add_field_update(field, value(), sub_objs)
  26. else:
  27. def set_on_delete(collector, field, sub_objs, using):
  28. collector.add_field_update(field, value, sub_objs)
  29. set_on_delete.deconstruct = lambda: ('django.db.models.SET', (value,), {})
  30. return set_on_delete
  31. def SET_NULL(collector, field, sub_objs, using):
  32. collector.add_field_update(field, None, sub_objs)
  33. def SET_DEFAULT(collector, field, sub_objs, using):
  34. collector.add_field_update(field, field.get_default(), sub_objs)
  35. def DO_NOTHING(collector, field, sub_objs, using):
  36. pass
  37. def get_candidate_relations_to_delete(opts):
  38. # The candidate relations are the ones that come from N-1 and 1-1 relations.
  39. # N-N (i.e., many-to-many) relations aren't candidates for deletion.
  40. return (
  41. f for f in opts.get_fields(include_hidden=True)
  42. if f.auto_created and not f.concrete and (f.one_to_one or f.one_to_many)
  43. )
  44. class Collector:
  45. def __init__(self, using):
  46. self.using = using
  47. # Initially, {model: {instances}}, later values become lists.
  48. self.data = OrderedDict()
  49. self.field_updates = {} # {model: {(field, value): {instances}}}
  50. # fast_deletes is a list of queryset-likes that can be deleted without
  51. # fetching the objects into memory.
  52. self.fast_deletes = []
  53. # Tracks deletion-order dependency for databases without transactions
  54. # or ability to defer constraint checks. Only concrete model classes
  55. # should be included, as the dependencies exist only between actual
  56. # database tables; proxy models are represented here by their concrete
  57. # parent.
  58. self.dependencies = {} # {model: {models}}
  59. def add(self, objs, source=None, nullable=False, reverse_dependency=False):
  60. """
  61. Add 'objs' to the collection of objects to be deleted. If the call is
  62. the result of a cascade, 'source' should be the model that caused it,
  63. and 'nullable' should be set to True if the relation can be null.
  64. Return a list of all objects that were not already collected.
  65. """
  66. if not objs:
  67. return []
  68. new_objs = []
  69. model = objs[0].__class__
  70. instances = self.data.setdefault(model, set())
  71. for obj in objs:
  72. if obj not in instances:
  73. new_objs.append(obj)
  74. instances.update(new_objs)
  75. # Nullable relationships can be ignored -- they are nulled out before
  76. # deleting, and therefore do not affect the order in which objects have
  77. # to be deleted.
  78. if source is not None and not nullable:
  79. if reverse_dependency:
  80. source, model = model, source
  81. self.dependencies.setdefault(
  82. source._meta.concrete_model, set()).add(model._meta.concrete_model)
  83. return new_objs
  84. def add_field_update(self, field, value, objs):
  85. """
  86. Schedule a field update. 'objs' must be a homogeneous iterable
  87. collection of model instances (e.g. a QuerySet).
  88. """
  89. if not objs:
  90. return
  91. model = objs[0].__class__
  92. self.field_updates.setdefault(
  93. model, {}).setdefault(
  94. (field, value), set()).update(objs)
  95. def can_fast_delete(self, objs, from_field=None):
  96. """
  97. Determine if the objects in the given queryset-like or single object
  98. can be fast-deleted. This can be done if there are no cascades, no
  99. parents and no signal listeners for the object class.
  100. The 'from_field' tells where we are coming from - we need this to
  101. determine if the objects are in fact to be deleted. Allow also
  102. skipping parent -> child -> parent chain preventing fast delete of
  103. the child.
  104. """
  105. if from_field and from_field.remote_field.on_delete is not CASCADE:
  106. return False
  107. if hasattr(objs, '_meta'):
  108. model = type(objs)
  109. elif hasattr(objs, 'model') and hasattr(objs, '_raw_delete'):
  110. model = objs.model
  111. else:
  112. return False
  113. if (signals.pre_delete.has_listeners(model) or
  114. signals.post_delete.has_listeners(model) or
  115. signals.m2m_changed.has_listeners(model)):
  116. return False
  117. # The use of from_field comes from the need to avoid cascade back to
  118. # parent when parent delete is cascading to child.
  119. opts = model._meta
  120. return (
  121. all(link == from_field for link in opts.concrete_model._meta.parents.values()) and
  122. # Foreign keys pointing to this model.
  123. all(
  124. related.field.remote_field.on_delete is DO_NOTHING
  125. for related in get_candidate_relations_to_delete(opts)
  126. ) and (
  127. # Something like generic foreign key.
  128. not any(hasattr(field, 'bulk_related_objects') for field in opts.private_fields)
  129. )
  130. )
  131. def get_del_batches(self, objs, field):
  132. """
  133. Return the objs in suitably sized batches for the used connection.
  134. """
  135. conn_batch_size = max(
  136. connections[self.using].ops.bulk_batch_size([field.name], objs), 1)
  137. if len(objs) > conn_batch_size:
  138. return [objs[i:i + conn_batch_size]
  139. for i in range(0, len(objs), conn_batch_size)]
  140. else:
  141. return [objs]
  142. def collect(self, objs, source=None, nullable=False, collect_related=True,
  143. source_attr=None, reverse_dependency=False, keep_parents=False):
  144. """
  145. Add 'objs' to the collection of objects to be deleted as well as all
  146. parent instances. 'objs' must be a homogeneous iterable collection of
  147. model instances (e.g. a QuerySet). If 'collect_related' is True,
  148. related objects will be handled by their respective on_delete handler.
  149. If the call is the result of a cascade, 'source' should be the model
  150. that caused it and 'nullable' should be set to True, if the relation
  151. can be null.
  152. If 'reverse_dependency' is True, 'source' will be deleted before the
  153. current model, rather than after. (Needed for cascading to parent
  154. models, the one case in which the cascade follows the forwards
  155. direction of an FK rather than the reverse direction.)
  156. If 'keep_parents' is True, data of parent model's will be not deleted.
  157. """
  158. if self.can_fast_delete(objs):
  159. self.fast_deletes.append(objs)
  160. return
  161. new_objs = self.add(objs, source, nullable,
  162. reverse_dependency=reverse_dependency)
  163. if not new_objs:
  164. return
  165. model = new_objs[0].__class__
  166. if not keep_parents:
  167. # Recursively collect concrete model's parent models, but not their
  168. # related objects. These will be found by meta.get_fields()
  169. concrete_model = model._meta.concrete_model
  170. for ptr in concrete_model._meta.parents.values():
  171. if ptr:
  172. parent_objs = [getattr(obj, ptr.name) for obj in new_objs]
  173. self.collect(parent_objs, source=model,
  174. source_attr=ptr.remote_field.related_name,
  175. collect_related=False,
  176. reverse_dependency=True)
  177. if collect_related:
  178. parents = model._meta.parents
  179. for related in get_candidate_relations_to_delete(model._meta):
  180. # Preserve parent reverse relationships if keep_parents=True.
  181. if keep_parents and related.model in parents:
  182. continue
  183. field = related.field
  184. if field.remote_field.on_delete == DO_NOTHING:
  185. continue
  186. batches = self.get_del_batches(new_objs, field)
  187. for batch in batches:
  188. sub_objs = self.related_objects(related, batch)
  189. if self.can_fast_delete(sub_objs, from_field=field):
  190. self.fast_deletes.append(sub_objs)
  191. elif sub_objs:
  192. field.remote_field.on_delete(self, field, sub_objs, self.using)
  193. for field in model._meta.private_fields:
  194. if hasattr(field, 'bulk_related_objects'):
  195. # It's something like generic foreign key.
  196. sub_objs = field.bulk_related_objects(new_objs, self.using)
  197. self.collect(sub_objs, source=model, nullable=True)
  198. def related_objects(self, related, objs):
  199. """
  200. Get a QuerySet of objects related to `objs` via the relation `related`.
  201. """
  202. return related.related_model._base_manager.using(self.using).filter(
  203. **{"%s__in" % related.field.name: objs}
  204. )
  205. def instances_with_model(self):
  206. for model, instances in self.data.items():
  207. for obj in instances:
  208. yield model, obj
  209. def sort(self):
  210. sorted_models = []
  211. concrete_models = set()
  212. models = list(self.data)
  213. while len(sorted_models) < len(models):
  214. found = False
  215. for model in models:
  216. if model in sorted_models:
  217. continue
  218. dependencies = self.dependencies.get(model._meta.concrete_model)
  219. if not (dependencies and dependencies.difference(concrete_models)):
  220. sorted_models.append(model)
  221. concrete_models.add(model._meta.concrete_model)
  222. found = True
  223. if not found:
  224. return
  225. self.data = OrderedDict((model, self.data[model])
  226. for model in sorted_models)
  227. def delete(self):
  228. # sort instance collections
  229. for model, instances in self.data.items():
  230. self.data[model] = sorted(instances, key=attrgetter("pk"))
  231. # if possible, bring the models in an order suitable for databases that
  232. # don't support transactions or cannot defer constraint checks until the
  233. # end of a transaction.
  234. self.sort()
  235. # number of objects deleted for each model label
  236. deleted_counter = Counter()
  237. # Optimize for the case with a single obj and no dependencies
  238. if len(self.data) == 1 and len(instances) == 1:
  239. instance = list(instances)[0]
  240. if self.can_fast_delete(instance):
  241. with transaction.mark_for_rollback_on_error():
  242. count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)
  243. setattr(instance, model._meta.pk.attname, None)
  244. return count, {model._meta.label: count}
  245. with transaction.atomic(using=self.using, savepoint=False):
  246. # send pre_delete signals
  247. for model, obj in self.instances_with_model():
  248. if not model._meta.auto_created:
  249. signals.pre_delete.send(
  250. sender=model, instance=obj, using=self.using
  251. )
  252. # fast deletes
  253. for qs in self.fast_deletes:
  254. count = qs._raw_delete(using=self.using)
  255. deleted_counter[qs.model._meta.label] += count
  256. # update fields
  257. for model, instances_for_fieldvalues in self.field_updates.items():
  258. for (field, value), instances in instances_for_fieldvalues.items():
  259. query = sql.UpdateQuery(model)
  260. query.update_batch([obj.pk for obj in instances],
  261. {field.name: value}, self.using)
  262. # reverse instance collections
  263. for instances in self.data.values():
  264. instances.reverse()
  265. # delete instances
  266. for model, instances in self.data.items():
  267. query = sql.DeleteQuery(model)
  268. pk_list = [obj.pk for obj in instances]
  269. count = query.delete_batch(pk_list, self.using)
  270. deleted_counter[model._meta.label] += count
  271. if not model._meta.auto_created:
  272. for obj in instances:
  273. signals.post_delete.send(
  274. sender=model, instance=obj, using=self.using
  275. )
  276. # update collected instances
  277. for instances_for_fieldvalues in self.field_updates.values():
  278. for (field, value), instances in instances_for_fieldvalues.items():
  279. for obj in instances:
  280. setattr(obj, field.attname, value)
  281. for model, instances in self.data.items():
  282. for instance in instances:
  283. setattr(instance, model._meta.pk.attname, None)
  284. return sum(deleted_counter.values()), dict(deleted_counter)