creation.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import os
  2. import subprocess
  3. import sys
  4. from django.db.backends.base.creation import BaseDatabaseCreation
  5. from .client import DatabaseClient
  6. class DatabaseCreation(BaseDatabaseCreation):
  7. def sql_table_creation_suffix(self):
  8. suffix = []
  9. test_settings = self.connection.settings_dict["TEST"]
  10. if test_settings["CHARSET"]:
  11. suffix.append("CHARACTER SET %s" % test_settings["CHARSET"])
  12. if test_settings["COLLATION"]:
  13. suffix.append("COLLATE %s" % test_settings["COLLATION"])
  14. return " ".join(suffix)
  15. def _execute_create_test_db(self, cursor, parameters, keepdb=False):
  16. try:
  17. super()._execute_create_test_db(cursor, parameters, keepdb)
  18. except Exception as e:
  19. if len(e.args) < 1 or e.args[0] != 1007:
  20. # All errors except "database exists" (1007) cancel tests.
  21. self.log("Got an error creating the test database: %s" % e)
  22. sys.exit(2)
  23. else:
  24. raise
  25. def _clone_test_db(self, suffix, verbosity, keepdb=False):
  26. source_database_name = self.connection.settings_dict["NAME"]
  27. target_database_name = self.get_test_db_clone_settings(suffix)["NAME"]
  28. test_db_params = {
  29. "dbname": self.connection.ops.quote_name(target_database_name),
  30. "suffix": self.sql_table_creation_suffix(),
  31. }
  32. with self._nodb_cursor() as cursor:
  33. try:
  34. self._execute_create_test_db(cursor, test_db_params, keepdb)
  35. except Exception:
  36. if keepdb:
  37. # If the database should be kept, skip everything else.
  38. return
  39. try:
  40. if verbosity >= 1:
  41. self.log(
  42. "Destroying old test database for alias %s..."
  43. % (
  44. self._get_database_display_str(
  45. verbosity, target_database_name
  46. ),
  47. )
  48. )
  49. cursor.execute("DROP DATABASE %(dbname)s" % test_db_params)
  50. self._execute_create_test_db(cursor, test_db_params, keepdb)
  51. except Exception as e:
  52. self.log("Got an error recreating the test database: %s" % e)
  53. sys.exit(2)
  54. self._clone_db(source_database_name, target_database_name)
  55. def _clone_db(self, source_database_name, target_database_name):
  56. cmd_args, cmd_env = DatabaseClient.settings_to_cmd_args_env(
  57. self.connection.settings_dict, []
  58. )
  59. dump_cmd = [
  60. "mysqldump",
  61. *cmd_args[1:-1],
  62. "--routines",
  63. "--events",
  64. source_database_name,
  65. ]
  66. dump_env = load_env = {**os.environ, **cmd_env} if cmd_env else None
  67. load_cmd = cmd_args
  68. load_cmd[-1] = target_database_name
  69. with subprocess.Popen(
  70. dump_cmd, stdout=subprocess.PIPE, env=dump_env
  71. ) as dump_proc:
  72. with subprocess.Popen(
  73. load_cmd,
  74. stdin=dump_proc.stdout,
  75. stdout=subprocess.DEVNULL,
  76. env=load_env,
  77. ):
  78. # Allow dump_proc to receive a SIGPIPE if the load process exits.
  79. dump_proc.stdout.close()