| 1 |
import _thread |
| 2 |
import copy |
| 3 |
import datetime |
| 4 |
import logging |
| 5 |
import threading |
| 6 |
import time |
| 7 |
import warnings |
| 8 |
import zoneinfo |
| 9 |
from collections import deque |
| 10 |
from contextlib import contextmanager |
| 11 |
|
| 12 |
from django.conf import settings |
| 13 |
from django.core.exceptions import ImproperlyConfigured |
| 14 |
from django.db import DEFAULT_DB_ALIAS, DatabaseError, NotSupportedError |
| 15 |
from django.db.backends import utils |
| 16 |
from django.db.backends.base.validation import BaseDatabaseValidation |
| 17 |
from django.db.backends.signals import connection_created |
| 18 |
from django.db.backends.utils import debug_transaction |
| 19 |
from django.db.transaction import TransactionManagementError |
| 20 |
from django.db.utils import DatabaseErrorWrapper, ProgrammingError |
| 21 |
from django.utils.asyncio import async_unsafe |
| 22 |
from django.utils.functional import cached_property |
| 23 |
|
| 24 |
NO_DB_ALIAS = "__no_db__" |
| 25 |
RAN_DB_VERSION_CHECK = set() |
| 26 |
|
| 27 |
logger = logging.getLogger("django.db.backends.base") |
| 28 |
|
| 29 |
|
| 30 |
class BaseDatabaseWrapper: |
| 31 |
"""Represent a database connection.""" |
| 32 |
|
| 33 |
# Mapping of Field objects to their column types. |
| 34 |
data_types = {} |
| 35 |
# Mapping of Field objects to their SQL suffix such as AUTOINCREMENT. |
| 36 |
data_types_suffix = {} |
| 37 |
# Mapping of Field objects to their SQL for CHECK constraints. |
| 38 |
data_type_check_constraints = {} |
| 39 |
ops = None |
| 40 |
vendor = "unknown" |
| 41 |
display_name = "unknown" |
| 42 |
SchemaEditorClass = None |
| 43 |
# Classes instantiated in __init__(). |
| 44 |
client_class = None |
| 45 |
creation_class = None |
| 46 |
features_class = None |
| 47 |
introspection_class = None |
| 48 |
ops_class = None |
| 49 |
validation_class = BaseDatabaseValidation |
| 50 |
|
| 51 |
queries_limit = 9000 |
| 52 |
|
| 53 |
def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS): |
| 54 |
# Connection related attributes. |
| 55 |
# The underlying database connection. |
| 56 |
self.connection = None |
| 57 |
# `settings_dict` should be a dictionary containing keys such as |
| 58 |
# NAME, USER, etc. It's called `settings_dict` instead of `settings` |
| 59 |
# to disambiguate it from Django settings modules. |
| 60 |
self.settings_dict = settings_dict |
| 61 |
self.alias = alias |
| 62 |
# Query logging in debug mode or when explicitly enabled. |
| 63 |
self.queries_log = deque(maxlen=self.queries_limit) |
| 64 |
self.force_debug_cursor = False |
| 65 |
|
| 66 |
# Transaction related attributes. |
| 67 |
# Tracks if the connection is in autocommit mode. Per PEP 249, by |
| 68 |
# default, it isn't. |
| 69 |
self.autocommit = False |
| 70 |
# Tracks if the connection is in a transaction managed by 'atomic'. |
| 71 |
self.in_atomic_block = False |
| 72 |
# Increment to generate unique savepoint ids. |
| 73 |
self.savepoint_state = 0 |
| 74 |
# List of savepoints created by 'atomic'. |
| 75 |
self.savepoint_ids = [] |
| 76 |
# Stack of active 'atomic' blocks. |
| 77 |
self.atomic_blocks = [] |
| 78 |
# Tracks if the outermost 'atomic' block should commit on exit, |
| 79 |
# ie. if autocommit was active on entry. |
| 80 |
self.commit_on_exit = True |
| 81 |
# Tracks if the transaction should be rolled back to the next |
| 82 |
# available savepoint because of an exception in an inner block. |
| 83 |
self.needs_rollback = False |
| 84 |
self.rollback_exc = None |
| 85 |
|
| 86 |
# Connection termination related attributes. |
| 87 |
self.close_at = None |
| 88 |
self.closed_in_transaction = False |
| 89 |
self.errors_occurred = False |
| 90 |
self.health_check_enabled = False |
| 91 |
self.health_check_done = False |
| 92 |
|
| 93 |
# Thread-safety related attributes. |
| 94 |
self._thread_sharing_lock = threading.Lock() |
| 95 |
self._thread_sharing_count = 0 |
| 96 |
self._thread_ident = _thread.get_ident() |
| 97 |
|
| 98 |
# A list of no-argument functions to run when the transaction commits. |
| 99 |
# Each entry is an (sids, func, robust) tuple, where sids is a set of |
| 100 |
# the active savepoint IDs when this function was registered and robust |
| 101 |
# specifies whether it's allowed for the function to fail. |
| 102 |
self.run_on_commit = [] |
| 103 |
|
| 104 |
# Should we run the on-commit hooks the next time set_autocommit(True) |
| 105 |
# is called? |
| 106 |
self.run_commit_hooks_on_set_autocommit_on = False |
| 107 |
|
| 108 |
# A stack of wrappers to be invoked around execute()/executemany() |
| 109 |
# calls. Each entry is a function taking five arguments: execute, sql, |
| 110 |
# params, many, and context. It's the function's responsibility to |
| 111 |
# call execute(sql, params, many, context). |
| 112 |
self.execute_wrappers = [] |
| 113 |
|
| 114 |
self.client = self.client_class(self) |
| 115 |
self.creation = self.creation_class(self) |
| 116 |
self.features = self.features_class(self) |
| 117 |
self.introspection = self.introspection_class(self) |
| 118 |
self.ops = self.ops_class(self) |
| 119 |
self.validation = self.validation_class(self) |
| 120 |
|
| 121 |
def __repr__(self): |
| 122 |
return ( |
| 123 |
f"<{self.__class__.__qualname__} " |
| 124 |
f"vendor={self.vendor!r} alias={self.alias!r}>" |
| 125 |
) |
| 126 |
|
| 127 |
def ensure_timezone(self): |
| 128 |
""" |
| 129 |
Ensure the connection's timezone is set to `self.timezone_name` and |
| 130 |
return whether it changed or not. |
| 131 |
""" |
| 132 |
return False |
| 133 |
|
| 134 |
@cached_property |
| 135 |
def timezone(self): |
| 136 |
""" |
| 137 |
Return a tzinfo of the database connection time zone. |
| 138 |
|
| 139 |
This is only used when time zone support is enabled. When a datetime is |
| 140 |
read from the database, it is always returned in this time zone. |
| 141 |
|
| 142 |
When the database backend supports time zones, it doesn't matter which |
| 143 |
time zone Django uses, as long as aware datetimes are used everywhere. |
| 144 |
Other users connecting to the database can choose their own time zone. |
| 145 |
|
| 146 |
When the database backend doesn't support time zones, the time zone |
| 147 |
Django uses may be constrained by the requirements of other users of |
| 148 |
the database. |
| 149 |
""" |
| 150 |
if not settings.USE_TZ: |
| 151 |
return None |
| 152 |
elif self.settings_dict["TIME_ZONE"] is None: |
| 153 |
return datetime.timezone.utc |
| 154 |
else: |
| 155 |
return zoneinfo.ZoneInfo(self.settings_dict["TIME_ZONE"]) |
| 156 |
|
| 157 |
@cached_property |
| 158 |
def timezone_name(self): |
| 159 |
""" |
| 160 |
Name of the time zone of the database connection. |
| 161 |
""" |
| 162 |
if not settings.USE_TZ: |
| 163 |
return settings.TIME_ZONE |
| 164 |
elif self.settings_dict["TIME_ZONE"] is None: |
| 165 |
return "UTC" |
| 166 |
else: |
| 167 |
return self.settings_dict["TIME_ZONE"] |
| 168 |
|
| 169 |
@property |
| 170 |
def queries_logged(self): |
| 171 |
return self.force_debug_cursor or settings.DEBUG |
| 172 |
|
| 173 |
@property |
| 174 |
def queries(self): |
| 175 |
if len(self.queries_log) == self.queries_log.maxlen: |
| 176 |
warnings.warn( |
| 177 |
"Limit for query logging exceeded, only the last {} queries " |
| 178 |
"will be returned.".format(self.queries_log.maxlen), |
| 179 |
stacklevel=2, |
| 180 |
) |
| 181 |
return list(self.queries_log) |
| 182 |
|
| 183 |
def get_database_version(self): |
| 184 |
"""Return a tuple of the database's version.""" |
| 185 |
raise NotImplementedError( |
| 186 |
"subclasses of BaseDatabaseWrapper may require a get_database_version() " |
| 187 |
"method." |
| 188 |
) |
| 189 |
|
| 190 |
def check_database_version_supported(self): |
| 191 |
""" |
| 192 |
Raise an error if the database version isn't supported by this |
| 193 |
version of Django. |
| 194 |
""" |
| 195 |
if ( |
| 196 |
self.features.minimum_database_version is not None |
| 197 |
and self.get_database_version() < self.features.minimum_database_version |
| 198 |
): |
| 199 |
db_version = ".".join(map(str, self.get_database_version())) |
| 200 |
min_db_version = ".".join(map(str, self.features.minimum_database_version)) |
| 201 |
raise NotSupportedError( |
| 202 |
f"{self.display_name} {min_db_version} or later is required " |
| 203 |
f"(found {db_version})." |
| 204 |
) |
| 205 |
|
| 206 |
# ##### Backend-specific methods for creating connections and cursors ##### |
| 207 |
|
| 208 |
def get_connection_params(self): |
| 209 |
"""Return a dict of parameters suitable for get_new_connection.""" |
| 210 |
raise NotImplementedError( |
| 211 |
"subclasses of BaseDatabaseWrapper may require a get_connection_params() " |
| 212 |
"method" |
| 213 |
) |
| 214 |
|
| 215 |
def get_new_connection(self, conn_params): |
| 216 |
"""Open a connection to the database.""" |
| 217 |
raise NotImplementedError( |
| 218 |
"subclasses of BaseDatabaseWrapper may require a get_new_connection() " |
| 219 |
"method" |
| 220 |
) |
| 221 |
|
| 222 |
def init_connection_state(self): |
| 223 |
"""Initialize the database connection settings.""" |
| 224 |
if self.alias not in RAN_DB_VERSION_CHECK: |
| 225 |
self.check_database_version_supported() |
| 226 |
RAN_DB_VERSION_CHECK.add(self.alias) |
| 227 |
|
| 228 |
def create_cursor(self, name=None): |
| 229 |
"""Create a cursor. Assume that a connection is established.""" |
| 230 |
raise NotImplementedError( |
| 231 |
"subclasses of BaseDatabaseWrapper may require a create_cursor() method" |
| 232 |
) |
| 233 |
|
| 234 |
# ##### Backend-specific methods for creating connections ##### |
| 235 |
|
| 236 |
@async_unsafe |
| 237 |
def connect(self): |
| 238 |
"""Connect to the database. Assume that the connection is closed.""" |
| 239 |
# Check for invalid configurations. |
| 240 |
self.check_settings() |
| 241 |
# In case the previous connection was closed while in an atomic block |
| 242 |
self.in_atomic_block = False |
| 243 |
self.savepoint_ids = [] |
| 244 |
self.atomic_blocks = [] |
| 245 |
self.needs_rollback = False |
| 246 |
# Reset parameters defining when to close/health-check the connection. |
| 247 |
self.health_check_enabled = self.settings_dict["CONN_HEALTH_CHECKS"] |
| 248 |
max_age = self.settings_dict["CONN_MAX_AGE"] |
| 249 |
self.close_at = None if max_age is None else time.monotonic() + max_age |
| 250 |
self.closed_in_transaction = False |
| 251 |
self.errors_occurred = False |
| 252 |
# New connections are healthy. |
| 253 |
self.health_check_done = True |
| 254 |
# Establish the connection |
| 255 |
conn_params = self.get_connection_params() |
| 256 |
self.connection = self.get_new_connection(conn_params) |
| 257 |
self.set_autocommit(self.settings_dict["AUTOCOMMIT"]) |
| 258 |
self.init_connection_state() |
| 259 |
connection_created.send(sender=self.__class__, connection=self) |
| 260 |
|
| 261 |
self.run_on_commit = [] |
| 262 |
|
| 263 |
def check_settings(self): |
| 264 |
if self.settings_dict["TIME_ZONE"] is not None and not settings.USE_TZ: |
| 265 |
raise ImproperlyConfigured( |
| 266 |
"Connection '%s' cannot set TIME_ZONE because USE_TZ is False." |
| 267 |
% self.alias |
| 268 |
) |
| 269 |
|
| 270 |
@async_unsafe |
| 271 |
def ensure_connection(self): |
| 272 |
"""Guarantee that a connection to the database is established.""" |
| 273 |
if self.connection is None: |
| 274 |
if self.in_atomic_block and self.closed_in_transaction: |
| 275 |
raise ProgrammingError( |
| 276 |
"Cannot open a new connection in an atomic block." |
| 277 |
) |
| 278 |
with self.wrap_database_errors: |
| 279 |
self.connect() |
| 280 |
|
| 281 |
# ##### Backend-specific wrappers for PEP-249 connection methods ##### |
| 282 |
|
| 283 |
def _prepare_cursor(self, cursor): |
| 284 |
""" |
| 285 |
Validate the connection is usable and perform database cursor wrapping. |
| 286 |
""" |
| 287 |
self.validate_thread_sharing() |
| 288 |
if self.queries_logged: |
| 289 |
wrapped_cursor = self.make_debug_cursor(cursor) |
| 290 |
else: |
| 291 |
wrapped_cursor = self.make_cursor(cursor) |
| 292 |
return wrapped_cursor |
| 293 |
|
| 294 |
def _cursor(self, name=None): |
| 295 |
self.close_if_health_check_failed() |
| 296 |
self.ensure_connection() |
| 297 |
with self.wrap_database_errors: |
| 298 |
return self._prepare_cursor(self.create_cursor(name)) |
| 299 |
|
| 300 |
def _commit(self): |
| 301 |
if self.connection is not None: |
| 302 |
with debug_transaction(self, "COMMIT"), self.wrap_database_errors: |
| 303 |
return self.connection.commit() |
| 304 |
|
| 305 |
def _rollback(self): |
| 306 |
if self.connection is not None: |
| 307 |
with debug_transaction(self, "ROLLBACK"), self.wrap_database_errors: |
| 308 |
return self.connection.rollback() |
| 309 |
|
| 310 |
def _close(self): |
| 311 |
if self.connection is not None: |
| 312 |
with self.wrap_database_errors: |
| 313 |
return self.connection.close() |
| 314 |
|
| 315 |
# ##### Generic wrappers for PEP-249 connection methods ##### |
| 316 |
|
| 317 |
@async_unsafe |
| 318 |
def cursor(self): |
| 319 |
"""Create a cursor, opening a connection if necessary.""" |
| 320 |
return self._cursor() |
| 321 |
|
| 322 |
@async_unsafe |
| 323 |
def commit(self): |
| 324 |
"""Commit a transaction and reset the dirty flag.""" |
| 325 |
self.validate_thread_sharing() |
| 326 |
self.validate_no_atomic_block() |
| 327 |
self._commit() |
| 328 |
# A successful commit means that the database connection works. |
| 329 |
self.errors_occurred = False |
| 330 |
self.run_commit_hooks_on_set_autocommit_on = True |
| 331 |
|
| 332 |
@async_unsafe |
| 333 |
def rollback(self): |
| 334 |
"""Roll back a transaction and reset the dirty flag.""" |
| 335 |
self.validate_thread_sharing() |
| 336 |
self.validate_no_atomic_block() |
| 337 |
self._rollback() |
| 338 |
# A successful rollback means that the database connection works. |
| 339 |
self.errors_occurred = False |
| 340 |
self.needs_rollback = False |
| 341 |
self.run_on_commit = [] |
| 342 |
|
| 343 |
@async_unsafe |
| 344 |
def close(self): |
| 345 |
"""Close the connection to the database.""" |
| 346 |
self.validate_thread_sharing() |
| 347 |
self.run_on_commit = [] |
| 348 |
|
| 349 |
# Don't call validate_no_atomic_block() to avoid making it difficult |
| 350 |
# to get rid of a connection in an invalid state. The next connect() |
| 351 |
# will reset the transaction state anyway. |
| 352 |
if self.closed_in_transaction or self.connection is None: |
| 353 |
return |
| 354 |
try: |
| 355 |
self._close() |
| 356 |
finally: |
| 357 |
if self.in_atomic_block: |
| 358 |
self.closed_in_transaction = True |
| 359 |
self.needs_rollback = True |
| 360 |
else: |
| 361 |
self.connection = None |
| 362 |
|
| 363 |
# ##### Backend-specific savepoint management methods ##### |
| 364 |
|
| 365 |
def _savepoint(self, sid): |
| 366 |
with self.cursor() as cursor: |
| 367 |
cursor.execute(self.ops.savepoint_create_sql(sid)) |
| 368 |
|
| 369 |
def _savepoint_rollback(self, sid): |
| 370 |
with self.cursor() as cursor: |
| 371 |
cursor.execute(self.ops.savepoint_rollback_sql(sid)) |
| 372 |
|
| 373 |
def _savepoint_commit(self, sid): |
| 374 |
with self.cursor() as cursor: |
| 375 |
cursor.execute(self.ops.savepoint_commit_sql(sid)) |
| 376 |
|
| 377 |
def _savepoint_allowed(self): |
| 378 |
# Savepoints cannot be created outside a transaction |
| 379 |
return self.features.uses_savepoints and not self.get_autocommit() |
| 380 |
|
| 381 |
# ##### Generic savepoint management methods ##### |
| 382 |
|
| 383 |
@async_unsafe |
| 384 |
def savepoint(self): |
| 385 |
""" |
| 386 |
Create a savepoint inside the current transaction. Return an |
| 387 |
identifier for the savepoint that will be used for the subsequent |
| 388 |
rollback or commit. Do nothing if savepoints are not supported. |
| 389 |
""" |
| 390 |
if not self._savepoint_allowed(): |
| 391 |
return |
| 392 |
|
| 393 |
thread_ident = _thread.get_ident() |
| 394 |
tid = str(thread_ident).replace("-", "") |
| 395 |
|
| 396 |
self.savepoint_state += 1 |
| 397 |
sid = "s%s_x%d" % (tid, self.savepoint_state) |
| 398 |
|
| 399 |
self.validate_thread_sharing() |
| 400 |
self._savepoint(sid) |
| 401 |
|
| 402 |
return sid |
| 403 |
|
| 404 |
@async_unsafe |
| 405 |
def savepoint_rollback(self, sid): |
| 406 |
""" |
| 407 |
Roll back to a savepoint. Do nothing if savepoints are not supported. |
| 408 |
""" |
| 409 |
if not self._savepoint_allowed(): |
| 410 |
return |
| 411 |
|
| 412 |
self.validate_thread_sharing() |
| 413 |
self._savepoint_rollback(sid) |
| 414 |
|
| 415 |
# Remove any callbacks registered while this savepoint was active. |
| 416 |
self.run_on_commit = [ |
| 417 |
(sids, func, robust) |
| 418 |
for (sids, func, robust) in self.run_on_commit |
| 419 |
if sid not in sids |
| 420 |
] |
| 421 |
|
| 422 |
@async_unsafe |
| 423 |
def savepoint_commit(self, sid): |
| 424 |
""" |
| 425 |
Release a savepoint. Do nothing if savepoints are not supported. |
| 426 |
""" |
| 427 |
if not self._savepoint_allowed(): |
| 428 |
return |
| 429 |
|
| 430 |
self.validate_thread_sharing() |
| 431 |
self._savepoint_commit(sid) |
| 432 |
|
| 433 |
@async_unsafe |
| 434 |
def clean_savepoints(self): |
| 435 |
""" |
| 436 |
Reset the counter used to generate unique savepoint ids in this thread. |
| 437 |
""" |
| 438 |
self.savepoint_state = 0 |
| 439 |
|
| 440 |
# ##### Backend-specific transaction management methods ##### |
| 441 |
|
| 442 |
def _set_autocommit(self, autocommit): |
| 443 |
""" |
| 444 |
Backend-specific implementation to enable or disable autocommit. |
| 445 |
""" |
| 446 |
raise NotImplementedError( |
| 447 |
"subclasses of BaseDatabaseWrapper may require a _set_autocommit() method" |
| 448 |
) |
| 449 |
|
| 450 |
# ##### Generic transaction management methods ##### |
| 451 |
|
| 452 |
def get_autocommit(self): |
| 453 |
"""Get the autocommit state.""" |
| 454 |
self.ensure_connection() |
| 455 |
return self.autocommit |
| 456 |
|
| 457 |
def set_autocommit( |
| 458 |
self, autocommit, force_begin_transaction_with_broken_autocommit=False |
| 459 |
): |
| 460 |
""" |
| 461 |
Enable or disable autocommit. |
| 462 |
|
| 463 |
The usual way to start a transaction is to turn autocommit off. |
| 464 |
SQLite does not properly start a transaction when disabling |
| 465 |
autocommit. To avoid this buggy behavior and to actually enter a new |
| 466 |
transaction, an explicit BEGIN is required. Using |
| 467 |
force_begin_transaction_with_broken_autocommit=True will issue an |
| 468 |
explicit BEGIN with SQLite. This option will be ignored for other |
| 469 |
backends. |
| 470 |
""" |
| 471 |
self.validate_no_atomic_block() |
| 472 |
self.close_if_health_check_failed() |
| 473 |
self.ensure_connection() |
| 474 |
|
| 475 |
start_transaction_under_autocommit = ( |
| 476 |
force_begin_transaction_with_broken_autocommit |
| 477 |
and not autocommit |
| 478 |
and hasattr(self, "_start_transaction_under_autocommit") |
| 479 |
) |
| 480 |
|
| 481 |
if start_transaction_under_autocommit: |
| 482 |
self._start_transaction_under_autocommit() |
| 483 |
elif autocommit: |
| 484 |
self._set_autocommit(autocommit) |
| 485 |
else: |
| 486 |
with debug_transaction(self, "BEGIN"): |
| 487 |
self._set_autocommit(autocommit) |
| 488 |
self.autocommit = autocommit |
| 489 |
|
| 490 |
if autocommit and self.run_commit_hooks_on_set_autocommit_on: |
| 491 |
self.run_and_clear_commit_hooks() |
| 492 |
self.run_commit_hooks_on_set_autocommit_on = False |
| 493 |
|
| 494 |
def get_rollback(self): |
| 495 |
"""Get the "needs rollback" flag -- for *advanced use* only.""" |
| 496 |
if not self.in_atomic_block: |
| 497 |
raise TransactionManagementError( |
| 498 |
"The rollback flag doesn't work outside of an 'atomic' block." |
| 499 |
) |
| 500 |
return self.needs_rollback |
| 501 |
|
| 502 |
def set_rollback(self, rollback): |
| 503 |
""" |
| 504 |
Set or unset the "needs rollback" flag -- for *advanced use* only. |
| 505 |
""" |
| 506 |
if not self.in_atomic_block: |
| 507 |
raise TransactionManagementError( |
| 508 |
"The rollback flag doesn't work outside of an 'atomic' block." |
| 509 |
) |
| 510 |
self.needs_rollback = rollback |
| 511 |
|
| 512 |
def validate_no_atomic_block(self): |
| 513 |
"""Raise an error if an atomic block is active.""" |
| 514 |
if self.in_atomic_block: |
| 515 |
raise TransactionManagementError( |
| 516 |
"This is forbidden when an 'atomic' block is active." |
| 517 |
) |
| 518 |
|
| 519 |
def validate_no_broken_transaction(self): |
| 520 |
if self.needs_rollback: |
| 521 |
raise TransactionManagementError( |
| 522 |
"An error occurred in the current transaction. You can't " |
| 523 |
"execute queries until the end of the 'atomic' block." |
| 524 |
) from self.rollback_exc |
| 525 |
|
| 526 |
# ##### Foreign key constraints checks handling ##### |
| 527 |
|
| 528 |
@contextmanager |
| 529 |
def constraint_checks_disabled(self): |
| 530 |
""" |
| 531 |
Disable foreign key constraint checking. |
| 532 |
""" |
| 533 |
disabled = self.disable_constraint_checking() |
| 534 |
try: |
| 535 |
yield |
| 536 |
finally: |
| 537 |
if disabled: |
| 538 |
self.enable_constraint_checking() |
| 539 |
|
| 540 |
def disable_constraint_checking(self): |
| 541 |
""" |
| 542 |
Backends can implement as needed to temporarily disable foreign key |
| 543 |
constraint checking. Should return True if the constraints were |
| 544 |
disabled and will need to be reenabled. |
| 545 |
""" |
| 546 |
return False |
| 547 |
|
| 548 |
def enable_constraint_checking(self): |
| 549 |
""" |
| 550 |
Backends can implement as needed to re-enable foreign key constraint |
| 551 |
checking. |
| 552 |
""" |
| 553 |
pass |
| 554 |
|
| 555 |
def check_constraints(self, table_names=None): |
| 556 |
""" |
| 557 |
Backends can override this method if they can apply constraint |
| 558 |
checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an |
| 559 |
IntegrityError if any invalid foreign key references are encountered. |
| 560 |
""" |
| 561 |
pass |
| 562 |
|
| 563 |
# ##### Connection termination handling ##### |
| 564 |
|
| 565 |
def is_usable(self): |
| 566 |
""" |
| 567 |
Test if the database connection is usable. |
| 568 |
|
| 569 |
This method may assume that self.connection is not None. |
| 570 |
|
| 571 |
Actual implementations should take care not to raise exceptions |
| 572 |
as that may prevent Django from recycling unusable connections. |
| 573 |
""" |
| 574 |
raise NotImplementedError( |
| 575 |
"subclasses of BaseDatabaseWrapper may require an is_usable() method" |
| 576 |
) |
| 577 |
|
| 578 |
def close_if_health_check_failed(self): |
| 579 |
"""Close existing connection if it fails a health check.""" |
| 580 |
if ( |
| 581 |
self.connection is None |
| 582 |
or not self.health_check_enabled |
| 583 |
or self.health_check_done |
| 584 |
): |
| 585 |
return |
| 586 |
|
| 587 |
if not self.is_usable(): |
| 588 |
self.close() |
| 589 |
self.health_check_done = True |
| 590 |
|
| 591 |
def close_if_unusable_or_obsolete(self): |
| 592 |
""" |
| 593 |
Close the current connection if unrecoverable errors have occurred |
| 594 |
or if it outlived its maximum age. |
| 595 |
""" |
| 596 |
if self.connection is not None: |
| 597 |
self.health_check_done = False |
| 598 |
# If the application didn't restore the original autocommit setting, |
| 599 |
# don't take chances, drop the connection. |
| 600 |
if self.get_autocommit() != self.settings_dict["AUTOCOMMIT"]: |
| 601 |
self.close() |
| 602 |
return |
| 603 |
|
| 604 |
# If an exception other than DataError or IntegrityError occurred |
| 605 |
# since the last commit / rollback, check if the connection works. |
| 606 |
if self.errors_occurred: |
| 607 |
if self.is_usable(): |
| 608 |
self.errors_occurred = False |
| 609 |
self.health_check_done = True |
| 610 |
else: |
| 611 |
self.close() |
| 612 |
return |
| 613 |
|
| 614 |
if self.close_at is not None and time.monotonic() >= self.close_at: |
| 615 |
self.close() |
| 616 |
return |
| 617 |
|
| 618 |
# ##### Thread safety handling ##### |
| 619 |
|
| 620 |
@property |
| 621 |
def allow_thread_sharing(self): |
| 622 |
with self._thread_sharing_lock: |
| 623 |
return self._thread_sharing_count > 0 |
| 624 |
|
| 625 |
def inc_thread_sharing(self): |
| 626 |
with self._thread_sharing_lock: |
| 627 |
self._thread_sharing_count += 1 |
| 628 |
|
| 629 |
def dec_thread_sharing(self): |
| 630 |
with self._thread_sharing_lock: |
| 631 |
if self._thread_sharing_count <= 0: |
| 632 |
raise RuntimeError( |
| 633 |
"Cannot decrement the thread sharing count below zero." |
| 634 |
) |
| 635 |
self._thread_sharing_count -= 1 |
| 636 |
|
| 637 |
def validate_thread_sharing(self): |
| 638 |
""" |
| 639 |
Validate that the connection isn't accessed by another thread than the |
| 640 |
one which originally created it, unless the connection was explicitly |
| 641 |
authorized to be shared between threads (via the `inc_thread_sharing()` |
| 642 |
method). Raise an exception if the validation fails. |
| 643 |
""" |
| 644 |
if not (self.allow_thread_sharing or self._thread_ident == _thread.get_ident()): |
| 645 |
raise DatabaseError( |
| 646 |
"DatabaseWrapper objects created in a " |
| 647 |
"thread can only be used in that same thread. The object " |
| 648 |
"with alias '%s' was created in thread id %s and this is " |
| 649 |
"thread id %s." % (self.alias, self._thread_ident, _thread.get_ident()) |
| 650 |
) |
| 651 |
|
| 652 |
# ##### Miscellaneous ##### |
| 653 |
|
| 654 |
def prepare_database(self): |
| 655 |
""" |
| 656 |
Hook to do any database check or preparation, generally called before |
| 657 |
migrating a project or an app. |
| 658 |
""" |
| 659 |
pass |
| 660 |
|
| 661 |
@cached_property |
| 662 |
def wrap_database_errors(self): |
| 663 |
""" |
| 664 |
Context manager and decorator that re-throws backend-specific database |
| 665 |
exceptions using Django's common wrappers. |
| 666 |
""" |
| 667 |
return DatabaseErrorWrapper(self) |
| 668 |
|
| 669 |
def chunked_cursor(self): |
| 670 |
""" |
| 671 |
Return a cursor that tries to avoid caching in the database (if |
| 672 |
supported by the database), otherwise return a regular cursor. |
| 673 |
""" |
| 674 |
return self.cursor() |
| 675 |
|
| 676 |
def make_debug_cursor(self, cursor): |
| 677 |
"""Create a cursor that logs all queries in self.queries_log.""" |
| 678 |
return utils.CursorDebugWrapper(cursor, self) |
| 679 |
|
| 680 |
def make_cursor(self, cursor): |
| 681 |
"""Create a cursor without debug logging.""" |
| 682 |
return utils.CursorWrapper(cursor, self) |
| 683 |
|
| 684 |
@contextmanager |
| 685 |
def temporary_connection(self): |
| 686 |
""" |
| 687 |
Context manager that ensures that a connection is established, and |
| 688 |
if it opened one, closes it to avoid leaving a dangling connection. |
| 689 |
This is useful for operations outside of the request-response cycle. |
| 690 |
|
| 691 |
Provide a cursor: with self.temporary_connection() as cursor: ... |
| 692 |
""" |
| 693 |
must_close = self.connection is None |
| 694 |
try: |
| 695 |
with self.cursor() as cursor: |
| 696 |
yield cursor |
| 697 |
finally: |
| 698 |
if must_close: |
| 699 |
self.close() |
| 700 |
|
| 701 |
@contextmanager |
| 702 |
def _nodb_cursor(self): |
| 703 |
""" |
| 704 |
Return a cursor from an alternative connection to be used when there is |
| 705 |
no need to access the main database, specifically for test db |
| 706 |
creation/deletion. This also prevents the production database from |
| 707 |
being exposed to potential child threads while (or after) the test |
| 708 |
database is destroyed. Refs #10868, #17786, #16969. |
| 709 |
""" |
| 710 |
conn = self.__class__({**self.settings_dict, "NAME": None}, alias=NO_DB_ALIAS) |
| 711 |
try: |
| 712 |
with conn.cursor() as cursor: |
| 713 |
yield cursor |
| 714 |
finally: |
| 715 |
conn.close() |
| 716 |
|
| 717 |
def schema_editor(self, *args, **kwargs): |
| 718 |
""" |
| 719 |
Return a new instance of this backend's SchemaEditor. |
| 720 |
""" |
| 721 |
if self.SchemaEditorClass is None: |
| 722 |
raise NotImplementedError( |
| 723 |
"The SchemaEditorClass attribute of this database wrapper is still None" |
| 724 |
) |
| 725 |
return self.SchemaEditorClass(self, *args, **kwargs) |
| 726 |
|
| 727 |
def on_commit(self, func, robust=False): |
| 728 |
if not callable(func): |
| 729 |
raise TypeError("on_commit()'s callback must be a callable.") |
| 730 |
if self.in_atomic_block: |
| 731 |
# Transaction in progress; save for execution on commit. |
| 732 |
self.run_on_commit.append((set(self.savepoint_ids), func, robust)) |
| 733 |
elif not self.get_autocommit(): |
| 734 |
raise TransactionManagementError( |
| 735 |
"on_commit() cannot be used in manual transaction management" |
| 736 |
) |
| 737 |
else: |
| 738 |
# No transaction in progress and in autocommit mode; execute |
| 739 |
# immediately. |
| 740 |
if robust: |
| 741 |
try: |
| 742 |
func() |
| 743 |
except Exception as e: |
| 744 |
logger.error( |
| 745 |
f"Error calling {func.__qualname__} in on_commit() (%s).", |
| 746 |
e, |
| 747 |
exc_info=True, |
| 748 |
) |
| 749 |
else: |
| 750 |
func() |
| 751 |
|
| 752 |
def run_and_clear_commit_hooks(self): |
| 753 |
self.validate_no_atomic_block() |
| 754 |
current_run_on_commit = self.run_on_commit |
| 755 |
self.run_on_commit = [] |
| 756 |
while current_run_on_commit: |
| 757 |
_, func, robust = current_run_on_commit.pop(0) |
| 758 |
if robust: |
| 759 |
try: |
| 760 |
func() |
| 761 |
except Exception as e: |
| 762 |
logger.error( |
| 763 |
f"Error calling {func.__qualname__} in on_commit() during " |
| 764 |
f"transaction (%s).", |
| 765 |
e, |
| 766 |
exc_info=True, |
| 767 |
) |
| 768 |
else: |
| 769 |
func() |
| 770 |
|
| 771 |
@contextmanager |
| 772 |
def execute_wrapper(self, wrapper): |
| 773 |
""" |
| 774 |
Return a context manager under which the wrapper is applied to suitable |
| 775 |
database query executions. |
| 776 |
""" |
| 777 |
self.execute_wrappers.append(wrapper) |
| 778 |
try: |
| 779 |
yield |
| 780 |
finally: |
| 781 |
self.execute_wrappers.pop() |
| 782 |
|
| 783 |
def copy(self, alias=None): |
| 784 |
""" |
| 785 |
Return a copy of this connection. |
| 786 |
|
| 787 |
For tests that require two connections to the same database. |
| 788 |
""" |
| 789 |
settings_dict = copy.deepcopy(self.settings_dict) |
| 790 |
if alias is None: |
| 791 |
alias = self.alias |
| 792 |
return type(self)(settings_dict, alias) |