mysql_server.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. """Hostname of the DB connector"""
  30. port = 3306
  31. """Port of the DB connector"""
  32. database = ""
  33. """Name of the database."""
  34. username = ""
  35. """Username for the DB connection."""
  36. password = ""
  37. """Password for the DB connection."""
  38. query_str = ""
  39. """SQL query that returns the result items."""
  40. limit = 10
  41. paging = True
  42. result_template = 'key-value.html'
  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):
  59. query_params = {'query': query}
  60. query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  61. with _connection.cursor() as cur:
  62. cur.execute(query_to_run, query_params)
  63. return _fetch_results(cur)
  64. def _fetch_results(cur):
  65. results = []
  66. for res in cur:
  67. result = dict(zip(cur.column_names, map(str, res)))
  68. result['template'] = result_template
  69. results.append(result)
  70. return results