.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
29from typing import TYPE_CHECKING
30
31try:
32 import mariadb
33except ImportError:
34 # import error is ignored because the admin has to install mysql manually to use
35 # the engine
36 pass
37
38if TYPE_CHECKING:
39 import logging
40
41 logger = logging.getLogger()
42
43
44engine_type = 'offline'
45
46host = "127.0.0.1"
47"""Hostname of the DB connector"""
48
49port = 3306
50"""Port of the DB connector"""
51
52database = ""
53"""Name of the database."""
54
55username = ""
56"""Username for the DB connection."""
57
58password = ""
59"""Password for the DB connection."""
60
61query_str = ""
62"""SQL query that returns the result items."""
63
64limit = 10
65paging = True
66result_template = 'key-value.html'
67_connection = None
68
69
70def init(engine_settings):
71 global _connection # pylint: disable=global-statement
72
73 if 'query_str' not in engine_settings:
74 raise ValueError('query_str cannot be empty')
75
76 if not engine_settings['query_str'].lower().startswith('select '):
77 raise ValueError('only SELECT query is supported')
78
79 _connection = mariadb.connect(database=database, user=username, password=password, host=host, port=port)
80
81
82def search(query, params):
83 query_params = {'query': query}
84 query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
85 logger.debug("SQL Query: %s", query_to_run)
86
87 with _connection.cursor() as cur:
88 cur.execute(query_to_run, query_params)
89 results = []
90 col_names = [i[0] for i in cur.description]
91 for res in cur:
92 result = dict(zip(col_names, map(str, res)))
93 result['template'] = result_template
94 results.append(result)
95 return results