__init__.py 56 KB

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