postgresql.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pylint: disable=missing-function-docstring
  4. """PostgreSQL database (offline)
  5. """
  6. # import error is ignored because the admin has to install mysql manually to use
  7. # the engine
  8. import psycopg2 # pylint: disable=import-error
  9. engine_type = 'offline'
  10. host = "127.0.0.1"
  11. port = "5432"
  12. database = ""
  13. username = ""
  14. password = ""
  15. query_str = ""
  16. limit = 10
  17. paging = True
  18. result_template = 'key-value.html'
  19. _connection = None
  20. def init(engine_settings):
  21. global _connection # pylint: disable=global-statement
  22. if 'query_str' not in engine_settings:
  23. raise ValueError('query_str cannot be empty')
  24. if not engine_settings['query_str'].lower().startswith('select '):
  25. raise ValueError('only SELECT query is supported')
  26. _connection = psycopg2.connect(
  27. database = database,
  28. user = username,
  29. password = password,
  30. host = host,
  31. port = port,
  32. )
  33. def search(query, params):
  34. query_params = {'query': query}
  35. query_to_run = (
  36. query_str
  37. + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  38. )
  39. with _connection:
  40. with _connection.cursor() as cur:
  41. cur.execute(query_to_run, query_params)
  42. return _fetch_results(cur)
  43. def _fetch_results(cur):
  44. results = []
  45. titles = []
  46. try:
  47. titles = [column_desc.name for column_desc in cur.description]
  48. for res in cur:
  49. result = dict(zip(titles, map(str, res)))
  50. result['template'] = result_template
  51. results.append(result)
  52. # no results to fetch
  53. except psycopg2.ProgrammingError:
  54. pass
  55. return results