deletion.py 21 KB

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