postgresql.py 2.0 KB

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