postgresql.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. """Hostname of the DB connector"""
  26. port = "5432"
  27. """Port of the DB connector"""
  28. database = ""
  29. """Name of the database."""
  30. username = ""
  31. """Username for the DB connection."""
  32. password = ""
  33. """Password for the DB connection."""
  34. query_str = ""
  35. """SQL query that returns the result items."""
  36. limit = 10
  37. paging = True
  38. result_template = 'key-value.html'
  39. _connection = None
  40. def init(engine_settings):
  41. global _connection # pylint: disable=global-statement
  42. if 'query_str' not in engine_settings:
  43. raise ValueError('query_str cannot be empty')
  44. if not engine_settings['query_str'].lower().startswith('select '):
  45. raise ValueError('only SELECT query is supported')
  46. _connection = psycopg2.connect(
  47. database=database,
  48. user=username,
  49. password=password,
  50. host=host,
  51. port=port,
  52. )
  53. def search(query, params):
  54. query_params = {'query': query}
  55. query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  56. with _connection:
  57. with _connection.cursor() as cur:
  58. cur.execute(query_to_run, query_params)
  59. return _fetch_results(cur)
  60. def _fetch_results(cur):
  61. results = []
  62. titles = []
  63. try:
  64. titles = [column_desc.name for column_desc in cur.description]
  65. for res in cur:
  66. result = dict(zip(titles, map(str, res)))
  67. result['template'] = result_template
  68. results.append(result)
  69. # no results to fetch
  70. except psycopg2.ProgrammingError:
  71. pass
  72. return results