base.py 28 KB

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