/bangkokhotel/lib/python2.5/site-packages/django/db/backends/__init__.py

https://bitbucket.org/luisrodriguez/bangkokhotel · Python · 1012 lines · 746 code · 78 blank · 188 comment · 51 complexity · 4674c0e606646fe6ed3b96c7743ce6e6 MD5 · raw file

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