mariadb_server.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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
  24. except ImportError:
  25. # import error is ignored because the admin has to install mysql manually to use
  26. # the engine
  27. pass
  28. if TYPE_CHECKING:
  29. import logging
  30. logger = logging.getLogger()
  31. engine_type = 'offline'
  32. host = "127.0.0.1"
  33. """Hostname of the DB connector"""
  34. port = 3306
  35. """Port of the DB connector"""
  36. database = ""
  37. """Name of the database."""
  38. username = ""
  39. """Username for the DB connection."""
  40. password = ""
  41. """Password for the DB connection."""
  42. query_str = ""
  43. """SQL query that returns the result items."""
  44. limit = 10
  45. paging = True
  46. result_template = 'key-value.html'
  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):
  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. with _connection.cursor() as cur:
  60. cur.execute(query_to_run, query_params)
  61. results = []
  62. col_names = [i[0] for i in cur.description]
  63. for res in cur:
  64. result = dict(zip(col_names, map(str, res)))
  65. result['template'] = result_template
  66. results.append(result)
  67. return results