Development of an internal social media platform with personalised dashboards for students
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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 can be
  98. 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 not (hasattr(objs, 'model') and hasattr(objs, '_raw_delete')):
  108. return False
  109. model = objs.model
  110. if (signals.pre_delete.has_listeners(model) or
  111. signals.post_delete.has_listeners(model) or
  112. signals.m2m_changed.has_listeners(model)):
  113. return False
  114. # The use of from_field comes from the need to avoid cascade back to
  115. # parent when parent delete is cascading to child.
  116. opts = model._meta
  117. return (
  118. all(link == from_field for link in opts.concrete_model._meta.parents.values()) and
  119. # Foreign keys pointing to this model.
  120. all(
  121. related.field.remote_field.on_delete is DO_NOTHING
  122. for related in get_candidate_relations_to_delete(opts)
  123. ) and (
  124. # Something like generic foreign key.
  125. not any(hasattr(field, 'bulk_related_objects') for field in model._meta.private_fields)
  126. )
  127. )
  128. def get_del_batches(self, objs, field):
  129. """
  130. Return the objs in suitably sized batches for the used connection.
  131. """
  132. conn_batch_size = max(
  133. connections[self.using].ops.bulk_batch_size([field.name], objs), 1)
  134. if len(objs) > conn_batch_size:
  135. return [objs[i:i + conn_batch_size]
  136. for i in range(0, len(objs), conn_batch_size)]
  137. else:
  138. return [objs]
  139. def collect(self, objs, source=None, nullable=False, collect_related=True,
  140. source_attr=None, reverse_dependency=False, keep_parents=False):
  141. """
  142. Add 'objs' to the collection of objects to be deleted as well as all
  143. parent instances. 'objs' must be a homogeneous iterable collection of
  144. model instances (e.g. a QuerySet). If 'collect_related' is True,
  145. related objects will be handled by their respective on_delete handler.
  146. If the call is the result of a cascade, 'source' should be the model
  147. that caused it and 'nullable' should be set to True, if the relation
  148. can be null.
  149. If 'reverse_dependency' is True, 'source' will be deleted before the
  150. current model, rather than after. (Needed for cascading to parent
  151. models, the one case in which the cascade follows the forwards
  152. direction of an FK rather than the reverse direction.)
  153. If 'keep_parents' is True, data of parent model's will be not deleted.
  154. """
  155. if self.can_fast_delete(objs):
  156. self.fast_deletes.append(objs)
  157. return
  158. new_objs = self.add(objs, source, nullable,
  159. reverse_dependency=reverse_dependency)
  160. if not new_objs:
  161. return
  162. model = new_objs[0].__class__
  163. if not keep_parents:
  164. # Recursively collect concrete model's parent models, but not their
  165. # related objects. These will be found by meta.get_fields()
  166. concrete_model = model._meta.concrete_model
  167. for ptr in concrete_model._meta.parents.values():
  168. if ptr:
  169. parent_objs = [getattr(obj, ptr.name) for obj in new_objs]
  170. self.collect(parent_objs, source=model,
  171. source_attr=ptr.remote_field.related_name,
  172. collect_related=False,
  173. reverse_dependency=True)
  174. if collect_related:
  175. parents = model._meta.parents
  176. for related in get_candidate_relations_to_delete(model._meta):
  177. # Preserve parent reverse relationships if keep_parents=True.
  178. if keep_parents and related.model in parents:
  179. continue
  180. field = related.field
  181. if field.remote_field.on_delete == DO_NOTHING:
  182. continue
  183. batches = self.get_del_batches(new_objs, field)
  184. for batch in batches:
  185. sub_objs = self.related_objects(related, batch)
  186. if self.can_fast_delete(sub_objs, from_field=field):
  187. self.fast_deletes.append(sub_objs)
  188. elif sub_objs:
  189. field.remote_field.on_delete(self, field, sub_objs, self.using)
  190. for field in model._meta.private_fields:
  191. if hasattr(field, 'bulk_related_objects'):
  192. # It's something like generic foreign key.
  193. sub_objs = field.bulk_related_objects(new_objs, self.using)
  194. self.collect(sub_objs, source=model, nullable=True)
  195. def related_objects(self, related, objs):
  196. """
  197. Get a QuerySet of objects related to `objs` via the relation `related`.
  198. """
  199. return related.related_model._base_manager.using(self.using).filter(
  200. **{"%s__in" % related.field.name: objs}
  201. )
  202. def instances_with_model(self):
  203. for model, instances in self.data.items():
  204. for obj in instances:
  205. yield model, obj
  206. def sort(self):
  207. sorted_models = []
  208. concrete_models = set()
  209. models = list(self.data)
  210. while len(sorted_models) < len(models):
  211. found = False
  212. for model in models:
  213. if model in sorted_models:
  214. continue
  215. dependencies = self.dependencies.get(model._meta.concrete_model)
  216. if not (dependencies and dependencies.difference(concrete_models)):
  217. sorted_models.append(model)
  218. concrete_models.add(model._meta.concrete_model)
  219. found = True
  220. if not found:
  221. return
  222. self.data = OrderedDict((model, self.data[model])
  223. for model in sorted_models)
  224. def delete(self):
  225. # sort instance collections
  226. for model, instances in self.data.items():
  227. self.data[model] = sorted(instances, key=attrgetter("pk"))
  228. # if possible, bring the models in an order suitable for databases that
  229. # don't support transactions or cannot defer constraint checks until the
  230. # end of a transaction.
  231. self.sort()
  232. # number of objects deleted for each model label
  233. deleted_counter = Counter()
  234. with transaction.atomic(using=self.using, savepoint=False):
  235. # send pre_delete signals
  236. for model, obj in self.instances_with_model():
  237. if not model._meta.auto_created:
  238. signals.pre_delete.send(
  239. sender=model, instance=obj, using=self.using
  240. )
  241. # fast deletes
  242. for qs in self.fast_deletes:
  243. count = qs._raw_delete(using=self.using)
  244. deleted_counter[qs.model._meta.label] += count
  245. # update fields
  246. for model, instances_for_fieldvalues in self.field_updates.items():
  247. for (field, value), instances in instances_for_fieldvalues.items():
  248. query = sql.UpdateQuery(model)
  249. query.update_batch([obj.pk for obj in instances],
  250. {field.name: value}, self.using)
  251. # reverse instance collections
  252. for instances in self.data.values():
  253. instances.reverse()
  254. # delete instances
  255. for model, instances in self.data.items():
  256. query = sql.DeleteQuery(model)
  257. pk_list = [obj.pk for obj in instances]
  258. count = query.delete_batch(pk_list, self.using)
  259. deleted_counter[model._meta.label] += count
  260. if not model._meta.auto_created:
  261. for obj in instances:
  262. signals.post_delete.send(
  263. sender=model, instance=obj, using=self.using
  264. )
  265. # update collected instances
  266. for instances_for_fieldvalues in self.field_updates.values():
  267. for (field, value), instances in instances_for_fieldvalues.items():
  268. for obj in instances:
  269. setattr(obj, field.attname, value)
  270. for model, instances in self.data.items():
  271. for instance in instances:
  272. setattr(instance, model._meta.pk.attname, None)
  273. return sum(deleted_counter.values()), dict(deleted_counter)