operations.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import datetime
  2. import decimal
  3. import sqlite3
  4. import uuid
  5. from functools import lru_cache
  6. from itertools import chain
  7. from django.conf import settings
  8. from django.core.exceptions import FieldError
  9. from django.db import DatabaseError, NotSupportedError, models
  10. from django.db.backends.base.operations import BaseDatabaseOperations
  11. from django.db.models.constants import OnConflict
  12. from django.db.models.expressions import Col
  13. from django.utils import timezone
  14. from django.utils.dateparse import parse_date, parse_datetime, parse_time
  15. from django.utils.functional import cached_property
  16. from .base import Database
  17. UNSUPPORTED_DATETIME_AGGREGATES = (
  18. models.Sum,
  19. models.Avg,
  20. models.Variance,
  21. models.StdDev,
  22. )
  23. DATETIME_FIELDS = (models.DateField, models.DateTimeField, models.TimeField)
  24. class DatabaseOperations(BaseDatabaseOperations):
  25. cast_char_field_without_max_length = "text"
  26. cast_data_types = {
  27. "DateField": "TEXT",
  28. "DateTimeField": "TEXT",
  29. }
  30. explain_prefix = "EXPLAIN QUERY PLAN"
  31. # List of datatypes to that cannot be extracted with JSON_EXTRACT() on
  32. # SQLite. Use JSON_TYPE() instead.
  33. jsonfield_datatype_values = frozenset(["null", "false", "true"])
  34. def check_expression_support(self, expression):
  35. if isinstance(expression, UNSUPPORTED_DATETIME_AGGREGATES):
  36. for expr in expression.get_source_expressions():
  37. try:
  38. output_field = expr.output_field
  39. except (AttributeError, FieldError):
  40. # Not every subexpression has an output_field which is fine
  41. # to ignore.
  42. pass
  43. else:
  44. if isinstance(output_field, DATETIME_FIELDS):
  45. klass = expression.__class__.__name__
  46. raise NotSupportedError(
  47. f"SQLite does not support {klass} on date or time "
  48. "fields, because they are stored as text."
  49. )
  50. if (
  51. isinstance(expression, models.Aggregate)
  52. and expression.distinct
  53. and len(expression.source_expressions) > 1
  54. ):
  55. raise NotSupportedError(
  56. "SQLite doesn't support DISTINCT on aggregate functions "
  57. "accepting multiple arguments."
  58. )
  59. def date_extract_sql(self, lookup_type, sql, params):
  60. """
  61. Support EXTRACT with a user-defined function django_date_extract()
  62. that's registered in connect(). Use single quotes because this is a
  63. string and could otherwise cause a collision with a field name.
  64. """
  65. return f"django_date_extract(%s, {sql})", (lookup_type.lower(), *params)
  66. def format_for_duration_arithmetic(self, sql):
  67. """Do nothing since formatting is handled in the custom function."""
  68. return sql
  69. def date_trunc_sql(self, lookup_type, sql, params, tzname=None):
  70. return f"django_date_trunc(%s, {sql}, %s, %s)", (
  71. lookup_type.lower(),
  72. *params,
  73. *self._convert_tznames_to_sql(tzname),
  74. )
  75. def time_trunc_sql(self, lookup_type, sql, params, tzname=None):
  76. return f"django_time_trunc(%s, {sql}, %s, %s)", (
  77. lookup_type.lower(),
  78. *params,
  79. *self._convert_tznames_to_sql(tzname),
  80. )
  81. def _convert_tznames_to_sql(self, tzname):
  82. if tzname and settings.USE_TZ:
  83. return tzname, self.connection.timezone_name
  84. return None, None
  85. def datetime_cast_date_sql(self, sql, params, tzname):
  86. return f"django_datetime_cast_date({sql}, %s, %s)", (
  87. *params,
  88. *self._convert_tznames_to_sql(tzname),
  89. )
  90. def datetime_cast_time_sql(self, sql, params, tzname):
  91. return f"django_datetime_cast_time({sql}, %s, %s)", (
  92. *params,
  93. *self._convert_tznames_to_sql(tzname),
  94. )
  95. def datetime_extract_sql(self, lookup_type, sql, params, tzname):
  96. return f"django_datetime_extract(%s, {sql}, %s, %s)", (
  97. lookup_type.lower(),
  98. *params,
  99. *self._convert_tznames_to_sql(tzname),
  100. )
  101. def datetime_trunc_sql(self, lookup_type, sql, params, tzname):
  102. return f"django_datetime_trunc(%s, {sql}, %s, %s)", (
  103. lookup_type.lower(),
  104. *params,
  105. *self._convert_tznames_to_sql(tzname),
  106. )
  107. def time_extract_sql(self, lookup_type, sql, params):
  108. return f"django_time_extract(%s, {sql})", (lookup_type.lower(), *params)
  109. def pk_default_value(self):
  110. return "NULL"
  111. def _quote_params_for_last_executed_query(self, params):
  112. """
  113. Only for last_executed_query! Don't use this to execute SQL queries!
  114. """
  115. connection = self.connection.connection
  116. variable_limit = self.connection.features.max_query_params
  117. column_limit = connection.getlimit(sqlite3.SQLITE_LIMIT_COLUMN)
  118. batch_size = min(variable_limit, column_limit)
  119. if len(params) > batch_size:
  120. results = ()
  121. for index in range(0, len(params), batch_size):
  122. chunk = params[index : index + batch_size]
  123. results += self._quote_params_for_last_executed_query(chunk)
  124. return results
  125. sql = "SELECT " + ", ".join(["QUOTE(?)"] * len(params))
  126. # Bypass Django's wrappers and use the underlying sqlite3 connection
  127. # to avoid logging this query - it would trigger infinite recursion.
  128. cursor = self.connection.connection.cursor()
  129. # Native sqlite3 cursors cannot be used as context managers.
  130. try:
  131. return cursor.execute(sql, params).fetchone()
  132. finally:
  133. cursor.close()
  134. def last_executed_query(self, cursor, sql, params):
  135. # Python substitutes parameters in Modules/_sqlite/cursor.c with:
  136. # bind_parameters(state, self->statement, parameters);
  137. # Unfortunately there is no way to reach self->statement from Python,
  138. # so we quote and substitute parameters manually.
  139. if params:
  140. if isinstance(params, (list, tuple)):
  141. params = self._quote_params_for_last_executed_query(params)
  142. else:
  143. values = tuple(params.values())
  144. values = self._quote_params_for_last_executed_query(values)
  145. params = dict(zip(params, values))
  146. return sql % params
  147. # For consistency with SQLiteCursorWrapper.execute(), just return sql
  148. # when there are no parameters. See #13648 and #17158.
  149. else:
  150. return sql
  151. def quote_name(self, name):
  152. if name.startswith('"') and name.endswith('"'):
  153. return name # Quoting once is enough.
  154. return '"%s"' % name
  155. def no_limit_value(self):
  156. return -1
  157. def __references_graph(self, table_name):
  158. query = """
  159. WITH tables AS (
  160. SELECT %s name
  161. UNION
  162. SELECT sqlite_master.name
  163. FROM sqlite_master
  164. JOIN tables ON (sql REGEXP %s || tables.name || %s)
  165. ) SELECT name FROM tables;
  166. """
  167. params = (
  168. table_name,
  169. r'(?i)\s+references\s+("|\')?',
  170. r'("|\')?\s*\(',
  171. )
  172. with self.connection.cursor() as cursor:
  173. results = cursor.execute(query, params)
  174. return [row[0] for row in results.fetchall()]
  175. @cached_property
  176. def _references_graph(self):
  177. # 512 is large enough to fit the ~330 tables (as of this writing) in
  178. # Django's test suite.
  179. return lru_cache(maxsize=512)(self.__references_graph)
  180. def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False):
  181. if tables and allow_cascade:
  182. # Simulate TRUNCATE CASCADE by recursively collecting the tables
  183. # referencing the tables to be flushed.
  184. tables = set(
  185. chain.from_iterable(self._references_graph(table) for table in tables)
  186. )
  187. sql = [
  188. "%s %s %s;"
  189. % (
  190. style.SQL_KEYWORD("DELETE"),
  191. style.SQL_KEYWORD("FROM"),
  192. style.SQL_FIELD(self.quote_name(table)),
  193. )
  194. for table in tables
  195. ]
  196. if reset_sequences:
  197. sequences = [{"table": table} for table in tables]
  198. sql.extend(self.sequence_reset_by_name_sql(style, sequences))
  199. return sql
  200. def sequence_reset_by_name_sql(self, style, sequences):
  201. if not sequences:
  202. return []
  203. return [
  204. "%s %s %s %s = 0 %s %s %s (%s);"
  205. % (
  206. style.SQL_KEYWORD("UPDATE"),
  207. style.SQL_TABLE(self.quote_name("sqlite_sequence")),
  208. style.SQL_KEYWORD("SET"),
  209. style.SQL_FIELD(self.quote_name("seq")),
  210. style.SQL_KEYWORD("WHERE"),
  211. style.SQL_FIELD(self.quote_name("name")),
  212. style.SQL_KEYWORD("IN"),
  213. ", ".join(
  214. ["'%s'" % sequence_info["table"] for sequence_info in sequences]
  215. ),
  216. ),
  217. ]
  218. def adapt_datetimefield_value(self, value):
  219. if value is None:
  220. return None
  221. # SQLite doesn't support tz-aware datetimes
  222. if timezone.is_aware(value):
  223. if settings.USE_TZ:
  224. value = timezone.make_naive(value, self.connection.timezone)
  225. else:
  226. raise ValueError(
  227. "SQLite backend does not support timezone-aware datetimes when "
  228. "USE_TZ is False."
  229. )
  230. return str(value)
  231. def adapt_timefield_value(self, value):
  232. if value is None:
  233. return None
  234. # SQLite doesn't support tz-aware datetimes
  235. if timezone.is_aware(value):
  236. raise ValueError("SQLite backend does not support timezone-aware times.")
  237. return str(value)
  238. def get_db_converters(self, expression):
  239. converters = super().get_db_converters(expression)
  240. internal_type = expression.output_field.get_internal_type()
  241. if internal_type == "DateTimeField":
  242. converters.append(self.convert_datetimefield_value)
  243. elif internal_type == "DateField":
  244. converters.append(self.convert_datefield_value)
  245. elif internal_type == "TimeField":
  246. converters.append(self.convert_timefield_value)
  247. elif internal_type == "DecimalField":
  248. converters.append(self.get_decimalfield_converter(expression))
  249. elif internal_type == "UUIDField":
  250. converters.append(self.convert_uuidfield_value)
  251. elif internal_type == "BooleanField":
  252. converters.append(self.convert_booleanfield_value)
  253. return converters
  254. def convert_datetimefield_value(self, value, expression, connection):
  255. if value is not None:
  256. if not isinstance(value, datetime.datetime):
  257. value = parse_datetime(value)
  258. if settings.USE_TZ and not timezone.is_aware(value):
  259. value = timezone.make_aware(value, self.connection.timezone)
  260. return value
  261. def convert_datefield_value(self, value, expression, connection):
  262. if value is not None:
  263. if not isinstance(value, datetime.date):
  264. value = parse_date(value)
  265. return value
  266. def convert_timefield_value(self, value, expression, connection):
  267. if value is not None:
  268. if not isinstance(value, datetime.time):
  269. value = parse_time(value)
  270. return value
  271. @staticmethod
  272. def _create_decimal(value):
  273. if isinstance(value, (int, str)):
  274. return decimal.Decimal(value)
  275. return decimal.Context(prec=15).create_decimal_from_float(value)
  276. def get_decimalfield_converter(self, expression):
  277. # SQLite stores only 15 significant digits. Digits coming from
  278. # float inaccuracy must be removed.
  279. if isinstance(expression, Col):
  280. quantize_value = decimal.Decimal(1).scaleb(
  281. -expression.output_field.decimal_places
  282. )
  283. def converter(value, expression, connection):
  284. if value is not None:
  285. return self._create_decimal(value).quantize(
  286. quantize_value, context=expression.output_field.context
  287. )
  288. else:
  289. def converter(value, expression, connection):
  290. if value is not None:
  291. return self._create_decimal(value)
  292. return converter
  293. def convert_uuidfield_value(self, value, expression, connection):
  294. if value is not None:
  295. value = uuid.UUID(value)
  296. return value
  297. def convert_booleanfield_value(self, value, expression, connection):
  298. return bool(value) if value in (1, 0) else value
  299. def combine_expression(self, connector, sub_expressions):
  300. # SQLite doesn't have a ^ operator, so use the user-defined POWER
  301. # function that's registered in connect().
  302. if connector == "^":
  303. return "POWER(%s)" % ",".join(sub_expressions)
  304. elif connector == "#":
  305. return "BITXOR(%s)" % ",".join(sub_expressions)
  306. return super().combine_expression(connector, sub_expressions)
  307. def combine_duration_expression(self, connector, sub_expressions):
  308. if connector not in ["+", "-", "*", "/"]:
  309. raise DatabaseError("Invalid connector for timedelta: %s." % connector)
  310. fn_params = ["'%s'" % connector, *sub_expressions]
  311. if len(fn_params) > 3:
  312. raise ValueError("Too many params for timedelta operations.")
  313. return "django_format_dtdelta(%s)" % ", ".join(fn_params)
  314. def integer_field_range(self, internal_type):
  315. # SQLite doesn't enforce any integer constraints, but sqlite3 supports
  316. # integers up to 64 bits.
  317. if internal_type in [
  318. "PositiveBigIntegerField",
  319. "PositiveIntegerField",
  320. "PositiveSmallIntegerField",
  321. ]:
  322. return (0, 9223372036854775807)
  323. return (-9223372036854775808, 9223372036854775807)
  324. def subtract_temporals(self, internal_type, lhs, rhs):
  325. lhs_sql, lhs_params = lhs
  326. rhs_sql, rhs_params = rhs
  327. params = (*lhs_params, *rhs_params)
  328. if internal_type == "TimeField":
  329. return "django_time_diff(%s, %s)" % (lhs_sql, rhs_sql), params
  330. return "django_timestamp_diff(%s, %s)" % (lhs_sql, rhs_sql), params
  331. def insert_statement(self, on_conflict=None):
  332. if on_conflict == OnConflict.IGNORE:
  333. return "INSERT OR IGNORE INTO"
  334. return super().insert_statement(on_conflict=on_conflict)
  335. def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields):
  336. if (
  337. on_conflict == OnConflict.UPDATE
  338. and self.connection.features.supports_update_conflicts_with_target
  339. ):
  340. return "ON CONFLICT(%s) DO UPDATE SET %s" % (
  341. ", ".join(map(self.quote_name, unique_fields)),
  342. ", ".join(
  343. [
  344. f"{field} = EXCLUDED.{field}"
  345. for field in map(self.quote_name, update_fields)
  346. ]
  347. ),
  348. )
  349. return super().on_conflict_suffix_sql(
  350. fields,
  351. on_conflict,
  352. update_fields,
  353. unique_fields,
  354. )
  355. def force_group_by(self):
  356. return ["GROUP BY TRUE"] if Database.sqlite_version_info < (3, 39) else []
  357. def format_json_path_numeric_index(self, num):
  358. return "[#%s]" % num if num < 0 else super().format_json_path_numeric_index(num)