deletion.py 21 KB

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