mysql_server.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """MySQL is said to be the most popular open source database. Before enabling
  4. MySQL engine, you must install the package ``mysql-connector-python``.
  5. The authentication plugin is configurable by setting ``auth_plugin`` in the
  6. attributes. By default it is set to ``caching_sha2_password``.
  7. Example
  8. =======
  9. This is an example configuration for querying a MySQL server:
  10. .. code:: yaml
  11. - name: my_database
  12. engine: mysql_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. 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. port = 3306
  31. database = ""
  32. username = ""
  33. password = ""
  34. query_str = ""
  35. limit = 10
  36. paging = True
  37. result_template = 'key-value.html'
  38. _connection = None
  39. def init(engine_settings):
  40. global _connection # pylint: disable=global-statement
  41. if 'query_str' not in engine_settings:
  42. raise ValueError('query_str cannot be empty')
  43. if not engine_settings['query_str'].lower().startswith('select '):
  44. raise ValueError('only SELECT query is supported')
  45. _connection = mysql.connector.connect(
  46. database=database,
  47. user=username,
  48. password=password,
  49. host=host,
  50. port=port,
  51. auth_plugin=auth_plugin,
  52. )
  53. def search(query, params):
  54. query_params = {'query': query}
  55. query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  56. with _connection.cursor() as cur:
  57. cur.execute(query_to_run, query_params)
  58. return _fetch_results(cur)
  59. def _fetch_results(cur):
  60. results = []
  61. for res in cur:
  62. result = dict(zip(cur.column_names, map(str, res)))
  63. result['template'] = result_template
  64. results.append(result)
  65. return results