operations.py 15 KB

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