__init__.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. import datetime
  2. import time
  3. from django.db.utils import DatabaseError
  4. try:
  5. from django.utils.six.moves import _thread as thread
  6. except ImportError:
  7. from django.utils.six.moves import _dummy_thread as thread
  8. from collections import namedtuple
  9. from contextlib import contextmanager
  10. from django.conf import settings
  11. from django.db import DEFAULT_DB_ALIAS
  12. from django.db.backends.signals import connection_created
  13. from django.db.backends import util
  14. from django.db.transaction import TransactionManagementError
  15. from django.db.utils import DatabaseErrorWrapper
  16. from django.utils.functional import cached_property
  17. from django.utils.importlib import import_module
  18. from django.utils import six
  19. from django.utils import timezone
  20. class BaseDatabaseWrapper(object):
  21. """
  22. Represents a database connection.
  23. """
  24. ops = None
  25. vendor = 'unknown'
  26. def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS,
  27. allow_thread_sharing=False):
  28. # `settings_dict` should be a dictionary containing keys such as
  29. # NAME, USER, etc. It's called `settings_dict` instead of `settings`
  30. # to disambiguate it from Django settings modules.
  31. self.connection = None
  32. self.queries = []
  33. self.settings_dict = settings_dict
  34. self.alias = alias
  35. self.use_debug_cursor = None
  36. # Savepoint management related attributes
  37. self.savepoint_state = 0
  38. # Transaction management related attributes
  39. self.autocommit = False
  40. self.transaction_state = []
  41. # Tracks if the connection is believed to be in transaction. This is
  42. # set somewhat aggressively, as the DBAPI doesn't make it easy to
  43. # deduce if the connection is in transaction or not.
  44. self._dirty = False
  45. # Tracks if the connection is in a transaction managed by 'atomic'.
  46. self.in_atomic_block = False
  47. # List of savepoints created by 'atomic'
  48. self.savepoint_ids = []
  49. # Tracks if the outermost 'atomic' block should commit on exit,
  50. # ie. if autocommit was active on entry.
  51. self.commit_on_exit = True
  52. # Tracks if the transaction should be rolled back to the next
  53. # available savepoint because of an exception in an inner block.
  54. self.needs_rollback = False
  55. # Connection termination related attributes
  56. self.close_at = None
  57. self.errors_occurred = False
  58. # Thread-safety related attributes
  59. self.allow_thread_sharing = allow_thread_sharing
  60. self._thread_ident = thread.get_ident()
  61. def __eq__(self, other):
  62. if isinstance(other, BaseDatabaseWrapper):
  63. return self.alias == other.alias
  64. return NotImplemented
  65. def __ne__(self, other):
  66. return not self == other
  67. def __hash__(self):
  68. return hash(self.alias)
  69. ##### Backend-specific methods for creating connections and cursors #####
  70. def get_connection_params(self):
  71. """Returns a dict of parameters suitable for get_new_connection."""
  72. raise NotImplementedError
  73. def get_new_connection(self, conn_params):
  74. """Opens a connection to the database."""
  75. raise NotImplementedError
  76. def init_connection_state(self):
  77. """Initializes the database connection settings."""
  78. raise NotImplementedError
  79. def create_cursor(self):
  80. """Creates a cursor. Assumes that a connection is established."""
  81. raise NotImplementedError
  82. ##### Backend-specific methods for creating connections #####
  83. def connect(self):
  84. """Connects to the database. Assumes that the connection is closed."""
  85. # In case the previous connection was closed while in an atomic block
  86. self.in_atomic_block = False
  87. self.savepoint_ids = []
  88. # Reset parameters defining when to close the connection
  89. max_age = self.settings_dict['CONN_MAX_AGE']
  90. self.close_at = None if max_age is None else time.time() + max_age
  91. self.errors_occurred = False
  92. # Establish the connection
  93. conn_params = self.get_connection_params()
  94. self.connection = self.get_new_connection(conn_params)
  95. self.init_connection_state()
  96. if self.settings_dict['AUTOCOMMIT']:
  97. self.set_autocommit(True)
  98. connection_created.send(sender=self.__class__, connection=self)
  99. def ensure_connection(self):
  100. """
  101. Guarantees that a connection to the database is established.
  102. """
  103. if self.connection is None:
  104. with self.wrap_database_errors():
  105. self.connect()
  106. ##### Backend-specific wrappers for PEP-249 connection methods #####
  107. def _cursor(self):
  108. self.ensure_connection()
  109. with self.wrap_database_errors():
  110. return self.create_cursor()
  111. def _commit(self):
  112. if self.connection is not None:
  113. with self.wrap_database_errors():
  114. return self.connection.commit()
  115. def _rollback(self):
  116. if self.connection is not None:
  117. with self.wrap_database_errors():
  118. return self.connection.rollback()
  119. def _close(self):
  120. if self.connection is not None:
  121. with self.wrap_database_errors():
  122. return self.connection.close()
  123. ##### Generic wrappers for PEP-249 connection methods #####
  124. def cursor(self):
  125. """
  126. Creates a cursor, opening a connection if necessary.
  127. """
  128. self.validate_thread_sharing()
  129. if (self.use_debug_cursor or
  130. (self.use_debug_cursor is None and settings.DEBUG)):
  131. cursor = self.make_debug_cursor(self._cursor())
  132. else:
  133. cursor = util.CursorWrapper(self._cursor(), self)
  134. return cursor
  135. def commit(self):
  136. """
  137. Commits a transaction and resets the dirty flag.
  138. """
  139. self.validate_thread_sharing()
  140. self.validate_no_atomic_block()
  141. self._commit()
  142. self.set_clean()
  143. def rollback(self):
  144. """
  145. Rolls back a transaction and resets the dirty flag.
  146. """
  147. self.validate_thread_sharing()
  148. self.validate_no_atomic_block()
  149. self._rollback()
  150. self.set_clean()
  151. def close(self):
  152. """
  153. Closes the connection to the database.
  154. """
  155. self.validate_thread_sharing()
  156. # Don't call validate_no_atomic_block() to avoid making it difficult
  157. # to get rid of a connection in an invalid state. The next connect()
  158. # will reset the transaction state anyway.
  159. try:
  160. self._close()
  161. finally:
  162. self.connection = None
  163. self.set_clean()
  164. ##### Backend-specific savepoint management methods #####
  165. def _savepoint(self, sid):
  166. self.cursor().execute(self.ops.savepoint_create_sql(sid))
  167. def _savepoint_rollback(self, sid):
  168. self.cursor().execute(self.ops.savepoint_rollback_sql(sid))
  169. def _savepoint_commit(self, sid):
  170. self.cursor().execute(self.ops.savepoint_commit_sql(sid))
  171. def _savepoint_allowed(self):
  172. # Savepoints cannot be created outside a transaction
  173. return self.features.uses_savepoints and not self.get_autocommit()
  174. ##### Generic savepoint management methods #####
  175. def savepoint(self):
  176. """
  177. Creates a savepoint inside the current transaction. Returns an
  178. identifier for the savepoint that will be used for the subsequent
  179. rollback or commit. Does nothing if savepoints are not supported.
  180. """
  181. if not self._savepoint_allowed():
  182. return
  183. thread_ident = thread.get_ident()
  184. tid = str(thread_ident).replace('-', '')
  185. self.savepoint_state += 1
  186. sid = "s%s_x%d" % (tid, self.savepoint_state)
  187. self.validate_thread_sharing()
  188. self._savepoint(sid)
  189. return sid
  190. def savepoint_rollback(self, sid):
  191. """
  192. Rolls back to a savepoint. Does nothing if savepoints are not supported.
  193. """
  194. if not self._savepoint_allowed():
  195. return
  196. self.validate_thread_sharing()
  197. self._savepoint_rollback(sid)
  198. def savepoint_commit(self, sid):
  199. """
  200. Releases a savepoint. Does nothing if savepoints are not supported.
  201. """
  202. if not self._savepoint_allowed():
  203. return
  204. self.validate_thread_sharing()
  205. self._savepoint_commit(sid)
  206. def clean_savepoints(self):
  207. """
  208. Resets the counter used to generate unique savepoint ids in this thread.
  209. """
  210. self.savepoint_state = 0
  211. ##### Backend-specific transaction management methods #####
  212. def _set_autocommit(self, autocommit):
  213. """
  214. Backend-specific implementation to enable or disable autocommit.
  215. """
  216. raise NotImplementedError
  217. ##### Generic transaction management methods #####
  218. def enter_transaction_management(self, managed=True, forced=False):
  219. """
  220. Enters transaction management for a running thread. It must be balanced with
  221. the appropriate leave_transaction_management call, since the actual state is
  222. managed as a stack.
  223. The state and dirty flag are carried over from the surrounding block or
  224. from the settings, if there is no surrounding block (dirty is always false
  225. when no current block is running).
  226. If you switch off transaction management and there is a pending
  227. commit/rollback, the data will be commited, unless "forced" is True.
  228. """
  229. self.validate_no_atomic_block()
  230. self.transaction_state.append(managed)
  231. if not managed and self.is_dirty() and not forced:
  232. self.commit()
  233. self.set_clean()
  234. if managed == self.get_autocommit():
  235. self.set_autocommit(not managed)
  236. def leave_transaction_management(self):
  237. """
  238. Leaves transaction management for a running thread. A dirty flag is carried
  239. over to the surrounding block, as a commit will commit all changes, even
  240. those from outside. (Commits are on connection level.)
  241. """
  242. self.validate_no_atomic_block()
  243. if self.transaction_state:
  244. del self.transaction_state[-1]
  245. else:
  246. raise TransactionManagementError(
  247. "This code isn't under transaction management")
  248. if self.transaction_state:
  249. managed = self.transaction_state[-1]
  250. else:
  251. managed = not self.settings_dict['AUTOCOMMIT']
  252. if self._dirty:
  253. self.rollback()
  254. if managed == self.get_autocommit():
  255. self.set_autocommit(not managed)
  256. raise TransactionManagementError(
  257. "Transaction managed block ended with pending COMMIT/ROLLBACK")
  258. if managed == self.get_autocommit():
  259. self.set_autocommit(not managed)
  260. def get_autocommit(self):
  261. """
  262. Check the autocommit state.
  263. """
  264. self.ensure_connection()
  265. return self.autocommit
  266. def set_autocommit(self, autocommit):
  267. """
  268. Enable or disable autocommit.
  269. """
  270. self.validate_no_atomic_block()
  271. self.ensure_connection()
  272. self._set_autocommit(autocommit)
  273. self.autocommit = autocommit
  274. def get_rollback(self):
  275. """
  276. Get the "needs rollback" flag -- for *advanced use* only.
  277. """
  278. if not self.in_atomic_block:
  279. raise TransactionManagementError(
  280. "The rollback flag doesn't work outside of an 'atomic' block.")
  281. return self.needs_rollback
  282. def set_rollback(self, rollback):
  283. """
  284. Set or unset the "needs rollback" flag -- for *advanced use* only.
  285. """
  286. if not self.in_atomic_block:
  287. raise TransactionManagementError(
  288. "The rollback flag doesn't work outside of an 'atomic' block.")
  289. self.needs_rollback = rollback
  290. def validate_no_atomic_block(self):
  291. """
  292. Raise an error if an atomic block is active.
  293. """
  294. if self.in_atomic_block:
  295. raise TransactionManagementError(
  296. "This is forbidden when an 'atomic' block is active.")
  297. def abort(self):
  298. """
  299. Roll back any ongoing transaction and clean the transaction state
  300. stack.
  301. """
  302. if self._dirty:
  303. self.rollback()
  304. while self.transaction_state:
  305. self.leave_transaction_management()
  306. def is_dirty(self):
  307. """
  308. Returns True if the current transaction requires a commit for changes to
  309. happen.
  310. """
  311. return self._dirty
  312. def set_dirty(self):
  313. """
  314. Sets a dirty flag for the current thread and code streak. This can be used
  315. to decide in a managed block of code to decide whether there are open
  316. changes waiting for commit.
  317. """
  318. if not self.get_autocommit():
  319. self._dirty = True
  320. def set_clean(self):
  321. """
  322. Resets a dirty flag for the current thread and code streak. This can be used
  323. to decide in a managed block of code to decide whether a commit or rollback
  324. should happen.
  325. """
  326. self._dirty = False
  327. self.clean_savepoints()
  328. ##### Foreign key constraints checks handling #####
  329. @contextmanager
  330. def constraint_checks_disabled(self):
  331. """
  332. Context manager that disables foreign key constraint checking.
  333. """
  334. disabled = self.disable_constraint_checking()
  335. try:
  336. yield
  337. finally:
  338. if disabled:
  339. self.enable_constraint_checking()
  340. def disable_constraint_checking(self):
  341. """
  342. Backends can implement as needed to temporarily disable foreign key
  343. constraint checking. Should return True if the constraints were
  344. disabled and will need to be reenabled.
  345. """
  346. return False
  347. def enable_constraint_checking(self):
  348. """
  349. Backends can implement as needed to re-enable foreign key constraint
  350. checking.
  351. """
  352. pass
  353. def check_constraints(self, table_names=None):
  354. """
  355. Backends can override this method if they can apply constraint
  356. checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an
  357. IntegrityError if any invalid foreign key references are encountered.
  358. """
  359. pass
  360. ##### Connection termination handling #####
  361. def is_usable(self):
  362. """
  363. Tests if the database connection is usable.
  364. This function may assume that self.connection is not None.
  365. """
  366. raise NotImplementedError
  367. def close_if_unusable_or_obsolete(self):
  368. """
  369. Closes the current connection if unrecoverable errors have occurred,
  370. or if it outlived its maximum age.
  371. """
  372. if self.connection is not None:
  373. # If the application didn't restore the original autocommit setting,
  374. # don't take chances, drop the connection.
  375. if self.get_autocommit() != self.settings_dict['AUTOCOMMIT']:
  376. self.close()
  377. return
  378. if self.errors_occurred:
  379. if self.is_usable():
  380. self.errors_occurred = False
  381. else:
  382. self.close()
  383. return
  384. if self.close_at is not None and time.time() >= self.close_at:
  385. self.close()
  386. return
  387. ##### Thread safety handling #####
  388. def validate_thread_sharing(self):
  389. """
  390. Validates that the connection isn't accessed by another thread than the
  391. one which originally created it, unless the connection was explicitly
  392. authorized to be shared between threads (via the `allow_thread_sharing`
  393. property). Raises an exception if the validation fails.
  394. """
  395. if not (self.allow_thread_sharing
  396. or self._thread_ident == thread.get_ident()):
  397. raise DatabaseError("DatabaseWrapper objects created in a "
  398. "thread can only be used in that same thread. The object "
  399. "with alias '%s' was created in thread id %s and this is "
  400. "thread id %s."
  401. % (self.alias, self._thread_ident, thread.get_ident()))
  402. ##### Miscellaneous #####
  403. def wrap_database_errors(self):
  404. """
  405. Context manager and decorator that re-throws backend-specific database
  406. exceptions using Django's common wrappers.
  407. """
  408. return DatabaseErrorWrapper(self)
  409. def make_debug_cursor(self, cursor):
  410. """
  411. Creates a cursor that logs all queries in self.queries.
  412. """
  413. return util.CursorDebugWrapper(cursor, self)
  414. @contextmanager
  415. def temporary_connection(self):
  416. """
  417. Context manager that ensures that a connection is established, and
  418. if it opened one, closes it to avoid leaving a dangling connection.
  419. This is useful for operations outside of the request-response cycle.
  420. Provides a cursor: with self.temporary_connection() as cursor: ...
  421. """
  422. must_close = self.connection is None
  423. cursor = self.cursor()
  424. try:
  425. yield cursor
  426. finally:
  427. cursor.close()
  428. if must_close:
  429. self.close()
  430. def _start_transaction_under_autocommit(self):
  431. """
  432. Only required when autocommits_when_autocommit_is_off = True.
  433. """
  434. raise NotImplementedError
  435. def schema_editor(self):
  436. "Returns a new instance of this backend's SchemaEditor"
  437. raise NotImplementedError()
  438. class BaseDatabaseFeatures(object):
  439. allows_group_by_pk = False
  440. # True if django.db.backend.utils.typecast_timestamp is used on values
  441. # returned from dates() calls.
  442. needs_datetime_string_cast = True
  443. empty_fetchmany_value = []
  444. update_can_self_select = True
  445. # Does the backend distinguish between '' and None?
  446. interprets_empty_strings_as_nulls = False
  447. # Does the backend allow inserting duplicate rows when a unique_together
  448. # constraint exists, but one of the unique_together columns is NULL?
  449. ignores_nulls_in_unique_constraints = True
  450. can_use_chunked_reads = True
  451. can_return_id_from_insert = False
  452. has_bulk_insert = False
  453. uses_savepoints = False
  454. can_combine_inserts_with_and_without_auto_increment_pk = False
  455. # If True, don't use integer foreign keys referring to, e.g., positive
  456. # integer primary keys.
  457. related_fields_match_type = False
  458. allow_sliced_subqueries = True
  459. has_select_for_update = False
  460. has_select_for_update_nowait = False
  461. supports_select_related = True
  462. # Does the default test database allow multiple connections?
  463. # Usually an indication that the test database is in-memory
  464. test_db_allows_multiple_connections = True
  465. # Can an object be saved without an explicit primary key?
  466. supports_unspecified_pk = False
  467. # Can a fixture contain forward references? i.e., are
  468. # FK constraints checked at the end of transaction, or
  469. # at the end of each save operation?
  470. supports_forward_references = True
  471. # Does a dirty transaction need to be rolled back
  472. # before the cursor can be used again?
  473. requires_rollback_on_dirty_transaction = False
  474. # Does the backend allow very long model names without error?
  475. supports_long_model_names = True
  476. # Is there a REAL datatype in addition to floats/doubles?
  477. has_real_datatype = False
  478. supports_subqueries_in_group_by = True
  479. supports_bitwise_or = True
  480. # Do time/datetime fields have microsecond precision?
  481. supports_microsecond_precision = True
  482. # Does the __regex lookup support backreferencing and grouping?
  483. supports_regex_backreferencing = True
  484. # Can date/datetime lookups be performed using a string?
  485. supports_date_lookup_using_string = True
  486. # Can datetimes with timezones be used?
  487. supports_timezones = True
  488. # Does the database have a copy of the zoneinfo database?
  489. has_zoneinfo_database = True
  490. # When performing a GROUP BY, is an ORDER BY NULL required
  491. # to remove any ordering?
  492. requires_explicit_null_ordering_when_grouping = False
  493. # Is there a 1000 item limit on query parameters?
  494. supports_1000_query_parameters = True
  495. # Can an object have a primary key of 0? MySQL says No.
  496. allows_primary_key_0 = True
  497. # Do we need to NULL a ForeignKey out, or can the constraint check be
  498. # deferred
  499. can_defer_constraint_checks = False
  500. # date_interval_sql can properly handle mixed Date/DateTime fields and timedeltas
  501. supports_mixed_date_datetime_comparisons = True
  502. # Does the backend support tablespaces? Default to False because it isn't
  503. # in the SQL standard.
  504. supports_tablespaces = False
  505. # Does the backend reset sequences between tests?
  506. supports_sequence_reset = True
  507. # Confirm support for introspected foreign keys
  508. # Every database can do this reliably, except MySQL,
  509. # which can't do it for MyISAM tables
  510. can_introspect_foreign_keys = True
  511. # Support for the DISTINCT ON clause
  512. can_distinct_on_fields = False
  513. # Does the backend decide to commit before SAVEPOINT statements
  514. # when autocommit is disabled? http://bugs.python.org/issue8145#msg109965
  515. autocommits_when_autocommit_is_off = False
  516. # Can we roll back DDL in a transaction?
  517. can_rollback_ddl = False
  518. # Can we issue more than one ALTER COLUMN clause in an ALTER TABLE?
  519. supports_combined_alters = False
  520. # What's the maximum length for index names?
  521. max_index_name_length = 63
  522. # Does it support foreign keys?
  523. supports_foreign_keys = True
  524. # Does it support CHECK constraints?
  525. supports_check_constraints = True
  526. # Does the backend support 'pyformat' style ("... %(name)s ...", {'name': value})
  527. # parameter passing? Note this can be provided by the backend even if not
  528. # supported by the Python driver
  529. supports_paramstyle_pyformat = True
  530. def __init__(self, connection):
  531. self.connection = connection
  532. @cached_property
  533. def supports_transactions(self):
  534. "Confirm support for transactions"
  535. try:
  536. # Make sure to run inside a managed transaction block,
  537. # otherwise autocommit will cause the confimation to
  538. # fail.
  539. self.connection.enter_transaction_management()
  540. cursor = self.connection.cursor()
  541. cursor.execute('CREATE TABLE ROLLBACK_TEST (X INT)')
  542. self.connection.commit()
  543. cursor.execute('INSERT INTO ROLLBACK_TEST (X) VALUES (8)')
  544. self.connection.rollback()
  545. cursor.execute('SELECT COUNT(X) FROM ROLLBACK_TEST')
  546. count, = cursor.fetchone()
  547. cursor.execute('DROP TABLE ROLLBACK_TEST')
  548. self.connection.commit()
  549. finally:
  550. self.connection.leave_transaction_management()
  551. return count == 0
  552. @cached_property
  553. def supports_stddev(self):
  554. "Confirm support for STDDEV and related stats functions"
  555. class StdDevPop(object):
  556. sql_function = 'STDDEV_POP'
  557. try:
  558. self.connection.ops.check_aggregate_support(StdDevPop())
  559. return True
  560. except NotImplementedError:
  561. return False
  562. class BaseDatabaseOperations(object):
  563. """
  564. This class encapsulates all backend-specific differences, such as the way
  565. a backend performs ordering or calculates the ID of a recently-inserted
  566. row.
  567. """
  568. compiler_module = "django.db.models.sql.compiler"
  569. def __init__(self, connection):
  570. self.connection = connection
  571. self._cache = None
  572. def autoinc_sql(self, table, column):
  573. """
  574. Returns any SQL needed to support auto-incrementing primary keys, or
  575. None if no SQL is necessary.
  576. This SQL is executed when a table is created.
  577. """
  578. return None
  579. def bulk_batch_size(self, fields, objs):
  580. """
  581. Returns the maximum allowed batch size for the backend. The fields
  582. are the fields going to be inserted in the batch, the objs contains
  583. all the objects to be inserted.
  584. """
  585. return len(objs)
  586. def cache_key_culling_sql(self):
  587. """
  588. Returns a SQL query that retrieves the first cache key greater than the
  589. n smallest.
  590. This is used by the 'db' cache backend to determine where to start
  591. culling.
  592. """
  593. return "SELECT cache_key FROM %s ORDER BY cache_key LIMIT 1 OFFSET %%s"
  594. def date_extract_sql(self, lookup_type, field_name):
  595. """
  596. Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
  597. extracts a value from the given date field field_name.
  598. """
  599. raise NotImplementedError()
  600. def date_interval_sql(self, sql, connector, timedelta):
  601. """
  602. Implements the date interval functionality for expressions
  603. """
  604. raise NotImplementedError()
  605. def date_trunc_sql(self, lookup_type, field_name):
  606. """
  607. Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
  608. truncates the given date field field_name to a date object with only
  609. the given specificity.
  610. """
  611. raise NotImplementedError()
  612. def datetime_cast_sql(self):
  613. """
  614. Returns the SQL necessary to cast a datetime value so that it will be
  615. retrieved as a Python datetime object instead of a string.
  616. This SQL should include a '%s' in place of the field's name.
  617. """
  618. return "%s"
  619. def datetime_extract_sql(self, lookup_type, field_name, tzname):
  620. """
  621. Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or
  622. 'second', returns the SQL that extracts a value from the given
  623. datetime field field_name, and a tuple of parameters.
  624. """
  625. raise NotImplementedError()
  626. def datetime_trunc_sql(self, lookup_type, field_name, tzname):
  627. """
  628. Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or
  629. 'second', returns the SQL that truncates the given datetime field
  630. field_name to a datetime object with only the given specificity, and
  631. a tuple of parameters.
  632. """
  633. raise NotImplementedError()
  634. def deferrable_sql(self):
  635. """
  636. Returns the SQL necessary to make a constraint "initially deferred"
  637. during a CREATE TABLE statement.
  638. """
  639. return ''
  640. def distinct_sql(self, fields):
  641. """
  642. Returns an SQL DISTINCT clause which removes duplicate rows from the
  643. result set. If any fields are given, only the given fields are being
  644. checked for duplicates.
  645. """
  646. if fields:
  647. raise NotImplementedError('DISTINCT ON fields is not supported by this database backend')
  648. else:
  649. return 'DISTINCT'
  650. def drop_foreignkey_sql(self):
  651. """
  652. Returns the SQL command that drops a foreign key.
  653. """
  654. return "DROP CONSTRAINT"
  655. def drop_sequence_sql(self, table):
  656. """
  657. Returns any SQL necessary to drop the sequence for the given table.
  658. Returns None if no SQL is necessary.
  659. """
  660. return None
  661. def fetch_returned_insert_id(self, cursor):
  662. """
  663. Given a cursor object that has just performed an INSERT...RETURNING
  664. statement into a table that has an auto-incrementing ID, returns the
  665. newly created ID.
  666. """
  667. return cursor.fetchone()[0]
  668. def field_cast_sql(self, db_type, internal_type):
  669. """
  670. Given a column type (e.g. 'BLOB', 'VARCHAR'), and an internal type
  671. (e.g. 'GenericIPAddressField'), returns the SQL necessary to cast it
  672. before using it in a WHERE statement. Note that the resulting string
  673. should contain a '%s' placeholder for the column being searched against.
  674. """
  675. return '%s'
  676. def force_no_ordering(self):
  677. """
  678. Returns a list used in the "ORDER BY" clause to force no ordering at
  679. all. Returning an empty list means that nothing will be included in the
  680. ordering.
  681. """
  682. return []
  683. def for_update_sql(self, nowait=False):
  684. """
  685. Returns the FOR UPDATE SQL clause to lock rows for an update operation.
  686. """
  687. if nowait:
  688. return 'FOR UPDATE NOWAIT'
  689. else:
  690. return 'FOR UPDATE'
  691. def fulltext_search_sql(self, field_name):
  692. """
  693. Returns the SQL WHERE clause to use in order to perform a full-text
  694. search of the given field_name. Note that the resulting string should
  695. contain a '%s' placeholder for the value being searched against.
  696. """
  697. raise NotImplementedError('Full-text search is not implemented for this database backend')
  698. def last_executed_query(self, cursor, sql, params):
  699. """
  700. Returns a string of the query last executed by the given cursor, with
  701. placeholders replaced with actual values.
  702. `sql` is the raw query containing placeholders, and `params` is the
  703. sequence of parameters. These are used by default, but this method
  704. exists for database backends to provide a better implementation
  705. according to their own quoting schemes.
  706. """
  707. from django.utils.encoding import force_text
  708. # Convert params to contain Unicode values.
  709. to_unicode = lambda s: force_text(s, strings_only=True, errors='replace')
  710. if isinstance(params, (list, tuple)):
  711. u_params = tuple(to_unicode(val) for val in params)
  712. elif params is None:
  713. u_params = ()
  714. else:
  715. u_params = dict((to_unicode(k), to_unicode(v)) for k, v in params.items())
  716. return six.text_type("QUERY = %r - PARAMS = %r") % (sql, u_params)
  717. def last_insert_id(self, cursor, table_name, pk_name):
  718. """
  719. Given a cursor object that has just performed an INSERT statement into
  720. a table that has an auto-incrementing ID, returns the newly created ID.
  721. This method also receives the table name and the name of the primary-key
  722. column.
  723. """
  724. return cursor.lastrowid
  725. def lookup_cast(self, lookup_type):
  726. """
  727. Returns the string to use in a query when performing lookups
  728. ("contains", "like", etc). The resulting string should contain a '%s'
  729. placeholder for the column being searched against.
  730. """
  731. return "%s"
  732. def max_in_list_size(self):
  733. """
  734. Returns the maximum number of items that can be passed in a single 'IN'
  735. list condition, or None if the backend does not impose a limit.
  736. """
  737. return None
  738. def max_name_length(self):
  739. """
  740. Returns the maximum length of table and column names, or None if there
  741. is no limit.
  742. """
  743. return None
  744. def no_limit_value(self):
  745. """
  746. Returns the value to use for the LIMIT when we are wanting "LIMIT
  747. infinity". Returns None if the limit clause can be omitted in this case.
  748. """
  749. raise NotImplementedError
  750. def pk_default_value(self):
  751. """
  752. Returns the value to use during an INSERT statement to specify that
  753. the field should use its default value.
  754. """
  755. return 'DEFAULT'
  756. def process_clob(self, value):
  757. """
  758. Returns the value of a CLOB column, for backends that return a locator
  759. object that requires additional processing.
  760. """
  761. return value
  762. def return_insert_id(self):
  763. """
  764. For backends that support returning the last insert ID as part
  765. of an insert query, this method returns the SQL and params to
  766. append to the INSERT query. The returned fragment should
  767. contain a format string to hold the appropriate column.
  768. """
  769. pass
  770. def compiler(self, compiler_name):
  771. """
  772. Returns the SQLCompiler class corresponding to the given name,
  773. in the namespace corresponding to the `compiler_module` attribute
  774. on this backend.
  775. """
  776. if self._cache is None:
  777. self._cache = import_module(self.compiler_module)
  778. return getattr(self._cache, compiler_name)
  779. def quote_name(self, name):
  780. """
  781. Returns a quoted version of the given table, index or column name. Does
  782. not quote the given name if it's already been quoted.
  783. """
  784. raise NotImplementedError()
  785. def random_function_sql(self):
  786. """
  787. Returns a SQL expression that returns a random value.
  788. """
  789. return 'RANDOM()'
  790. def regex_lookup(self, lookup_type):
  791. """
  792. Returns the string to use in a query when performing regular expression
  793. lookups (using "regex" or "iregex"). The resulting string should
  794. contain a '%s' placeholder for the column being searched against.
  795. If the feature is not supported (or part of it is not supported), a
  796. NotImplementedError exception can be raised.
  797. """
  798. raise NotImplementedError
  799. def savepoint_create_sql(self, sid):
  800. """
  801. Returns the SQL for starting a new savepoint. Only required if the
  802. "uses_savepoints" feature is True. The "sid" parameter is a string
  803. for the savepoint id.
  804. """
  805. return "SAVEPOINT %s" % self.quote_name(sid)
  806. def savepoint_commit_sql(self, sid):
  807. """
  808. Returns the SQL for committing the given savepoint.
  809. """
  810. return "RELEASE SAVEPOINT %s" % self.quote_name(sid)
  811. def savepoint_rollback_sql(self, sid):
  812. """
  813. Returns the SQL for rolling back the given savepoint.
  814. """
  815. return "ROLLBACK TO SAVEPOINT %s" % self.quote_name(sid)
  816. def set_time_zone_sql(self):
  817. """
  818. Returns the SQL that will set the connection's time zone.
  819. Returns '' if the backend doesn't support time zones.
  820. """
  821. return ''
  822. def sql_flush(self, style, tables, sequences, allow_cascade=False):
  823. """
  824. Returns a list of SQL statements required to remove all data from
  825. the given database tables (without actually removing the tables
  826. themselves).
  827. The returned value also includes SQL statements required to reset DB
  828. sequences passed in :param sequences:.
  829. The `style` argument is a Style object as returned by either
  830. color_style() or no_style() in django.core.management.color.
  831. The `allow_cascade` argument determines whether truncation may cascade
  832. to tables with foreign keys pointing the tables being truncated.
  833. PostgreSQL requires a cascade even if these tables are empty.
  834. """
  835. raise NotImplementedError()
  836. def sequence_reset_by_name_sql(self, style, sequences):
  837. """
  838. Returns a list of the SQL statements required to reset sequences
  839. passed in :param sequences:.
  840. The `style` argument is a Style object as returned by either
  841. color_style() or no_style() in django.core.management.color.
  842. """
  843. return []
  844. def sequence_reset_sql(self, style, model_list):
  845. """
  846. Returns a list of the SQL statements required to reset sequences for
  847. the given models.
  848. The `style` argument is a Style object as returned by either
  849. color_style() or no_style() in django.core.management.color.
  850. """
  851. return [] # No sequence reset required by default.
  852. def start_transaction_sql(self):
  853. """
  854. Returns the SQL statement required to start a transaction.
  855. """
  856. return "BEGIN;"
  857. def end_transaction_sql(self, success=True):
  858. """
  859. Returns the SQL statement required to end a transaction.
  860. """
  861. if not success:
  862. return "ROLLBACK;"
  863. return "COMMIT;"
  864. def tablespace_sql(self, tablespace, inline=False):
  865. """
  866. Returns the SQL that will be used in a query to define the tablespace.
  867. Returns '' if the backend doesn't support tablespaces.
  868. If inline is True, the SQL is appended to a row; otherwise it's appended
  869. to the entire CREATE TABLE or CREATE INDEX statement.
  870. """
  871. return ''
  872. def prep_for_like_query(self, x):
  873. """Prepares a value for use in a LIKE query."""
  874. from django.utils.encoding import force_text
  875. return force_text(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_")
  876. # Same as prep_for_like_query(), but called for "iexact" matches, which
  877. # need not necessarily be implemented using "LIKE" in the backend.
  878. prep_for_iexact_query = prep_for_like_query
  879. def validate_autopk_value(self, value):
  880. """
  881. Certain backends do not accept some values for "serial" fields
  882. (for example zero in MySQL). This method will raise a ValueError
  883. if the value is invalid, otherwise returns validated value.
  884. """
  885. return value
  886. def value_to_db_date(self, value):
  887. """
  888. Transform a date value to an object compatible with what is expected
  889. by the backend driver for date columns.
  890. """
  891. if value is None:
  892. return None
  893. return six.text_type(value)
  894. def value_to_db_datetime(self, value):
  895. """
  896. Transform a datetime value to an object compatible with what is expected
  897. by the backend driver for datetime columns.
  898. """
  899. if value is None:
  900. return None
  901. return six.text_type(value)
  902. def value_to_db_time(self, value):
  903. """
  904. Transform a time value to an object compatible with what is expected
  905. by the backend driver for time columns.
  906. """
  907. if value is None:
  908. return None
  909. if timezone.is_aware(value):
  910. raise ValueError("Django does not support timezone-aware times.")
  911. return six.text_type(value)
  912. def value_to_db_decimal(self, value, max_digits, decimal_places):
  913. """
  914. Transform a decimal.Decimal value to an object compatible with what is
  915. expected by the backend driver for decimal (numeric) columns.
  916. """
  917. if value is None:
  918. return None
  919. return util.format_number(value, max_digits, decimal_places)
  920. def year_lookup_bounds_for_date_field(self, value):
  921. """
  922. Returns a two-elements list with the lower and upper bound to be used
  923. with a BETWEEN operator to query a DateField value using a year
  924. lookup.
  925. `value` is an int, containing the looked-up year.
  926. """
  927. first = datetime.date(value, 1, 1)
  928. second = datetime.date(value, 12, 31)
  929. return [first, second]
  930. def year_lookup_bounds_for_datetime_field(self, value):
  931. """
  932. Returns a two-elements list with the lower and upper bound to be used
  933. with a BETWEEN operator to query a DateTimeField value using a year
  934. lookup.
  935. `value` is an int, containing the looked-up year.
  936. """
  937. first = datetime.datetime(value, 1, 1)
  938. second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999)
  939. if settings.USE_TZ:
  940. tz = timezone.get_current_timezone()
  941. first = timezone.make_aware(first, tz)
  942. second = timezone.make_aware(second, tz)
  943. return [first, second]
  944. def convert_values(self, value, field):
  945. """
  946. Coerce the value returned by the database backend into a consistent type
  947. that is compatible with the field type.
  948. """
  949. if value is None:
  950. return value
  951. internal_type = field.get_internal_type()
  952. if internal_type == 'FloatField':
  953. return float(value)
  954. elif (internal_type and (internal_type.endswith('IntegerField')
  955. or internal_type == 'AutoField')):
  956. return int(value)
  957. return value
  958. def check_aggregate_support(self, aggregate_func):
  959. """Check that the backend supports the provided aggregate
  960. This is used on specific backends to rule out known aggregates
  961. that are known to have faulty implementations. If the named
  962. aggregate function has a known problem, the backend should
  963. raise NotImplementedError.
  964. """
  965. pass
  966. def combine_expression(self, connector, sub_expressions):
  967. """Combine a list of subexpressions into a single expression, using
  968. the provided connecting operator. This is required because operators
  969. can vary between backends (e.g., Oracle with %% and &) and between
  970. subexpression types (e.g., date expressions)
  971. """
  972. conn = ' %s ' % connector
  973. return conn.join(sub_expressions)
  974. def modify_insert_params(self, placeholders, params):
  975. """Allow modification of insert parameters. Needed for Oracle Spatial
  976. backend due to #10888.
  977. """
  978. return params
  979. # Structure returned by the DB-API cursor.description interface (PEP 249)
  980. FieldInfo = namedtuple('FieldInfo',
  981. 'name type_code display_size internal_size precision scale null_ok'
  982. )
  983. class BaseDatabaseIntrospection(object):
  984. """
  985. This class encapsulates all backend-specific introspection utilities
  986. """
  987. data_types_reverse = {}
  988. def __init__(self, connection):
  989. self.connection = connection
  990. def get_field_type(self, data_type, description):
  991. """Hook for a database backend to use the cursor description to
  992. match a Django field type to a database column.
  993. For Oracle, the column data_type on its own is insufficient to
  994. distinguish between a FloatField and IntegerField, for example."""
  995. return self.data_types_reverse[data_type]
  996. def table_name_converter(self, name):
  997. """Apply a conversion to the name for the purposes of comparison.
  998. The default table name converter is for case sensitive comparison.
  999. """
  1000. return name
  1001. def table_names(self, cursor=None):
  1002. """
  1003. Returns a list of names of all tables that exist in the database.
  1004. The returned table list is sorted by Python's default sorting. We
  1005. do NOT use database's ORDER BY here to avoid subtle differences
  1006. in sorting order between databases.
  1007. """
  1008. if cursor is None:
  1009. cursor = self.connection.cursor()
  1010. return sorted(self.get_table_list(cursor))
  1011. def get_table_list(self, cursor):
  1012. """
  1013. Returns an unsorted list of names of all tables that exist in the
  1014. database.
  1015. """
  1016. raise NotImplementedError
  1017. def django_table_names(self, only_existing=False):
  1018. """
  1019. Returns a list of all table names that have associated Django models and
  1020. are in INSTALLED_APPS.
  1021. If only_existing is True, the resulting list will only include the tables
  1022. that actually exist in the database.
  1023. """
  1024. from django.db import models, router
  1025. tables = set()
  1026. for app in models.get_apps():
  1027. for model in models.get_models(app):
  1028. if not model._meta.managed:
  1029. continue
  1030. if not router.allow_migrate(self.connection.alias, model):
  1031. continue
  1032. tables.add(model._meta.db_table)
  1033. tables.update([f.m2m_db_table() for f in model._meta.local_many_to_many])
  1034. tables = list(tables)
  1035. if only_existing:
  1036. existing_tables = self.table_names()
  1037. tables = [
  1038. t
  1039. for t in tables
  1040. if self.table_name_converter(t) in existing_tables
  1041. ]
  1042. return tables
  1043. def installed_models(self, tables):
  1044. "Returns a set of all models represented by the provided list of table names."
  1045. from django.db import models, router
  1046. all_models = []
  1047. for app in models.get_apps():
  1048. for model in models.get_models(app):
  1049. if router.allow_migrate(self.connection.alias, model):
  1050. all_models.append(model)
  1051. tables = list(map(self.table_name_converter, tables))
  1052. return set([
  1053. m for m in all_models
  1054. if self.table_name_converter(m._meta.db_table) in tables
  1055. ])
  1056. def sequence_list(self):
  1057. "Returns a list of information about all DB sequences for all models in all apps."
  1058. from django.db import models, router
  1059. apps = models.get_apps()
  1060. sequence_list = []
  1061. for app in apps:
  1062. for model in models.get_models(app):
  1063. if not model._meta.managed:
  1064. continue
  1065. if model._meta.swapped:
  1066. continue
  1067. if not router.allow_migrate(self.connection.alias, model):
  1068. continue
  1069. for f in model._meta.local_fields:
  1070. if isinstance(f, models.AutoField):
  1071. sequence_list.append({'table': model._meta.db_table, 'column': f.column})
  1072. break # Only one AutoField is allowed per model, so don't bother continuing.
  1073. for f in model._meta.local_many_to_many:
  1074. # If this is an m2m using an intermediate table,
  1075. # we don't need to reset the sequence.
  1076. if f.rel.through is None:
  1077. sequence_list.append({'table': f.m2m_db_table(), 'column': None})
  1078. return sequence_list
  1079. def get_key_columns(self, cursor, table_name):
  1080. """
  1081. Backends can override this to return a list of (column_name, referenced_table_name,
  1082. referenced_column_name) for all key columns in given table.
  1083. """
  1084. raise NotImplementedError
  1085. def get_primary_key_column(self, cursor, table_name):
  1086. """
  1087. Returns the name of the primary key column for the given table.
  1088. """
  1089. for column in six.iteritems(self.get_indexes(cursor, table_name)):
  1090. if column[1]['primary_key']:
  1091. return column[0]
  1092. return None
  1093. def get_indexes(self, cursor, table_name):
  1094. """
  1095. Returns a dictionary of indexed fieldname -> infodict for the given
  1096. table, where each infodict is in the format:
  1097. {'primary_key': boolean representing whether it's the primary key,
  1098. 'unique': boolean representing whether it's a unique index}
  1099. Only single-column indexes are introspected.
  1100. """
  1101. raise NotImplementedError
  1102. def get_constraints(self, cursor, table_name):
  1103. """
  1104. Returns {'cnname': {'columns': set(columns), 'primary_key': bool, 'unique': bool}}
  1105. Both single- and multi-column constraints are introspected.
  1106. """
  1107. raise NotImplementedError
  1108. class BaseDatabaseClient(object):
  1109. """
  1110. This class encapsulates all backend-specific methods for opening a
  1111. client shell.
  1112. """
  1113. # This should be a string representing the name of the executable
  1114. # (e.g., "psql"). Subclasses must override this.
  1115. executable_name = None
  1116. def __init__(self, connection):
  1117. # connection is an instance of BaseDatabaseWrapper.
  1118. self.connection = connection
  1119. def runshell(self):
  1120. raise NotImplementedError()
  1121. class BaseDatabaseValidation(object):
  1122. """
  1123. This class encapsualtes all backend-specific model validation.
  1124. """
  1125. def __init__(self, connection):
  1126. self.connection = connection
  1127. def validate_field(self, errors, opts, f):
  1128. "By default, there is no backend-specific validation"
  1129. pass