From e1671278e88265e64811657b8b939b5d786295cb Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Wed, 2 Jul 2025 01:47:47 -0400 Subject: Fixed #36490 -- Avoided unnecessary transaction in bulk_create. When dealing with an heterogeneous set of object with regards to primary key assignment that fits in a single batch there's no need to wrap the single INSERT statement in a transaction. --- tests/bulk_create/tests.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'tests') diff --git a/tests/bulk_create/tests.py b/tests/bulk_create/tests.py index d590a292de..35180bf487 100644 --- a/tests/bulk_create/tests.py +++ b/tests/bulk_create/tests.py @@ -14,6 +14,7 @@ from django.db.models import FileField, Value from django.db.models.functions import Lower, Now from django.test import ( TestCase, + TransactionTestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, @@ -884,3 +885,35 @@ class BulkCreateTests(TestCase): def test_db_default_primary_key(self): (obj,) = DbDefaultPrimaryKey.objects.bulk_create([DbDefaultPrimaryKey()]) self.assertIsInstance(obj.id, datetime) + + +@skipUnlessDBFeature("supports_transactions", "has_bulk_insert") +class BulkCreateTransactionTests(TransactionTestCase): + available_apps = ["bulk_create"] + + def test_no_unnecessary_transaction(self): + with self.assertNumQueries(1): + Country.objects.bulk_create( + [Country(id=1, name="France", iso_two_letter="FR")] + ) + with self.assertNumQueries(1): + Country.objects.bulk_create([Country(name="Canada", iso_two_letter="CA")]) + + def test_objs_with_and_without_pk(self): + with self.assertNumQueries(4): + Country.objects.bulk_create( + [ + Country(id=1, name="France", iso_two_letter="FR"), + Country(name="Canada", iso_two_letter="CA"), + ] + ) + + def test_multiple_batches(self): + with self.assertNumQueries(4): + Country.objects.bulk_create( + [ + Country(name="France", iso_two_letter="FR"), + Country(name="Canada", iso_two_letter="CA"), + ], + batch_size=1, + ) -- cgit v1.3