__init__.py 44 KB

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