mariadb_server.py 2.3 KB

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