postgresql.py 1.6 KB

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