sqlite.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """SQLite is a small, fast and reliable SQL database engine. It does not require
  4. any extra dependency.
  5. Example
  6. =======
  7. .. _MediathekView: https://mediathekview.de/
  8. To demonstrate the power of database engines, here is a more complex example
  9. which reads from a MediathekView_ (DE) movie database. For this example of the
  10. SQlite engine download the database:
  11. - https://liste.mediathekview.de/filmliste-v2.db.bz2
  12. and unpack into ``searx/data/filmliste-v2.db``. To search the database use e.g
  13. Query to test: ``!mediathekview concert``
  14. .. code:: yaml
  15. - name: mediathekview
  16. engine: sqlite
  17. disabled: False
  18. categories: general
  19. result_template: default.html
  20. database: searx/data/filmliste-v2.db
  21. query_str: >-
  22. SELECT title || ' (' || time(duration, 'unixepoch') || ')' AS title,
  23. COALESCE( NULLIF(url_video_hd,''), NULLIF(url_video_sd,''), url_video) AS url,
  24. description AS content
  25. FROM film
  26. WHERE title LIKE :wildcard OR description LIKE :wildcard
  27. ORDER BY duration DESC
  28. Implementations
  29. ===============
  30. """
  31. import sqlite3
  32. import contextlib
  33. engine_type = 'offline'
  34. database = ""
  35. query_str = ""
  36. limit = 10
  37. paging = True
  38. result_template = 'key-value.html'
  39. def init(engine_settings):
  40. if 'query_str' not in engine_settings:
  41. raise ValueError('query_str cannot be empty')
  42. if not engine_settings['query_str'].lower().startswith('select '):
  43. raise ValueError('only SELECT query is supported')
  44. @contextlib.contextmanager
  45. def sqlite_cursor():
  46. """Implements a :py:obj:`Context Manager <contextlib.contextmanager>` for a
  47. :py:obj:`sqlite3.Cursor`.
  48. Open database in read only mode: if the database doesn't exist. The default
  49. mode creates an empty file on the file system. See:
  50. * https://docs.python.org/3/library/sqlite3.html#sqlite3.connect
  51. * https://www.sqlite.org/uri.html
  52. """
  53. uri = 'file:' + database + '?mode=ro'
  54. with contextlib.closing(sqlite3.connect(uri, uri=True)) as connect:
  55. connect.row_factory = sqlite3.Row
  56. with contextlib.closing(connect.cursor()) as cursor:
  57. yield cursor
  58. def search(query, params):
  59. results = []
  60. query_params = {
  61. 'query': query,
  62. 'wildcard': r'%' + query.replace(' ', r'%') + r'%',
  63. 'limit': limit,
  64. 'offset': (params['pageno'] - 1) * limit,
  65. }
  66. query_to_run = query_str + ' LIMIT :limit OFFSET :offset'
  67. with sqlite_cursor() as cur:
  68. cur.execute(query_to_run, query_params)
  69. col_names = [cn[0] for cn in cur.description]
  70. for row in cur.fetchall():
  71. item = dict(zip(col_names, map(str, row)))
  72. item['template'] = result_template
  73. logger.debug("append result --> %s", item)
  74. results.append(item)
  75. return results