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.

operations.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import datetime
  2. import decimal
  3. import uuid
  4. from functools import lru_cache
  5. from itertools import chain
  6. from django.conf import settings
  7. from django.core.exceptions import FieldError
  8. from django.db import utils
  9. from django.db.backends.base.operations import BaseDatabaseOperations
  10. from django.db.models import aggregates, fields
  11. from django.db.models.expressions import Col
  12. from django.utils import timezone
  13. from django.utils.dateparse import parse_date, parse_datetime, parse_time
  14. from django.utils.duration import duration_microseconds
  15. from django.utils.functional import cached_property
  16. class DatabaseOperations(BaseDatabaseOperations):
  17. cast_char_field_without_max_length = 'text'
  18. cast_data_types = {
  19. 'DateField': 'TEXT',
  20. 'DateTimeField': 'TEXT',
  21. }
  22. explain_prefix = 'EXPLAIN QUERY PLAN'
  23. def bulk_batch_size(self, fields, objs):
  24. """
  25. SQLite has a compile-time default (SQLITE_LIMIT_VARIABLE_NUMBER) of
  26. 999 variables per query.
  27. If there's only a single field to insert, the limit is 500
  28. (SQLITE_MAX_COMPOUND_SELECT).
  29. """
  30. if len(fields) == 1:
  31. return 500
  32. elif len(fields) > 1:
  33. return self.connection.features.max_query_params // len(fields)
  34. else:
  35. return len(objs)
  36. def check_expression_support(self, expression):
  37. bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
  38. bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
  39. if isinstance(expression, bad_aggregates):
  40. for expr in expression.get_source_expressions():
  41. try:
  42. output_field = expr.output_field
  43. except FieldError:
  44. # Not every subexpression has an output_field which is fine
  45. # to ignore.
  46. pass
  47. else:
  48. if isinstance(output_field, bad_fields):
  49. raise utils.NotSupportedError(
  50. 'You cannot use Sum, Avg, StdDev, and Variance '
  51. 'aggregations on date/time fields in sqlite3 '
  52. 'since date/time is saved as text.'
  53. )
  54. if isinstance(expression, aggregates.Aggregate) and len(expression.source_expressions) > 1:
  55. raise utils.NotSupportedError(
  56. "SQLite doesn't support DISTINCT on aggregate functions "
  57. "accepting multiple arguments."
  58. )
  59. def date_extract_sql(self, lookup_type, field_name):
  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 "django_date_extract('%s', %s)" % (lookup_type.lower(), field_name)
  66. def date_interval_sql(self, timedelta):
  67. return str(duration_microseconds(timedelta))
  68. def format_for_duration_arithmetic(self, sql):
  69. """Do nothing since formatting is handled in the custom function."""
  70. return sql
  71. def date_trunc_sql(self, lookup_type, field_name):
  72. return "django_date_trunc('%s', %s)" % (lookup_type.lower(), field_name)
  73. def time_trunc_sql(self, lookup_type, field_name):
  74. return "django_time_trunc('%s', %s)" % (lookup_type.lower(), field_name)
  75. def _convert_tzname_to_sql(self, tzname):
  76. return "'%s'" % tzname if settings.USE_TZ else 'NULL'
  77. def datetime_cast_date_sql(self, field_name, tzname):
  78. return "django_datetime_cast_date(%s, %s)" % (
  79. field_name, self._convert_tzname_to_sql(tzname),
  80. )
  81. def datetime_cast_time_sql(self, field_name, tzname):
  82. return "django_datetime_cast_time(%s, %s)" % (
  83. field_name, self._convert_tzname_to_sql(tzname),
  84. )
  85. def datetime_extract_sql(self, lookup_type, field_name, tzname):
  86. return "django_datetime_extract('%s', %s, %s)" % (
  87. lookup_type.lower(), field_name, self._convert_tzname_to_sql(tzname),
  88. )
  89. def datetime_trunc_sql(self, lookup_type, field_name, tzname):
  90. return "django_datetime_trunc('%s', %s, %s)" % (
  91. lookup_type.lower(), field_name, self._convert_tzname_to_sql(tzname),
  92. )
  93. def time_extract_sql(self, lookup_type, field_name):
  94. return "django_time_extract('%s', %s)" % (lookup_type.lower(), field_name)
  95. def pk_default_value(self):
  96. return "NULL"
  97. def _quote_params_for_last_executed_query(self, params):
  98. """
  99. Only for last_executed_query! Don't use this to execute SQL queries!
  100. """
  101. # This function is limited both by SQLITE_LIMIT_VARIABLE_NUMBER (the
  102. # number of parameters, default = 999) and SQLITE_MAX_COLUMN (the
  103. # number of return values, default = 2000). Since Python's sqlite3
  104. # module doesn't expose the get_limit() C API, assume the default
  105. # limits are in effect and split the work in batches if needed.
  106. BATCH_SIZE = 999
  107. if len(params) > BATCH_SIZE:
  108. results = ()
  109. for index in range(0, len(params), BATCH_SIZE):
  110. chunk = params[index:index + BATCH_SIZE]
  111. results += self._quote_params_for_last_executed_query(chunk)
  112. return results
  113. sql = 'SELECT ' + ', '.join(['QUOTE(?)'] * len(params))
  114. # Bypass Django's wrappers and use the underlying sqlite3 connection
  115. # to avoid logging this query - it would trigger infinite recursion.
  116. cursor = self.connection.connection.cursor()
  117. # Native sqlite3 cursors cannot be used as context managers.
  118. try:
  119. return cursor.execute(sql, params).fetchone()
  120. finally:
  121. cursor.close()
  122. def last_executed_query(self, cursor, sql, params):
  123. # Python substitutes parameters in Modules/_sqlite/cursor.c with:
  124. # pysqlite_statement_bind_parameters(self->statement, parameters, allow_8bit_chars);
  125. # Unfortunately there is no way to reach self->statement from Python,
  126. # so we quote and substitute parameters manually.
  127. if params:
  128. if isinstance(params, (list, tuple)):
  129. params = self._quote_params_for_last_executed_query(params)
  130. else:
  131. values = tuple(params.values())
  132. values = self._quote_params_for_last_executed_query(values)
  133. params = dict(zip(params, values))
  134. return sql % params
  135. # For consistency with SQLiteCursorWrapper.execute(), just return sql
  136. # when there are no parameters. See #13648 and #17158.
  137. else:
  138. return sql
  139. def quote_name(self, name):
  140. if name.startswith('"') and name.endswith('"'):
  141. return name # Quoting once is enough.
  142. return '"%s"' % name
  143. def no_limit_value(self):
  144. return -1
  145. def __references_graph(self, table_name):
  146. query = """
  147. WITH tables AS (
  148. SELECT %s name
  149. UNION
  150. SELECT sqlite_master.name
  151. FROM sqlite_master
  152. JOIN tables ON (sql REGEXP %s || tables.name || %s)
  153. ) SELECT name FROM tables;
  154. """
  155. params = (
  156. table_name,
  157. r'(?i)\s+references\s+("|\')?',
  158. r'("|\')?\s*\(',
  159. )
  160. with self.connection.cursor() as cursor:
  161. results = cursor.execute(query, params)
  162. return [row[0] for row in results.fetchall()]
  163. @cached_property
  164. def _references_graph(self):
  165. # 512 is large enough to fit the ~330 tables (as of this writing) in
  166. # Django's test suite.
  167. return lru_cache(maxsize=512)(self.__references_graph)
  168. def sql_flush(self, style, tables, sequences, allow_cascade=False):
  169. if tables and allow_cascade:
  170. # Simulate TRUNCATE CASCADE by recursively collecting the tables
  171. # referencing the tables to be flushed.
  172. tables = set(chain.from_iterable(self._references_graph(table) for table in tables))
  173. sql = ['%s %s %s;' % (
  174. style.SQL_KEYWORD('DELETE'),
  175. style.SQL_KEYWORD('FROM'),
  176. style.SQL_FIELD(self.quote_name(table))
  177. ) for table in tables]
  178. # Note: No requirement for reset of auto-incremented indices (cf. other
  179. # sql_flush() implementations). Just return SQL at this point
  180. return sql
  181. def adapt_datetimefield_value(self, value):
  182. if value is None:
  183. return None
  184. # Expression values are adapted by the database.
  185. if hasattr(value, 'resolve_expression'):
  186. return value
  187. # SQLite doesn't support tz-aware datetimes
  188. if timezone.is_aware(value):
  189. if settings.USE_TZ:
  190. value = timezone.make_naive(value, self.connection.timezone)
  191. else:
  192. raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")
  193. return str(value)
  194. def adapt_timefield_value(self, value):
  195. if value is None:
  196. return None
  197. # Expression values are adapted by the database.
  198. if hasattr(value, 'resolve_expression'):
  199. return value
  200. # SQLite doesn't support tz-aware datetimes
  201. if timezone.is_aware(value):
  202. raise ValueError("SQLite backend does not support timezone-aware times.")
  203. return str(value)
  204. def get_db_converters(self, expression):
  205. converters = super().get_db_converters(expression)
  206. internal_type = expression.output_field.get_internal_type()
  207. if internal_type == 'DateTimeField':
  208. converters.append(self.convert_datetimefield_value)
  209. elif internal_type == 'DateField':
  210. converters.append(self.convert_datefield_value)
  211. elif internal_type == 'TimeField':
  212. converters.append(self.convert_timefield_value)
  213. elif internal_type == 'DecimalField':
  214. converters.append(self.get_decimalfield_converter(expression))
  215. elif internal_type == 'UUIDField':
  216. converters.append(self.convert_uuidfield_value)
  217. elif internal_type in ('NullBooleanField', 'BooleanField'):
  218. converters.append(self.convert_booleanfield_value)
  219. return converters
  220. def convert_datetimefield_value(self, value, expression, connection):
  221. if value is not None:
  222. if not isinstance(value, datetime.datetime):
  223. value = parse_datetime(value)
  224. if settings.USE_TZ and not timezone.is_aware(value):
  225. value = timezone.make_aware(value, self.connection.timezone)
  226. return value
  227. def convert_datefield_value(self, value, expression, connection):
  228. if value is not None:
  229. if not isinstance(value, datetime.date):
  230. value = parse_date(value)
  231. return value
  232. def convert_timefield_value(self, value, expression, connection):
  233. if value is not None:
  234. if not isinstance(value, datetime.time):
  235. value = parse_time(value)
  236. return value
  237. def get_decimalfield_converter(self, expression):
  238. # SQLite stores only 15 significant digits. Digits coming from
  239. # float inaccuracy must be removed.
  240. create_decimal = decimal.Context(prec=15).create_decimal_from_float
  241. if isinstance(expression, Col):
  242. quantize_value = decimal.Decimal(1).scaleb(-expression.output_field.decimal_places)
  243. def converter(value, expression, connection):
  244. if value is not None:
  245. return create_decimal(value).quantize(quantize_value, context=expression.output_field.context)
  246. else:
  247. def converter(value, expression, connection):
  248. if value is not None:
  249. return create_decimal(value)
  250. return converter
  251. def convert_uuidfield_value(self, value, expression, connection):
  252. if value is not None:
  253. value = uuid.UUID(value)
  254. return value
  255. def convert_booleanfield_value(self, value, expression, connection):
  256. return bool(value) if value in (1, 0) else value
  257. def bulk_insert_sql(self, fields, placeholder_rows):
  258. return " UNION ALL ".join(
  259. "SELECT %s" % ", ".join(row)
  260. for row in placeholder_rows
  261. )
  262. def combine_expression(self, connector, sub_expressions):
  263. # SQLite doesn't have a ^ operator, so use the user-defined POWER
  264. # function that's registered in connect().
  265. if connector == '^':
  266. return 'POWER(%s)' % ','.join(sub_expressions)
  267. return super().combine_expression(connector, sub_expressions)
  268. def combine_duration_expression(self, connector, sub_expressions):
  269. if connector not in ['+', '-']:
  270. raise utils.DatabaseError('Invalid connector for timedelta: %s.' % connector)
  271. fn_params = ["'%s'" % connector] + sub_expressions
  272. if len(fn_params) > 3:
  273. raise ValueError('Too many params for timedelta operations.')
  274. return "django_format_dtdelta(%s)" % ', '.join(fn_params)
  275. def integer_field_range(self, internal_type):
  276. # SQLite doesn't enforce any integer constraints
  277. return (None, None)
  278. def subtract_temporals(self, internal_type, lhs, rhs):
  279. lhs_sql, lhs_params = lhs
  280. rhs_sql, rhs_params = rhs
  281. if internal_type == 'TimeField':
  282. return "django_time_diff(%s, %s)" % (lhs_sql, rhs_sql), lhs_params + rhs_params
  283. return "django_timestamp_diff(%s, %s)" % (lhs_sql, rhs_sql), lhs_params + rhs_params
  284. def insert_statement(self, ignore_conflicts=False):
  285. return 'INSERT OR IGNORE INTO' if ignore_conflicts else super().insert_statement(ignore_conflicts)