base.py 23 KB

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