mariadb_server.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. """
  19. from typing import TYPE_CHECKING
  20. try:
  21. import mariadb
  22. except ImportError:
  23. # import error is ignored because the admin has to install mysql manually to use
  24. # the engine
  25. pass
  26. if TYPE_CHECKING:
  27. import logging
  28. logger = logging.getLogger()
  29. engine_type = 'offline'
  30. host = "127.0.0.1"
  31. port = 3306
  32. database = ""
  33. username = ""
  34. password = ""
  35. query_str = ""
  36. limit = 10
  37. paging = True
  38. result_template = 'key-value.html'
  39. _connection = None
  40. def init(engine_settings):
  41. global _connection # pylint: disable=global-statement
  42. if 'query_str' not in engine_settings:
  43. raise ValueError('query_str cannot be empty')
  44. if not engine_settings['query_str'].lower().startswith('select '):
  45. raise ValueError('only SELECT query is supported')
  46. _connection = mariadb.connect(database=database, user=username, password=password, host=host, port=port)
  47. def search(query, params):
  48. query_params = {'query': query}
  49. query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  50. logger.debug("SQL Query: %s", query_to_run)
  51. with _connection.cursor() as cur:
  52. cur.execute(query_to_run, query_params)
  53. results = []
  54. col_names = [i[0] for i in cur.description]
  55. for res in cur:
  56. result = dict(zip(col_names, map(str, res)))
  57. result['template'] = result_template
  58. results.append(result)
  59. return results