__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. try:
  2. # Only exists in Python 2.4+
  3. from threading import local
  4. except ImportError:
  5. # Import copy of _thread_local.py from Python 2.4
  6. from django.utils._threading_local import local
  7. try:
  8. set
  9. except NameError:
  10. # Python 2.3 compat
  11. from sets import Set as set
  12. try:
  13. import decimal
  14. except ImportError:
  15. # Python 2.3 fallback
  16. from django.utils import _decimal as decimal
  17. from django.db.backends import util
  18. from django.utils import datetime_safe
  19. class BaseDatabaseWrapper(local):
  20. """
  21. Represents a database connection.
  22. """
  23. ops = None
  24. def __init__(self, **kwargs):
  25. self.connection = None
  26. self.queries = []
  27. self.options = kwargs
  28. def _commit(self):
  29. if self.connection is not None:
  30. return self.connection.commit()
  31. def _rollback(self):
  32. if self.connection is not None:
  33. return self.connection.rollback()
  34. def _savepoint(self, sid):
  35. if not self.features.uses_savepoints:
  36. return
  37. self.connection.cursor().execute(self.ops.savepoint_create_sql(sid))
  38. def _savepoint_rollback(self, sid):
  39. if not self.features.uses_savepoints:
  40. return
  41. self.connection.cursor().execute(self.ops.savepoint_rollback_sql(sid))
  42. def _savepoint_commit(self, sid):
  43. if not self.features.uses_savepoints:
  44. return
  45. self.connection.cursor().execute(self.ops.savepoint_commit_sql(sid))
  46. def close(self):
  47. if self.connection is not None:
  48. self.connection.close()
  49. self.connection = None
  50. def cursor(self):
  51. from django.conf import settings
  52. cursor = self._cursor(settings)
  53. if settings.DEBUG:
  54. return self.make_debug_cursor(cursor)
  55. return cursor
  56. def make_debug_cursor(self, cursor):
  57. return util.CursorDebugWrapper(cursor, self)
  58. class BaseDatabaseFeatures(object):
  59. allows_group_by_pk = False
  60. # True if django.db.backend.utils.typecast_timestamp is used on values
  61. # returned from dates() calls.
  62. needs_datetime_string_cast = True
  63. uses_custom_query_class = False
  64. empty_fetchmany_value = []
  65. update_can_self_select = True
  66. interprets_empty_strings_as_nulls = False
  67. can_use_chunked_reads = True
  68. uses_savepoints = False
  69. # If True, don't use integer foreign keys referring to, e.g., positive
  70. # integer primary keys.
  71. related_fields_match_type = False
  72. class BaseDatabaseOperations(object):
  73. """
  74. This class encapsulates all backend-specific differences, such as the way
  75. a backend performs ordering or calculates the ID of a recently-inserted
  76. row.
  77. """
  78. def autoinc_sql(self, table, column):
  79. """
  80. Returns any SQL needed to support auto-incrementing primary keys, or
  81. None if no SQL is necessary.
  82. This SQL is executed when a table is created.
  83. """
  84. return None
  85. def date_extract_sql(self, lookup_type, field_name):
  86. """
  87. Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
  88. extracts a value from the given date field field_name.
  89. """
  90. raise NotImplementedError()
  91. def date_trunc_sql(self, lookup_type, field_name):
  92. """
  93. Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
  94. truncates the given date field field_name to a DATE object with only
  95. the given specificity.
  96. """
  97. raise NotImplementedError()
  98. def datetime_cast_sql(self):
  99. """
  100. Returns the SQL necessary to cast a datetime value so that it will be
  101. retrieved as a Python datetime object instead of a string.
  102. This SQL should include a '%s' in place of the field's name.
  103. """
  104. return "%s"
  105. def deferrable_sql(self):
  106. """
  107. Returns the SQL necessary to make a constraint "initially deferred"
  108. during a CREATE TABLE statement.
  109. """
  110. return ''
  111. def drop_foreignkey_sql(self):
  112. """
  113. Returns the SQL command that drops a foreign key.
  114. """
  115. return "DROP CONSTRAINT"
  116. def drop_sequence_sql(self, table):
  117. """
  118. Returns any SQL necessary to drop the sequence for the given table.
  119. Returns None if no SQL is necessary.
  120. """
  121. return None
  122. def field_cast_sql(self, db_type):
  123. """
  124. Given a column type (e.g. 'BLOB', 'VARCHAR'), returns the SQL necessary
  125. to cast it before using it in a WHERE statement. Note that the
  126. resulting string should contain a '%s' placeholder for the column being
  127. searched against.
  128. """
  129. return '%s'
  130. def force_no_ordering(self):
  131. """
  132. Returns a list used in the "ORDER BY" clause to force no ordering at
  133. all. Returning an empty list means that nothing will be included in the
  134. ordering.
  135. """
  136. return []
  137. def fulltext_search_sql(self, field_name):
  138. """
  139. Returns the SQL WHERE clause to use in order to perform a full-text
  140. search of the given field_name. Note that the resulting string should
  141. contain a '%s' placeholder for the value being searched against.
  142. """
  143. raise NotImplementedError('Full-text search is not implemented for this database backend')
  144. def last_executed_query(self, cursor, sql, params):
  145. """
  146. Returns a string of the query last executed by the given cursor, with
  147. placeholders replaced with actual values.
  148. `sql` is the raw query containing placeholders, and `params` is the
  149. sequence of parameters. These are used by default, but this method
  150. exists for database backends to provide a better implementation
  151. according to their own quoting schemes.
  152. """
  153. from django.utils.encoding import smart_unicode, force_unicode
  154. # Convert params to contain Unicode values.
  155. to_unicode = lambda s: force_unicode(s, strings_only=True)
  156. if isinstance(params, (list, tuple)):
  157. u_params = tuple([to_unicode(val) for val in params])
  158. else:
  159. u_params = dict([(to_unicode(k), to_unicode(v)) for k, v in params.items()])
  160. return smart_unicode(sql) % u_params
  161. def last_insert_id(self, cursor, table_name, pk_name):
  162. """
  163. Given a cursor object that has just performed an INSERT statement into
  164. a table that has an auto-incrementing ID, returns the newly created ID.
  165. This method also receives the table name and the name of the primary-key
  166. column.
  167. """
  168. return cursor.lastrowid
  169. def lookup_cast(self, lookup_type):
  170. """
  171. Returns the string to use in a query when performing lookups
  172. ("contains", "like", etc). The resulting string should contain a '%s'
  173. placeholder for the column being searched against.
  174. """
  175. return "%s"
  176. def max_name_length(self):
  177. """
  178. Returns the maximum length of table and column names, or None if there
  179. is no limit.
  180. """
  181. return None
  182. def no_limit_value(self):
  183. """
  184. Returns the value to use for the LIMIT when we are wanting "LIMIT
  185. infinity". Returns None if the limit clause can be omitted in this case.
  186. """
  187. # FIXME: API may need to change once Oracle backend is repaired.
  188. raise NotImplementedError()
  189. def pk_default_value(self):
  190. """
  191. Returns the value to use during an INSERT statement to specify that
  192. the field should use its default value.
  193. """
  194. return 'DEFAULT'
  195. def query_class(self, DefaultQueryClass):
  196. """
  197. Given the default Query class, returns a custom Query class
  198. to use for this backend. Returns None if a custom Query isn't used.
  199. See also BaseDatabaseFeatures.uses_custom_query_class, which regulates
  200. whether this method is called at all.
  201. """
  202. return None
  203. def quote_name(self, name):
  204. """
  205. Returns a quoted version of the given table, index or column name. Does
  206. not quote the given name if it's already been quoted.
  207. """
  208. raise NotImplementedError()
  209. def random_function_sql(self):
  210. """
  211. Returns a SQL expression that returns a random value.
  212. """
  213. return 'RANDOM()'
  214. def regex_lookup(self, lookup_type):
  215. """
  216. Returns the string to use in a query when performing regular expression
  217. lookups (using "regex" or "iregex"). The resulting string should
  218. contain a '%s' placeholder for the column being searched against.
  219. If the feature is not supported (or part of it is not supported), a
  220. NotImplementedError exception can be raised.
  221. """
  222. raise NotImplementedError
  223. def savepoint_create_sql(self, sid):
  224. """
  225. Returns the SQL for starting a new savepoint. Only required if the
  226. "uses_savepoints" feature is True. The "sid" parameter is a string
  227. for the savepoint id.
  228. """
  229. raise NotImplementedError
  230. def savepoint_commit_sql(self, sid):
  231. """
  232. Returns the SQL for committing the given savepoint.
  233. """
  234. raise NotImplementedError
  235. def savepoint_rollback_sql(self, sid):
  236. """
  237. Returns the SQL for rolling back the given savepoint.
  238. """
  239. raise NotImplementedError
  240. def sql_flush(self, style, tables, sequences):
  241. """
  242. Returns a list of SQL statements required to remove all data from
  243. the given database tables (without actually removing the tables
  244. themselves).
  245. The `style` argument is a Style object as returned by either
  246. color_style() or no_style() in django.core.management.color.
  247. """
  248. raise NotImplementedError()
  249. def sequence_reset_sql(self, style, model_list):
  250. """
  251. Returns a list of the SQL statements required to reset sequences for
  252. the given models.
  253. The `style` argument is a Style object as returned by either
  254. color_style() or no_style() in django.core.management.color.
  255. """
  256. return [] # No sequence reset required by default.
  257. def start_transaction_sql(self):
  258. """
  259. Returns the SQL statement required to start a transaction.
  260. """
  261. return "BEGIN;"
  262. def tablespace_sql(self, tablespace, inline=False):
  263. """
  264. Returns the SQL that will be appended to tables or rows to define
  265. a tablespace. Returns '' if the backend doesn't use tablespaces.
  266. """
  267. return ''
  268. def prep_for_like_query(self, x):
  269. """Prepares a value for use in a LIKE query."""
  270. from django.utils.encoding import smart_unicode
  271. return smart_unicode(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_")
  272. # Same as prep_for_like_query(), but called for "iexact" matches, which
  273. # need not necessarily be implemented using "LIKE" in the backend.
  274. prep_for_iexact_query = prep_for_like_query
  275. def value_to_db_date(self, value):
  276. """
  277. Transform a date value to an object compatible with what is expected
  278. by the backend driver for date columns.
  279. """
  280. if value is None:
  281. return None
  282. return datetime_safe.new_date(value).strftime('%Y-%m-%d')
  283. def value_to_db_datetime(self, value):
  284. """
  285. Transform a datetime value to an object compatible with what is expected
  286. by the backend driver for datetime columns.
  287. """
  288. if value is None:
  289. return None
  290. return unicode(value)
  291. def value_to_db_time(self, value):
  292. """
  293. Transform a datetime value to an object compatible with what is expected
  294. by the backend driver for time columns.
  295. """
  296. if value is None:
  297. return None
  298. return unicode(value)
  299. def value_to_db_decimal(self, value, max_digits, decimal_places):
  300. """
  301. Transform a decimal.Decimal value to an object compatible with what is
  302. expected by the backend driver for decimal (numeric) columns.
  303. """
  304. if value is None:
  305. return None
  306. return util.format_number(value, max_digits, decimal_places)
  307. def year_lookup_bounds(self, value):
  308. """
  309. Returns a two-elements list with the lower and upper bound to be used
  310. with a BETWEEN operator to query a field value using a year lookup
  311. `value` is an int, containing the looked-up year.
  312. """
  313. first = '%s-01-01 00:00:00'
  314. second = '%s-12-31 23:59:59.999999'
  315. return [first % value, second % value]
  316. def year_lookup_bounds_for_date_field(self, value):
  317. """
  318. Returns a two-elements list with the lower and upper bound to be used
  319. with a BETWEEN operator to query a DateField value using a year lookup
  320. `value` is an int, containing the looked-up year.
  321. By default, it just calls `self.year_lookup_bounds`. Some backends need
  322. this hook because on their DB date fields can't be compared to values
  323. which include a time part.
  324. """
  325. return self.year_lookup_bounds(value)
  326. def convert_values(self, value, field):
  327. """Coerce the value returned by the database backend into a consistent type that
  328. is compatible with the field type.
  329. """
  330. internal_type = field.get_internal_type()
  331. if internal_type == 'DecimalField':
  332. return value
  333. elif internal_type and internal_type.endswith('IntegerField') or internal_type == 'AutoField':
  334. return int(value)
  335. elif internal_type in ('DateField', 'DateTimeField', 'TimeField'):
  336. return value
  337. # No field, or the field isn't known to be a decimal or integer
  338. # Default to a float
  339. return float(value)
  340. class BaseDatabaseIntrospection(object):
  341. """
  342. This class encapsulates all backend-specific introspection utilities
  343. """
  344. data_types_reverse = {}
  345. def __init__(self, connection):
  346. self.connection = connection
  347. def table_name_converter(self, name):
  348. """Apply a conversion to the name for the purposes of comparison.
  349. The default table name converter is for case sensitive comparison.
  350. """
  351. return name
  352. def table_names(self):
  353. "Returns a list of names of all tables that exist in the database."
  354. cursor = self.connection.cursor()
  355. return self.get_table_list(cursor)
  356. def django_table_names(self, only_existing=False):
  357. """
  358. Returns a list of all table names that have associated Django models and
  359. are in INSTALLED_APPS.
  360. If only_existing is True, the resulting list will only include the tables
  361. that actually exist in the database.
  362. """
  363. from django.db import models
  364. tables = set()
  365. for app in models.get_apps():
  366. for model in models.get_models(app):
  367. tables.add(model._meta.db_table)
  368. tables.update([f.m2m_db_table() for f in model._meta.local_many_to_many])
  369. if only_existing:
  370. tables = [t for t in tables if self.table_name_converter(t) in self.table_names()]
  371. return tables
  372. def installed_models(self, tables):
  373. "Returns a set of all models represented by the provided list of table names."
  374. from django.db import models
  375. all_models = []
  376. for app in models.get_apps():
  377. for model in models.get_models(app):
  378. all_models.append(model)
  379. return set([m for m in all_models
  380. if self.table_name_converter(m._meta.db_table) in map(self.table_name_converter, tables)
  381. ])
  382. def sequence_list(self):
  383. "Returns a list of information about all DB sequences for all models in all apps."
  384. from django.db import models
  385. apps = models.get_apps()
  386. sequence_list = []
  387. for app in apps:
  388. for model in models.get_models(app):
  389. for f in model._meta.local_fields:
  390. if isinstance(f, models.AutoField):
  391. sequence_list.append({'table': model._meta.db_table, 'column': f.column})
  392. break # Only one AutoField is allowed per model, so don't bother continuing.
  393. for f in model._meta.local_many_to_many:
  394. sequence_list.append({'table': f.m2m_db_table(), 'column': None})
  395. return sequence_list
  396. class BaseDatabaseClient(object):
  397. """
  398. This class encapsulates all backend-specific methods for opening a
  399. client shell.
  400. """
  401. # This should be a string representing the name of the executable
  402. # (e.g., "psql"). Subclasses must override this.
  403. executable_name = None
  404. def runshell(self):
  405. raise NotImplementedError()
  406. class BaseDatabaseValidation(object):
  407. """
  408. This class encapsualtes all backend-specific model validation.
  409. """
  410. def validate_field(self, errors, opts, f):
  411. "By default, there is no backend-specific validation"
  412. pass