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.
 
 
 
 

638 lines
22 KiB

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