sqlite.py 1.9 KB

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