sqlite.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """SQLite database (Offline)
  4. """
  5. import sqlite3
  6. import contextlib
  7. engine_type = 'offline'
  8. database = ""
  9. query_str = ""
  10. limit = 10
  11. paging = True
  12. result_template = 'key-value.html'
  13. def init(engine_settings):
  14. if 'query_str' not in engine_settings:
  15. raise ValueError('query_str cannot be empty')
  16. if not engine_settings['query_str'].lower().startswith('select '):
  17. raise ValueError('only SELECT query is supported')
  18. @contextlib.contextmanager
  19. def sqlite_cursor():
  20. """Implements a `Context Manager`_ for a :py:obj:`sqlite3.Cursor`.
  21. Open database in read only mode: if the database doesn't exist.
  22. The default mode creates an empty file on the file system.
  23. see:
  24. * https://docs.python.org/3/library/sqlite3.html#sqlite3.connect
  25. * https://www.sqlite.org/uri.html
  26. """
  27. uri = 'file:' + database + '?mode=ro'
  28. with contextlib.closing(sqlite3.connect(uri, uri=True)) as connect:
  29. connect.row_factory = sqlite3.Row
  30. with contextlib.closing(connect.cursor()) as cursor:
  31. yield cursor
  32. def search(query, params):
  33. results = []
  34. query_params = {
  35. 'query': query,
  36. 'wildcard': r'%' + query.replace(' ', r'%') + r'%',
  37. 'limit': limit,
  38. 'offset': (params['pageno'] - 1) * limit,
  39. }
  40. query_to_run = query_str + ' LIMIT :limit OFFSET :offset'
  41. with sqlite_cursor() as cur:
  42. cur.execute(query_to_run, query_params)
  43. col_names = [cn[0] for cn in cur.description]
  44. for row in cur.fetchall():
  45. item = dict(zip(col_names, map(str, row)))
  46. item['template'] = result_template
  47. logger.debug("append result --> %s", item)
  48. results.append(item)
  49. return results