Skip to content

Commit d346d81

Browse files
authored
Single DATABASE instead of DATABASES and DATABASE_ROUTERS (#47)
1 parent ea1a242 commit d346d81

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

66 files changed

+821
-1592
lines changed

demos/full/app/settings.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,9 @@
2828
SUPPORT_EMAIL = "support@example.com"
2929
OAUTH_LOGIN_PROVIDERS = {}
3030

31-
DATABASES = {
32-
"default": {
33-
"ENGINE": "plain.models.backends.sqlite3",
34-
"NAME": ":memory:",
35-
}
31+
DATABASE = {
32+
"ENGINE": "plain.models.backends.sqlite3",
33+
"NAME": ":memory:",
3634
}
3735

3836
MIDDLEWARE = [

plain-admin/plain/admin/querystats/middleware.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import re
44

55
from plain.json import PlainJSONEncoder
6-
from plain.models import DEFAULT_DB_ALIAS, connections
6+
from plain.models import db_connection
77
from plain.runtime import settings
88

99
from .core import QueryStats
@@ -59,11 +59,11 @@ def is_tracking():
5959

6060
querystats = QueryStats(include_tracebacks=is_tracking())
6161

62-
with connections[DEFAULT_DB_ALIAS].execute_wrapper(querystats):
62+
with db_connection.execute_wrapper(querystats):
6363
is_admin = self.is_admin_request(request)
6464

6565
if settings.DEBUG or is_admin:
66-
with connections[DEFAULT_DB_ALIAS].execute_wrapper(querystats):
66+
with db_connection.execute_wrapper(querystats):
6767
response = self.get_response(request)
6868

6969
if settings.DEBUG:

plain-admin/tests/app/settings.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,9 @@
99
"plain.admin",
1010
"app.users",
1111
]
12-
DATABASES = {
13-
"default": {
14-
"ENGINE": "plain.models.backends.sqlite3",
15-
"NAME": ":memory:",
16-
}
12+
DATABASE = {
13+
"ENGINE": "plain.models.backends.sqlite3",
14+
"NAME": ":memory:",
1715
}
1816
MIDDLEWARE = [
1917
"plain.sessions.middleware.SessionMiddleware",

plain-flags/plain/flags/admin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class UnusedFlagsCard(Card):
1818

1919
@cached_property
2020
def flag_errors(self):
21-
return Flag.check(databases=["default"])
21+
return Flag.check(database=True)
2222

2323
def get_number(self):
2424
return len(self.flag_errors)

plain-flags/plain/flags/models.py

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -79,33 +79,30 @@ def check(cls, **kwargs):
7979
"""
8080
errors = super().check(**kwargs)
8181

82-
databases = kwargs["databases"]
83-
if not databases:
82+
database = kwargs.get("database", False)
83+
if not database:
8484
return errors
8585

86-
for database in databases:
87-
flag_names = (
88-
cls.objects.using(database).all().values_list("name", flat=True)
89-
)
86+
flag_names = cls.objects.all().values_list("name", flat=True)
9087

88+
try:
89+
flag_names = set(flag_names)
90+
except ProgrammingError:
91+
# The table doesn't exist yet
92+
# (migrations probably haven't run yet),
93+
# so we can't check it.
94+
return errors
95+
96+
for flag_name in flag_names:
9197
try:
92-
flag_names = set(flag_names)
93-
except ProgrammingError:
94-
# The table doesn't exist yet
95-
# (migrations probably haven't run yet),
96-
# so we can't check it.
97-
continue
98-
99-
for flag_name in flag_names:
100-
try:
101-
get_flag_class(flag_name)
102-
except FlagImportError:
103-
errors.append(
104-
Info(
105-
f"Flag {flag_name} is not used.",
106-
hint=f"Remove the flag from the database or define it in the {settings.FLAGS_MODULE} module.",
107-
id="plain.flags.I001",
108-
)
98+
get_flag_class(flag_name)
99+
except FlagImportError:
100+
errors.append(
101+
Info(
102+
f"Flag {flag_name} is not used.",
103+
hint=f"Remove the flag from the database or define it in the {settings.FLAGS_MODULE} module.",
104+
id="plain.flags.I001",
109105
)
106+
)
110107

111108
return errors

plain-flags/tests/app/settings.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@
44
"plain.models",
55
"plain.flags",
66
]
7-
DATABASES = {
8-
"default": {
9-
"ENGINE": "plain.models.backends.sqlite3",
10-
"NAME": ":memory:",
11-
}
7+
DATABASE = {
8+
"ENGINE": "plain.models.backends.sqlite3",
9+
"NAME": ":memory:",
1210
}

plain-models/plain/models/README.md

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -60,19 +60,17 @@ To connect to a database, you can provide a `DATABASE_URL` environment variable.
6060
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
6161
```
6262

63-
Or you can manually define the `DATABASES` setting.
63+
Or you can manually define the `DATABASE` setting.
6464

6565
```python
6666
# app/settings.py
67-
DATABASES = {
68-
"default": {
69-
"ENGINE": "plain.models.backends.postgresql",
70-
"NAME": "dbname",
71-
"USER": "user",
72-
"PASSWORD": "password",
73-
"HOST": "localhost",
74-
"PORT": "5432",
75-
}
67+
DATABASE = {
68+
"ENGINE": "plain.models.backends.postgresql",
69+
"NAME": "dbname",
70+
"USER": "user",
71+
"PASSWORD": "password",
72+
"HOST": "localhost",
73+
"PORT": "5432",
7674
}
7775
```
7876

plain-models/plain/models/__init__.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
from .constraints import * # NOQA
99
from .constraints import __all__ as constraints_all
1010
from .db import (
11-
DEFAULT_DB_ALIAS,
1211
PLAIN_VERSION_PICKLE_KEY,
1312
DatabaseError,
1413
DataError,
@@ -20,9 +19,8 @@
2019
OperationalError,
2120
ProgrammingError,
2221
close_old_connections,
23-
connections,
22+
db_connection,
2423
reset_queries,
25-
router,
2624
)
2725
from .deletion import (
2826
CASCADE,
@@ -127,8 +125,7 @@
127125

128126
# DB-related exports
129127
__all__ += [
130-
"connections",
131-
"router",
128+
"db_connection",
132129
"reset_queries",
133130
"close_old_connections",
134131
"DatabaseError",
@@ -140,7 +137,6 @@
140137
"Error",
141138
"InterfaceError",
142139
"OperationalError",
143-
"DEFAULT_DB_ALIAS",
144140
"PLAIN_VERSION_PICKLE_KEY",
145141
]
146142

plain-models/plain/models/backends/base/base.py

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,14 @@
1414
from plain.models.backends.base.validation import BaseDatabaseValidation
1515
from plain.models.backends.utils import debug_transaction
1616
from plain.models.db import (
17-
DEFAULT_DB_ALIAS,
1817
DatabaseError,
1918
DatabaseErrorWrapper,
2019
NotSupportedError,
2120
)
2221
from plain.models.transaction import TransactionManagementError
2322
from plain.runtime import settings
2423

25-
NO_DB_ALIAS = "__no_db__"
26-
RAN_DB_VERSION_CHECK = set()
24+
RAN_DB_VERSION_CHECK = False
2725

2826
logger = logging.getLogger("plain.models.backends.base")
2927

@@ -51,15 +49,14 @@ class BaseDatabaseWrapper:
5149

5250
queries_limit = 9000
5351

54-
def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS):
52+
def __init__(self, settings_dict):
5553
# Connection related attributes.
5654
# The underlying database connection.
5755
self.connection = None
5856
# `settings_dict` should be a dictionary containing keys such as
5957
# NAME, USER, etc. It's called `settings_dict` instead of `settings`
6058
# to disambiguate it from Plain settings modules.
6159
self.settings_dict = settings_dict
62-
self.alias = alias
6360
# Query logging in debug mode or when explicitly enabled.
6461
self.queries_log = deque(maxlen=self.queries_limit)
6562
self.force_debug_cursor = False
@@ -120,10 +117,7 @@ def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS):
120117
self.validation = self.validation_class(self)
121118

122119
def __repr__(self):
123-
return (
124-
f"<{self.__class__.__qualname__} "
125-
f"vendor={self.vendor!r} alias={self.alias!r}>"
126-
)
120+
return f"<{self.__class__.__qualname__} vendor={self.vendor!r}>"
127121

128122
def ensure_timezone(self):
129123
"""
@@ -218,9 +212,9 @@ def get_new_connection(self, conn_params):
218212
def init_connection_state(self):
219213
"""Initialize the database connection settings."""
220214
global RAN_DB_VERSION_CHECK
221-
if self.alias not in RAN_DB_VERSION_CHECK:
215+
if not RAN_DB_VERSION_CHECK:
222216
self.check_database_version_supported()
223-
RAN_DB_VERSION_CHECK.add(self.alias)
217+
RAN_DB_VERSION_CHECK = True
224218

225219
def create_cursor(self, name=None):
226220
"""Create a cursor. Assume that a connection is established."""
@@ -593,8 +587,8 @@ def validate_thread_sharing(self):
593587
if not (self.allow_thread_sharing or self._thread_ident == _thread.get_ident()):
594588
raise DatabaseError(
595589
"DatabaseWrapper objects created in a "
596-
"thread can only be used in that same thread. The object "
597-
f"with alias '{self.alias}' was created in thread id {self._thread_ident} and this is "
590+
"thread can only be used in that same thread. The connection "
591+
f"was created in thread id {self._thread_ident} and this is "
598592
f"thread id {_thread.get_ident()}."
599593
)
600594

@@ -656,7 +650,7 @@ def _nodb_cursor(self):
656650
being exposed to potential child threads while (or after) the test
657651
database is destroyed. Refs #10868, #17786, #16969.
658652
"""
659-
conn = self.__class__({**self.settings_dict, "NAME": None}, alias=NO_DB_ALIAS)
653+
conn = self.__class__({**self.settings_dict, "NAME": None})
660654
try:
661655
with conn.cursor() as cursor:
662656
yield cursor
@@ -729,13 +723,11 @@ def execute_wrapper(self, wrapper):
729723
finally:
730724
self.execute_wrappers.pop()
731725

732-
def copy(self, alias=None):
726+
def copy(self):
733727
"""
734728
Return a copy of this connection.
735729
736730
For tests that require two connections to the same database.
737731
"""
738732
settings_dict = copy.deepcopy(self.settings_dict)
739-
if alias is None:
740-
alias = self.alias
741-
return type(self)(settings_dict, alias)
733+
return type(self)(settings_dict)

plain-models/plain/models/backends/base/creation.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def create_test_db(self, verbosity=1, prefix=""):
4545
)
4646

4747
self.connection.close()
48-
settings.DATABASES[self.connection.alias]["NAME"] = test_database_name
48+
settings.DATABASE["NAME"] = test_database_name
4949
self.connection.settings_dict["NAME"] = test_database_name
5050

5151
# We report migrate messages at one level lower than that
@@ -54,7 +54,6 @@ def create_test_db(self, verbosity=1, prefix=""):
5454
migrate.callback(
5555
package_label=None,
5656
migration_name=None,
57-
database=self.connection.alias,
5857
fake=False,
5958
fake_initial=False,
6059
plan=False,
@@ -219,7 +218,7 @@ def destroy_test_db(self, old_database_name=None, verbosity=1):
219218

220219
# Restore the original database name
221220
if old_database_name is not None:
222-
settings.DATABASES[self.connection.alias]["NAME"] = old_database_name
221+
settings.DATABASE["NAME"] = old_database_name
223222
self.connection.settings_dict["NAME"] = old_database_name
224223

225224
def _destroy_test_db(self, test_database_name, verbosity):
@@ -244,7 +243,7 @@ def sql_table_creation_suffix(self):
244243
def test_db_signature(self, prefix=""):
245244
"""
246245
Return a tuple with elements of self.connection.settings_dict (a
247-
DATABASES setting value) that uniquely identify a database
246+
DATABASE setting value) that uniquely identify a database
248247
accordingly to the RDBMS particularities.
249248
"""
250249
settings_dict = self.connection.settings_dict

0 commit comments

Comments
 (0)