postgresql.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. PostgreSQL database (Offline)
  4. """
  5. # error is ignored because the admin has to
  6. # install it manually to use the engine
  7. # pylint: disable=import-error
  8. import psycopg2
  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. if 'query_str' not in engine_settings:
  22. raise ValueError('query_str cannot be empty')
  23. if not engine_settings['query_str'].lower().startswith('select '):
  24. raise ValueError('only SELECT query is supported')
  25. global _connection
  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 = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  36. with _connection:
  37. with _connection.cursor() as cur:
  38. cur.execute(query_to_run, query_params)
  39. return _fetch_results(cur)
  40. def _fetch_results(cur):
  41. results = []
  42. titles = []
  43. try:
  44. titles = [column_desc.name for column_desc in cur.description]
  45. for res in cur:
  46. result = dict(zip(titles, map(str, res)))
  47. result['template'] = result_template
  48. results.append(result)
  49. # no results to fetch
  50. except psycopg2.ProgrammingError:
  51. pass
  52. return results