You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

592 lines
22 KiB

  1. import datetime
  2. import decimal
  3. import warnings
  4. from importlib import import_module
  5. from django.conf import settings
  6. from django.core.exceptions import ImproperlyConfigured
  7. from django.db.backends import utils
  8. from django.utils import six, timezone
  9. from django.utils.dateparse import parse_duration
  10. from django.utils.deprecation import RemovedInDjango20Warning
  11. from django.utils.encoding import force_text
  12. class BaseDatabaseOperations(object):
  13. """
  14. This class encapsulates all backend-specific differences, such as the way
  15. a backend performs ordering or calculates the ID of a recently-inserted
  16. row.
  17. """
  18. compiler_module = "django.db.models.sql.compiler"
  19. # Integer field safe ranges by `internal_type` as documented
  20. # in docs/ref/models/fields.txt.
  21. integer_field_ranges = {
  22. 'SmallIntegerField': (-32768, 32767),
  23. 'IntegerField': (-2147483648, 2147483647),
  24. 'BigIntegerField': (-9223372036854775808, 9223372036854775807),
  25. 'PositiveSmallIntegerField': (0, 32767),
  26. 'PositiveIntegerField': (0, 2147483647),
  27. }
  28. def __init__(self, connection):
  29. self.connection = connection
  30. self._cache = None
  31. def autoinc_sql(self, table, column):
  32. """
  33. Returns any SQL needed to support auto-incrementing primary keys, or
  34. None if no SQL is necessary.
  35. This SQL is executed when a table is created.
  36. """
  37. return None
  38. def bulk_batch_size(self, fields, objs):
  39. """
  40. Returns the maximum allowed batch size for the backend. The fields
  41. are the fields going to be inserted in the batch, the objs contains
  42. all the objects to be inserted.
  43. """
  44. return len(objs)
  45. def cache_key_culling_sql(self):
  46. """
  47. Returns an SQL query that retrieves the first cache key greater than the
  48. n smallest.
  49. This is used by the 'db' cache backend to determine where to start
  50. culling.
  51. """
  52. return "SELECT cache_key FROM %s ORDER BY cache_key LIMIT 1 OFFSET %%s"
  53. def unification_cast_sql(self, output_field):
  54. """
  55. Given a field instance, returns the SQL necessary to cast the result of
  56. a union to that type. Note that the resulting string should contain a
  57. '%s' placeholder for the expression being cast.
  58. """
  59. return '%s'
  60. def date_extract_sql(self, lookup_type, field_name):
  61. """
  62. Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
  63. extracts a value from the given date field field_name.
  64. """
  65. raise NotImplementedError('subclasses of BaseDatabaseOperations may require a date_extract_sql() method')
  66. def date_interval_sql(self, timedelta):
  67. """
  68. Implements the date interval functionality for expressions
  69. """
  70. raise NotImplementedError('subclasses of BaseDatabaseOperations may require a date_interval_sql() method')
  71. def date_trunc_sql(self, lookup_type, field_name):
  72. """
  73. Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
  74. truncates the given date field field_name to a date object with only
  75. the given specificity.
  76. """
  77. raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetrunc_sql() method')
  78. def datetime_cast_date_sql(self, field_name, tzname):
  79. """
  80. Returns the SQL necessary to cast a datetime value to date value.
  81. """
  82. raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_cast_date() method')
  83. def datetime_extract_sql(self, lookup_type, field_name, tzname):
  84. """
  85. Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or
  86. 'second', returns the SQL that extracts a value from the given
  87. datetime field field_name, and a tuple of parameters.
  88. """
  89. raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method')
  90. def datetime_trunc_sql(self, lookup_type, field_name, tzname):
  91. """
  92. Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or
  93. 'second', returns the SQL that truncates the given datetime field
  94. field_name to a datetime object with only the given specificity, and
  95. a tuple of parameters.
  96. """
  97. raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_trunk_sql() method')
  98. def time_extract_sql(self, lookup_type, field_name):
  99. """
  100. Given a lookup_type of 'hour', 'minute' or 'second', returns the SQL
  101. that extracts a value from the given time field field_name.
  102. """
  103. return self.date_extract_sql(lookup_type, field_name)
  104. def deferrable_sql(self):
  105. """
  106. Returns the SQL necessary to make a constraint "initially deferred"
  107. during a CREATE TABLE statement.
  108. """
  109. return ''
  110. def distinct_sql(self, fields):
  111. """
  112. Returns an SQL DISTINCT clause which removes duplicate rows from the
  113. result set. If any fields are given, only the given fields are being
  114. checked for duplicates.
  115. """
  116. if fields:
  117. raise NotImplementedError('DISTINCT ON fields is not supported by this database backend')
  118. else:
  119. return 'DISTINCT'
  120. def drop_foreignkey_sql(self):
  121. """
  122. Returns the SQL command that drops a foreign key.
  123. """
  124. return "DROP CONSTRAINT"
  125. def drop_sequence_sql(self, table):
  126. """
  127. Returns any SQL necessary to drop the sequence for the given table.
  128. Returns None if no SQL is necessary.
  129. """
  130. return None
  131. def fetch_returned_insert_id(self, cursor):
  132. """
  133. Given a cursor object that has just performed an INSERT...RETURNING
  134. statement into a table that has an auto-incrementing ID, returns the
  135. newly created ID.
  136. """
  137. return cursor.fetchone()[0]
  138. def field_cast_sql(self, db_type, internal_type):
  139. """
  140. Given a column type (e.g. 'BLOB', 'VARCHAR'), and an internal type
  141. (e.g. 'GenericIPAddressField'), returns the SQL necessary to cast it
  142. before using it in a WHERE statement. Note that the resulting string
  143. should contain a '%s' placeholder for the column being searched against.
  144. """
  145. return '%s'
  146. def force_no_ordering(self):
  147. """
  148. Returns a list used in the "ORDER BY" clause to force no ordering at
  149. all. Returning an empty list means that nothing will be included in the
  150. ordering.
  151. """
  152. return []
  153. def for_update_sql(self, nowait=False):
  154. """
  155. Returns the FOR UPDATE SQL clause to lock rows for an update operation.
  156. """
  157. if nowait:
  158. return 'FOR UPDATE NOWAIT'
  159. else:
  160. return 'FOR UPDATE'
  161. def fulltext_search_sql(self, field_name):
  162. """
  163. Returns the SQL WHERE clause to use in order to perform a full-text
  164. search of the given field_name. Note that the resulting string should
  165. contain a '%s' placeholder for the value being searched against.
  166. """
  167. raise NotImplementedError('Full-text search is not implemented for this database backend')
  168. def last_executed_query(self, cursor, sql, params):
  169. """
  170. Returns a string of the query last executed by the given cursor, with
  171. placeholders replaced with actual values.
  172. `sql` is the raw query containing placeholders, and `params` is the
  173. sequence of parameters. These are used by default, but this method
  174. exists for database backends to provide a better implementation
  175. according to their own quoting schemes.
  176. """
  177. # Convert params to contain Unicode values.
  178. to_unicode = lambda s: force_text(s, strings_only=True, errors='replace')
  179. if isinstance(params, (list, tuple)):
  180. u_params = tuple(to_unicode(val) for val in params)
  181. elif params is None:
  182. u_params = ()
  183. else:
  184. u_params = {to_unicode(k): to_unicode(v) for k, v in params.items()}
  185. return six.text_type("QUERY = %r - PARAMS = %r") % (sql, u_params)
  186. def last_insert_id(self, cursor, table_name, pk_name):
  187. """
  188. Given a cursor object that has just performed an INSERT statement into
  189. a table that has an auto-incrementing ID, returns the newly created ID.
  190. This method also receives the table name and the name of the primary-key
  191. column.
  192. """
  193. return cursor.lastrowid
  194. def lookup_cast(self, lookup_type, internal_type=None):
  195. """
  196. Returns the string to use in a query when performing lookups
  197. ("contains", "like", etc.). The resulting string should contain a '%s'
  198. placeholder for the column being searched against.
  199. """
  200. return "%s"
  201. def max_in_list_size(self):
  202. """
  203. Returns the maximum number of items that can be passed in a single 'IN'
  204. list condition, or None if the backend does not impose a limit.
  205. """
  206. return None
  207. def max_name_length(self):
  208. """
  209. Returns the maximum length of table and column names, or None if there
  210. is no limit.
  211. """
  212. return None
  213. def no_limit_value(self):
  214. """
  215. Returns the value to use for the LIMIT when we are wanting "LIMIT
  216. infinity". Returns None if the limit clause can be omitted in this case.
  217. """
  218. raise NotImplementedError('subclasses of BaseDatabaseOperations may require a no_limit_value() method')
  219. def pk_default_value(self):
  220. """
  221. Returns the value to use during an INSERT statement to specify that
  222. the field should use its default value.
  223. """
  224. return 'DEFAULT'
  225. def prepare_sql_script(self, sql):
  226. """
  227. Takes an SQL script that may contain multiple lines and returns a list
  228. of statements to feed to successive cursor.execute() calls.
  229. Since few databases are able to process raw SQL scripts in a single
  230. cursor.execute() call and PEP 249 doesn't talk about this use case,
  231. the default implementation is conservative.
  232. """
  233. try:
  234. import sqlparse
  235. except ImportError:
  236. raise ImproperlyConfigured(
  237. "sqlparse is required if you don't split your SQL "
  238. "statements manually."
  239. )
  240. else:
  241. return [sqlparse.format(statement, strip_comments=True)
  242. for statement in sqlparse.split(sql) if statement]
  243. def process_clob(self, value):
  244. """
  245. Returns the value of a CLOB column, for backends that return a locator
  246. object that requires additional processing.
  247. """
  248. return value
  249. def return_insert_id(self):
  250. """
  251. For backends that support returning the last insert ID as part
  252. of an insert query, this method returns the SQL and params to
  253. append to the INSERT query. The returned fragment should
  254. contain a format string to hold the appropriate column.
  255. """
  256. pass
  257. def compiler(self, compiler_name):
  258. """
  259. Returns the SQLCompiler class corresponding to the given name,
  260. in the namespace corresponding to the `compiler_module` attribute
  261. on this backend.
  262. """
  263. if self._cache is None:
  264. self._cache = import_module(self.compiler_module)
  265. return getattr(self._cache, compiler_name)
  266. def quote_name(self, name):
  267. """
  268. Returns a quoted version of the given table, index or column name. Does
  269. not quote the given name if it's already been quoted.
  270. """
  271. raise NotImplementedError('subclasses of BaseDatabaseOperations may require a quote_name() method')
  272. def random_function_sql(self):
  273. """
  274. Returns an SQL expression that returns a random value.
  275. """
  276. return 'RANDOM()'
  277. def regex_lookup(self, lookup_type):
  278. """
  279. Returns the string to use in a query when performing regular expression
  280. lookups (using "regex" or "iregex"). The resulting string should
  281. contain a '%s' placeholder for the column being searched against.
  282. If the feature is not supported (or part of it is not supported), a
  283. NotImplementedError exception can be raised.
  284. """
  285. raise NotImplementedError('subclasses of BaseDatabaseOperations may require a regex_lookup() method')
  286. def savepoint_create_sql(self, sid):
  287. """
  288. Returns the SQL for starting a new savepoint. Only required if the
  289. "uses_savepoints" feature is True. The "sid" parameter is a string
  290. for the savepoint id.
  291. """
  292. return "SAVEPOINT %s" % self.quote_name(sid)
  293. def savepoint_commit_sql(self, sid):
  294. """
  295. Returns the SQL for committing the given savepoint.
  296. """
  297. return "RELEASE SAVEPOINT %s" % self.quote_name(sid)
  298. def savepoint_rollback_sql(self, sid):
  299. """
  300. Returns the SQL for rolling back the given savepoint.
  301. """
  302. return "ROLLBACK TO SAVEPOINT %s" % self.quote_name(sid)
  303. def set_time_zone_sql(self):
  304. """
  305. Returns the SQL that will set the connection's time zone.
  306. Returns '' if the backend doesn't support time zones.
  307. """
  308. return ''
  309. def sql_flush(self, style, tables, sequences, allow_cascade=False):
  310. """
  311. Returns a list of SQL statements required to remove all data from
  312. the given database tables (without actually removing the tables
  313. themselves).
  314. The returned value also includes SQL statements required to reset DB
  315. sequences passed in :param sequences:.
  316. The `style` argument is a Style object as returned by either
  317. color_style() or no_style() in django.core.management.color.
  318. The `allow_cascade` argument determines whether truncation may cascade
  319. to tables with foreign keys pointing the tables being truncated.
  320. PostgreSQL requires a cascade even if these tables are empty.
  321. """
  322. raise NotImplementedError('subclasses of BaseDatabaseOperations must provide an sql_flush() method')
  323. def sequence_reset_by_name_sql(self, style, sequences):
  324. """
  325. Returns a list of the SQL statements required to reset sequences
  326. passed in :param sequences:.
  327. The `style` argument is a Style object as returned by either
  328. color_style() or no_style() in django.core.management.color.
  329. """
  330. return []
  331. def sequence_reset_sql(self, style, model_list):
  332. """
  333. Returns a list of the SQL statements required to reset sequences for
  334. the given models.
  335. The `style` argument is a Style object as returned by either
  336. color_style() or no_style() in django.core.management.color.
  337. """
  338. return [] # No sequence reset required by default.
  339. def start_transaction_sql(self):
  340. """
  341. Returns the SQL statement required to start a transaction.
  342. """
  343. return "BEGIN;"
  344. def end_transaction_sql(self, success=True):
  345. """
  346. Returns the SQL statement required to end a transaction.
  347. """
  348. if not success:
  349. return "ROLLBACK;"
  350. return "COMMIT;"
  351. def tablespace_sql(self, tablespace, inline=False):
  352. """
  353. Returns the SQL that will be used in a query to define the tablespace.
  354. Returns '' if the backend doesn't support tablespaces.
  355. If inline is True, the SQL is appended to a row; otherwise it's appended
  356. to the entire CREATE TABLE or CREATE INDEX statement.
  357. """
  358. return ''
  359. def prep_for_like_query(self, x):
  360. """Prepares a value for use in a LIKE query."""
  361. return force_text(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_")
  362. # Same as prep_for_like_query(), but called for "iexact" matches, which
  363. # need not necessarily be implemented using "LIKE" in the backend.
  364. prep_for_iexact_query = prep_for_like_query
  365. def validate_autopk_value(self, value):
  366. """
  367. Certain backends do not accept some values for "serial" fields
  368. (for example zero in MySQL). This method will raise a ValueError
  369. if the value is invalid, otherwise returns validated value.
  370. """
  371. return value
  372. def adapt_unknown_value(self, value):
  373. """
  374. Transforms a value to something compatible with the backend driver.
  375. This method only depends on the type of the value. It's designed for
  376. cases where the target type isn't known, such as .raw() SQL queries.
  377. As a consequence it may not work perfectly in all circumstances.
  378. """
  379. if isinstance(value, datetime.datetime): # must be before date
  380. return self.adapt_datetimefield_value(value)
  381. elif isinstance(value, datetime.date):
  382. return self.adapt_datefield_value(value)
  383. elif isinstance(value, datetime.time):
  384. return self.adapt_timefield_value(value)
  385. elif isinstance(value, decimal.Decimal):
  386. return self.adapt_decimalfield_value(value)
  387. else:
  388. return value
  389. def adapt_datefield_value(self, value):
  390. """
  391. Transforms a date value to an object compatible with what is expected
  392. by the backend driver for date columns.
  393. """
  394. if value is None:
  395. return None
  396. return six.text_type(value)
  397. def adapt_datetimefield_value(self, value):
  398. """
  399. Transforms a datetime value to an object compatible with what is expected
  400. by the backend driver for datetime columns.
  401. """
  402. if value is None:
  403. return None
  404. return six.text_type(value)
  405. def adapt_timefield_value(self, value):
  406. """
  407. Transforms a time value to an object compatible with what is expected
  408. by the backend driver for time columns.
  409. """
  410. if value is None:
  411. return None
  412. if timezone.is_aware(value):
  413. raise ValueError("Django does not support timezone-aware times.")
  414. return six.text_type(value)
  415. def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None):
  416. """
  417. Transforms a decimal.Decimal value to an object compatible with what is
  418. expected by the backend driver for decimal (numeric) columns.
  419. """
  420. return utils.format_number(value, max_digits, decimal_places)
  421. def adapt_ipaddressfield_value(self, value):
  422. """
  423. Transforms a string representation of an IP address into the expected
  424. type for the backend driver.
  425. """
  426. return value or None
  427. def year_lookup_bounds_for_date_field(self, value):
  428. """
  429. Returns a two-elements list with the lower and upper bound to be used
  430. with a BETWEEN operator to query a DateField value using a year
  431. lookup.
  432. `value` is an int, containing the looked-up year.
  433. """
  434. first = datetime.date(value, 1, 1)
  435. second = datetime.date(value, 12, 31)
  436. first = self.adapt_datefield_value(first)
  437. second = self.adapt_datefield_value(second)
  438. return [first, second]
  439. def year_lookup_bounds_for_datetime_field(self, value):
  440. """
  441. Returns a two-elements list with the lower and upper bound to be used
  442. with a BETWEEN operator to query a DateTimeField value using a year
  443. lookup.
  444. `value` is an int, containing the looked-up year.
  445. """
  446. first = datetime.datetime(value, 1, 1)
  447. second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999)
  448. if settings.USE_TZ:
  449. tz = timezone.get_current_timezone()
  450. first = timezone.make_aware(first, tz)
  451. second = timezone.make_aware(second, tz)
  452. first = self.adapt_datetimefield_value(first)
  453. second = self.adapt_datetimefield_value(second)
  454. return [first, second]
  455. def get_db_converters(self, expression):
  456. """
  457. Get a list of functions needed to convert field data.
  458. Some field types on some backends do not provide data in the correct
  459. format, this is the hook for converter functions.
  460. """
  461. return []
  462. def convert_durationfield_value(self, value, expression, connection, context):
  463. if value is not None:
  464. value = str(decimal.Decimal(value) / decimal.Decimal(1000000))
  465. value = parse_duration(value)
  466. return value
  467. def check_aggregate_support(self, aggregate_func):
  468. warnings.warn(
  469. "check_aggregate_support has been deprecated. Use "
  470. "check_expression_support instead.",
  471. RemovedInDjango20Warning, stacklevel=2)
  472. return self.check_expression_support(aggregate_func)
  473. def check_expression_support(self, expression):
  474. """
  475. Check that the backend supports the provided expression.
  476. This is used on specific backends to rule out known expressions
  477. that have problematic or nonexistent implementations. If the
  478. expression has a known problem, the backend should raise
  479. NotImplementedError.
  480. """
  481. pass
  482. def combine_expression(self, connector, sub_expressions):
  483. """Combine a list of subexpressions into a single expression, using
  484. the provided connecting operator. This is required because operators
  485. can vary between backends (e.g., Oracle with %% and &) and between
  486. subexpression types (e.g., date expressions)
  487. """
  488. conn = ' %s ' % connector
  489. return conn.join(sub_expressions)
  490. def combine_duration_expression(self, connector, sub_expressions):
  491. return self.combine_expression(connector, sub_expressions)
  492. def modify_insert_params(self, placeholder, params):
  493. """Allow modification of insert parameters. Needed for Oracle Spatial
  494. backend due to #10888.
  495. """
  496. return params
  497. def integer_field_range(self, internal_type):
  498. """
  499. Given an integer field internal type (e.g. 'PositiveIntegerField'),
  500. returns a tuple of the (min_value, max_value) form representing the
  501. range of the column type bound to the field.
  502. """
  503. return self.integer_field_ranges[internal_type]