base.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. """
  2. SQLite backend for the sqlite3 module in the standard library.
  3. """
  4. import datetime
  5. import decimal
  6. import functools
  7. import hashlib
  8. import math
  9. import operator
  10. import re
  11. import statistics
  12. import warnings
  13. from itertools import chain
  14. from sqlite3 import dbapi2 as Database
  15. import pytz
  16. from django.core.exceptions import ImproperlyConfigured
  17. from django.db import utils
  18. from django.db.backends import utils as backend_utils
  19. from django.db.backends.base.base import BaseDatabaseWrapper
  20. from django.utils import timezone
  21. from django.utils.asyncio import async_unsafe
  22. from django.utils.dateparse import parse_datetime, parse_time
  23. from django.utils.duration import duration_microseconds
  24. from .client import DatabaseClient # isort:skip
  25. from .creation import DatabaseCreation # isort:skip
  26. from .features import DatabaseFeatures # isort:skip
  27. from .introspection import DatabaseIntrospection # isort:skip
  28. from .operations import DatabaseOperations # isort:skip
  29. from .schema import DatabaseSchemaEditor # isort:skip
  30. def decoder(conv_func):
  31. """
  32. Convert bytestrings from Python's sqlite3 interface to a regular string.
  33. """
  34. return lambda s: conv_func(s.decode())
  35. def none_guard(func):
  36. """
  37. Decorator that returns None if any of the arguments to the decorated
  38. function are None. Many SQL functions return NULL if any of their arguments
  39. are NULL. This decorator simplifies the implementation of this for the
  40. custom functions registered below.
  41. """
  42. @functools.wraps(func)
  43. def wrapper(*args, **kwargs):
  44. return None if None in args else func(*args, **kwargs)
  45. return wrapper
  46. def list_aggregate(function):
  47. """
  48. Return an aggregate class that accumulates values in a list and applies
  49. the provided function to the data.
  50. """
  51. return type('ListAggregate', (list,), {'finalize': function, 'step': list.append})
  52. def check_sqlite_version():
  53. if Database.sqlite_version_info < (3, 8, 3):
  54. raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
  55. check_sqlite_version()
  56. Database.register_converter("bool", b'1'.__eq__)
  57. Database.register_converter("time", decoder(parse_time))
  58. Database.register_converter("datetime", decoder(parse_datetime))
  59. Database.register_converter("timestamp", decoder(parse_datetime))
  60. Database.register_converter("TIMESTAMP", decoder(parse_datetime))
  61. Database.register_adapter(decimal.Decimal, str)
  62. class DatabaseWrapper(BaseDatabaseWrapper):
  63. vendor = 'sqlite'
  64. display_name = 'SQLite'
  65. # SQLite doesn't actually support most of these types, but it "does the right
  66. # thing" given more verbose field definitions, so leave them as is so that
  67. # schema inspection is more useful.
  68. data_types = {
  69. 'AutoField': 'integer',
  70. 'BigAutoField': 'integer',
  71. 'BinaryField': 'BLOB',
  72. 'BooleanField': 'bool',
  73. 'CharField': 'varchar(%(max_length)s)',
  74. 'DateField': 'date',
  75. 'DateTimeField': 'datetime',
  76. 'DecimalField': 'decimal',
  77. 'DurationField': 'bigint',
  78. 'FileField': 'varchar(%(max_length)s)',
  79. 'FilePathField': 'varchar(%(max_length)s)',
  80. 'FloatField': 'real',
  81. 'IntegerField': 'integer',
  82. 'BigIntegerField': 'bigint',
  83. 'IPAddressField': 'char(15)',
  84. 'GenericIPAddressField': 'char(39)',
  85. 'NullBooleanField': 'bool',
  86. 'OneToOneField': 'integer',
  87. 'PositiveIntegerField': 'integer unsigned',
  88. 'PositiveSmallIntegerField': 'smallint unsigned',
  89. 'SlugField': 'varchar(%(max_length)s)',
  90. 'SmallIntegerField': 'smallint',
  91. 'TextField': 'text',
  92. 'TimeField': 'time',
  93. 'UUIDField': 'char(32)',
  94. }
  95. data_type_check_constraints = {
  96. 'PositiveIntegerField': '"%(column)s" >= 0',
  97. 'PositiveSmallIntegerField': '"%(column)s" >= 0',
  98. }
  99. data_types_suffix = {
  100. 'AutoField': 'AUTOINCREMENT',
  101. 'BigAutoField': 'AUTOINCREMENT',
  102. }
  103. # SQLite requires LIKE statements to include an ESCAPE clause if the value
  104. # being escaped has a percent or underscore in it.
  105. # See https://www.sqlite.org/lang_expr.html for an explanation.
  106. operators = {
  107. 'exact': '= %s',
  108. 'iexact': "LIKE %s ESCAPE '\\'",
  109. 'contains': "LIKE %s ESCAPE '\\'",
  110. 'icontains': "LIKE %s ESCAPE '\\'",
  111. 'regex': 'REGEXP %s',
  112. 'iregex': "REGEXP '(?i)' || %s",
  113. 'gt': '> %s',
  114. 'gte': '>= %s',
  115. 'lt': '< %s',
  116. 'lte': '<= %s',
  117. 'startswith': "LIKE %s ESCAPE '\\'",
  118. 'endswith': "LIKE %s ESCAPE '\\'",
  119. 'istartswith': "LIKE %s ESCAPE '\\'",
  120. 'iendswith': "LIKE %s ESCAPE '\\'",
  121. }
  122. # The patterns below are used to generate SQL pattern lookup clauses when
  123. # the right-hand side of the lookup isn't a raw string (it might be an expression
  124. # or the result of a bilateral transformation).
  125. # In those cases, special characters for LIKE operators (e.g. \, *, _) should be
  126. # escaped on database side.
  127. #
  128. # Note: we use str.format() here for readability as '%' is used as a wildcard for
  129. # the LIKE operator.
  130. pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\', '\\'), '%%', '\%%'), '_', '\_')"
  131. pattern_ops = {
  132. 'contains': r"LIKE '%%' || {} || '%%' ESCAPE '\'",
  133. 'icontains': r"LIKE '%%' || UPPER({}) || '%%' ESCAPE '\'",
  134. 'startswith': r"LIKE {} || '%%' ESCAPE '\'",
  135. 'istartswith': r"LIKE UPPER({}) || '%%' ESCAPE '\'",
  136. 'endswith': r"LIKE '%%' || {} ESCAPE '\'",
  137. 'iendswith': r"LIKE '%%' || UPPER({}) ESCAPE '\'",
  138. }
  139. Database = Database
  140. SchemaEditorClass = DatabaseSchemaEditor
  141. # Classes instantiated in __init__().
  142. client_class = DatabaseClient
  143. creation_class = DatabaseCreation
  144. features_class = DatabaseFeatures
  145. introspection_class = DatabaseIntrospection
  146. ops_class = DatabaseOperations
  147. def get_connection_params(self):
  148. settings_dict = self.settings_dict
  149. if not settings_dict['NAME']:
  150. raise ImproperlyConfigured(
  151. "settings.DATABASES is improperly configured. "
  152. "Please supply the NAME value.")
  153. kwargs = {
  154. 'database': settings_dict['NAME'],
  155. 'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,
  156. **settings_dict['OPTIONS'],
  157. }
  158. # Always allow the underlying SQLite connection to be shareable
  159. # between multiple threads. The safe-guarding will be handled at a
  160. # higher level by the `BaseDatabaseWrapper.allow_thread_sharing`
  161. # property. This is necessary as the shareability is disabled by
  162. # default in pysqlite and it cannot be changed once a connection is
  163. # opened.
  164. if 'check_same_thread' in kwargs and kwargs['check_same_thread']:
  165. warnings.warn(
  166. 'The `check_same_thread` option was provided and set to '
  167. 'True. It will be overridden with False. Use the '
  168. '`DatabaseWrapper.allow_thread_sharing` property instead '
  169. 'for controlling thread shareability.',
  170. RuntimeWarning
  171. )
  172. kwargs.update({'check_same_thread': False, 'uri': True})
  173. return kwargs
  174. @async_unsafe
  175. def get_new_connection(self, conn_params):
  176. conn = Database.connect(**conn_params)
  177. conn.create_function("django_date_extract", 2, _sqlite_datetime_extract)
  178. conn.create_function("django_date_trunc", 2, _sqlite_date_trunc)
  179. conn.create_function('django_datetime_cast_date', 3, _sqlite_datetime_cast_date)
  180. conn.create_function('django_datetime_cast_time', 3, _sqlite_datetime_cast_time)
  181. conn.create_function('django_datetime_extract', 4, _sqlite_datetime_extract)
  182. conn.create_function('django_datetime_trunc', 4, _sqlite_datetime_trunc)
  183. conn.create_function("django_time_extract", 2, _sqlite_time_extract)
  184. conn.create_function("django_time_trunc", 2, _sqlite_time_trunc)
  185. conn.create_function("django_time_diff", 2, _sqlite_time_diff)
  186. conn.create_function("django_timestamp_diff", 2, _sqlite_timestamp_diff)
  187. conn.create_function("django_format_dtdelta", 3, _sqlite_format_dtdelta)
  188. conn.create_function('regexp', 2, _sqlite_regexp)
  189. conn.create_function('ACOS', 1, none_guard(math.acos))
  190. conn.create_function('ASIN', 1, none_guard(math.asin))
  191. conn.create_function('ATAN', 1, none_guard(math.atan))
  192. conn.create_function('ATAN2', 2, none_guard(math.atan2))
  193. conn.create_function('CEILING', 1, none_guard(math.ceil))
  194. conn.create_function('COS', 1, none_guard(math.cos))
  195. conn.create_function('COT', 1, none_guard(lambda x: 1 / math.tan(x)))
  196. conn.create_function('DEGREES', 1, none_guard(math.degrees))
  197. conn.create_function('EXP', 1, none_guard(math.exp))
  198. conn.create_function('FLOOR', 1, none_guard(math.floor))
  199. conn.create_function('LN', 1, none_guard(math.log))
  200. conn.create_function('LOG', 2, none_guard(lambda x, y: math.log(y, x)))
  201. conn.create_function('LPAD', 3, _sqlite_lpad)
  202. conn.create_function('MD5', 1, none_guard(lambda x: hashlib.md5(x.encode()).hexdigest()))
  203. conn.create_function('MOD', 2, none_guard(math.fmod))
  204. conn.create_function('PI', 0, lambda: math.pi)
  205. conn.create_function('POWER', 2, none_guard(operator.pow))
  206. conn.create_function('RADIANS', 1, none_guard(math.radians))
  207. conn.create_function('REPEAT', 2, none_guard(operator.mul))
  208. conn.create_function('REVERSE', 1, none_guard(lambda x: x[::-1]))
  209. conn.create_function('RPAD', 3, _sqlite_rpad)
  210. conn.create_function('SHA1', 1, none_guard(lambda x: hashlib.sha1(x.encode()).hexdigest()))
  211. conn.create_function('SHA224', 1, none_guard(lambda x: hashlib.sha224(x.encode()).hexdigest()))
  212. conn.create_function('SHA256', 1, none_guard(lambda x: hashlib.sha256(x.encode()).hexdigest()))
  213. conn.create_function('SHA384', 1, none_guard(lambda x: hashlib.sha384(x.encode()).hexdigest()))
  214. conn.create_function('SHA512', 1, none_guard(lambda x: hashlib.sha512(x.encode()).hexdigest()))
  215. conn.create_function('SIGN', 1, none_guard(lambda x: (x > 0) - (x < 0)))
  216. conn.create_function('SIN', 1, none_guard(math.sin))
  217. conn.create_function('SQRT', 1, none_guard(math.sqrt))
  218. conn.create_function('TAN', 1, none_guard(math.tan))
  219. conn.create_aggregate('STDDEV_POP', 1, list_aggregate(statistics.pstdev))
  220. conn.create_aggregate('STDDEV_SAMP', 1, list_aggregate(statistics.stdev))
  221. conn.create_aggregate('VAR_POP', 1, list_aggregate(statistics.pvariance))
  222. conn.create_aggregate('VAR_SAMP', 1, list_aggregate(statistics.variance))
  223. conn.execute('PRAGMA foreign_keys = ON')
  224. return conn
  225. def init_connection_state(self):
  226. pass
  227. def create_cursor(self, name=None):
  228. return self.connection.cursor(factory=SQLiteCursorWrapper)
  229. @async_unsafe
  230. def close(self):
  231. self.validate_thread_sharing()
  232. # If database is in memory, closing the connection destroys the
  233. # database. To prevent accidental data loss, ignore close requests on
  234. # an in-memory db.
  235. if not self.is_in_memory_db():
  236. BaseDatabaseWrapper.close(self)
  237. def _savepoint_allowed(self):
  238. # When 'isolation_level' is not None, sqlite3 commits before each
  239. # savepoint; it's a bug. When it is None, savepoints don't make sense
  240. # because autocommit is enabled. The only exception is inside 'atomic'
  241. # blocks. To work around that bug, on SQLite, 'atomic' starts a
  242. # transaction explicitly rather than simply disable autocommit.
  243. return self.in_atomic_block
  244. def _set_autocommit(self, autocommit):
  245. if autocommit:
  246. level = None
  247. else:
  248. # sqlite3's internal default is ''. It's different from None.
  249. # See Modules/_sqlite/connection.c.
  250. level = ''
  251. # 'isolation_level' is a misleading API.
  252. # SQLite always runs at the SERIALIZABLE isolation level.
  253. with self.wrap_database_errors:
  254. self.connection.isolation_level = level
  255. def disable_constraint_checking(self):
  256. with self.cursor() as cursor:
  257. cursor.execute('PRAGMA foreign_keys = OFF')
  258. # Foreign key constraints cannot be turned off while in a multi-
  259. # statement transaction. Fetch the current state of the pragma
  260. # to determine if constraints are effectively disabled.
  261. enabled = cursor.execute('PRAGMA foreign_keys').fetchone()[0]
  262. return not bool(enabled)
  263. def enable_constraint_checking(self):
  264. self.cursor().execute('PRAGMA foreign_keys = ON')
  265. def check_constraints(self, table_names=None):
  266. """
  267. Check each table name in `table_names` for rows with invalid foreign
  268. key references. This method is intended to be used in conjunction with
  269. `disable_constraint_checking()` and `enable_constraint_checking()`, to
  270. determine if rows with invalid references were entered while constraint
  271. checks were off.
  272. """
  273. if self.features.supports_pragma_foreign_key_check:
  274. with self.cursor() as cursor:
  275. if table_names is None:
  276. violations = self.cursor().execute('PRAGMA foreign_key_check').fetchall()
  277. else:
  278. violations = chain.from_iterable(
  279. cursor.execute('PRAGMA foreign_key_check(%s)' % table_name).fetchall()
  280. for table_name in table_names
  281. )
  282. # See https://www.sqlite.org/pragma.html#pragma_foreign_key_check
  283. for table_name, rowid, referenced_table_name, foreign_key_index in violations:
  284. foreign_key = cursor.execute(
  285. 'PRAGMA foreign_key_list(%s)' % table_name
  286. ).fetchall()[foreign_key_index]
  287. column_name, referenced_column_name = foreign_key[3:5]
  288. primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
  289. primary_key_value, bad_value = cursor.execute(
  290. 'SELECT %s, %s FROM %s WHERE rowid = %%s' % (
  291. primary_key_column_name, column_name, table_name
  292. ),
  293. (rowid,),
  294. ).fetchone()
  295. raise utils.IntegrityError(
  296. "The row in table '%s' with primary key '%s' has an "
  297. "invalid foreign key: %s.%s contains a value '%s' that "
  298. "does not have a corresponding value in %s.%s." % (
  299. table_name, primary_key_value, table_name, column_name,
  300. bad_value, referenced_table_name, referenced_column_name
  301. )
  302. )
  303. else:
  304. with self.cursor() as cursor:
  305. if table_names is None:
  306. table_names = self.introspection.table_names(cursor)
  307. for table_name in table_names:
  308. primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
  309. if not primary_key_column_name:
  310. continue
  311. key_columns = self.introspection.get_key_columns(cursor, table_name)
  312. for column_name, referenced_table_name, referenced_column_name in key_columns:
  313. cursor.execute(
  314. """
  315. SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
  316. LEFT JOIN `%s` as REFERRED
  317. ON (REFERRING.`%s` = REFERRED.`%s`)
  318. WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL
  319. """
  320. % (
  321. primary_key_column_name, column_name, table_name,
  322. referenced_table_name, column_name, referenced_column_name,
  323. column_name, referenced_column_name,
  324. )
  325. )
  326. for bad_row in cursor.fetchall():
  327. raise utils.IntegrityError(
  328. "The row in table '%s' with primary key '%s' has an "
  329. "invalid foreign key: %s.%s contains a value '%s' that "
  330. "does not have a corresponding value in %s.%s." % (
  331. table_name, bad_row[0], table_name, column_name,
  332. bad_row[1], referenced_table_name, referenced_column_name,
  333. )
  334. )
  335. def is_usable(self):
  336. return True
  337. def _start_transaction_under_autocommit(self):
  338. """
  339. Start a transaction explicitly in autocommit mode.
  340. Staying in autocommit mode works around a bug of sqlite3 that breaks
  341. savepoints when autocommit is disabled.
  342. """
  343. self.cursor().execute("BEGIN")
  344. def is_in_memory_db(self):
  345. return self.creation.is_in_memory_db(self.settings_dict['NAME'])
  346. FORMAT_QMARK_REGEX = re.compile(r'(?<!%)%s')
  347. class SQLiteCursorWrapper(Database.Cursor):
  348. """
  349. Django uses "format" style placeholders, but pysqlite2 uses "qmark" style.
  350. This fixes it -- but note that if you want to use a literal "%s" in a query,
  351. you'll need to use "%%s".
  352. """
  353. def execute(self, query, params=None):
  354. if params is None:
  355. return Database.Cursor.execute(self, query)
  356. query = self.convert_query(query)
  357. return Database.Cursor.execute(self, query, params)
  358. def executemany(self, query, param_list):
  359. query = self.convert_query(query)
  360. return Database.Cursor.executemany(self, query, param_list)
  361. def convert_query(self, query):
  362. return FORMAT_QMARK_REGEX.sub('?', query).replace('%%', '%')
  363. def _sqlite_datetime_parse(dt, tzname=None, conn_tzname=None):
  364. if dt is None:
  365. return None
  366. try:
  367. dt = backend_utils.typecast_timestamp(dt)
  368. except (TypeError, ValueError):
  369. return None
  370. if conn_tzname:
  371. dt = dt.replace(tzinfo=pytz.timezone(conn_tzname))
  372. if tzname is not None and tzname != conn_tzname:
  373. sign_index = tzname.find('+') + tzname.find('-') + 1
  374. if sign_index > -1:
  375. sign = tzname[sign_index]
  376. tzname, offset = tzname.split(sign)
  377. if offset:
  378. hours, minutes = offset.split(':')
  379. offset_delta = datetime.timedelta(hours=int(hours), minutes=int(minutes))
  380. dt += offset_delta if sign == '+' else -offset_delta
  381. dt = timezone.localtime(dt, pytz.timezone(tzname))
  382. return dt
  383. def _sqlite_date_trunc(lookup_type, dt):
  384. dt = _sqlite_datetime_parse(dt)
  385. if dt is None:
  386. return None
  387. if lookup_type == 'year':
  388. return "%i-01-01" % dt.year
  389. elif lookup_type == 'quarter':
  390. month_in_quarter = dt.month - (dt.month - 1) % 3
  391. return '%i-%02i-01' % (dt.year, month_in_quarter)
  392. elif lookup_type == 'month':
  393. return "%i-%02i-01" % (dt.year, dt.month)
  394. elif lookup_type == 'week':
  395. dt = dt - datetime.timedelta(days=dt.weekday())
  396. return "%i-%02i-%02i" % (dt.year, dt.month, dt.day)
  397. elif lookup_type == 'day':
  398. return "%i-%02i-%02i" % (dt.year, dt.month, dt.day)
  399. def _sqlite_time_trunc(lookup_type, dt):
  400. if dt is None:
  401. return None
  402. try:
  403. dt = backend_utils.typecast_time(dt)
  404. except (ValueError, TypeError):
  405. return None
  406. if lookup_type == 'hour':
  407. return "%02i:00:00" % dt.hour
  408. elif lookup_type == 'minute':
  409. return "%02i:%02i:00" % (dt.hour, dt.minute)
  410. elif lookup_type == 'second':
  411. return "%02i:%02i:%02i" % (dt.hour, dt.minute, dt.second)
  412. def _sqlite_datetime_cast_date(dt, tzname, conn_tzname):
  413. dt = _sqlite_datetime_parse(dt, tzname, conn_tzname)
  414. if dt is None:
  415. return None
  416. return dt.date().isoformat()
  417. def _sqlite_datetime_cast_time(dt, tzname, conn_tzname):
  418. dt = _sqlite_datetime_parse(dt, tzname, conn_tzname)
  419. if dt is None:
  420. return None
  421. return dt.time().isoformat()
  422. def _sqlite_datetime_extract(lookup_type, dt, tzname=None, conn_tzname=None):
  423. dt = _sqlite_datetime_parse(dt, tzname, conn_tzname)
  424. if dt is None:
  425. return None
  426. if lookup_type == 'week_day':
  427. return (dt.isoweekday() % 7) + 1
  428. elif lookup_type == 'week':
  429. return dt.isocalendar()[1]
  430. elif lookup_type == 'quarter':
  431. return math.ceil(dt.month / 3)
  432. elif lookup_type == 'iso_year':
  433. return dt.isocalendar()[0]
  434. else:
  435. return getattr(dt, lookup_type)
  436. def _sqlite_datetime_trunc(lookup_type, dt, tzname, conn_tzname):
  437. dt = _sqlite_datetime_parse(dt, tzname, conn_tzname)
  438. if dt is None:
  439. return None
  440. if lookup_type == 'year':
  441. return "%i-01-01 00:00:00" % dt.year
  442. elif lookup_type == 'quarter':
  443. month_in_quarter = dt.month - (dt.month - 1) % 3
  444. return '%i-%02i-01 00:00:00' % (dt.year, month_in_quarter)
  445. elif lookup_type == 'month':
  446. return "%i-%02i-01 00:00:00" % (dt.year, dt.month)
  447. elif lookup_type == 'week':
  448. dt = dt - datetime.timedelta(days=dt.weekday())
  449. return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
  450. elif lookup_type == 'day':
  451. return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
  452. elif lookup_type == 'hour':
  453. return "%i-%02i-%02i %02i:00:00" % (dt.year, dt.month, dt.day, dt.hour)
  454. elif lookup_type == 'minute':
  455. return "%i-%02i-%02i %02i:%02i:00" % (dt.year, dt.month, dt.day, dt.hour, dt.minute)
  456. elif lookup_type == 'second':
  457. return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
  458. def _sqlite_time_extract(lookup_type, dt):
  459. if dt is None:
  460. return None
  461. try:
  462. dt = backend_utils.typecast_time(dt)
  463. except (ValueError, TypeError):
  464. return None
  465. return getattr(dt, lookup_type)
  466. @none_guard
  467. def _sqlite_format_dtdelta(conn, lhs, rhs):
  468. """
  469. LHS and RHS can be either:
  470. - An integer number of microseconds
  471. - A string representing a datetime
  472. """
  473. try:
  474. real_lhs = datetime.timedelta(0, 0, lhs) if isinstance(lhs, int) else backend_utils.typecast_timestamp(lhs)
  475. real_rhs = datetime.timedelta(0, 0, rhs) if isinstance(rhs, int) else backend_utils.typecast_timestamp(rhs)
  476. if conn.strip() == '+':
  477. out = real_lhs + real_rhs
  478. else:
  479. out = real_lhs - real_rhs
  480. except (ValueError, TypeError):
  481. return None
  482. # typecast_timestamp returns a date or a datetime without timezone.
  483. # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
  484. return str(out)
  485. @none_guard
  486. def _sqlite_time_diff(lhs, rhs):
  487. left = backend_utils.typecast_time(lhs)
  488. right = backend_utils.typecast_time(rhs)
  489. return (
  490. (left.hour * 60 * 60 * 1000000) +
  491. (left.minute * 60 * 1000000) +
  492. (left.second * 1000000) +
  493. (left.microsecond) -
  494. (right.hour * 60 * 60 * 1000000) -
  495. (right.minute * 60 * 1000000) -
  496. (right.second * 1000000) -
  497. (right.microsecond)
  498. )
  499. @none_guard
  500. def _sqlite_timestamp_diff(lhs, rhs):
  501. left = backend_utils.typecast_timestamp(lhs)
  502. right = backend_utils.typecast_timestamp(rhs)
  503. return duration_microseconds(left - right)
  504. @none_guard
  505. def _sqlite_regexp(re_pattern, re_string):
  506. return bool(re.search(re_pattern, str(re_string)))
  507. @none_guard
  508. def _sqlite_lpad(text, length, fill_text):
  509. if len(text) >= length:
  510. return text[:length]
  511. return (fill_text * length)[:length - len(text)] + text
  512. @none_guard
  513. def _sqlite_rpad(text, length, fill_text):
  514. return (text + fill_text * length)[:length]