PageRenderTime 58ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/django/db/backends/sqlite3/base.py

https://github.com/andnils/django
Python | 571 lines | 512 code | 22 blank | 37 comment | 21 complexity | 03fc12db71d5b56528d070848a533734 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. SQLite3 backend for django.
  3. Works with either the pysqlite2 module or the sqlite3 module in the
  4. standard library.
  5. """
  6. from __future__ import unicode_literals
  7. import datetime
  8. import decimal
  9. import warnings
  10. import re
  11. from django.conf import settings
  12. from django.db import utils
  13. from django.db.backends import (utils as backend_utils, BaseDatabaseFeatures,
  14. BaseDatabaseOperations, BaseDatabaseWrapper, BaseDatabaseValidation)
  15. from django.db.backends.sqlite3.client import DatabaseClient
  16. from django.db.backends.sqlite3.creation import DatabaseCreation
  17. from django.db.backends.sqlite3.introspection import DatabaseIntrospection
  18. from django.db.backends.sqlite3.schema import DatabaseSchemaEditor
  19. from django.db.models import fields
  20. from django.db.models.sql import aggregates
  21. from django.utils.dateparse import parse_date, parse_datetime, parse_time
  22. from django.utils.encoding import force_text
  23. from django.utils.functional import cached_property
  24. from django.utils.safestring import SafeBytes
  25. from django.utils import six
  26. from django.utils import timezone
  27. try:
  28. try:
  29. from pysqlite2 import dbapi2 as Database
  30. except ImportError:
  31. from sqlite3 import dbapi2 as Database
  32. except ImportError as exc:
  33. from django.core.exceptions import ImproperlyConfigured
  34. raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
  35. try:
  36. import pytz
  37. except ImportError:
  38. pytz = None
  39. DatabaseError = Database.DatabaseError
  40. IntegrityError = Database.IntegrityError
  41. def parse_datetime_with_timezone_support(value):
  42. dt = parse_datetime(value)
  43. # Confirm that dt is naive before overwriting its tzinfo.
  44. if dt is not None and settings.USE_TZ and timezone.is_naive(dt):
  45. dt = dt.replace(tzinfo=timezone.utc)
  46. return dt
  47. def adapt_datetime_with_timezone_support(value):
  48. # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
  49. if settings.USE_TZ:
  50. if timezone.is_naive(value):
  51. warnings.warn("SQLite received a naive datetime (%s)"
  52. " while time zone support is active." % value,
  53. RuntimeWarning)
  54. default_timezone = timezone.get_default_timezone()
  55. value = timezone.make_aware(value, default_timezone)
  56. value = value.astimezone(timezone.utc).replace(tzinfo=None)
  57. return value.isoformat(str(" "))
  58. def decoder(conv_func):
  59. """ The Python sqlite3 interface returns always byte strings.
  60. This function converts the received value to a regular string before
  61. passing it to the receiver function.
  62. """
  63. return lambda s: conv_func(s.decode('utf-8'))
  64. Database.register_converter(str("bool"), decoder(lambda s: s == '1'))
  65. Database.register_converter(str("time"), decoder(parse_time))
  66. Database.register_converter(str("date"), decoder(parse_date))
  67. Database.register_converter(str("datetime"), decoder(parse_datetime_with_timezone_support))
  68. Database.register_converter(str("timestamp"), decoder(parse_datetime_with_timezone_support))
  69. Database.register_converter(str("TIMESTAMP"), decoder(parse_datetime_with_timezone_support))
  70. Database.register_converter(str("decimal"), decoder(backend_utils.typecast_decimal))
  71. Database.register_adapter(datetime.datetime, adapt_datetime_with_timezone_support)
  72. Database.register_adapter(decimal.Decimal, backend_utils.rev_typecast_decimal)
  73. if six.PY2:
  74. Database.register_adapter(str, lambda s: s.decode('utf-8'))
  75. Database.register_adapter(SafeBytes, lambda s: s.decode('utf-8'))
  76. class DatabaseFeatures(BaseDatabaseFeatures):
  77. # SQLite cannot handle us only partially reading from a cursor's result set
  78. # and then writing the same rows to the database in another cursor. This
  79. # setting ensures we always read result sets fully into memory all in one
  80. # go.
  81. can_use_chunked_reads = False
  82. test_db_allows_multiple_connections = False
  83. supports_unspecified_pk = True
  84. supports_timezones = False
  85. supports_1000_query_parameters = False
  86. supports_mixed_date_datetime_comparisons = False
  87. has_bulk_insert = True
  88. can_combine_inserts_with_and_without_auto_increment_pk = False
  89. supports_foreign_keys = False
  90. supports_check_constraints = False
  91. autocommits_when_autocommit_is_off = True
  92. atomic_transactions = False
  93. supports_paramstyle_pyformat = False
  94. supports_sequence_reset = False
  95. @cached_property
  96. def uses_savepoints(self):
  97. return Database.sqlite_version_info >= (3, 6, 8)
  98. @cached_property
  99. def supports_stddev(self):
  100. """Confirm support for STDDEV and related stats functions
  101. SQLite supports STDDEV as an extension package; so
  102. connection.ops.check_aggregate_support() can't unilaterally
  103. rule out support for STDDEV. We need to manually check
  104. whether the call works.
  105. """
  106. with self.connection.cursor() as cursor:
  107. cursor.execute('CREATE TABLE STDDEV_TEST (X INT)')
  108. try:
  109. cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST')
  110. has_support = True
  111. except utils.DatabaseError:
  112. has_support = False
  113. cursor.execute('DROP TABLE STDDEV_TEST')
  114. return has_support
  115. @cached_property
  116. def has_zoneinfo_database(self):
  117. return pytz is not None
  118. class DatabaseOperations(BaseDatabaseOperations):
  119. def bulk_batch_size(self, fields, objs):
  120. """
  121. SQLite has a compile-time default (SQLITE_LIMIT_VARIABLE_NUMBER) of
  122. 999 variables per query.
  123. If there is just single field to insert, then we can hit another
  124. limit, SQLITE_MAX_COMPOUND_SELECT which defaults to 500.
  125. """
  126. limit = 999 if len(fields) > 1 else 500
  127. return (limit // len(fields)) if len(fields) > 0 else len(objs)
  128. def check_aggregate_support(self, aggregate):
  129. bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
  130. bad_aggregates = (aggregates.Sum, aggregates.Avg,
  131. aggregates.Variance, aggregates.StdDev)
  132. if (isinstance(aggregate.source, bad_fields) and
  133. isinstance(aggregate, bad_aggregates)):
  134. raise NotImplementedError(
  135. 'You cannot use Sum, Avg, StdDev and Variance aggregations '
  136. 'on date/time fields in sqlite3 '
  137. 'since date/time is saved as text.')
  138. def date_extract_sql(self, lookup_type, field_name):
  139. # sqlite doesn't support extract, so we fake it with the user-defined
  140. # function django_date_extract that's registered in connect(). Note that
  141. # single quotes are used because this is a string (and could otherwise
  142. # cause a collision with a field name).
  143. return "django_date_extract('%s', %s)" % (lookup_type.lower(), field_name)
  144. def date_interval_sql(self, sql, connector, timedelta):
  145. # It would be more straightforward if we could use the sqlite strftime
  146. # function, but it does not allow for keeping six digits of fractional
  147. # second information, nor does it allow for formatting date and datetime
  148. # values differently. So instead we register our own function that
  149. # formats the datetime combined with the delta in a manner suitable
  150. # for comparisons.
  151. return 'django_format_dtdelta(%s, "%s", "%d", "%d", "%d")' % (sql,
  152. connector, timedelta.days, timedelta.seconds, timedelta.microseconds)
  153. def date_trunc_sql(self, lookup_type, field_name):
  154. # sqlite doesn't support DATE_TRUNC, so we fake it with a user-defined
  155. # function django_date_trunc that's registered in connect(). Note that
  156. # single quotes are used because this is a string (and could otherwise
  157. # cause a collision with a field name).
  158. return "django_date_trunc('%s', %s)" % (lookup_type.lower(), field_name)
  159. def datetime_extract_sql(self, lookup_type, field_name, tzname):
  160. # Same comment as in date_extract_sql.
  161. if settings.USE_TZ:
  162. if pytz is None:
  163. from django.core.exceptions import ImproperlyConfigured
  164. raise ImproperlyConfigured("This query requires pytz, "
  165. "but it isn't installed.")
  166. return "django_datetime_extract('%s', %s, %%s)" % (
  167. lookup_type.lower(), field_name), [tzname]
  168. def datetime_trunc_sql(self, lookup_type, field_name, tzname):
  169. # Same comment as in date_trunc_sql.
  170. if settings.USE_TZ:
  171. if pytz is None:
  172. from django.core.exceptions import ImproperlyConfigured
  173. raise ImproperlyConfigured("This query requires pytz, "
  174. "but it isn't installed.")
  175. return "django_datetime_trunc('%s', %s, %%s)" % (
  176. lookup_type.lower(), field_name), [tzname]
  177. def drop_foreignkey_sql(self):
  178. return ""
  179. def pk_default_value(self):
  180. return "NULL"
  181. def quote_name(self, name):
  182. if name.startswith('"') and name.endswith('"'):
  183. return name # Quoting once is enough.
  184. return '"%s"' % name
  185. def no_limit_value(self):
  186. return -1
  187. def sql_flush(self, style, tables, sequences, allow_cascade=False):
  188. # NB: The generated SQL below is specific to SQLite
  189. # Note: The DELETE FROM... SQL generated below works for SQLite databases
  190. # because constraints don't exist
  191. sql = ['%s %s %s;' % (
  192. style.SQL_KEYWORD('DELETE'),
  193. style.SQL_KEYWORD('FROM'),
  194. style.SQL_FIELD(self.quote_name(table))
  195. ) for table in tables]
  196. # Note: No requirement for reset of auto-incremented indices (cf. other
  197. # sql_flush() implementations). Just return SQL at this point
  198. return sql
  199. def value_to_db_datetime(self, value):
  200. if value is None:
  201. return None
  202. # SQLite doesn't support tz-aware datetimes
  203. if timezone.is_aware(value):
  204. if settings.USE_TZ:
  205. value = value.astimezone(timezone.utc).replace(tzinfo=None)
  206. else:
  207. raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")
  208. return six.text_type(value)
  209. def value_to_db_time(self, value):
  210. if value is None:
  211. return None
  212. # SQLite doesn't support tz-aware datetimes
  213. if timezone.is_aware(value):
  214. raise ValueError("SQLite backend does not support timezone-aware times.")
  215. return six.text_type(value)
  216. def convert_values(self, value, field):
  217. """SQLite returns floats when it should be returning decimals,
  218. and gets dates and datetimes wrong.
  219. For consistency with other backends, coerce when required.
  220. """
  221. if value is None:
  222. return None
  223. internal_type = field.get_internal_type()
  224. if internal_type == 'DecimalField':
  225. return backend_utils.typecast_decimal(field.format_number(value))
  226. elif internal_type and internal_type.endswith('IntegerField') or internal_type == 'AutoField':
  227. return int(value)
  228. elif internal_type == 'DateField':
  229. return parse_date(value)
  230. elif internal_type == 'DateTimeField':
  231. return parse_datetime_with_timezone_support(value)
  232. elif internal_type == 'TimeField':
  233. return parse_time(value)
  234. # No field, or the field isn't known to be a decimal or integer
  235. return value
  236. def bulk_insert_sql(self, fields, num_values):
  237. res = []
  238. res.append("SELECT %s" % ", ".join(
  239. "%%s AS %s" % self.quote_name(f.column) for f in fields
  240. ))
  241. res.extend(["UNION ALL SELECT %s" % ", ".join(["%s"] * len(fields))] * (num_values - 1))
  242. return " ".join(res)
  243. def combine_expression(self, connector, sub_expressions):
  244. # SQLite doesn't have a power function, so we fake it with a
  245. # user-defined function django_power that's registered in connect().
  246. if connector == '^':
  247. return 'django_power(%s)' % ','.join(sub_expressions)
  248. return super(DatabaseOperations, self).combine_expression(connector, sub_expressions)
  249. def integer_field_range(self, internal_type):
  250. # SQLite doesn't enforce any integer constraints
  251. return (None, None)
  252. class DatabaseWrapper(BaseDatabaseWrapper):
  253. vendor = 'sqlite'
  254. # SQLite requires LIKE statements to include an ESCAPE clause if the value
  255. # being escaped has a percent or underscore in it.
  256. # See http://www.sqlite.org/lang_expr.html for an explanation.
  257. operators = {
  258. 'exact': '= %s',
  259. 'iexact': "LIKE %s ESCAPE '\\'",
  260. 'contains': "LIKE %s ESCAPE '\\'",
  261. 'icontains': "LIKE %s ESCAPE '\\'",
  262. 'regex': 'REGEXP %s',
  263. 'iregex': "REGEXP '(?i)' || %s",
  264. 'gt': '> %s',
  265. 'gte': '>= %s',
  266. 'lt': '< %s',
  267. 'lte': '<= %s',
  268. 'startswith': "LIKE %s ESCAPE '\\'",
  269. 'endswith': "LIKE %s ESCAPE '\\'",
  270. 'istartswith': "LIKE %s ESCAPE '\\'",
  271. 'iendswith': "LIKE %s ESCAPE '\\'",
  272. }
  273. pattern_ops = {
  274. 'startswith': "LIKE %s || '%%%%'",
  275. 'istartswith': "LIKE UPPER(%s) || '%%%%'",
  276. }
  277. Database = Database
  278. def __init__(self, *args, **kwargs):
  279. super(DatabaseWrapper, self).__init__(*args, **kwargs)
  280. self.features = DatabaseFeatures(self)
  281. self.ops = DatabaseOperations(self)
  282. self.client = DatabaseClient(self)
  283. self.creation = DatabaseCreation(self)
  284. self.introspection = DatabaseIntrospection(self)
  285. self.validation = BaseDatabaseValidation(self)
  286. def get_connection_params(self):
  287. settings_dict = self.settings_dict
  288. if not settings_dict['NAME']:
  289. from django.core.exceptions import ImproperlyConfigured
  290. raise ImproperlyConfigured(
  291. "settings.DATABASES is improperly configured. "
  292. "Please supply the NAME value.")
  293. kwargs = {
  294. 'database': settings_dict['NAME'],
  295. 'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,
  296. }
  297. kwargs.update(settings_dict['OPTIONS'])
  298. # Always allow the underlying SQLite connection to be shareable
  299. # between multiple threads. The safe-guarding will be handled at a
  300. # higher level by the `BaseDatabaseWrapper.allow_thread_sharing`
  301. # property. This is necessary as the shareability is disabled by
  302. # default in pysqlite and it cannot be changed once a connection is
  303. # opened.
  304. if 'check_same_thread' in kwargs and kwargs['check_same_thread']:
  305. warnings.warn(
  306. 'The `check_same_thread` option was provided and set to '
  307. 'True. It will be overridden with False. Use the '
  308. '`DatabaseWrapper.allow_thread_sharing` property instead '
  309. 'for controlling thread shareability.',
  310. RuntimeWarning
  311. )
  312. kwargs.update({'check_same_thread': False})
  313. return kwargs
  314. def get_new_connection(self, conn_params):
  315. conn = Database.connect(**conn_params)
  316. conn.create_function("django_date_extract", 2, _sqlite_date_extract)
  317. conn.create_function("django_date_trunc", 2, _sqlite_date_trunc)
  318. conn.create_function("django_datetime_extract", 3, _sqlite_datetime_extract)
  319. conn.create_function("django_datetime_trunc", 3, _sqlite_datetime_trunc)
  320. conn.create_function("regexp", 2, _sqlite_regexp)
  321. conn.create_function("django_format_dtdelta", 5, _sqlite_format_dtdelta)
  322. conn.create_function("django_power", 2, _sqlite_power)
  323. return conn
  324. def init_connection_state(self):
  325. pass
  326. def create_cursor(self):
  327. return self.connection.cursor(factory=SQLiteCursorWrapper)
  328. def close(self):
  329. self.validate_thread_sharing()
  330. # If database is in memory, closing the connection destroys the
  331. # database. To prevent accidental data loss, ignore close requests on
  332. # an in-memory db.
  333. if self.settings_dict['NAME'] != ":memory:":
  334. BaseDatabaseWrapper.close(self)
  335. def _savepoint_allowed(self):
  336. # Two conditions are required here:
  337. # - A sufficiently recent version of SQLite to support savepoints,
  338. # - Being in a transaction, which can only happen inside 'atomic'.
  339. # When 'isolation_level' is not None, sqlite3 commits before each
  340. # savepoint; it's a bug. When it is None, savepoints don't make sense
  341. # because autocommit is enabled. The only exception is inside 'atomic'
  342. # blocks. To work around that bug, on SQLite, 'atomic' starts a
  343. # transaction explicitly rather than simply disable autocommit.
  344. return self.features.uses_savepoints and self.in_atomic_block
  345. def _set_autocommit(self, autocommit):
  346. if autocommit:
  347. level = None
  348. else:
  349. # sqlite3's internal default is ''. It's different from None.
  350. # See Modules/_sqlite/connection.c.
  351. level = ''
  352. # 'isolation_level' is a misleading API.
  353. # SQLite always runs at the SERIALIZABLE isolation level.
  354. self.connection.isolation_level = level
  355. def check_constraints(self, table_names=None):
  356. """
  357. Checks each table name in `table_names` for rows with invalid foreign key references. This method is
  358. intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to
  359. determine if rows with invalid references were entered while constraint checks were off.
  360. Raises an IntegrityError on the first invalid foreign key reference encountered (if any) and provides
  361. detailed information about the invalid reference in the error message.
  362. Backends can override this method if they can more directly apply constraint checking (e.g. via "SET CONSTRAINTS
  363. ALL IMMEDIATE")
  364. """
  365. cursor = self.cursor()
  366. if table_names is None:
  367. table_names = self.introspection.table_names(cursor)
  368. for table_name in table_names:
  369. primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
  370. if not primary_key_column_name:
  371. continue
  372. key_columns = self.introspection.get_key_columns(cursor, table_name)
  373. for column_name, referenced_table_name, referenced_column_name in key_columns:
  374. cursor.execute("""
  375. SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
  376. LEFT JOIN `%s` as REFERRED
  377. ON (REFERRING.`%s` = REFERRED.`%s`)
  378. WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
  379. % (primary_key_column_name, column_name, table_name, referenced_table_name,
  380. column_name, referenced_column_name, column_name, referenced_column_name))
  381. for bad_row in cursor.fetchall():
  382. raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
  383. "foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
  384. % (table_name, bad_row[0], table_name, column_name, bad_row[1],
  385. referenced_table_name, referenced_column_name))
  386. def is_usable(self):
  387. return True
  388. def _start_transaction_under_autocommit(self):
  389. """
  390. Start a transaction explicitly in autocommit mode.
  391. Staying in autocommit mode works around a bug of sqlite3 that breaks
  392. savepoints when autocommit is disabled.
  393. """
  394. self.cursor().execute("BEGIN")
  395. def schema_editor(self, *args, **kwargs):
  396. "Returns a new instance of this backend's SchemaEditor"
  397. return DatabaseSchemaEditor(self, *args, **kwargs)
  398. FORMAT_QMARK_REGEX = re.compile(r'(?<!%)%s')
  399. class SQLiteCursorWrapper(Database.Cursor):
  400. """
  401. Django uses "format" style placeholders, but pysqlite2 uses "qmark" style.
  402. This fixes it -- but note that if you want to use a literal "%s" in a query,
  403. you'll need to use "%%s".
  404. """
  405. def execute(self, query, params=None):
  406. if params is None:
  407. return Database.Cursor.execute(self, query)
  408. query = self.convert_query(query)
  409. return Database.Cursor.execute(self, query, params)
  410. def executemany(self, query, param_list):
  411. query = self.convert_query(query)
  412. return Database.Cursor.executemany(self, query, param_list)
  413. def convert_query(self, query):
  414. return FORMAT_QMARK_REGEX.sub('?', query).replace('%%', '%')
  415. def _sqlite_date_extract(lookup_type, dt):
  416. if dt is None:
  417. return None
  418. try:
  419. dt = backend_utils.typecast_timestamp(dt)
  420. except (ValueError, TypeError):
  421. return None
  422. if lookup_type == 'week_day':
  423. return (dt.isoweekday() % 7) + 1
  424. else:
  425. return getattr(dt, lookup_type)
  426. def _sqlite_date_trunc(lookup_type, dt):
  427. try:
  428. dt = backend_utils.typecast_timestamp(dt)
  429. except (ValueError, TypeError):
  430. return None
  431. if lookup_type == 'year':
  432. return "%i-01-01" % dt.year
  433. elif lookup_type == 'month':
  434. return "%i-%02i-01" % (dt.year, dt.month)
  435. elif lookup_type == 'day':
  436. return "%i-%02i-%02i" % (dt.year, dt.month, dt.day)
  437. def _sqlite_datetime_extract(lookup_type, dt, tzname):
  438. if dt is None:
  439. return None
  440. try:
  441. dt = backend_utils.typecast_timestamp(dt)
  442. except (ValueError, TypeError):
  443. return None
  444. if tzname is not None:
  445. dt = timezone.localtime(dt, pytz.timezone(tzname))
  446. if lookup_type == 'week_day':
  447. return (dt.isoweekday() % 7) + 1
  448. else:
  449. return getattr(dt, lookup_type)
  450. def _sqlite_datetime_trunc(lookup_type, dt, tzname):
  451. try:
  452. dt = backend_utils.typecast_timestamp(dt)
  453. except (ValueError, TypeError):
  454. return None
  455. if tzname is not None:
  456. dt = timezone.localtime(dt, pytz.timezone(tzname))
  457. if lookup_type == 'year':
  458. return "%i-01-01 00:00:00" % dt.year
  459. elif lookup_type == 'month':
  460. return "%i-%02i-01 00:00:00" % (dt.year, dt.month)
  461. elif lookup_type == 'day':
  462. return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
  463. elif lookup_type == 'hour':
  464. return "%i-%02i-%02i %02i:00:00" % (dt.year, dt.month, dt.day, dt.hour)
  465. elif lookup_type == 'minute':
  466. return "%i-%02i-%02i %02i:%02i:00" % (dt.year, dt.month, dt.day, dt.hour, dt.minute)
  467. elif lookup_type == 'second':
  468. return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
  469. def _sqlite_format_dtdelta(dt, conn, days, secs, usecs):
  470. try:
  471. dt = backend_utils.typecast_timestamp(dt)
  472. delta = datetime.timedelta(int(days), int(secs), int(usecs))
  473. if conn.strip() == '+':
  474. dt = dt + delta
  475. else:
  476. dt = dt - delta
  477. except (ValueError, TypeError):
  478. return None
  479. # typecast_timestamp returns a date or a datetime without timezone.
  480. # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
  481. return str(dt)
  482. def _sqlite_regexp(re_pattern, re_string):
  483. return bool(re.search(re_pattern, force_text(re_string))) if re_string is not None else False
  484. def _sqlite_power(x, y):
  485. return x ** y