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