mysql_server.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. from searx.result_types import EngineResults
  21. try:
  22. import mysql.connector # type: ignore
  23. except ImportError:
  24. # import error is ignored because the admin has to install mysql manually to use
  25. # the engine
  26. pass
  27. engine_type = 'offline'
  28. auth_plugin = 'caching_sha2_password'
  29. host = "127.0.0.1"
  30. """Hostname of the DB connector"""
  31. port = 3306
  32. """Port of the DB connector"""
  33. database = ""
  34. """Name of the database."""
  35. username = ""
  36. """Username for the DB connection."""
  37. password = ""
  38. """Password for the DB connection."""
  39. query_str = ""
  40. """SQL query that returns the result items."""
  41. limit = 10
  42. paging = True
  43. _connection = None
  44. def init(engine_settings):
  45. global _connection # pylint: disable=global-statement
  46. if 'query_str' not in engine_settings:
  47. raise ValueError('query_str cannot be empty')
  48. if not engine_settings['query_str'].lower().startswith('select '):
  49. raise ValueError('only SELECT query is supported')
  50. _connection = mysql.connector.connect(
  51. database=database,
  52. user=username,
  53. password=password,
  54. host=host,
  55. port=port,
  56. auth_plugin=auth_plugin,
  57. )
  58. def search(query, params) -> EngineResults:
  59. res = EngineResults()
  60. query_params = {'query': query}
  61. query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  62. with _connection.cursor() as cur:
  63. cur.execute(query_to_run, query_params)
  64. for row in cur:
  65. kvmap = dict(zip(cur.column_names, map(str, row)))
  66. res.add(res.types.KeyValue(kvmap=kvmap))
  67. return res