From d4748bf53c213272cecf4e7b8d8dd5516a60eb97 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Sat, 27 Sep 2025 15:04:56 -0400 Subject: [PATCH] INTPYTHON-772 Fix transaction.atomic() crash if connection isn't initialized --- django_mongodb_backend/base.py | 1 + docs/releases/5.2.x.rst | 2 ++ tests/transactions_/tests.py | 8 +++++++- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/django_mongodb_backend/base.py b/django_mongodb_backend/base.py index f751c27fa..ecc7f78c7 100644 --- a/django_mongodb_backend/base.py +++ b/django_mongodb_backend/base.py @@ -272,6 +272,7 @@ def get_database_version(self): @async_unsafe def start_transaction_mongo(self): if self.session is None: + self.ensure_connection() self.session = self.connection.start_session() with debug_transaction(self, "session.start_transaction()"): self.session.start_transaction() diff --git a/docs/releases/5.2.x.rst b/docs/releases/5.2.x.rst index 54e1e6cb2..757caa551 100644 --- a/docs/releases/5.2.x.rst +++ b/docs/releases/5.2.x.rst @@ -23,6 +23,8 @@ Bug fixes :attr:`~django.db.models.Field.db_column`. - Corrected the search index type of ``EmbeddedModelField`` and ``PolymorphicEmbeddedModelField`` from ``embeddedDocuments`` to ``document``. +- Fixed ``transaction.atomic()`` crash if the database connection isn't + initialized. Deprecated features ------------------- diff --git a/tests/transactions_/tests.py b/tests/transactions_/tests.py index 0a2b4cedb..2c63e262a 100644 --- a/tests/transactions_/tests.py +++ b/tests/transactions_/tests.py @@ -1,4 +1,4 @@ -from django.db import DatabaseError +from django.db import DatabaseError, connection from django.test import TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature from django_mongodb_backend import transaction @@ -140,6 +140,12 @@ def __call__(self): transaction.atomic(Callable()) # Must not raise an exception + def test_initializes_connection(self): + """transaction.atomic() opens the connection if needed.""" + connection.close_pool() + with transaction.atomic(): + pass + @skipIfDBFeature("_supports_transactions") class AtomicNotSupportedTests(TransactionTestCase):