operations.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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_group_by(self):
  204. """
  205. Return a GROUP BY clause to use with a HAVING clause when no grouping
  206. is specified.
  207. """
  208. return []
  209. def force_no_ordering(self):
  210. """
  211. Return a list used in the "ORDER BY" clause to force no ordering at
  212. all. Return an empty list to include nothing in the ordering.
  213. """
  214. return []
  215. def for_update_sql(self, nowait=False, skip_locked=False, of=(), no_key=False):
  216. """
  217. Return the FOR UPDATE SQL clause to lock rows for an update operation.
  218. """
  219. return "FOR%s UPDATE%s%s%s" % (
  220. " NO KEY" if no_key else "",
  221. " OF %s" % ", ".join(of) if of else "",
  222. " NOWAIT" if nowait else "",
  223. " SKIP LOCKED" if skip_locked else "",
  224. )
  225. def _get_limit_offset_params(self, low_mark, high_mark):
  226. offset = low_mark or 0
  227. if high_mark is not None:
  228. return (high_mark - offset), offset
  229. elif offset:
  230. return self.connection.ops.no_limit_value(), offset
  231. return None, offset
  232. def limit_offset_sql(self, low_mark, high_mark):
  233. """Return LIMIT/OFFSET SQL clause."""
  234. limit, offset = self._get_limit_offset_params(low_mark, high_mark)
  235. return " ".join(
  236. sql
  237. for sql in (
  238. ("LIMIT %d" % limit) if limit else None,
  239. ("OFFSET %d" % offset) if offset else None,
  240. )
  241. if sql
  242. )
  243. def bulk_insert_sql(self, fields, placeholder_rows):
  244. placeholder_rows_sql = (", ".join(row) for row in placeholder_rows)
  245. values_sql = ", ".join([f"({sql})" for sql in placeholder_rows_sql])
  246. return f"VALUES {values_sql}"
  247. def last_executed_query(self, cursor, sql, params):
  248. """
  249. Return a string of the query last executed by the given cursor, with
  250. placeholders replaced with actual values.
  251. `sql` is the raw query containing placeholders and `params` is the
  252. sequence of parameters. These are used by default, but this method
  253. exists for database backends to provide a better implementation
  254. according to their own quoting schemes.
  255. """
  256. # Convert params to contain string values.
  257. def to_string(s):
  258. return force_str(s, strings_only=True, errors="replace")
  259. if isinstance(params, (list, tuple)):
  260. u_params = tuple(to_string(val) for val in params)
  261. elif params is None:
  262. u_params = ()
  263. else:
  264. u_params = {to_string(k): to_string(v) for k, v in params.items()}
  265. return "QUERY = %r - PARAMS = %r" % (sql, u_params)
  266. def last_insert_id(self, cursor, table_name, pk_name):
  267. """
  268. Given a cursor object that has just performed an INSERT statement into
  269. a table that has an auto-incrementing ID, return the newly created ID.
  270. `pk_name` is the name of the primary-key column.
  271. """
  272. return cursor.lastrowid
  273. def lookup_cast(self, lookup_type, internal_type=None):
  274. """
  275. Return the string to use in a query when performing lookups
  276. ("contains", "like", etc.). It should contain a '%s' placeholder for
  277. the column being searched against.
  278. """
  279. return "%s"
  280. def max_in_list_size(self):
  281. """
  282. Return the maximum number of items that can be passed in a single 'IN'
  283. list condition, or None if the backend does not impose a limit.
  284. """
  285. return None
  286. def max_name_length(self):
  287. """
  288. Return the maximum length of table and column names, or None if there
  289. is no limit.
  290. """
  291. return None
  292. def no_limit_value(self):
  293. """
  294. Return the value to use for the LIMIT when we are wanting "LIMIT
  295. infinity". Return None if the limit clause can be omitted in this case.
  296. """
  297. raise NotImplementedError(
  298. "subclasses of BaseDatabaseOperations may require a no_limit_value() method"
  299. )
  300. def pk_default_value(self):
  301. """
  302. Return the value to use during an INSERT statement to specify that
  303. the field should use its default value.
  304. """
  305. return "DEFAULT"
  306. def prepare_sql_script(self, sql):
  307. """
  308. Take an SQL script that may contain multiple lines and return a list
  309. of statements to feed to successive cursor.execute() calls.
  310. Since few databases are able to process raw SQL scripts in a single
  311. cursor.execute() call and PEP 249 doesn't talk about this use case,
  312. the default implementation is conservative.
  313. """
  314. return [
  315. sqlparse.format(statement, strip_comments=True)
  316. for statement in sqlparse.split(sql)
  317. if statement
  318. ]
  319. def process_clob(self, value):
  320. """
  321. Return the value of a CLOB column, for backends that return a locator
  322. object that requires additional processing.
  323. """
  324. return value
  325. def return_insert_columns(self, fields):
  326. """
  327. For backends that support returning columns as part of an insert query,
  328. return the SQL and params to append to the INSERT query. The returned
  329. fragment should contain a format string to hold the appropriate column.
  330. """
  331. pass
  332. def compiler(self, compiler_name):
  333. """
  334. Return the SQLCompiler class corresponding to the given name,
  335. in the namespace corresponding to the `compiler_module` attribute
  336. on this backend.
  337. """
  338. if self._cache is None:
  339. self._cache = import_module(self.compiler_module)
  340. return getattr(self._cache, compiler_name)
  341. def quote_name(self, name):
  342. """
  343. Return a quoted version of the given table, index, or column name. Do
  344. not quote the given name if it's already been quoted.
  345. """
  346. raise NotImplementedError(
  347. "subclasses of BaseDatabaseOperations may require a quote_name() method"
  348. )
  349. def regex_lookup(self, lookup_type):
  350. """
  351. Return the string to use in a query when performing regular expression
  352. lookups (using "regex" or "iregex"). It should contain a '%s'
  353. placeholder for the column being searched against.
  354. If the feature is not supported (or part of it is not supported), raise
  355. NotImplementedError.
  356. """
  357. raise NotImplementedError(
  358. "subclasses of BaseDatabaseOperations may require a regex_lookup() method"
  359. )
  360. def savepoint_create_sql(self, sid):
  361. """
  362. Return the SQL for starting a new savepoint. Only required if the
  363. "uses_savepoints" feature is True. The "sid" parameter is a string
  364. for the savepoint id.
  365. """
  366. return "SAVEPOINT %s" % self.quote_name(sid)
  367. def savepoint_commit_sql(self, sid):
  368. """
  369. Return the SQL for committing the given savepoint.
  370. """
  371. return "RELEASE SAVEPOINT %s" % self.quote_name(sid)
  372. def savepoint_rollback_sql(self, sid):
  373. """
  374. Return the SQL for rolling back the given savepoint.
  375. """
  376. return "ROLLBACK TO SAVEPOINT %s" % self.quote_name(sid)
  377. def set_time_zone_sql(self):
  378. """
  379. Return the SQL that will set the connection's time zone.
  380. Return '' if the backend doesn't support time zones.
  381. """
  382. return ""
  383. def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False):
  384. """
  385. Return a list of SQL statements required to remove all data from
  386. the given database tables (without actually removing the tables
  387. themselves).
  388. The `style` argument is a Style object as returned by either
  389. color_style() or no_style() in django.core.management.color.
  390. If `reset_sequences` is True, the list includes SQL statements required
  391. to reset the sequences.
  392. The `allow_cascade` argument determines whether truncation may cascade
  393. to tables with foreign keys pointing the tables being truncated.
  394. PostgreSQL requires a cascade even if these tables are empty.
  395. """
  396. raise NotImplementedError(
  397. "subclasses of BaseDatabaseOperations must provide an sql_flush() method"
  398. )
  399. def execute_sql_flush(self, sql_list):
  400. """Execute a list of SQL statements to flush the database."""
  401. with transaction.atomic(
  402. using=self.connection.alias,
  403. savepoint=self.connection.features.can_rollback_ddl,
  404. ):
  405. with self.connection.cursor() as cursor:
  406. for sql in sql_list:
  407. cursor.execute(sql)
  408. def sequence_reset_by_name_sql(self, style, sequences):
  409. """
  410. Return a list of the SQL statements required to reset sequences
  411. passed in `sequences`.
  412. The `style` argument is a Style object as returned by either
  413. color_style() or no_style() in django.core.management.color.
  414. """
  415. return []
  416. def sequence_reset_sql(self, style, model_list):
  417. """
  418. Return a list of the SQL statements required to reset sequences for
  419. the given models.
  420. The `style` argument is a Style object as returned by either
  421. color_style() or no_style() in django.core.management.color.
  422. """
  423. return [] # No sequence reset required by default.
  424. def start_transaction_sql(self):
  425. """Return the SQL statement required to start a transaction."""
  426. return "BEGIN;"
  427. def end_transaction_sql(self, success=True):
  428. """Return the SQL statement required to end a transaction."""
  429. if not success:
  430. return "ROLLBACK;"
  431. return "COMMIT;"
  432. def tablespace_sql(self, tablespace, inline=False):
  433. """
  434. Return the SQL that will be used in a query to define the tablespace.
  435. Return '' if the backend doesn't support tablespaces.
  436. If `inline` is True, append the SQL to a row; otherwise append it to
  437. the entire CREATE TABLE or CREATE INDEX statement.
  438. """
  439. return ""
  440. def prep_for_like_query(self, x):
  441. """Prepare a value for use in a LIKE query."""
  442. return str(x).replace("\\", "\\\\").replace("%", r"\%").replace("_", r"\_")
  443. # Same as prep_for_like_query(), but called for "iexact" matches, which
  444. # need not necessarily be implemented using "LIKE" in the backend.
  445. prep_for_iexact_query = prep_for_like_query
  446. def validate_autopk_value(self, value):
  447. """
  448. Certain backends do not accept some values for "serial" fields
  449. (for example zero in MySQL). Raise a ValueError if the value is
  450. invalid, otherwise return the validated value.
  451. """
  452. return value
  453. def adapt_unknown_value(self, value):
  454. """
  455. Transform a value to something compatible with the backend driver.
  456. This method only depends on the type of the value. It's designed for
  457. cases where the target type isn't known, such as .raw() SQL queries.
  458. As a consequence it may not work perfectly in all circumstances.
  459. """
  460. if isinstance(value, datetime.datetime): # must be before date
  461. return self.adapt_datetimefield_value(value)
  462. elif isinstance(value, datetime.date):
  463. return self.adapt_datefield_value(value)
  464. elif isinstance(value, datetime.time):
  465. return self.adapt_timefield_value(value)
  466. elif isinstance(value, decimal.Decimal):
  467. return self.adapt_decimalfield_value(value)
  468. else:
  469. return value
  470. def adapt_integerfield_value(self, value, internal_type):
  471. return value
  472. def adapt_datefield_value(self, value):
  473. """
  474. Transform a date value to an object compatible with what is expected
  475. by the backend driver for date columns.
  476. """
  477. if value is None:
  478. return None
  479. return str(value)
  480. def adapt_datetimefield_value(self, value):
  481. """
  482. Transform a datetime value to an object compatible with what is expected
  483. by the backend driver for datetime columns.
  484. """
  485. if value is None:
  486. return None
  487. return str(value)
  488. def adapt_timefield_value(self, value):
  489. """
  490. Transform a time value to an object compatible with what is expected
  491. by the backend driver for time columns.
  492. """
  493. if value is None:
  494. return None
  495. if timezone.is_aware(value):
  496. raise ValueError("Django does not support timezone-aware times.")
  497. return str(value)
  498. def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None):
  499. """
  500. Transform a decimal.Decimal value to an object compatible with what is
  501. expected by the backend driver for decimal (numeric) columns.
  502. """
  503. return utils.format_number(value, max_digits, decimal_places)
  504. def adapt_ipaddressfield_value(self, value):
  505. """
  506. Transform a string representation of an IP address into the expected
  507. type for the backend driver.
  508. """
  509. return value or None
  510. def adapt_json_value(self, value, encoder):
  511. return json.dumps(value, cls=encoder)
  512. def year_lookup_bounds_for_date_field(self, value, iso_year=False):
  513. """
  514. Return a two-elements list with the lower and upper bound to be used
  515. with a BETWEEN operator to query a DateField value using a year
  516. lookup.
  517. `value` is an int, containing the looked-up year.
  518. If `iso_year` is True, return bounds for ISO-8601 week-numbering years.
  519. """
  520. if iso_year:
  521. first = datetime.date.fromisocalendar(value, 1, 1)
  522. second = datetime.date.fromisocalendar(
  523. value + 1, 1, 1
  524. ) - datetime.timedelta(days=1)
  525. else:
  526. first = datetime.date(value, 1, 1)
  527. second = datetime.date(value, 12, 31)
  528. first = self.adapt_datefield_value(first)
  529. second = self.adapt_datefield_value(second)
  530. return [first, second]
  531. def year_lookup_bounds_for_datetime_field(self, value, iso_year=False):
  532. """
  533. Return a two-elements list with the lower and upper bound to be used
  534. with a BETWEEN operator to query a DateTimeField value using a year
  535. lookup.
  536. `value` is an int, containing the looked-up year.
  537. If `iso_year` is True, return bounds for ISO-8601 week-numbering years.
  538. """
  539. if iso_year:
  540. first = datetime.datetime.fromisocalendar(value, 1, 1)
  541. second = datetime.datetime.fromisocalendar(
  542. value + 1, 1, 1
  543. ) - datetime.timedelta(microseconds=1)
  544. else:
  545. first = datetime.datetime(value, 1, 1)
  546. second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999)
  547. if settings.USE_TZ:
  548. tz = timezone.get_current_timezone()
  549. first = timezone.make_aware(first, tz)
  550. second = timezone.make_aware(second, tz)
  551. first = self.adapt_datetimefield_value(first)
  552. second = self.adapt_datetimefield_value(second)
  553. return [first, second]
  554. def get_db_converters(self, expression):
  555. """
  556. Return a list of functions needed to convert field data.
  557. Some field types on some backends do not provide data in the correct
  558. format, this is the hook for converter functions.
  559. """
  560. return []
  561. def convert_durationfield_value(self, value, expression, connection):
  562. if value is not None:
  563. return datetime.timedelta(0, 0, value)
  564. def check_expression_support(self, expression):
  565. """
  566. Check that the backend supports the provided expression.
  567. This is used on specific backends to rule out known expressions
  568. that have problematic or nonexistent implementations. If the
  569. expression has a known problem, the backend should raise
  570. NotSupportedError.
  571. """
  572. pass
  573. def conditional_expression_supported_in_where_clause(self, expression):
  574. """
  575. Return True, if the conditional expression is supported in the WHERE
  576. clause.
  577. """
  578. return True
  579. def combine_expression(self, connector, sub_expressions):
  580. """
  581. Combine a list of subexpressions into a single expression, using
  582. the provided connecting operator. This is required because operators
  583. can vary between backends (e.g., Oracle with %% and &) and between
  584. subexpression types (e.g., date expressions).
  585. """
  586. conn = " %s " % connector
  587. return conn.join(sub_expressions)
  588. def combine_duration_expression(self, connector, sub_expressions):
  589. return self.combine_expression(connector, sub_expressions)
  590. def binary_placeholder_sql(self, value):
  591. """
  592. Some backends require special syntax to insert binary content (MySQL
  593. for example uses '_binary %s').
  594. """
  595. return "%s"
  596. def modify_insert_params(self, placeholder, params):
  597. """
  598. Allow modification of insert parameters. Needed for Oracle Spatial
  599. backend due to #10888.
  600. """
  601. return params
  602. def integer_field_range(self, internal_type):
  603. """
  604. Given an integer field internal type (e.g. 'PositiveIntegerField'),
  605. return a tuple of the (min_value, max_value) form representing the
  606. range of the column type bound to the field.
  607. """
  608. return self.integer_field_ranges[internal_type]
  609. def subtract_temporals(self, internal_type, lhs, rhs):
  610. if self.connection.features.supports_temporal_subtraction:
  611. lhs_sql, lhs_params = lhs
  612. rhs_sql, rhs_params = rhs
  613. return "(%s - %s)" % (lhs_sql, rhs_sql), (*lhs_params, *rhs_params)
  614. raise NotSupportedError(
  615. "This backend does not support %s subtraction." % internal_type
  616. )
  617. def window_frame_value(self, value):
  618. if isinstance(value, int):
  619. if value == 0:
  620. return self.CURRENT_ROW
  621. elif value < 0:
  622. return "%d %s" % (abs(value), self.PRECEDING)
  623. else:
  624. return "%d %s" % (value, self.FOLLOWING)
  625. def window_frame_rows_start_end(self, start=None, end=None):
  626. """
  627. Return SQL for start and end points in an OVER clause window frame.
  628. """
  629. if isinstance(start, int) and isinstance(end, int) and start > end:
  630. raise ValueError("start cannot be greater than end.")
  631. if start is not None and not isinstance(start, int):
  632. raise ValueError(
  633. f"start argument must be an integer, zero, or None, but got '{start}'."
  634. )
  635. if end is not None and not isinstance(end, int):
  636. raise ValueError(
  637. f"end argument must be an integer, zero, or None, but got '{end}'."
  638. )
  639. start_ = self.window_frame_value(start) or self.UNBOUNDED_PRECEDING
  640. end_ = self.window_frame_value(end) or self.UNBOUNDED_FOLLOWING
  641. return start_, end_
  642. def window_frame_range_start_end(self, start=None, end=None):
  643. if (start is not None and not isinstance(start, int)) or (
  644. isinstance(start, int) and start > 0
  645. ):
  646. raise ValueError(
  647. "start argument must be a negative integer, zero, or None, "
  648. "but got '%s'." % start
  649. )
  650. if (end is not None and not isinstance(end, int)) or (
  651. isinstance(end, int) and end < 0
  652. ):
  653. raise ValueError(
  654. "end argument must be a positive integer, zero, or None, but got '%s'."
  655. % end
  656. )
  657. start_ = self.window_frame_value(start) or self.UNBOUNDED_PRECEDING
  658. end_ = self.window_frame_value(end) or self.UNBOUNDED_FOLLOWING
  659. features = self.connection.features
  660. if features.only_supports_unbounded_with_preceding_and_following and (
  661. (start and start < 0) or (end and end > 0)
  662. ):
  663. raise NotSupportedError(
  664. "%s only supports UNBOUNDED together with PRECEDING and "
  665. "FOLLOWING." % self.connection.display_name
  666. )
  667. return start_, end_
  668. def explain_query_prefix(self, format=None, **options):
  669. if not self.connection.features.supports_explaining_query_execution:
  670. raise NotSupportedError(
  671. "This backend does not support explaining query execution."
  672. )
  673. if format:
  674. supported_formats = self.connection.features.supported_explain_formats
  675. normalized_format = format.upper()
  676. if normalized_format not in supported_formats:
  677. msg = "%s is not a recognized format." % normalized_format
  678. if supported_formats:
  679. msg += " Allowed formats: %s" % ", ".join(sorted(supported_formats))
  680. else:
  681. msg += (
  682. f" {self.connection.display_name} does not support any formats."
  683. )
  684. raise ValueError(msg)
  685. if options:
  686. raise ValueError("Unknown options: %s" % ", ".join(sorted(options.keys())))
  687. return self.explain_prefix
  688. def insert_statement(self, on_conflict=None):
  689. return "INSERT INTO"
  690. def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields):
  691. return ""
  692. def prepare_join_on_clause(self, lhs_table, lhs_field, rhs_table, rhs_field):
  693. lhs_expr = Col(lhs_table, lhs_field)
  694. rhs_expr = Col(rhs_table, rhs_field)
  695. return lhs_expr, rhs_expr