sqlite.py 2.9 KB

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