base.py 24 KB

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