You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.py 22KB

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