2015-03-07 16:56:25 +08:00
|
|
|
from collections import Counter, OrderedDict
|
2010-11-10 00:46:42 +08:00
|
|
|
from operator import attrgetter
|
|
|
|
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.db import IntegrityError, connections, transaction
|
2010-11-10 00:46:42 +08:00
|
|
|
from django.db.models import signals, sql
|
|
|
|
|
|
|
|
|
2011-01-20 08:33:32 +08:00
|
|
|
class ProtectedError(IntegrityError):
|
|
|
|
def __init__(self, msg, protected_objects):
|
|
|
|
self.protected_objects = protected_objects
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(msg, protected_objects)
|
2011-01-20 08:33:32 +08:00
|
|
|
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def CASCADE(collector, field, sub_objs, using):
|
2015-02-26 22:19:17 +08:00
|
|
|
collector.collect(sub_objs, source=field.remote_field.model,
|
2010-11-10 00:46:42 +08:00
|
|
|
source_attr=field.name, nullable=field.null)
|
|
|
|
if field.null and not connections[using].features.can_defer_constraint_checks:
|
|
|
|
collector.add_field_update(field, None, sub_objs)
|
|
|
|
|
2011-01-20 08:33:32 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def PROTECT(collector, field, sub_objs, using):
|
2016-03-29 06:33:29 +08:00
|
|
|
raise ProtectedError(
|
|
|
|
"Cannot delete some instances of model '%s' because they are "
|
|
|
|
"referenced through a protected foreign key: '%s.%s'" % (
|
2015-02-26 22:19:17 +08:00
|
|
|
field.remote_field.model.__name__, sub_objs[0].__class__.__name__, field.name
|
2011-01-20 08:33:32 +08:00
|
|
|
),
|
|
|
|
sub_objs
|
|
|
|
)
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
|
|
|
|
def SET(value):
|
|
|
|
if callable(value):
|
|
|
|
def set_on_delete(collector, field, sub_objs, using):
|
|
|
|
collector.add_field_update(field, value(), sub_objs)
|
|
|
|
else:
|
|
|
|
def set_on_delete(collector, field, sub_objs, using):
|
|
|
|
collector.add_field_update(field, value, sub_objs)
|
2013-09-02 14:02:07 +08:00
|
|
|
set_on_delete.deconstruct = lambda: ('django.db.models.SET', (value,), {})
|
2010-11-10 00:46:42 +08:00
|
|
|
return set_on_delete
|
|
|
|
|
2011-01-20 08:33:32 +08:00
|
|
|
|
2013-09-02 02:21:08 +08:00
|
|
|
def SET_NULL(collector, field, sub_objs, using):
|
|
|
|
collector.add_field_update(field, None, sub_objs)
|
2010-11-10 00:46:42 +08:00
|
|
|
|
2011-01-20 08:33:32 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def SET_DEFAULT(collector, field, sub_objs, using):
|
|
|
|
collector.add_field_update(field, field.get_default(), sub_objs)
|
|
|
|
|
2011-01-20 08:33:32 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def DO_NOTHING(collector, field, sub_objs, using):
|
|
|
|
pass
|
|
|
|
|
2011-01-20 08:33:32 +08:00
|
|
|
|
2015-01-07 08:16:35 +08:00
|
|
|
def get_candidate_relations_to_delete(opts):
|
|
|
|
# The candidate relations are the ones that come from N-1 and 1-1 relations.
|
|
|
|
# N-N (i.e., many-to-many) relations aren't candidates for deletion.
|
|
|
|
return (
|
2015-10-08 03:29:20 +08:00
|
|
|
f for f in opts.get_fields(include_hidden=True)
|
2015-02-14 02:55:36 +08:00
|
|
|
if f.auto_created and not f.concrete and (f.one_to_one or f.one_to_many)
|
2015-01-07 08:16:35 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Collector:
|
2010-11-10 00:46:42 +08:00
|
|
|
def __init__(self, using):
|
|
|
|
self.using = using
|
2014-09-26 20:31:50 +08:00
|
|
|
# Initially, {model: {instances}}, later values become lists.
|
2015-11-04 20:27:35 +08:00
|
|
|
self.data = OrderedDict()
|
2014-09-26 20:31:50 +08:00
|
|
|
self.field_updates = {} # {model: {(field, value): {instances}}}
|
2012-09-20 23:51:30 +08:00
|
|
|
# fast_deletes is a list of queryset-likes that can be deleted without
|
|
|
|
# fetching the objects into memory.
|
2013-01-12 06:12:22 +08:00
|
|
|
self.fast_deletes = []
|
2012-03-17 09:24:39 +08:00
|
|
|
|
|
|
|
# Tracks deletion-order dependency for databases without transactions
|
|
|
|
# or ability to defer constraint checks. Only concrete model classes
|
|
|
|
# should be included, as the dependencies exist only between actual
|
|
|
|
# database tables; proxy models are represented here by their concrete
|
|
|
|
# parent.
|
2014-09-26 20:31:50 +08:00
|
|
|
self.dependencies = {} # {model: {models}}
|
2010-11-10 00:46:42 +08:00
|
|
|
|
2011-01-20 04:11:56 +08:00
|
|
|
def add(self, objs, source=None, nullable=False, reverse_dependency=False):
|
2010-11-10 00:46:42 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Add 'objs' to the collection of objects to be deleted. If the call is
|
2011-05-31 00:04:25 +08:00
|
|
|
the result of a cascade, 'source' should be the model that caused it,
|
|
|
|
and 'nullable' should be set to True if the relation can be null.
|
2010-11-10 00:46:42 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Return a list of all objects that were not already collected.
|
2010-11-10 00:46:42 +08:00
|
|
|
"""
|
|
|
|
if not objs:
|
|
|
|
return []
|
|
|
|
new_objs = []
|
|
|
|
model = objs[0].__class__
|
2011-01-19 22:39:54 +08:00
|
|
|
instances = self.data.setdefault(model, set())
|
2010-11-10 00:46:42 +08:00
|
|
|
for obj in objs:
|
|
|
|
if obj not in instances:
|
|
|
|
new_objs.append(obj)
|
2011-01-19 22:39:54 +08:00
|
|
|
instances.update(new_objs)
|
2010-11-10 00:46:42 +08:00
|
|
|
# Nullable relationships can be ignored -- they are nulled out before
|
|
|
|
# deleting, and therefore do not affect the order in which objects have
|
|
|
|
# to be deleted.
|
2011-05-31 00:04:25 +08:00
|
|
|
if source is not None and not nullable:
|
2011-01-20 04:11:56 +08:00
|
|
|
if reverse_dependency:
|
|
|
|
source, model = model, source
|
2012-03-17 09:24:39 +08:00
|
|
|
self.dependencies.setdefault(
|
|
|
|
source._meta.concrete_model, set()).add(model._meta.concrete_model)
|
2010-11-10 00:46:42 +08:00
|
|
|
return new_objs
|
|
|
|
|
|
|
|
def add_field_update(self, field, value, objs):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Schedule a field update. 'objs' must be a homogeneous iterable
|
2010-11-10 00:46:42 +08:00
|
|
|
collection of model instances (e.g. a QuerySet).
|
|
|
|
"""
|
|
|
|
if not objs:
|
|
|
|
return
|
|
|
|
model = objs[0].__class__
|
|
|
|
self.field_updates.setdefault(
|
|
|
|
model, {}).setdefault(
|
|
|
|
(field, value), set()).update(objs)
|
|
|
|
|
2012-09-20 23:51:30 +08:00
|
|
|
def can_fast_delete(self, objs, from_field=None):
|
|
|
|
"""
|
2018-09-27 15:45:10 +08:00
|
|
|
Determine if the objects in the given queryset-like or single object
|
|
|
|
can be fast-deleted. This can be done if there are no cascades, no
|
2012-09-20 23:51:30 +08:00
|
|
|
parents and no signal listeners for the object class.
|
|
|
|
|
|
|
|
The 'from_field' tells where we are coming from - we need this to
|
2017-01-25 07:04:12 +08:00
|
|
|
determine if the objects are in fact to be deleted. Allow also
|
2012-09-20 23:51:30 +08:00
|
|
|
skipping parent -> child -> parent chain preventing fast delete of
|
|
|
|
the child.
|
|
|
|
"""
|
2015-02-26 22:19:17 +08:00
|
|
|
if from_field and from_field.remote_field.on_delete is not CASCADE:
|
2012-09-20 23:51:30 +08:00
|
|
|
return False
|
2018-09-27 15:45:10 +08:00
|
|
|
if hasattr(objs, '_meta'):
|
|
|
|
model = type(objs)
|
|
|
|
elif hasattr(objs, 'model') and hasattr(objs, '_raw_delete'):
|
|
|
|
model = objs.model
|
|
|
|
else:
|
2012-09-20 23:51:30 +08:00
|
|
|
return False
|
2016-04-04 08:37:32 +08:00
|
|
|
if (signals.pre_delete.has_listeners(model) or
|
|
|
|
signals.post_delete.has_listeners(model) or
|
|
|
|
signals.m2m_changed.has_listeners(model)):
|
2012-09-20 23:51:30 +08:00
|
|
|
return False
|
|
|
|
# The use of from_field comes from the need to avoid cascade back to
|
|
|
|
# parent when parent delete is cascading to child.
|
|
|
|
opts = model._meta
|
2017-12-27 02:44:12 +08:00
|
|
|
return (
|
|
|
|
all(link == from_field for link in opts.concrete_model._meta.parents.values()) and
|
|
|
|
# Foreign keys pointing to this model.
|
|
|
|
all(
|
|
|
|
related.field.remote_field.on_delete is DO_NOTHING
|
|
|
|
for related in get_candidate_relations_to_delete(opts)
|
|
|
|
) and (
|
|
|
|
# Something like generic foreign key.
|
2018-09-27 15:45:10 +08:00
|
|
|
not any(hasattr(field, 'bulk_related_objects') for field in opts.private_fields)
|
2017-12-27 02:44:12 +08:00
|
|
|
)
|
|
|
|
)
|
2012-09-20 23:51:30 +08:00
|
|
|
|
2014-08-11 17:47:37 +08:00
|
|
|
def get_del_batches(self, objs, field):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the objs in suitably sized batches for the used connection.
|
2014-08-11 17:47:37 +08:00
|
|
|
"""
|
|
|
|
conn_batch_size = max(
|
|
|
|
connections[self.using].ops.bulk_batch_size([field.name], objs), 1)
|
|
|
|
if len(objs) > conn_batch_size:
|
|
|
|
return [objs[i:i + conn_batch_size]
|
|
|
|
for i in range(0, len(objs), conn_batch_size)]
|
|
|
|
else:
|
|
|
|
return [objs]
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
def collect(self, objs, source=None, nullable=False, collect_related=True,
|
2016-03-29 06:33:29 +08:00
|
|
|
source_attr=None, reverse_dependency=False, keep_parents=False):
|
2010-11-10 00:46:42 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Add 'objs' to the collection of objects to be deleted as well as all
|
2014-03-02 22:25:53 +08:00
|
|
|
parent instances. 'objs' must be a homogeneous iterable collection of
|
2010-11-10 00:46:42 +08:00
|
|
|
model instances (e.g. a QuerySet). If 'collect_related' is True,
|
|
|
|
related objects will be handled by their respective on_delete handler.
|
|
|
|
|
|
|
|
If the call is the result of a cascade, 'source' should be the model
|
|
|
|
that caused it and 'nullable' should be set to True, if the relation
|
|
|
|
can be null.
|
|
|
|
|
2011-01-20 04:11:56 +08:00
|
|
|
If 'reverse_dependency' is True, 'source' will be deleted before the
|
|
|
|
current model, rather than after. (Needed for cascading to parent
|
|
|
|
models, the one case in which the cascade follows the forwards
|
|
|
|
direction of an FK rather than the reverse direction.)
|
2015-02-07 07:16:26 +08:00
|
|
|
|
2015-03-17 21:08:02 +08:00
|
|
|
If 'keep_parents' is True, data of parent model's will be not deleted.
|
2011-01-20 04:11:56 +08:00
|
|
|
"""
|
2012-09-20 23:51:30 +08:00
|
|
|
if self.can_fast_delete(objs):
|
|
|
|
self.fast_deletes.append(objs)
|
|
|
|
return
|
2011-01-20 04:11:56 +08:00
|
|
|
new_objs = self.add(objs, source, nullable,
|
|
|
|
reverse_dependency=reverse_dependency)
|
2010-11-10 00:46:42 +08:00
|
|
|
if not new_objs:
|
|
|
|
return
|
2012-03-05 11:41:01 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
model = new_objs[0].__class__
|
|
|
|
|
2015-02-07 07:16:26 +08:00
|
|
|
if not keep_parents:
|
|
|
|
# Recursively collect concrete model's parent models, but not their
|
|
|
|
# related objects. These will be found by meta.get_fields()
|
|
|
|
concrete_model = model._meta.concrete_model
|
2017-01-07 19:11:46 +08:00
|
|
|
for ptr in concrete_model._meta.parents.values():
|
2015-02-07 07:16:26 +08:00
|
|
|
if ptr:
|
|
|
|
parent_objs = [getattr(obj, ptr.name) for obj in new_objs]
|
|
|
|
self.collect(parent_objs, source=model,
|
2015-02-26 22:19:17 +08:00
|
|
|
source_attr=ptr.remote_field.related_name,
|
2015-02-07 07:16:26 +08:00
|
|
|
collect_related=False,
|
|
|
|
reverse_dependency=True)
|
2010-11-10 00:46:42 +08:00
|
|
|
if collect_related:
|
2016-09-11 08:30:14 +08:00
|
|
|
parents = model._meta.parents
|
2015-01-07 08:16:35 +08:00
|
|
|
for related in get_candidate_relations_to_delete(model._meta):
|
2016-09-11 08:30:14 +08:00
|
|
|
# Preserve parent reverse relationships if keep_parents=True.
|
|
|
|
if keep_parents and related.model in parents:
|
|
|
|
continue
|
2010-11-10 00:46:42 +08:00
|
|
|
field = related.field
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.remote_field.on_delete == DO_NOTHING:
|
2012-09-20 23:51:30 +08:00
|
|
|
continue
|
2014-08-11 17:47:37 +08:00
|
|
|
batches = self.get_del_batches(new_objs, field)
|
|
|
|
for batch in batches:
|
|
|
|
sub_objs = self.related_objects(related, batch)
|
|
|
|
if self.can_fast_delete(sub_objs, from_field=field):
|
|
|
|
self.fast_deletes.append(sub_objs)
|
|
|
|
elif sub_objs:
|
2015-02-26 22:19:17 +08:00
|
|
|
field.remote_field.on_delete(self, field, sub_objs, self.using)
|
2016-03-21 01:10:55 +08:00
|
|
|
for field in model._meta.private_fields:
|
2013-03-25 00:40:40 +08:00
|
|
|
if hasattr(field, 'bulk_related_objects'):
|
2015-08-28 04:13:24 +08:00
|
|
|
# It's something like generic foreign key.
|
2013-03-25 00:40:40 +08:00
|
|
|
sub_objs = field.bulk_related_objects(new_objs, self.using)
|
2015-08-28 04:13:24 +08:00
|
|
|
self.collect(sub_objs, source=model, nullable=True)
|
2010-11-10 00:46:42 +08:00
|
|
|
|
|
|
|
def related_objects(self, related, objs):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Get a QuerySet of objects related to `objs` via the relation `related`.
|
2010-11-10 00:46:42 +08:00
|
|
|
"""
|
2015-01-07 08:16:35 +08:00
|
|
|
return related.related_model._base_manager.using(self.using).filter(
|
2010-11-10 00:46:42 +08:00
|
|
|
**{"%s__in" % related.field.name: objs}
|
|
|
|
)
|
|
|
|
|
|
|
|
def instances_with_model(self):
|
2017-01-07 19:11:46 +08:00
|
|
|
for model, instances in self.data.items():
|
2010-11-10 00:46:42 +08:00
|
|
|
for obj in instances:
|
|
|
|
yield model, obj
|
|
|
|
|
|
|
|
def sort(self):
|
|
|
|
sorted_models = []
|
2012-03-17 09:24:39 +08:00
|
|
|
concrete_models = set()
|
2012-08-08 22:33:15 +08:00
|
|
|
models = list(self.data)
|
2010-11-10 00:46:42 +08:00
|
|
|
while len(sorted_models) < len(models):
|
|
|
|
found = False
|
|
|
|
for model in models:
|
|
|
|
if model in sorted_models:
|
|
|
|
continue
|
2012-03-17 09:24:39 +08:00
|
|
|
dependencies = self.dependencies.get(model._meta.concrete_model)
|
|
|
|
if not (dependencies and dependencies.difference(concrete_models)):
|
2010-11-10 00:46:42 +08:00
|
|
|
sorted_models.append(model)
|
2012-03-17 09:24:39 +08:00
|
|
|
concrete_models.add(model._meta.concrete_model)
|
2010-11-10 00:46:42 +08:00
|
|
|
found = True
|
|
|
|
if not found:
|
|
|
|
return
|
2013-08-30 07:20:00 +08:00
|
|
|
self.data = OrderedDict((model, self.data[model])
|
|
|
|
for model in sorted_models)
|
2010-11-10 00:46:42 +08:00
|
|
|
|
|
|
|
def delete(self):
|
|
|
|
# sort instance collections
|
2011-01-19 22:39:54 +08:00
|
|
|
for model, instances in self.data.items():
|
|
|
|
self.data[model] = sorted(instances, key=attrgetter("pk"))
|
2010-11-10 00:46:42 +08:00
|
|
|
|
|
|
|
# if possible, bring the models in an order suitable for databases that
|
2011-08-12 22:14:15 +08:00
|
|
|
# don't support transactions or cannot defer constraint checks until the
|
2010-11-10 00:46:42 +08:00
|
|
|
# end of a transaction.
|
|
|
|
self.sort()
|
2015-03-07 16:56:25 +08:00
|
|
|
# number of objects deleted for each model label
|
|
|
|
deleted_counter = Counter()
|
2010-11-10 00:46:42 +08:00
|
|
|
|
2018-09-27 15:45:10 +08:00
|
|
|
# Optimize for the case with a single obj and no dependencies
|
|
|
|
if len(self.data) == 1 and len(instances) == 1:
|
|
|
|
instance = list(instances)[0]
|
|
|
|
if self.can_fast_delete(instance):
|
|
|
|
with transaction.mark_for_rollback_on_error():
|
|
|
|
count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)
|
|
|
|
return count, {model._meta.label: count}
|
|
|
|
|
2014-03-21 21:21:43 +08:00
|
|
|
with transaction.atomic(using=self.using, savepoint=False):
|
2013-03-08 18:35:54 +08:00
|
|
|
# send pre_delete signals
|
|
|
|
for model, obj in self.instances_with_model():
|
|
|
|
if not model._meta.auto_created:
|
|
|
|
signals.pre_delete.send(
|
2013-01-15 05:17:01 +08:00
|
|
|
sender=model, instance=obj, using=self.using
|
|
|
|
)
|
2010-11-10 00:46:42 +08:00
|
|
|
|
2013-03-08 18:35:54 +08:00
|
|
|
# fast deletes
|
|
|
|
for qs in self.fast_deletes:
|
2015-03-07 16:56:25 +08:00
|
|
|
count = qs._raw_delete(using=self.using)
|
|
|
|
deleted_counter[qs.model._meta.label] += count
|
2013-03-08 18:35:54 +08:00
|
|
|
|
|
|
|
# update fields
|
2017-01-07 19:11:46 +08:00
|
|
|
for model, instances_for_fieldvalues in self.field_updates.items():
|
|
|
|
for (field, value), instances in instances_for_fieldvalues.items():
|
2018-01-13 19:23:48 +08:00
|
|
|
query = sql.UpdateQuery(model)
|
2013-03-08 18:35:54 +08:00
|
|
|
query.update_batch([obj.pk for obj in instances],
|
|
|
|
{field.name: value}, self.using)
|
|
|
|
|
|
|
|
# reverse instance collections
|
2017-01-07 19:11:46 +08:00
|
|
|
for instances in self.data.values():
|
2013-03-08 18:35:54 +08:00
|
|
|
instances.reverse()
|
|
|
|
|
|
|
|
# delete instances
|
2017-01-07 19:11:46 +08:00
|
|
|
for model, instances in self.data.items():
|
2013-03-08 18:35:54 +08:00
|
|
|
query = sql.DeleteQuery(model)
|
|
|
|
pk_list = [obj.pk for obj in instances]
|
2015-03-07 16:56:25 +08:00
|
|
|
count = query.delete_batch(pk_list, self.using)
|
|
|
|
deleted_counter[model._meta.label] += count
|
2013-03-08 18:35:54 +08:00
|
|
|
|
|
|
|
if not model._meta.auto_created:
|
|
|
|
for obj in instances:
|
|
|
|
signals.post_delete.send(
|
|
|
|
sender=model, instance=obj, using=self.using
|
|
|
|
)
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
# update collected instances
|
2017-12-07 06:17:59 +08:00
|
|
|
for instances_for_fieldvalues in self.field_updates.values():
|
2017-01-07 19:11:46 +08:00
|
|
|
for (field, value), instances in instances_for_fieldvalues.items():
|
2010-11-10 00:46:42 +08:00
|
|
|
for obj in instances:
|
|
|
|
setattr(obj, field.attname, value)
|
2017-01-07 19:11:46 +08:00
|
|
|
for model, instances in self.data.items():
|
2010-11-10 00:46:42 +08:00
|
|
|
for instance in instances:
|
|
|
|
setattr(instance, model._meta.pk.attname, None)
|
2015-03-07 16:56:25 +08:00
|
|
|
return sum(deleted_counter.values()), dict(deleted_counter)
|