mysql_server.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """MySQL is said to be the most popular open source database. Before enabling
  3. MySQL engine, you must install the package ``mysql-connector-python``.
  4. The authentication plugin is configurable by setting ``auth_plugin`` in the
  5. attributes. By default it is set to ``caching_sha2_password``.
  6. Example
  7. =======
  8. This is an example configuration for querying a MySQL server:
  9. .. code:: yaml
  10. - name: my_database
  11. engine: mysql_server
  12. database: my_database
  13. username: searxng
  14. password: password
  15. limit: 5
  16. query_str: 'SELECT * from my_table WHERE my_column=%(query)s'
  17. Implementations
  18. ===============
  19. """
  20. try:
  21. import mysql.connector # type: ignore
  22. except ImportError:
  23. # import error is ignored because the admin has to install mysql manually to use
  24. # the engine
  25. pass
  26. engine_type = 'offline'
  27. auth_plugin = 'caching_sha2_password'
  28. host = "127.0.0.1"
  29. port = 3306
  30. database = ""
  31. username = ""
  32. password = ""
  33. query_str = ""
  34. limit = 10
  35. paging = True
  36. result_template = 'key-value.html'
  37. _connection = None
  38. def init(engine_settings):
  39. global _connection # pylint: disable=global-statement
  40. if 'query_str' not in engine_settings:
  41. raise ValueError('query_str cannot be empty')
  42. if not engine_settings['query_str'].lower().startswith('select '):
  43. raise ValueError('only SELECT query is supported')
  44. _connection = mysql.connector.connect(
  45. database=database,
  46. user=username,
  47. password=password,
  48. host=host,
  49. port=port,
  50. auth_plugin=auth_plugin,
  51. )
  52. def search(query, params):
  53. query_params = {'query': query}
  54. query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  55. with _connection.cursor() as cur:
  56. cur.execute(query_to_run, query_params)
  57. return _fetch_results(cur)
  58. def _fetch_results(cur):
  59. results = []
  60. for res in cur:
  61. result = dict(zip(cur.column_names, map(str, res)))
  62. result['template'] = result_template
  63. results.append(result)
  64. return results