deletion.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. import operator
  2. from collections import Counter, defaultdict
  3. from functools import partial, reduce
  4. from itertools import chain
  5. from operator import attrgetter
  6. from django.db import IntegrityError, connections, transaction
  7. from django.db.models import query_utils, signals, sql
  8. class ProtectedError(IntegrityError):
  9. def __init__(self, msg, protected_objects):
  10. self.protected_objects = protected_objects
  11. super().__init__(msg, protected_objects)
  12. class RestrictedError(IntegrityError):
  13. def __init__(self, msg, restricted_objects):
  14. self.restricted_objects = restricted_objects
  15. super().__init__(msg, restricted_objects)
  16. def CASCADE(collector, field, sub_objs, using):
  17. collector.collect(
  18. sub_objs, source=field.remote_field.model, source_attr=field.name,
  19. nullable=field.null, fail_on_restricted=False,
  20. )
  21. if field.null and not connections[using].features.can_defer_constraint_checks:
  22. collector.add_field_update(field, None, sub_objs)
  23. def PROTECT(collector, field, sub_objs, using):
  24. raise ProtectedError(
  25. "Cannot delete some instances of model '%s' because they are "
  26. "referenced through a protected foreign key: '%s.%s'" % (
  27. field.remote_field.model.__name__, sub_objs[0].__class__.__name__, field.name
  28. ),
  29. sub_objs
  30. )
  31. def RESTRICT(collector, field, sub_objs, using):
  32. collector.add_restricted_objects(field, sub_objs)
  33. collector.add_dependency(field.remote_field.model, field.model)
  34. def SET(value):
  35. if callable(value):
  36. def set_on_delete(collector, field, sub_objs, using):
  37. collector.add_field_update(field, value(), sub_objs)
  38. else:
  39. def set_on_delete(collector, field, sub_objs, using):
  40. collector.add_field_update(field, value, sub_objs)
  41. set_on_delete.deconstruct = lambda: ('django.db.models.SET', (value,), {})
  42. return set_on_delete
  43. def SET_NULL(collector, field, sub_objs, using):
  44. collector.add_field_update(field, None, sub_objs)
  45. def SET_DEFAULT(collector, field, sub_objs, using):
  46. collector.add_field_update(field, field.get_default(), sub_objs)
  47. def DO_NOTHING(collector, field, sub_objs, using):
  48. pass
  49. def get_candidate_relations_to_delete(opts):
  50. # The candidate relations are the ones that come from N-1 and 1-1 relations.
  51. # N-N (i.e., many-to-many) relations aren't candidates for deletion.
  52. return (
  53. f for f in opts.get_fields(include_hidden=True)
  54. if f.auto_created and not f.concrete and (f.one_to_one or f.one_to_many)
  55. )
  56. class Collector:
  57. def __init__(self, using):
  58. self.using = using
  59. # Initially, {model: {instances}}, later values become lists.
  60. self.data = defaultdict(set)
  61. # {model: {(field, value): {instances}}}
  62. self.field_updates = defaultdict(partial(defaultdict, set))
  63. # {model: {field: {instances}}}
  64. self.restricted_objects = defaultdict(partial(defaultdict, set))
  65. # fast_deletes is a list of queryset-likes that can be deleted without
  66. # fetching the objects into memory.
  67. self.fast_deletes = []
  68. # Tracks deletion-order dependency for databases without transactions
  69. # or ability to defer constraint checks. Only concrete model classes
  70. # should be included, as the dependencies exist only between actual
  71. # database tables; proxy models are represented here by their concrete
  72. # parent.
  73. self.dependencies = defaultdict(set) # {model: {models}}
  74. def add(self, objs, source=None, nullable=False, reverse_dependency=False):
  75. """
  76. Add 'objs' to the collection of objects to be deleted. If the call is
  77. the result of a cascade, 'source' should be the model that caused it,
  78. and 'nullable' should be set to True if the relation can be null.
  79. Return a list of all objects that were not already collected.
  80. """
  81. if not objs:
  82. return []
  83. new_objs = []
  84. model = objs[0].__class__
  85. instances = self.data[model]
  86. for obj in objs:
  87. if obj not in instances:
  88. new_objs.append(obj)
  89. instances.update(new_objs)
  90. # Nullable relationships can be ignored -- they are nulled out before
  91. # deleting, and therefore do not affect the order in which objects have
  92. # to be deleted.
  93. if source is not None and not nullable:
  94. self.add_dependency(source, model, reverse_dependency=reverse_dependency)
  95. return new_objs
  96. def add_dependency(self, model, dependency, reverse_dependency=False):
  97. if reverse_dependency:
  98. model, dependency = dependency, model
  99. self.dependencies[model._meta.concrete_model].add(dependency._meta.concrete_model)
  100. self.data.setdefault(dependency, self.data.default_factory())
  101. def add_field_update(self, field, value, objs):
  102. """
  103. Schedule a field update. 'objs' must be a homogeneous iterable
  104. collection of model instances (e.g. a QuerySet).
  105. """
  106. if not objs:
  107. return
  108. model = objs[0].__class__
  109. self.field_updates[model][field, value].update(objs)
  110. def add_restricted_objects(self, field, objs):
  111. if objs:
  112. model = objs[0].__class__
  113. self.restricted_objects[model][field].update(objs)
  114. def clear_restricted_objects_from_set(self, model, objs):
  115. if model in self.restricted_objects:
  116. self.restricted_objects[model] = {
  117. field: items - objs
  118. for field, items in self.restricted_objects[model].items()
  119. }
  120. def clear_restricted_objects_from_queryset(self, model, qs):
  121. if model in self.restricted_objects:
  122. objs = set(qs.filter(pk__in=[
  123. obj.pk
  124. for objs in self.restricted_objects[model].values() for obj in objs
  125. ]))
  126. self.clear_restricted_objects_from_set(model, objs)
  127. def _has_signal_listeners(self, model):
  128. return (
  129. signals.pre_delete.has_listeners(model) or
  130. signals.post_delete.has_listeners(model)
  131. )
  132. def can_fast_delete(self, objs, from_field=None):
  133. """
  134. Determine if the objects in the given queryset-like or single object
  135. can be fast-deleted. This can be done if there are no cascades, no
  136. parents and no signal listeners for the object class.
  137. The 'from_field' tells where we are coming from - we need this to
  138. determine if the objects are in fact to be deleted. Allow also
  139. skipping parent -> child -> parent chain preventing fast delete of
  140. the child.
  141. """
  142. if from_field and from_field.remote_field.on_delete is not CASCADE:
  143. return False
  144. if hasattr(objs, '_meta'):
  145. model = objs._meta.model
  146. elif hasattr(objs, 'model') and hasattr(objs, '_raw_delete'):
  147. model = objs.model
  148. else:
  149. return False
  150. if self._has_signal_listeners(model):
  151. return False
  152. # The use of from_field comes from the need to avoid cascade back to
  153. # parent when parent delete is cascading to child.
  154. opts = model._meta
  155. return (
  156. all(link == from_field for link in opts.concrete_model._meta.parents.values()) and
  157. # Foreign keys pointing to this model.
  158. all(
  159. related.field.remote_field.on_delete is DO_NOTHING
  160. for related in get_candidate_relations_to_delete(opts)
  161. ) and (
  162. # Something like generic foreign key.
  163. not any(hasattr(field, 'bulk_related_objects') for field in opts.private_fields)
  164. )
  165. )
  166. def get_del_batches(self, objs, fields):
  167. """
  168. Return the objs in suitably sized batches for the used connection.
  169. """
  170. field_names = [field.name for field in fields]
  171. conn_batch_size = max(
  172. connections[self.using].ops.bulk_batch_size(field_names, objs), 1)
  173. if len(objs) > conn_batch_size:
  174. return [objs[i:i + conn_batch_size]
  175. for i in range(0, len(objs), conn_batch_size)]
  176. else:
  177. return [objs]
  178. def collect(self, objs, source=None, nullable=False, collect_related=True,
  179. source_attr=None, reverse_dependency=False, keep_parents=False,
  180. fail_on_restricted=True):
  181. """
  182. Add 'objs' to the collection of objects to be deleted as well as all
  183. parent instances. 'objs' must be a homogeneous iterable collection of
  184. model instances (e.g. a QuerySet). If 'collect_related' is True,
  185. related objects will be handled by their respective on_delete handler.
  186. If the call is the result of a cascade, 'source' should be the model
  187. that caused it and 'nullable' should be set to True, if the relation
  188. can be null.
  189. If 'reverse_dependency' is True, 'source' will be deleted before the
  190. current model, rather than after. (Needed for cascading to parent
  191. models, the one case in which the cascade follows the forwards
  192. direction of an FK rather than the reverse direction.)
  193. If 'keep_parents' is True, data of parent model's will be not deleted.
  194. If 'fail_on_restricted' is False, error won't be raised even if it's
  195. prohibited to delete such objects due to RESTRICT, that defers
  196. restricted object checking in recursive calls where the top-level call
  197. may need to collect more objects to determine whether restricted ones
  198. can be deleted.
  199. """
  200. if self.can_fast_delete(objs):
  201. self.fast_deletes.append(objs)
  202. return
  203. new_objs = self.add(objs, source, nullable,
  204. reverse_dependency=reverse_dependency)
  205. if not new_objs:
  206. return
  207. model = new_objs[0].__class__
  208. if not keep_parents:
  209. # Recursively collect concrete model's parent models, but not their
  210. # related objects. These will be found by meta.get_fields()
  211. concrete_model = model._meta.concrete_model
  212. for ptr in concrete_model._meta.parents.values():
  213. if ptr:
  214. parent_objs = [getattr(obj, ptr.name) for obj in new_objs]
  215. self.collect(parent_objs, source=model,
  216. source_attr=ptr.remote_field.related_name,
  217. collect_related=False,
  218. reverse_dependency=True,
  219. fail_on_restricted=False)
  220. if not collect_related:
  221. return
  222. if keep_parents:
  223. parents = set(model._meta.get_parent_list())
  224. model_fast_deletes = defaultdict(list)
  225. protected_objects = defaultdict(list)
  226. for related in get_candidate_relations_to_delete(model._meta):
  227. # Preserve parent reverse relationships if keep_parents=True.
  228. if keep_parents and related.model in parents:
  229. continue
  230. field = related.field
  231. if field.remote_field.on_delete == DO_NOTHING:
  232. continue
  233. related_model = related.related_model
  234. if self.can_fast_delete(related_model, from_field=field):
  235. model_fast_deletes[related_model].append(field)
  236. continue
  237. batches = self.get_del_batches(new_objs, [field])
  238. for batch in batches:
  239. sub_objs = self.related_objects(related_model, [field], batch)
  240. # Non-referenced fields can be deferred if no signal receivers
  241. # are connected for the related model as they'll never be
  242. # exposed to the user. Skip field deferring when some
  243. # relationships are select_related as interactions between both
  244. # features are hard to get right. This should only happen in
  245. # the rare cases where .related_objects is overridden anyway.
  246. if not (sub_objs.query.select_related or self._has_signal_listeners(related_model)):
  247. referenced_fields = set(chain.from_iterable(
  248. (rf.attname for rf in rel.field.foreign_related_fields)
  249. for rel in get_candidate_relations_to_delete(related_model._meta)
  250. ))
  251. sub_objs = sub_objs.only(*tuple(referenced_fields))
  252. if sub_objs:
  253. try:
  254. field.remote_field.on_delete(self, field, sub_objs, self.using)
  255. except ProtectedError as error:
  256. key = "'%s.%s'" % (field.model.__name__, field.name)
  257. protected_objects[key] += error.protected_objects
  258. if protected_objects:
  259. raise ProtectedError(
  260. 'Cannot delete some instances of model %r because they are '
  261. 'referenced through protected foreign keys: %s.' % (
  262. model.__name__,
  263. ', '.join(protected_objects),
  264. ),
  265. set(chain.from_iterable(protected_objects.values())),
  266. )
  267. for related_model, related_fields in model_fast_deletes.items():
  268. batches = self.get_del_batches(new_objs, related_fields)
  269. for batch in batches:
  270. sub_objs = self.related_objects(related_model, related_fields, batch)
  271. self.fast_deletes.append(sub_objs)
  272. for field in model._meta.private_fields:
  273. if hasattr(field, 'bulk_related_objects'):
  274. # It's something like generic foreign key.
  275. sub_objs = field.bulk_related_objects(new_objs, self.using)
  276. self.collect(sub_objs, source=model, nullable=True, fail_on_restricted=False)
  277. if fail_on_restricted:
  278. # Raise an error if collected restricted objects (RESTRICT) aren't
  279. # candidates for deletion also collected via CASCADE.
  280. for related_model, instances in self.data.items():
  281. self.clear_restricted_objects_from_set(related_model, instances)
  282. for qs in self.fast_deletes:
  283. self.clear_restricted_objects_from_queryset(qs.model, qs)
  284. if self.restricted_objects.values():
  285. restricted_objects = defaultdict(list)
  286. for related_model, fields in self.restricted_objects.items():
  287. for field, objs in fields.items():
  288. if objs:
  289. key = "'%s.%s'" % (related_model.__name__, field.name)
  290. restricted_objects[key] += objs
  291. if restricted_objects:
  292. raise RestrictedError(
  293. 'Cannot delete some instances of model %r because '
  294. 'they are referenced through restricted foreign keys: '
  295. '%s.' % (
  296. model.__name__,
  297. ', '.join(restricted_objects),
  298. ),
  299. set(chain.from_iterable(restricted_objects.values())),
  300. )
  301. def related_objects(self, related_model, related_fields, objs):
  302. """
  303. Get a QuerySet of the related model to objs via related fields.
  304. """
  305. predicate = reduce(operator.or_, (
  306. query_utils.Q(**{'%s__in' % related_field.name: objs})
  307. for related_field in related_fields
  308. ))
  309. return related_model._base_manager.using(self.using).filter(predicate)
  310. def instances_with_model(self):
  311. for model, instances in self.data.items():
  312. for obj in instances:
  313. yield model, obj
  314. def sort(self):
  315. sorted_models = []
  316. concrete_models = set()
  317. models = list(self.data)
  318. while len(sorted_models) < len(models):
  319. found = False
  320. for model in models:
  321. if model in sorted_models:
  322. continue
  323. dependencies = self.dependencies.get(model._meta.concrete_model)
  324. if not (dependencies and dependencies.difference(concrete_models)):
  325. sorted_models.append(model)
  326. concrete_models.add(model._meta.concrete_model)
  327. found = True
  328. if not found:
  329. return
  330. self.data = {model: self.data[model] for model in sorted_models}
  331. def delete(self):
  332. # sort instance collections
  333. for model, instances in self.data.items():
  334. self.data[model] = sorted(instances, key=attrgetter("pk"))
  335. # if possible, bring the models in an order suitable for databases that
  336. # don't support transactions or cannot defer constraint checks until the
  337. # end of a transaction.
  338. self.sort()
  339. # number of objects deleted for each model label
  340. deleted_counter = Counter()
  341. # Optimize for the case with a single obj and no dependencies
  342. if len(self.data) == 1 and len(instances) == 1:
  343. instance = list(instances)[0]
  344. if self.can_fast_delete(instance):
  345. with transaction.mark_for_rollback_on_error(self.using):
  346. count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)
  347. setattr(instance, model._meta.pk.attname, None)
  348. return count, {model._meta.label: count}
  349. with transaction.atomic(using=self.using, savepoint=False):
  350. # send pre_delete signals
  351. for model, obj in self.instances_with_model():
  352. if not model._meta.auto_created:
  353. signals.pre_delete.send(
  354. sender=model, instance=obj, using=self.using
  355. )
  356. # fast deletes
  357. for qs in self.fast_deletes:
  358. count = qs._raw_delete(using=self.using)
  359. if count:
  360. deleted_counter[qs.model._meta.label] += count
  361. # update fields
  362. for model, instances_for_fieldvalues in self.field_updates.items():
  363. for (field, value), instances in instances_for_fieldvalues.items():
  364. query = sql.UpdateQuery(model)
  365. query.update_batch([obj.pk for obj in instances],
  366. {field.name: value}, self.using)
  367. # reverse instance collections
  368. for instances in self.data.values():
  369. instances.reverse()
  370. # delete instances
  371. for model, instances in self.data.items():
  372. query = sql.DeleteQuery(model)
  373. pk_list = [obj.pk for obj in instances]
  374. count = query.delete_batch(pk_list, self.using)
  375. if count:
  376. deleted_counter[model._meta.label] += count
  377. if not model._meta.auto_created:
  378. for obj in instances:
  379. signals.post_delete.send(
  380. sender=model, instance=obj, using=self.using
  381. )
  382. # update collected instances
  383. for instances_for_fieldvalues in self.field_updates.values():
  384. for (field, value), instances in instances_for_fieldvalues.items():
  385. for obj in instances:
  386. setattr(obj, field.attname, value)
  387. for model, instances in self.data.items():
  388. for instance in instances:
  389. setattr(instance, model._meta.pk.attname, None)
  390. return sum(deleted_counter.values()), dict(deleted_counter)