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 # pyright: ignore # 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 = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  35. with _connection:
  36. with _connection.cursor() as cur:
  37. cur.execute(query_to_run, query_params)
  38. return _fetch_results(cur)
  39. def _fetch_results(cur):
  40. results = []
  41. titles = []
  42. try:
  43. titles = [column_desc.name for column_desc in cur.description]
  44. for res in cur:
  45. result = dict(zip(titles, map(str, res)))
  46. result['template'] = result_template
  47. results.append(result)
  48. # no results to fetch
  49. except psycopg2.ProgrammingError:
  50. pass
  51. return results