You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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