.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
mysql_server.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""MySQL is said to be the most popular open source database. Before enabling
3MySQL engine, you must install the package ``mysql-connector-python``.
4
5The authentication plugin is configurable by setting ``auth_plugin`` in the
6attributes. By default it is set to ``caching_sha2_password``.
7
8Example
9=======
10
11This is an example configuration for querying a MySQL server:
12
13.. code:: yaml
14
15 - name: my_database
16 engine: mysql_server
17 database: my_database
18 username: searxng
19 password: password
20 limit: 5
21 query_str: 'SELECT * from my_table WHERE my_column=%(query)s'
22
23Implementations
24===============
25
26"""
27
28try:
29 import mysql.connector # type: ignore
30except ImportError:
31 # import error is ignored because the admin has to install mysql manually to use
32 # the engine
33 pass
34
35engine_type = 'offline'
36auth_plugin = 'caching_sha2_password'
37
38host = "127.0.0.1"
39"""Hostname of the DB connector"""
40
41port = 3306
42"""Port of the DB connector"""
43
44database = ""
45"""Name of the database."""
46
47username = ""
48"""Username for the DB connection."""
49
50password = ""
51"""Password for the DB connection."""
52
53query_str = ""
54"""SQL query that returns the result items."""
55
56limit = 10
57paging = True
58result_template = 'key-value.html'
59_connection = None
60
61
62def init(engine_settings):
63 global _connection # pylint: disable=global-statement
64
65 if 'query_str' not in engine_settings:
66 raise ValueError('query_str cannot be empty')
67
68 if not engine_settings['query_str'].lower().startswith('select '):
69 raise ValueError('only SELECT query is supported')
70
71 _connection = mysql.connector.connect(
72 database=database,
73 user=username,
74 password=password,
75 host=host,
76 port=port,
77 auth_plugin=auth_plugin,
78 )
79
80
81def search(query, params):
82 query_params = {'query': query}
83 query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
84
85 with _connection.cursor() as cur:
86 cur.execute(query_to_run, query_params)
87
88 return _fetch_results(cur)
89
90
91def _fetch_results(cur):
92 results = []
93 for res in cur:
94 result = dict(zip(cur.column_names, map(str, res)))
95 result['template'] = result_template
96 results.append(result)
97
98 return results