mysql_server.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """MySQL database (offline)
  4. """
  5. # import error is ignored because the admin has to install mysql manually to use
  6. # the engine
  7. import mysql.connector # pyright: ignore # pylint: disable=import-error
  8. engine_type = 'offline'
  9. auth_plugin = 'caching_sha2_password'
  10. host = "127.0.0.1"
  11. port = 3306
  12. database = ""
  13. username = ""
  14. password = ""
  15. query_str = ""
  16. limit = 10
  17. paging = True
  18. result_template = 'key-value.html'
  19. _connection = None
  20. def init(engine_settings):
  21. global _connection # pylint: disable=global-statement
  22. if 'query_str' not in engine_settings:
  23. raise ValueError('query_str cannot be empty')
  24. if not engine_settings['query_str'].lower().startswith('select '):
  25. raise ValueError('only SELECT query is supported')
  26. _connection = mysql.connector.connect(
  27. database=database,
  28. user=username,
  29. password=password,
  30. host=host,
  31. port=port,
  32. auth_plugin=auth_plugin,
  33. )
  34. def search(query, params):
  35. query_params = {'query': query}
  36. query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  37. with _connection.cursor() as cur:
  38. cur.execute(query_to_run, query_params)
  39. return _fetch_results(cur)
  40. def _fetch_results(cur):
  41. results = []
  42. for res in cur:
  43. result = dict(zip(cur.column_names, map(str, res)))
  44. result['template'] = result_template
  45. results.append(result)
  46. return results