diff options
| author | Simon Charette <charette.s@gmail.com> | 2025-07-02 01:47:47 -0400 |
|---|---|---|
| committer | Sarah Boyce <42296566+sarahboyce@users.noreply.github.com> | 2025-08-15 10:45:02 +0200 |
| commit | e1671278e88265e64811657b8b939b5d786295cb (patch) | |
| tree | 797023c32b73e3bab915173ca6c7eb8169c558ed /tests/bulk_create/tests.py | |
| parent | 5e06b970956af4854e970e74990cb971ba31c96b (diff) | |
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.
Diffstat (limited to 'tests/bulk_create/tests.py')
| -rw-r--r-- | tests/bulk_create/tests.py | 33 |
1 files changed, 33 insertions, 0 deletions
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, + ) |
