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