base.py 25 KB

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