sqlite.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. query_str = ""
  35. limit = 10
  36. paging = True
  37. result_template = 'key-value.html'
  38. def init(engine_settings):
  39. if 'query_str' not in engine_settings:
  40. raise ValueError('query_str cannot be empty')
  41. if not engine_settings['query_str'].lower().startswith('select '):
  42. raise ValueError('only SELECT query is supported')
  43. @contextlib.contextmanager
  44. def sqlite_cursor():
  45. """Implements a :py:obj:`Context Manager <contextlib.contextmanager>` for a
  46. :py:obj:`sqlite3.Cursor`.
  47. Open database in read only mode: if the database doesn't exist. The default
  48. mode creates an empty file on the file system. See:
  49. * https://docs.python.org/3/library/sqlite3.html#sqlite3.connect
  50. * https://www.sqlite.org/uri.html
  51. """
  52. uri = 'file:' + database + '?mode=ro'
  53. with contextlib.closing(sqlite3.connect(uri, uri=True)) as connect:
  54. connect.row_factory = sqlite3.Row
  55. with contextlib.closing(connect.cursor()) as cursor:
  56. yield cursor
  57. def search(query, params):
  58. results = []
  59. query_params = {
  60. 'query': query,
  61. 'wildcard': r'%' + query.replace(' ', r'%') + r'%',
  62. 'limit': limit,
  63. 'offset': (params['pageno'] - 1) * limit,
  64. }
  65. query_to_run = query_str + ' LIMIT :limit OFFSET :offset'
  66. with sqlite_cursor() as cur:
  67. cur.execute(query_to_run, query_params)
  68. col_names = [cn[0] for cn in cur.description]
  69. for row in cur.fetchall():
  70. item = dict(zip(col_names, map(str, row)))
  71. item['template'] = result_template
  72. logger.debug("append result --> %s", item)
  73. results.append(item)
  74. return results