Skip to content

Replace DatabaseWrapper.__getattr__() with a simpler database attribute #287

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions django_mongodb_backend/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from django.core.exceptions import ImproperlyConfigured
from django.db.backends.base.base import BaseDatabaseWrapper
from django.utils.asyncio import async_unsafe
from django.utils.functional import cached_property
from pymongo.collection import Collection
from pymongo.driver_info import DriverInfo
from pymongo.mongo_client import MongoClient
Expand Down Expand Up @@ -149,13 +150,13 @@ def get_database(self):
return OperationDebugWrapper(self)
return self.database

def __getattr__(self, attr):
"""Connect to the database the first time `database` is accessed."""
if attr == "database":
if self.connection is None:
self.connect()
return getattr(self, attr)
raise AttributeError(attr)
Comment on lines -157 to -158
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So we now won't raise an error if something other than database is

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default implementation of __getattr__() raises AttributeError.

@cached_property
def database(self):
"""Connect to the database the first time it's accessed."""
if self.connection is None:
self.connect()
# Cache the database attribute set by init_connection_state()
return self.database

def init_connection_state(self):
self.database = self.connection[self.settings_dict["NAME"]]
Expand Down
21 changes: 21 additions & 0 deletions tests/backend_/test_base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from django.db.backends.signals import connection_created
from django.test import SimpleTestCase, TestCase

from django_mongodb_backend.base import DatabaseWrapper
Expand All @@ -21,3 +22,23 @@ def test_set_autocommit(self):
self.assertIs(connection.get_autocommit(), False)
connection.set_autocommit(True)
self.assertIs(connection.get_autocommit(), True)

def test_connection_created_database_attr(self):
"""
connection.database is available in the connection_created signal.
"""
data = {}

def receiver(sender, connection, **kwargs): # noqa: ARG001
data["database"] = connection.database

connection_created.connect(receiver)
connection.close()
Comment on lines +35 to +36
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we also assert that data is empty after calling close() or is that not necessary?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Certainly could, but if close() actually created a connection (thus firing the connection_created signal) instead of closing, I think there would be other rather obvious problems.

# Accessing database implicitly connects.
connection.database # noqa: B018
self.assertIs(data["database"], connection.database)
connection.close()
connection_created.disconnect(receiver)
data.clear()
connection.connect()
self.assertEqual(data, {})
Loading