client.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from django.db.backends.base.client import BaseDatabaseClient
  2. class DatabaseClient(BaseDatabaseClient):
  3. executable_name = 'mysql'
  4. @classmethod
  5. def settings_to_cmd_args_env(cls, settings_dict, parameters):
  6. args = [cls.executable_name]
  7. env = None
  8. database = settings_dict['OPTIONS'].get(
  9. 'database',
  10. settings_dict['OPTIONS'].get('db', settings_dict['NAME']),
  11. )
  12. user = settings_dict['OPTIONS'].get('user', settings_dict['USER'])
  13. password = settings_dict['OPTIONS'].get(
  14. 'password',
  15. settings_dict['OPTIONS'].get('passwd', settings_dict['PASSWORD'])
  16. )
  17. host = settings_dict['OPTIONS'].get('host', settings_dict['HOST'])
  18. port = settings_dict['OPTIONS'].get('port', settings_dict['PORT'])
  19. server_ca = settings_dict['OPTIONS'].get('ssl', {}).get('ca')
  20. client_cert = settings_dict['OPTIONS'].get('ssl', {}).get('cert')
  21. client_key = settings_dict['OPTIONS'].get('ssl', {}).get('key')
  22. defaults_file = settings_dict['OPTIONS'].get('read_default_file')
  23. charset = settings_dict['OPTIONS'].get('charset')
  24. # Seems to be no good way to set sql_mode with CLI.
  25. if defaults_file:
  26. args += ["--defaults-file=%s" % defaults_file]
  27. if user:
  28. args += ["--user=%s" % user]
  29. if password:
  30. # The MYSQL_PWD environment variable usage is discouraged per
  31. # MySQL's documentation due to the possibility of exposure through
  32. # `ps` on old Unix flavors but --password suffers from the same
  33. # flaw on even more systems. Usage of an environment variable also
  34. # prevents password exposure if the subprocess.run(check=True) call
  35. # raises a CalledProcessError since the string representation of
  36. # the latter includes all of the provided `args`.
  37. env = {'MYSQL_PWD': password}
  38. if host:
  39. if '/' in host:
  40. args += ["--socket=%s" % host]
  41. else:
  42. args += ["--host=%s" % host]
  43. if port:
  44. args += ["--port=%s" % port]
  45. if server_ca:
  46. args += ["--ssl-ca=%s" % server_ca]
  47. if client_cert:
  48. args += ["--ssl-cert=%s" % client_cert]
  49. if client_key:
  50. args += ["--ssl-key=%s" % client_key]
  51. if charset:
  52. args += ['--default-character-set=%s' % charset]
  53. if database:
  54. args += [database]
  55. args.extend(parameters)
  56. return args, env