operations.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. import datetime
  2. import decimal
  3. import json
  4. import warnings
  5. from importlib import import_module
  6. import sqlparse
  7. from django.conf import settings
  8. from django.db import NotSupportedError, transaction
  9. from django.db.backends import utils
  10. from django.db.models.expressions import Col
  11. from django.utils import timezone
  12. from django.utils.deprecation import RemovedInDjango60Warning
  13. from django.utils.encoding import force_str
  14. class BaseDatabaseOperations:
  15. """
  16. Encapsulate backend-specific differences, such as the way a backend
  17. performs ordering or calculates the ID of a recently-inserted row.
  18. """
  19. compiler_module = "django.db.models.sql.compiler"
  20. # Integer field safe ranges by `internal_type` as documented
  21. # in docs/ref/models/fields.txt.
  22. integer_field_ranges = {
  23. "SmallIntegerField": (-32768, 32767),
  24. "IntegerField": (-2147483648, 2147483647),
  25. "BigIntegerField": (-9223372036854775808, 9223372036854775807),
  26. "PositiveBigIntegerField": (0, 9223372036854775807),
  27. "PositiveSmallIntegerField": (0, 32767),
  28. "PositiveIntegerField": (0, 2147483647),
  29. "SmallAutoField": (-32768, 32767),
  30. "AutoField": (-2147483648, 2147483647),
  31. "BigAutoField": (-9223372036854775808, 9223372036854775807),
  32. }
  33. set_operators = {
  34. "union": "UNION",
  35. "intersection": "INTERSECT",
  36. "difference": "EXCEPT",
  37. }
  38. # Mapping of Field.get_internal_type() (typically the model field's class
  39. # name) to the data type to use for the Cast() function, if different from
  40. # DatabaseWrapper.data_types.
  41. cast_data_types = {}
  42. # CharField data type if the max_length argument isn't provided.
  43. cast_char_field_without_max_length = None
  44. # Start and end points for window expressions.
  45. PRECEDING = "PRECEDING"
  46. FOLLOWING = "FOLLOWING"
  47. UNBOUNDED_PRECEDING = "UNBOUNDED " + PRECEDING
  48. UNBOUNDED_FOLLOWING = "UNBOUNDED " + FOLLOWING
  49. CURRENT_ROW = "CURRENT ROW"
  50. # Prefix for EXPLAIN queries, or None EXPLAIN isn't supported.
  51. explain_prefix = None
  52. def __init__(self, connection):
  53. self.connection = connection
  54. self._cache = None
  55. def autoinc_sql(self, table, column):
  56. """
  57. Return any SQL needed to support auto-incrementing primary keys, or
  58. None if no SQL is necessary.
  59. This SQL is executed when a table is created.
  60. """
  61. return None
  62. def bulk_batch_size(self, fields, objs):
  63. """
  64. Return the maximum allowed batch size for the backend. The fields
  65. are the fields going to be inserted in the batch, the objs contains
  66. all the objects to be inserted.
  67. """
  68. return len(objs)
  69. def format_for_duration_arithmetic(self, sql):
  70. raise NotImplementedError(
  71. "subclasses of BaseDatabaseOperations may require a "
  72. "format_for_duration_arithmetic() method."
  73. )
  74. def cache_key_culling_sql(self):
  75. """
  76. Return an SQL query that retrieves the first cache key greater than the
  77. n smallest.
  78. This is used by the 'db' cache backend to determine where to start
  79. culling.
  80. """
  81. cache_key = self.quote_name("cache_key")
  82. return f"SELECT {cache_key} FROM %s ORDER BY {cache_key} LIMIT 1 OFFSET %%s"
  83. def unification_cast_sql(self, output_field):
  84. """
  85. Given a field instance, return the SQL that casts the result of a union
  86. to that type. The resulting string should contain a '%s' placeholder
  87. for the expression being cast.
  88. """
  89. return "%s"
  90. def date_extract_sql(self, lookup_type, sql, params):
  91. """
  92. Given a lookup_type of 'year', 'month', or 'day', return the SQL that
  93. extracts a value from the given date field field_name.
  94. """
  95. raise NotImplementedError(
  96. "subclasses of BaseDatabaseOperations may require a date_extract_sql() "
  97. "method"
  98. )
  99. def date_trunc_sql(self, lookup_type, sql, params, tzname=None):
  100. """
  101. Given a lookup_type of 'year', 'month', or 'day', return the SQL that
  102. truncates the given date or datetime field field_name to a date object
  103. with only the given specificity.
  104. If `tzname` is provided, the given value is truncated in a specific
  105. timezone.
  106. """
  107. raise NotImplementedError(
  108. "subclasses of BaseDatabaseOperations may require a date_trunc_sql() "
  109. "method."
  110. )
  111. def datetime_cast_date_sql(self, sql, params, tzname):
  112. """
  113. Return the SQL to cast a datetime value to date value.
  114. """
  115. raise NotImplementedError(
  116. "subclasses of BaseDatabaseOperations may require a "
  117. "datetime_cast_date_sql() method."
  118. )
  119. def datetime_cast_time_sql(self, sql, params, tzname):
  120. """
  121. Return the SQL to cast a datetime value to time value.
  122. """
  123. raise NotImplementedError(
  124. "subclasses of BaseDatabaseOperations may require a "
  125. "datetime_cast_time_sql() method"
  126. )
  127. def datetime_extract_sql(self, lookup_type, sql, params, tzname):
  128. """
  129. Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or
  130. 'second', return the SQL that extracts a value from the given
  131. datetime field field_name.
  132. """
  133. raise NotImplementedError(
  134. "subclasses of BaseDatabaseOperations may require a datetime_extract_sql() "
  135. "method"
  136. )
  137. def datetime_trunc_sql(self, lookup_type, sql, params, tzname):
  138. """
  139. Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or
  140. 'second', return the SQL that truncates the given datetime field
  141. field_name to a datetime object with only the given specificity.
  142. """
  143. raise NotImplementedError(
  144. "subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() "
  145. "method"
  146. )
  147. def time_trunc_sql(self, lookup_type, sql, params, tzname=None):
  148. """
  149. Given a lookup_type of 'hour', 'minute' or 'second', return the SQL
  150. that truncates the given time or datetime field field_name to a time
  151. object with only the given specificity.
  152. If `tzname` is provided, the given value is truncated in a specific
  153. timezone.
  154. """
  155. raise NotImplementedError(
  156. "subclasses of BaseDatabaseOperations may require a time_trunc_sql() method"
  157. )
  158. def time_extract_sql(self, lookup_type, sql, params):
  159. """
  160. Given a lookup_type of 'hour', 'minute', or 'second', return the SQL
  161. that extracts a value from the given time field field_name.
  162. """
  163. return self.date_extract_sql(lookup_type, sql, params)
  164. def deferrable_sql(self):
  165. """
  166. Return the SQL to make a constraint "initially deferred" during a
  167. CREATE TABLE statement.
  168. """
  169. return ""
  170. def distinct_sql(self, fields, params):
  171. """
  172. Return an SQL DISTINCT clause which removes duplicate rows from the
  173. result set. If any fields are given, only check the given fields for
  174. duplicates.
  175. """
  176. if fields:
  177. raise NotSupportedError(
  178. "DISTINCT ON fields is not supported by this database backend"
  179. )
  180. else:
  181. return ["DISTINCT"], []
  182. def fetch_returned_insert_columns(self, cursor, returning_params):
  183. """
  184. Given a cursor object that has just performed an INSERT...RETURNING
  185. statement into a table, return the newly created data.
  186. """
  187. return cursor.fetchone()
  188. def field_cast_sql(self, db_type, internal_type):
  189. """
  190. Given a column type (e.g. 'BLOB', 'VARCHAR') and an internal type
  191. (e.g. 'GenericIPAddressField'), return the SQL to cast it before using
  192. it in a WHERE statement. The resulting string should contain a '%s'
  193. placeholder for the column being searched against.
  194. """
  195. warnings.warn(
  196. (
  197. "DatabaseOperations.field_cast_sql() is deprecated use "
  198. "DatabaseOperations.lookup_cast() instead."
  199. ),
  200. RemovedInDjango60Warning,
  201. )
  202. return "%s"
  203. def force_no_ordering(self):
  204. """
  205. Return a list used in the "ORDER BY" clause to force no ordering at
  206. all. Return an empty list to include nothing in the ordering.
  207. """
  208. return []
  209. def for_update_sql(self, nowait=False, skip_locked=False, of=(), no_key=False):
  210. """
  211. Return the FOR UPDATE SQL clause to lock rows for an update operation.
  212. """
  213. return "FOR%s UPDATE%s%s%s" % (
  214. " NO KEY" if no_key else "",
  215. " OF %s" % ", ".join(of) if of else "",
  216. " NOWAIT" if nowait else "",
  217. " SKIP LOCKED" if skip_locked else "",
  218. )
  219. def _get_limit_offset_params(self, low_mark, high_mark):
  220. offset = low_mark or 0
  221. if high_mark is not None:
  222. return (high_mark - offset), offset
  223. elif offset:
  224. return self.connection.ops.no_limit_value(), offset
  225. return None, offset
  226. def limit_offset_sql(self, low_mark, high_mark):
  227. """Return LIMIT/OFFSET SQL clause."""
  228. limit, offset = self._get_limit_offset_params(low_mark, high_mark)
  229. return " ".join(
  230. sql
  231. for sql in (
  232. ("LIMIT %d" % limit) if limit else None,
  233. ("OFFSET %d" % offset) if offset else None,
  234. )
  235. if sql
  236. )
  237. def last_executed_query(self, cursor, sql, params):
  238. """
  239. Return a string of the query last executed by the given cursor, with
  240. placeholders replaced with actual values.
  241. `sql` is the raw query containing placeholders and `params` is the
  242. sequence of parameters. These are used by default, but this method
  243. exists for database backends to provide a better implementation
  244. according to their own quoting schemes.
  245. """
  246. # Convert params to contain string values.
  247. def to_string(s):
  248. return force_str(s, strings_only=True, errors="replace")
  249. if isinstance(params, (list, tuple)):
  250. u_params = tuple(to_string(val) for val in params)
  251. elif params is None:
  252. u_params = ()
  253. else:
  254. u_params = {to_string(k): to_string(v) for k, v in params.items()}
  255. return "QUERY = %r - PARAMS = %r" % (sql, u_params)
  256. def last_insert_id(self, cursor, table_name, pk_name):
  257. """
  258. Given a cursor object that has just performed an INSERT statement into
  259. a table that has an auto-incrementing ID, return the newly created ID.
  260. `pk_name` is the name of the primary-key column.
  261. """
  262. return cursor.lastrowid
  263. def lookup_cast(self, lookup_type, internal_type=None):
  264. """
  265. Return the string to use in a query when performing lookups
  266. ("contains", "like", etc.). It should contain a '%s' placeholder for
  267. the column being searched against.
  268. """
  269. return "%s"
  270. def max_in_list_size(self):
  271. """
  272. Return the maximum number of items that can be passed in a single 'IN'
  273. list condition, or None if the backend does not impose a limit.
  274. """
  275. return None
  276. def max_name_length(self):
  277. """
  278. Return the maximum length of table and column names, or None if there
  279. is no limit.
  280. """
  281. return None
  282. def no_limit_value(self):
  283. """
  284. Return the value to use for the LIMIT when we are wanting "LIMIT
  285. infinity". Return None if the limit clause can be omitted in this case.
  286. """
  287. raise NotImplementedError(
  288. "subclasses of BaseDatabaseOperations may require a no_limit_value() method"
  289. )
  290. def pk_default_value(self):
  291. """
  292. Return the value to use during an INSERT statement to specify that
  293. the field should use its default value.
  294. """
  295. return "DEFAULT"
  296. def prepare_sql_script(self, sql):
  297. """
  298. Take an SQL script that may contain multiple lines and return a list
  299. of statements to feed to successive cursor.execute() calls.
  300. Since few databases are able to process raw SQL scripts in a single
  301. cursor.execute() call and PEP 249 doesn't talk about this use case,
  302. the default implementation is conservative.
  303. """
  304. return [
  305. sqlparse.format(statement, strip_comments=True)
  306. for statement in sqlparse.split(sql)
  307. if statement
  308. ]
  309. def process_clob(self, value):
  310. """
  311. Return the value of a CLOB column, for backends that return a locator
  312. object that requires additional processing.
  313. """
  314. return value
  315. def return_insert_columns(self, fields):
  316. """
  317. For backends that support returning columns as part of an insert query,
  318. return the SQL and params to append to the INSERT query. The returned
  319. fragment should contain a format string to hold the appropriate column.
  320. """
  321. pass
  322. def compiler(self, compiler_name):
  323. """
  324. Return the SQLCompiler class corresponding to the given name,
  325. in the namespace corresponding to the `compiler_module` attribute
  326. on this backend.
  327. """
  328. if self._cache is None:
  329. self._cache = import_module(self.compiler_module)
  330. return getattr(self._cache, compiler_name)
  331. def quote_name(self, name):
  332. """
  333. Return a quoted version of the given table, index, or column name. Do
  334. not quote the given name if it's already been quoted.
  335. """
  336. raise NotImplementedError(
  337. "subclasses of BaseDatabaseOperations may require a quote_name() method"
  338. )
  339. def regex_lookup(self, lookup_type):
  340. """
  341. Return the string to use in a query when performing regular expression
  342. lookups (using "regex" or "iregex"). It should contain a '%s'
  343. placeholder for the column being searched against.
  344. If the feature is not supported (or part of it is not supported), raise
  345. NotImplementedError.
  346. """
  347. raise NotImplementedError(
  348. "subclasses of BaseDatabaseOperations may require a regex_lookup() method"
  349. )
  350. def savepoint_create_sql(self, sid):
  351. """
  352. Return the SQL for starting a new savepoint. Only required if the
  353. "uses_savepoints" feature is True. The "sid" parameter is a string
  354. for the savepoint id.
  355. """
  356. return "SAVEPOINT %s" % self.quote_name(sid)
  357. def savepoint_commit_sql(self, sid):
  358. """
  359. Return the SQL for committing the given savepoint.
  360. """
  361. return "RELEASE SAVEPOINT %s" % self.quote_name(sid)
  362. def savepoint_rollback_sql(self, sid):
  363. """
  364. Return the SQL for rolling back the given savepoint.
  365. """
  366. return "ROLLBACK TO SAVEPOINT %s" % self.quote_name(sid)
  367. def set_time_zone_sql(self):
  368. """
  369. Return the SQL that will set the connection's time zone.
  370. Return '' if the backend doesn't support time zones.
  371. """
  372. return ""
  373. def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False):
  374. """
  375. Return a list of SQL statements required to remove all data from
  376. the given database tables (without actually removing the tables
  377. themselves).
  378. The `style` argument is a Style object as returned by either
  379. color_style() or no_style() in django.core.management.color.
  380. If `reset_sequences` is True, the list includes SQL statements required
  381. to reset the sequences.
  382. The `allow_cascade` argument determines whether truncation may cascade
  383. to tables with foreign keys pointing the tables being truncated.
  384. PostgreSQL requires a cascade even if these tables are empty.
  385. """
  386. raise NotImplementedError(
  387. "subclasses of BaseDatabaseOperations must provide an sql_flush() method"
  388. )
  389. def execute_sql_flush(self, sql_list):
  390. """Execute a list of SQL statements to flush the database."""
  391. with transaction.atomic(
  392. using=self.connection.alias,
  393. savepoint=self.connection.features.can_rollback_ddl,
  394. ):
  395. with self.connection.cursor() as cursor:
  396. for sql in sql_list:
  397. cursor.execute(sql)
  398. def sequence_reset_by_name_sql(self, style, sequences):
  399. """
  400. Return a list of the SQL statements required to reset sequences
  401. passed in `sequences`.
  402. The `style` argument is a Style object as returned by either
  403. color_style() or no_style() in django.core.management.color.
  404. """
  405. return []
  406. def sequence_reset_sql(self, style, model_list):
  407. """
  408. Return a list of the SQL statements required to reset sequences for
  409. the given models.
  410. The `style` argument is a Style object as returned by either
  411. color_style() or no_style() in django.core.management.color.
  412. """
  413. return [] # No sequence reset required by default.
  414. def start_transaction_sql(self):
  415. """Return the SQL statement required to start a transaction."""
  416. return "BEGIN;"
  417. def end_transaction_sql(self, success=True):
  418. """Return the SQL statement required to end a transaction."""
  419. if not success:
  420. return "ROLLBACK;"
  421. return "COMMIT;"
  422. def tablespace_sql(self, tablespace, inline=False):
  423. """
  424. Return the SQL that will be used in a query to define the tablespace.
  425. Return '' if the backend doesn't support tablespaces.
  426. If `inline` is True, append the SQL to a row; otherwise append it to
  427. the entire CREATE TABLE or CREATE INDEX statement.
  428. """
  429. return ""
  430. def prep_for_like_query(self, x):
  431. """Prepare a value for use in a LIKE query."""
  432. return str(x).replace("\\", "\\\\").replace("%", r"\%").replace("_", r"\_")
  433. # Same as prep_for_like_query(), but called for "iexact" matches, which
  434. # need not necessarily be implemented using "LIKE" in the backend.
  435. prep_for_iexact_query = prep_for_like_query
  436. def validate_autopk_value(self, value):
  437. """
  438. Certain backends do not accept some values for "serial" fields
  439. (for example zero in MySQL). Raise a ValueError if the value is
  440. invalid, otherwise return the validated value.
  441. """
  442. return value
  443. def adapt_unknown_value(self, value):
  444. """
  445. Transform a value to something compatible with the backend driver.
  446. This method only depends on the type of the value. It's designed for
  447. cases where the target type isn't known, such as .raw() SQL queries.
  448. As a consequence it may not work perfectly in all circumstances.
  449. """
  450. if isinstance(value, datetime.datetime): # must be before date
  451. return self.adapt_datetimefield_value(value)
  452. elif isinstance(value, datetime.date):
  453. return self.adapt_datefield_value(value)
  454. elif isinstance(value, datetime.time):
  455. return self.adapt_timefield_value(value)
  456. elif isinstance(value, decimal.Decimal):
  457. return self.adapt_decimalfield_value(value)
  458. else:
  459. return value
  460. def adapt_integerfield_value(self, value, internal_type):
  461. return value
  462. def adapt_datefield_value(self, value):
  463. """
  464. Transform a date value to an object compatible with what is expected
  465. by the backend driver for date columns.
  466. """
  467. if value is None:
  468. return None
  469. return str(value)
  470. def adapt_datetimefield_value(self, value):
  471. """
  472. Transform a datetime value to an object compatible with what is expected
  473. by the backend driver for datetime columns.
  474. """
  475. if value is None:
  476. return None
  477. # Expression values are adapted by the database.
  478. if hasattr(value, "resolve_expression"):
  479. return value
  480. return str(value)
  481. def adapt_timefield_value(self, value):
  482. """
  483. Transform a time value to an object compatible with what is expected
  484. by the backend driver for time columns.
  485. """
  486. if value is None:
  487. return None
  488. # Expression values are adapted by the database.
  489. if hasattr(value, "resolve_expression"):
  490. return value
  491. if timezone.is_aware(value):
  492. raise ValueError("Django does not support timezone-aware times.")
  493. return str(value)
  494. def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None):
  495. """
  496. Transform a decimal.Decimal value to an object compatible with what is
  497. expected by the backend driver for decimal (numeric) columns.
  498. """
  499. return utils.format_number(value, max_digits, decimal_places)
  500. def adapt_ipaddressfield_value(self, value):
  501. """
  502. Transform a string representation of an IP address into the expected
  503. type for the backend driver.
  504. """
  505. return value or None
  506. def adapt_json_value(self, value, encoder):
  507. return json.dumps(value, cls=encoder)
  508. def year_lookup_bounds_for_date_field(self, value, iso_year=False):
  509. """
  510. Return a two-elements list with the lower and upper bound to be used
  511. with a BETWEEN operator to query a DateField value using a year
  512. lookup.
  513. `value` is an int, containing the looked-up year.
  514. If `iso_year` is True, return bounds for ISO-8601 week-numbering years.
  515. """
  516. if iso_year:
  517. first = datetime.date.fromisocalendar(value, 1, 1)
  518. second = datetime.date.fromisocalendar(
  519. value + 1, 1, 1
  520. ) - datetime.timedelta(days=1)
  521. else:
  522. first = datetime.date(value, 1, 1)
  523. second = datetime.date(value, 12, 31)
  524. first = self.adapt_datefield_value(first)
  525. second = self.adapt_datefield_value(second)
  526. return [first, second]
  527. def year_lookup_bounds_for_datetime_field(self, value, iso_year=False):
  528. """
  529. Return a two-elements list with the lower and upper bound to be used
  530. with a BETWEEN operator to query a DateTimeField value using a year
  531. lookup.
  532. `value` is an int, containing the looked-up year.
  533. If `iso_year` is True, return bounds for ISO-8601 week-numbering years.
  534. """
  535. if iso_year:
  536. first = datetime.datetime.fromisocalendar(value, 1, 1)
  537. second = datetime.datetime.fromisocalendar(
  538. value + 1, 1, 1
  539. ) - datetime.timedelta(microseconds=1)
  540. else:
  541. first = datetime.datetime(value, 1, 1)
  542. second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999)
  543. if settings.USE_TZ:
  544. tz = timezone.get_current_timezone()
  545. first = timezone.make_aware(first, tz)
  546. second = timezone.make_aware(second, tz)
  547. first = self.adapt_datetimefield_value(first)
  548. second = self.adapt_datetimefield_value(second)
  549. return [first, second]
  550. def get_db_converters(self, expression):
  551. """
  552. Return a list of functions needed to convert field data.
  553. Some field types on some backends do not provide data in the correct
  554. format, this is the hook for converter functions.
  555. """
  556. return []
  557. def convert_durationfield_value(self, value, expression, connection):
  558. if value is not None:
  559. return datetime.timedelta(0, 0, value)
  560. def check_expression_support(self, expression):
  561. """
  562. Check that the backend supports the provided expression.
  563. This is used on specific backends to rule out known expressions
  564. that have problematic or nonexistent implementations. If the
  565. expression has a known problem, the backend should raise
  566. NotSupportedError.
  567. """
  568. pass
  569. def conditional_expression_supported_in_where_clause(self, expression):
  570. """
  571. Return True, if the conditional expression is supported in the WHERE
  572. clause.
  573. """
  574. return True
  575. def combine_expression(self, connector, sub_expressions):
  576. """
  577. Combine a list of subexpressions into a single expression, using
  578. the provided connecting operator. This is required because operators
  579. can vary between backends (e.g., Oracle with %% and &) and between
  580. subexpression types (e.g., date expressions).
  581. """
  582. conn = " %s " % connector
  583. return conn.join(sub_expressions)
  584. def combine_duration_expression(self, connector, sub_expressions):
  585. return self.combine_expression(connector, sub_expressions)
  586. def binary_placeholder_sql(self, value):
  587. """
  588. Some backends require special syntax to insert binary content (MySQL
  589. for example uses '_binary %s').
  590. """
  591. return "%s"
  592. def modify_insert_params(self, placeholder, params):
  593. """
  594. Allow modification of insert parameters. Needed for Oracle Spatial
  595. backend due to #10888.
  596. """
  597. return params
  598. def integer_field_range(self, internal_type):
  599. """
  600. Given an integer field internal type (e.g. 'PositiveIntegerField'),
  601. return a tuple of the (min_value, max_value) form representing the
  602. range of the column type bound to the field.
  603. """
  604. return self.integer_field_ranges[internal_type]
  605. def subtract_temporals(self, internal_type, lhs, rhs):
  606. if self.connection.features.supports_temporal_subtraction:
  607. lhs_sql, lhs_params = lhs
  608. rhs_sql, rhs_params = rhs
  609. return "(%s - %s)" % (lhs_sql, rhs_sql), (*lhs_params, *rhs_params)
  610. raise NotSupportedError(
  611. "This backend does not support %s subtraction." % internal_type
  612. )
  613. def window_frame_start(self, start):
  614. if isinstance(start, int):
  615. if start < 0:
  616. return "%d %s" % (abs(start), self.PRECEDING)
  617. elif start == 0:
  618. return self.CURRENT_ROW
  619. elif start is None:
  620. return self.UNBOUNDED_PRECEDING
  621. raise ValueError(
  622. "start argument must be a negative integer, zero, or None, but got '%s'."
  623. % start
  624. )
  625. def window_frame_end(self, end):
  626. if isinstance(end, int):
  627. if end == 0:
  628. return self.CURRENT_ROW
  629. elif end > 0:
  630. return "%d %s" % (end, self.FOLLOWING)
  631. elif end is None:
  632. return self.UNBOUNDED_FOLLOWING
  633. raise ValueError(
  634. "end argument must be a positive integer, zero, or None, but got '%s'."
  635. % end
  636. )
  637. def window_frame_rows_start_end(self, start=None, end=None):
  638. """
  639. Return SQL for start and end points in an OVER clause window frame.
  640. """
  641. if not self.connection.features.supports_over_clause:
  642. raise NotSupportedError("This backend does not support window expressions.")
  643. return self.window_frame_start(start), self.window_frame_end(end)
  644. def window_frame_range_start_end(self, start=None, end=None):
  645. start_, end_ = self.window_frame_rows_start_end(start, end)
  646. features = self.connection.features
  647. if features.only_supports_unbounded_with_preceding_and_following and (
  648. (start and start < 0) or (end and end > 0)
  649. ):
  650. raise NotSupportedError(
  651. "%s only supports UNBOUNDED together with PRECEDING and "
  652. "FOLLOWING." % self.connection.display_name
  653. )
  654. return start_, end_
  655. def explain_query_prefix(self, format=None, **options):
  656. if not self.connection.features.supports_explaining_query_execution:
  657. raise NotSupportedError(
  658. "This backend does not support explaining query execution."
  659. )
  660. if format:
  661. supported_formats = self.connection.features.supported_explain_formats
  662. normalized_format = format.upper()
  663. if normalized_format not in supported_formats:
  664. msg = "%s is not a recognized format." % normalized_format
  665. if supported_formats:
  666. msg += " Allowed formats: %s" % ", ".join(sorted(supported_formats))
  667. else:
  668. msg += (
  669. f" {self.connection.display_name} does not support any formats."
  670. )
  671. raise ValueError(msg)
  672. if options:
  673. raise ValueError("Unknown options: %s" % ", ".join(sorted(options.keys())))
  674. return self.explain_prefix
  675. def insert_statement(self, on_conflict=None):
  676. return "INSERT INTO"
  677. def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields):
  678. return ""
  679. def prepare_join_on_clause(self, lhs_table, lhs_field, rhs_table, rhs_field):
  680. lhs_expr = Col(lhs_table, lhs_field)
  681. rhs_expr = Col(rhs_table, rhs_field)
  682. return lhs_expr, rhs_expr