postgresql.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. from searx.result_types import EngineResults
  24. engine_type = 'offline'
  25. host = "127.0.0.1"
  26. """Hostname of the DB connector"""
  27. port = "5432"
  28. """Port of the DB connector"""
  29. database = ""
  30. """Name of the database."""
  31. username = ""
  32. """Username for the DB connection."""
  33. password = ""
  34. """Password for the DB connection."""
  35. query_str = ""
  36. """SQL query that returns the result items."""
  37. limit = 10
  38. paging = True
  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) -> EngineResults:
  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) -> EngineResults:
  61. res = EngineResults()
  62. try:
  63. titles = [column_desc.name for column_desc in cur.description]
  64. for row in cur:
  65. kvmap = dict(zip(titles, map(str, row)))
  66. res.add(res.types.KeyValue(kvmap=kvmap))
  67. # no results to fetch
  68. except psycopg2.ProgrammingError:
  69. pass
  70. return res