postgresql.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """PostgreSQL is a powerful and robust open source database. Before configuring
  3. the PostgreSQL engine, you must install the dependency ``psychopg2``.
  4. Example
  5. =======
  6. Below is an example configuration:
  7. .. code:: yaml
  8. - name: my_database
  9. engine: postgresql
  10. database: my_database
  11. username: searxng
  12. password: password
  13. query_str: 'SELECT * from my_table WHERE my_column = %(query)s'
  14. Implementations
  15. ===============
  16. """
  17. try:
  18. import psycopg2 # type: ignore
  19. except ImportError:
  20. # import error is ignored because the admin has to install postgresql
  21. # manually to use the engine.
  22. pass
  23. engine_type = 'offline'
  24. host = "127.0.0.1"
  25. port = "5432"
  26. database = ""
  27. username = ""
  28. password = ""
  29. query_str = ""
  30. limit = 10
  31. paging = True
  32. result_template = 'key-value.html'
  33. _connection = None
  34. def init(engine_settings):
  35. global _connection # pylint: disable=global-statement
  36. if 'query_str' not in engine_settings:
  37. raise ValueError('query_str cannot be empty')
  38. if not engine_settings['query_str'].lower().startswith('select '):
  39. raise ValueError('only SELECT query is supported')
  40. _connection = psycopg2.connect(
  41. database=database,
  42. user=username,
  43. password=password,
  44. host=host,
  45. port=port,
  46. )
  47. def search(query, params):
  48. query_params = {'query': query}
  49. query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  50. with _connection:
  51. with _connection.cursor() as cur:
  52. cur.execute(query_to_run, query_params)
  53. return _fetch_results(cur)
  54. def _fetch_results(cur):
  55. results = []
  56. titles = []
  57. try:
  58. titles = [column_desc.name for column_desc in cur.description]
  59. for res in cur:
  60. result = dict(zip(titles, map(str, res)))
  61. result['template'] = result_template
  62. results.append(result)
  63. # no results to fetch
  64. except psycopg2.ProgrammingError:
  65. pass
  66. return results