Debian Codegraph @

tests/delete_regress/tests.py

raw
1 import datetime
2
3 from django.db import connection, models, transaction
4 from django.db.models import Exists, OuterRef
5 from django.test import (
6 SimpleTestCase,
7 TestCase,
8 TransactionTestCase,
9 skipUnlessDBFeature,
10 )
11
12 from .models import (
13 Award,
14 AwardNote,
15 Book,
16 Child,
17 Contact,
18 Eaten,
19 Email,
20 File,
21 Food,
22 FooFile,
23 FooFileProxy,
24 FooImage,
25 FooPhoto,
26 House,
27 Image,
28 Item,
29 Location,
30 Login,
31 OrderedPerson,
32 OrgUnit,
33 Person,
34 Photo,
35 PlayedWith,
36 PlayedWithNote,
37 Policy,
38 Researcher,
39 Toy,
40 Version,
41 )
42
43
44 # Can't run this test under SQLite, because you can't
45 # get two connections to an in-memory database.
46 @skipUnlessDBFeature("test_db_allows_multiple_connections")
47 class DeleteLockingTest(TransactionTestCase):
48 available_apps = ["delete_regress"]
49
50 def setUp(self):
51 # Create a second connection to the default database
52 self.conn2 = connection.copy()
53 self.conn2.set_autocommit(False)
54 # Close down the second connection.
55 self.addCleanup(self.conn2.close)
56 self.addCleanup(self.conn2.rollback)
57
58 def test_concurrent_delete(self):
59 """Concurrent deletes don't collide and lock the database (#9479)."""
60 with transaction.atomic():
61 Book.objects.create(id=1, pagecount=100)
62 Book.objects.create(id=2, pagecount=200)
63 Book.objects.create(id=3, pagecount=300)
64
65 with transaction.atomic():
66 # Start a transaction on the main connection.
67 self.assertEqual(3, Book.objects.count())
68
69 # Delete something using another database connection.
70 with self.conn2.cursor() as cursor2:
71 cursor2.execute("DELETE from delete_regress_book WHERE id = 1")
72 self.conn2.commit()
73
74 # In the same transaction on the main connection, perform a
75 # queryset delete that covers the object deleted with the other
76 # connection. This causes an infinite loop under MySQL InnoDB
77 # unless we keep track of already deleted objects.
78 Book.objects.filter(pagecount__lt=250).delete()
79
80 self.assertEqual(1, Book.objects.count())
81
82
83 class DeleteCascadeTests(TestCase):
84 def test_generic_relation_cascade(self):
85 """
86 Django cascades deletes through generic-related objects to their
87 reverse relations.
88 """
89 person = Person.objects.create(name="Nelson Mandela")
90 award = Award.objects.create(name="Nobel", content_object=person)
91 AwardNote.objects.create(note="a peace prize", award=award)
92 self.assertEqual(AwardNote.objects.count(), 1)
93 person.delete()
94 self.assertEqual(Award.objects.count(), 0)
95 # first two asserts are just sanity checks, this is the kicker:
96 self.assertEqual(AwardNote.objects.count(), 0)
97
98 def test_fk_to_m2m_through(self):
99 """
100 If an M2M relationship has an explicitly-specified through model, and
101 some other model has an FK to that through model, deletion is cascaded
102 from one of the participants in the M2M, to the through model, to its
103 related model.
104 """
105 juan = Child.objects.create(name="Juan")
106 paints = Toy.objects.create(name="Paints")
107 played = PlayedWith.objects.create(
108 child=juan, toy=paints, date=datetime.date.today()
109 )
110 PlayedWithNote.objects.create(played=played, note="the next Jackson Pollock")
111 self.assertEqual(PlayedWithNote.objects.count(), 1)
112 paints.delete()
113 self.assertEqual(PlayedWith.objects.count(), 0)
114 # first two asserts just sanity checks, this is the kicker:
115 self.assertEqual(PlayedWithNote.objects.count(), 0)
116
117 def test_15776(self):
118 policy = Policy.objects.create(pk=1, policy_number="1234")
119 version = Version.objects.create(policy=policy)
120 location = Location.objects.create(version=version)
121 Item.objects.create(version=version, location=location)
122 policy.delete()
123
124
125 class DeleteCascadeTransactionTests(TransactionTestCase):
126 available_apps = ["delete_regress"]
127
128 def test_inheritance(self):
129 """
130 Auto-created many-to-many through tables referencing a parent model are
131 correctly found by the delete cascade when a child of that parent is
132 deleted.
133
134 Refs #14896.
135 """
136 r = Researcher.objects.create()
137 email = Email.objects.create(
138 label="office-email", email_address="[email protected]"
139 )
140 r.contacts.add(email)
141
142 email.delete()
143
144 def test_to_field(self):
145 """
146 Cascade deletion works with ForeignKey.to_field set to non-PK.
147 """
148 apple = Food.objects.create(name="apple")
149 Eaten.objects.create(food=apple, meal="lunch")
150
151 apple.delete()
152 self.assertFalse(Food.objects.exists())
153 self.assertFalse(Eaten.objects.exists())
154
155
156 class LargeDeleteTests(TestCase):
157 def test_large_deletes(self):
158 """
159 If the number of objects > chunk size, deletion still occurs.
160 """
161 for x in range(300):
162 Book.objects.create(pagecount=x + 100)
163 # attach a signal to make sure we will not fast-delete
164
165 def noop(*args, **kwargs):
166 pass
167
168 models.signals.post_delete.connect(noop, sender=Book)
169 Book.objects.all().delete()
170 models.signals.post_delete.disconnect(noop, sender=Book)
171 self.assertEqual(Book.objects.count(), 0)
172
173
174 class ProxyDeleteTest(TestCase):
175 """
176 Tests on_delete behavior for proxy models.
177
178 See #16128.
179 """
180
181 def create_image(self):
182 """Return an Image referenced by both a FooImage and a FooFile."""
183 # Create an Image
184 test_image = Image()
185 test_image.save()
186 foo_image = FooImage(my_image=test_image)
187 foo_image.save()
188
189 # Get the Image instance as a File
190 test_file = File.objects.get(pk=test_image.pk)
191 foo_file = FooFile(my_file=test_file)
192 foo_file.save()
193
194 return test_image
195
196 def test_delete_proxy(self):
197 """
198 Deleting the *proxy* instance bubbles through to its non-proxy and
199 *all* referring objects are deleted.
200 """
201 self.create_image()
202
203 Image.objects.all().delete()
204
205 # An Image deletion == File deletion
206 self.assertEqual(len(Image.objects.all()), 0)
207 self.assertEqual(len(File.objects.all()), 0)
208
209 # The Image deletion cascaded and *all* references to it are deleted.
210 self.assertEqual(len(FooImage.objects.all()), 0)
211 self.assertEqual(len(FooFile.objects.all()), 0)
212
213 def test_delete_proxy_of_proxy(self):
214 """
215 Deleting a proxy-of-proxy instance should bubble through to its proxy
216 and non-proxy parents, deleting *all* referring objects.
217 """
218 test_image = self.create_image()
219
220 # Get the Image as a Photo
221 test_photo = Photo.objects.get(pk=test_image.pk)
222 foo_photo = FooPhoto(my_photo=test_photo)
223 foo_photo.save()
224
225 Photo.objects.all().delete()
226
227 # A Photo deletion == Image deletion == File deletion
228 self.assertEqual(len(Photo.objects.all()), 0)
229 self.assertEqual(len(Image.objects.all()), 0)
230 self.assertEqual(len(File.objects.all()), 0)
231
232 # The Photo deletion should have cascaded and deleted *all*
233 # references to it.
234 self.assertEqual(len(FooPhoto.objects.all()), 0)
235 self.assertEqual(len(FooFile.objects.all()), 0)
236 self.assertEqual(len(FooImage.objects.all()), 0)
237
238 def test_delete_concrete_parent(self):
239 """
240 Deleting an instance of a concrete model should also delete objects
241 referencing its proxy subclass.
242 """
243 self.create_image()
244
245 File.objects.all().delete()
246
247 # A File deletion == Image deletion
248 self.assertEqual(len(File.objects.all()), 0)
249 self.assertEqual(len(Image.objects.all()), 0)
250
251 # The File deletion should have cascaded and deleted *all* references
252 # to it.
253 self.assertEqual(len(FooFile.objects.all()), 0)
254 self.assertEqual(len(FooImage.objects.all()), 0)
255
256 def test_delete_proxy_pair(self):
257 """
258 If a pair of proxy models are linked by an FK from one concrete parent
259 to the other, deleting one proxy model cascade-deletes the other, and
260 the deletion happens in the right order (not triggering an
261 IntegrityError on databases unable to defer integrity checks).
262
263 Refs #17918.
264 """
265 # Create an Image (proxy of File) and FooFileProxy (proxy of FooFile,
266 # which has an FK to File)
267 image = Image.objects.create()
268 as_file = File.objects.get(pk=image.pk)
269 FooFileProxy.objects.create(my_file=as_file)
270
271 Image.objects.all().delete()
272
273 self.assertEqual(len(FooFileProxy.objects.all()), 0)
274
275 def test_19187_values(self):
276 msg = "Cannot call delete() after .values() or .values_list()"
277 with self.assertRaisesMessage(TypeError, msg):
278 Image.objects.values().delete()
279 with self.assertRaisesMessage(TypeError, msg):
280 Image.objects.values_list().delete()
281
282
283 class Ticket19102Tests(TestCase):
284 """
285 Test different queries which alter the SELECT clause of the query. We
286 also must be using a subquery for the deletion (that is, the original
287 query has a join in it). The deletion should be done as "fast-path"
288 deletion (that is, just one query for the .delete() call).
289
290 Note that .values() is not tested here on purpose. .values().delete()
291 doesn't work for non fast-path deletes at all.
292 """
293
294 @classmethod
295 def setUpTestData(cls):
296 cls.o1 = OrgUnit.objects.create(name="o1")
297 cls.o2 = OrgUnit.objects.create(name="o2")
298 cls.l1 = Login.objects.create(description="l1", orgunit=cls.o1)
299 cls.l2 = Login.objects.create(description="l2", orgunit=cls.o2)
300
301 @skipUnlessDBFeature("update_can_self_select")
302 def test_ticket_19102_annotate(self):
303 with self.assertNumQueries(1):
304 Login.objects.order_by("description").filter(
305 orgunit__name__isnull=False
306 ).annotate(n=models.Count("description")).filter(
307 n=1, pk=self.l1.pk
308 ).delete()
309 self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
310 self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())
311
312 @skipUnlessDBFeature("update_can_self_select")
313 def test_ticket_19102_extra(self):
314 with self.assertNumQueries(1):
315 Login.objects.order_by("description").filter(
316 orgunit__name__isnull=False
317 ).extra(select={"extraf": "1"}).filter(pk=self.l1.pk).delete()
318 self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
319 self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())
320
321 @skipUnlessDBFeature("update_can_self_select")
322 def test_ticket_19102_select_related(self):
323 with self.assertNumQueries(1):
324 Login.objects.filter(pk=self.l1.pk).filter(
325 orgunit__name__isnull=False
326 ).order_by("description").select_related("orgunit").delete()
327 self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
328 self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())
329
330 @skipUnlessDBFeature("update_can_self_select")
331 def test_ticket_19102_defer(self):
332 with self.assertNumQueries(1):
333 Login.objects.filter(pk=self.l1.pk).filter(
334 orgunit__name__isnull=False
335 ).order_by("description").only("id").delete()
336 self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
337 self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())
338
339
340 class DeleteTests(TestCase):
341 def test_meta_ordered_delete(self):
342 # When a subquery is performed by deletion code, the subquery must be
343 # cleared of all ordering. There was a but that caused _meta ordering
344 # to be used. Refs #19720.
345 h = House.objects.create(address="Foo")
346 OrderedPerson.objects.create(name="Jack", lives_in=h)
347 OrderedPerson.objects.create(name="Bob", lives_in=h)
348 OrderedPerson.objects.filter(lives_in__address="Foo").delete()
349 self.assertEqual(OrderedPerson.objects.count(), 0)
350
351 def test_foreign_key_delete_nullifies_correct_columns(self):
352 """
353 With a model (Researcher) that has two foreign keys pointing to the
354 same model (Contact), deleting an instance of the target model
355 (contact1) nullifies the correct fields of Researcher.
356 """
357 contact1 = Contact.objects.create(label="Contact 1")
358 contact2 = Contact.objects.create(label="Contact 2")
359 researcher1 = Researcher.objects.create(
360 primary_contact=contact1,
361 secondary_contact=contact2,
362 )
363 researcher2 = Researcher.objects.create(
364 primary_contact=contact2,
365 secondary_contact=contact1,
366 )
367 contact1.delete()
368 researcher1.refresh_from_db()
369 researcher2.refresh_from_db()
370 self.assertIsNone(researcher1.primary_contact)
371 self.assertEqual(researcher1.secondary_contact, contact2)
372 self.assertEqual(researcher2.primary_contact, contact2)
373 self.assertIsNone(researcher2.secondary_contact)
374
375 def test_self_reference_with_through_m2m_at_second_level(self):
376 toy = Toy.objects.create(name="Paints")
377 child = Child.objects.create(name="Juan")
378 Book.objects.create(pagecount=500, owner=child)
379 PlayedWith.objects.create(child=child, toy=toy, date=datetime.date.today())
380 with self.assertNumQueries(1) as ctx:
381 Book.objects.filter(
382 Exists(
383 Book.objects.filter(
384 pk=OuterRef("pk"),
385 owner__toys=toy.pk,
386 ),
387 )
388 ).delete()
389
390 self.assertIs(Book.objects.exists(), False)
391 sql = ctx.captured_queries[0]["sql"].lower()
392 if connection.features.delete_can_self_reference_subquery:
393 self.assertEqual(sql.count("select"), 1)
394
395
396 class DeleteDistinct(SimpleTestCase):
397 def test_disallowed_delete_distinct_on(self):
398 msg = "Cannot call delete() after .distinct(*fields)."
399 with self.assertRaisesMessage(TypeError, msg):
400 Book.objects.distinct("id").delete()
401
402
403 class SetQueryCountTests(TestCase):
404 def test_set_querycount(self):
405 policy = Policy.objects.create()
406 version = Version.objects.create(policy=policy)
407 location = Location.objects.create(version=version)
408 Item.objects.create(
409 version=version,
410 location=location,
411 location_value=location,
412 )
413 # 2 UPDATEs for SET of item values and one for DELETE locations.
414 with self.assertNumQueries(3):
415 location.delete()
416
417
418 class SetCallableCollectorDefaultTests(TestCase):
419 def test_set(self):
420 # Collector doesn't call callables used by models.SET and
421 # models.SET_DEFAULT if not necessary.
422 Toy.objects.create(name="test")
423 Toy.objects.all().delete()
424 self.assertSequenceEqual(Toy.objects.all(), [])