base.py 28 KB

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