__init__.py 37 KB

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