.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
mariadb_server.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""MariaDB is a community driven fork of MySQL. Before enabling MariaDB engine,
3you must the install the pip package ``mariadb`` along with the necessary
4prerequities.
5
6`See the following documentation for more details
7<https://mariadb.com/docs/server/connect/programming-languages/c/install/>`_
8
9Example
10=======
11
12This is an example configuration for querying a MariaDB server:
13
14.. code:: yaml
15
16 - name: my_database
17 engine: mariadb_server
18 database: my_database
19 username: searxng
20 password: password
21 limit: 5
22 query_str: 'SELECT * from my_table WHERE my_column=%(query)s'
23
24Implementations
25===============
26
27"""
28
29try:
30 import mariadb # pyright: ignore [reportMissingImports]
31except ImportError:
32 # import error is ignored because the admin has to install mysql manually to use
33 # the engine
34 pass
35
36from searx.result_types import EngineResults
37
38engine_type = 'offline'
39
40host = "127.0.0.1"
41"""Hostname of the DB connector"""
42
43port = 3306
44"""Port of the DB connector"""
45
46database = ""
47"""Name of the database."""
48
49username = ""
50"""Username for the DB connection."""
51
52password = ""
53"""Password for the DB connection."""
54
55query_str = ""
56"""SQL query that returns the result items."""
57
58limit = 10
59paging = True
60_connection = None
61
62
63def init(engine_settings):
64 global _connection # pylint: disable=global-statement
65
66 if 'query_str' not in engine_settings:
67 raise ValueError('query_str cannot be empty')
68
69 if not engine_settings['query_str'].lower().startswith('select '):
70 raise ValueError('only SELECT query is supported')
71
72 _connection = mariadb.connect(database=database, user=username, password=password, host=host, port=port)
73
74
75def search(query, params) -> EngineResults:
76 query_params = {'query': query}
77 query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
78 logger.debug("SQL Query: %s", query_to_run)
79 res = EngineResults()
80
81 with _connection.cursor() as cur:
82 cur.execute(query_to_run, query_params)
83 col_names = [i[0] for i in cur.description]
84 for row in cur:
85 kvmap = dict(zip(col_names, map(str, row)))
86 res.add(res.types.KeyValue(kvmap=kvmap))
87 return res