deletion.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. from collections import OrderedDict
  2. from operator import attrgetter
  3. from django.db import connections, transaction, IntegrityError
  4. from django.db.models import signals, sql
  5. from django.utils import six
  6. class ProtectedError(IntegrityError):
  7. def __init__(self, msg, protected_objects):
  8. self.protected_objects = protected_objects
  9. super(ProtectedError, self).__init__(msg, protected_objects)
  10. def CASCADE(collector, field, sub_objs, using):
  11. collector.collect(sub_objs, source=field.rel.to,
  12. source_attr=field.name, nullable=field.null)
  13. if field.null and not connections[using].features.can_defer_constraint_checks:
  14. collector.add_field_update(field, None, sub_objs)
  15. def PROTECT(collector, field, sub_objs, using):
  16. raise ProtectedError("Cannot delete some instances of model '%s' because "
  17. "they are referenced through a protected foreign key: '%s.%s'" % (
  18. field.rel.to.__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. class Collector(object):
  38. def __init__(self, using):
  39. self.using = using
  40. # Initially, {model: set([instances])}, later values become lists.
  41. self.data = {}
  42. self.field_updates = {} # {model: {(field, value): set([instances])}}
  43. # fast_deletes is a list of queryset-likes that can be deleted without
  44. # fetching the objects into memory.
  45. self.fast_deletes = []
  46. # Tracks deletion-order dependency for databases without transactions
  47. # or ability to defer constraint checks. Only concrete model classes
  48. # should be included, as the dependencies exist only between actual
  49. # database tables; proxy models are represented here by their concrete
  50. # parent.
  51. self.dependencies = {} # {model: set([models])}
  52. def add(self, objs, source=None, nullable=False, reverse_dependency=False):
  53. """
  54. Adds 'objs' to the collection of objects to be deleted. If the call is
  55. the result of a cascade, 'source' should be the model that caused it,
  56. and 'nullable' should be set to True if the relation can be null.
  57. Returns a list of all objects that were not already collected.
  58. """
  59. if not objs:
  60. return []
  61. new_objs = []
  62. model = objs[0].__class__
  63. instances = self.data.setdefault(model, set())
  64. for obj in objs:
  65. if obj not in instances:
  66. new_objs.append(obj)
  67. instances.update(new_objs)
  68. # Nullable relationships can be ignored -- they are nulled out before
  69. # deleting, and therefore do not affect the order in which objects have
  70. # to be deleted.
  71. if source is not None and not nullable:
  72. if reverse_dependency:
  73. source, model = model, source
  74. self.dependencies.setdefault(
  75. source._meta.concrete_model, set()).add(model._meta.concrete_model)
  76. return new_objs
  77. def add_field_update(self, field, value, objs):
  78. """
  79. Schedules a field update. 'objs' must be a homogeneous iterable
  80. collection of model instances (e.g. a QuerySet).
  81. """
  82. if not objs:
  83. return
  84. model = objs[0].__class__
  85. self.field_updates.setdefault(
  86. model, {}).setdefault(
  87. (field, value), set()).update(objs)
  88. def can_fast_delete(self, objs, from_field=None):
  89. """
  90. Determines if the objects in the given queryset-like can be
  91. fast-deleted. This can be done if there are no cascades, no
  92. parents and no signal listeners for the object class.
  93. The 'from_field' tells where we are coming from - we need this to
  94. determine if the objects are in fact to be deleted. Allows also
  95. skipping parent -> child -> parent chain preventing fast delete of
  96. the child.
  97. """
  98. if from_field and from_field.rel.on_delete is not CASCADE:
  99. return False
  100. if not (hasattr(objs, 'model') and hasattr(objs, '_raw_delete')):
  101. return False
  102. model = objs.model
  103. if (signals.pre_delete.has_listeners(model)
  104. or signals.post_delete.has_listeners(model)
  105. or signals.m2m_changed.has_listeners(model)):
  106. return False
  107. # The use of from_field comes from the need to avoid cascade back to
  108. # parent when parent delete is cascading to child.
  109. opts = model._meta
  110. if any(link != from_field for link in opts.concrete_model._meta.parents.values()):
  111. return False
  112. # Foreign keys pointing to this model, both from m2m and other
  113. # models.
  114. for related in opts.get_all_related_objects(
  115. include_hidden=True, include_proxy_eq=True):
  116. if related.field.rel.on_delete is not DO_NOTHING:
  117. return False
  118. for field in model._meta.virtual_fields:
  119. if hasattr(field, 'bulk_related_objects'):
  120. # It's something like generic foreign key.
  121. return False
  122. return True
  123. def collect(self, objs, source=None, nullable=False, collect_related=True,
  124. source_attr=None, reverse_dependency=False):
  125. """
  126. Adds 'objs' to the collection of objects to be deleted as well as all
  127. parent instances. 'objs' must be a homogeneous iterable collection of
  128. model instances (e.g. a QuerySet). If 'collect_related' is True,
  129. related objects will be handled by their respective on_delete handler.
  130. If the call is the result of a cascade, 'source' should be the model
  131. that caused it and 'nullable' should be set to True, if the relation
  132. can be null.
  133. If 'reverse_dependency' is True, 'source' will be deleted before the
  134. current model, rather than after. (Needed for cascading to parent
  135. models, the one case in which the cascade follows the forwards
  136. direction of an FK rather than the reverse direction.)
  137. """
  138. if self.can_fast_delete(objs):
  139. self.fast_deletes.append(objs)
  140. return
  141. new_objs = self.add(objs, source, nullable,
  142. reverse_dependency=reverse_dependency)
  143. if not new_objs:
  144. return
  145. model = new_objs[0].__class__
  146. # Recursively collect concrete model's parent models, but not their
  147. # related objects. These will be found by meta.get_all_related_objects()
  148. concrete_model = model._meta.concrete_model
  149. for ptr in six.itervalues(concrete_model._meta.parents):
  150. if ptr:
  151. # FIXME: This seems to be buggy and execute a query for each
  152. # parent object fetch. We have the parent data in the obj,
  153. # but we don't have a nice way to turn that data into parent
  154. # object instance.
  155. parent_objs = [getattr(obj, ptr.name) for obj in new_objs]
  156. self.collect(parent_objs, source=model,
  157. source_attr=ptr.rel.related_name,
  158. collect_related=False,
  159. reverse_dependency=True)
  160. if collect_related:
  161. for related in model._meta.get_all_related_objects(
  162. include_hidden=True, include_proxy_eq=True):
  163. field = related.field
  164. if field.rel.on_delete == DO_NOTHING:
  165. continue
  166. sub_objs = self.related_objects(related, new_objs)
  167. if self.can_fast_delete(sub_objs, from_field=field):
  168. self.fast_deletes.append(sub_objs)
  169. elif sub_objs:
  170. field.rel.on_delete(self, field, sub_objs, self.using)
  171. for field in model._meta.virtual_fields:
  172. if hasattr(field, 'bulk_related_objects'):
  173. # Its something like generic foreign key.
  174. sub_objs = field.bulk_related_objects(new_objs, self.using)
  175. self.collect(sub_objs,
  176. source=model,
  177. source_attr=field.rel.related_name,
  178. nullable=True)
  179. def related_objects(self, related, objs):
  180. """
  181. Gets a QuerySet of objects related to ``objs`` via the relation ``related``.
  182. """
  183. return related.model._base_manager.using(self.using).filter(
  184. **{"%s__in" % related.field.name: objs}
  185. )
  186. def instances_with_model(self):
  187. for model, instances in six.iteritems(self.data):
  188. for obj in instances:
  189. yield model, obj
  190. def sort(self):
  191. sorted_models = []
  192. concrete_models = set()
  193. models = list(self.data)
  194. while len(sorted_models) < len(models):
  195. found = False
  196. for model in models:
  197. if model in sorted_models:
  198. continue
  199. dependencies = self.dependencies.get(model._meta.concrete_model)
  200. if not (dependencies and dependencies.difference(concrete_models)):
  201. sorted_models.append(model)
  202. concrete_models.add(model._meta.concrete_model)
  203. found = True
  204. if not found:
  205. return
  206. self.data = OrderedDict((model, self.data[model])
  207. for model in sorted_models)
  208. def delete(self):
  209. # sort instance collections
  210. for model, instances in self.data.items():
  211. self.data[model] = sorted(instances, key=attrgetter("pk"))
  212. # if possible, bring the models in an order suitable for databases that
  213. # don't support transactions or cannot defer constraint checks until the
  214. # end of a transaction.
  215. self.sort()
  216. with transaction.commit_on_success_unless_managed(using=self.using):
  217. # send pre_delete signals
  218. for model, obj in self.instances_with_model():
  219. if not model._meta.auto_created:
  220. signals.pre_delete.send(
  221. sender=model, instance=obj, using=self.using
  222. )
  223. # fast deletes
  224. for qs in self.fast_deletes:
  225. qs._raw_delete(using=self.using)
  226. # update fields
  227. for model, instances_for_fieldvalues in six.iteritems(self.field_updates):
  228. query = sql.UpdateQuery(model)
  229. for (field, value), instances in six.iteritems(instances_for_fieldvalues):
  230. query.update_batch([obj.pk for obj in instances],
  231. {field.name: value}, self.using)
  232. # reverse instance collections
  233. for instances in six.itervalues(self.data):
  234. instances.reverse()
  235. # delete instances
  236. for model, instances in six.iteritems(self.data):
  237. query = sql.DeleteQuery(model)
  238. pk_list = [obj.pk for obj in instances]
  239. query.delete_batch(pk_list, self.using)
  240. if not model._meta.auto_created:
  241. for obj in instances:
  242. signals.post_delete.send(
  243. sender=model, instance=obj, using=self.using
  244. )
  245. # update collected instances
  246. for model, instances_for_fieldvalues in six.iteritems(self.field_updates):
  247. for (field, value), instances in six.iteritems(instances_for_fieldvalues):
  248. for obj in instances:
  249. setattr(obj, field.attname, value)
  250. for model, instances in six.iteritems(self.data):
  251. for instance in instances:
  252. setattr(instance, model._meta.pk.attname, None)