base.py 24 KB

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