You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

questioner.py 9.7KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import datetime
  2. import importlib
  3. import os
  4. import sys
  5. from django.apps import apps
  6. from django.db.models.fields import NOT_PROVIDED
  7. from django.utils import timezone
  8. from .loader import MigrationLoader
  9. class MigrationQuestioner:
  10. """
  11. Give the autodetector responses to questions it might have.
  12. This base class has a built-in noninteractive mode, but the
  13. interactive subclass is what the command-line arguments will use.
  14. """
  15. def __init__(self, defaults=None, specified_apps=None, dry_run=None):
  16. self.defaults = defaults or {}
  17. self.specified_apps = specified_apps or set()
  18. self.dry_run = dry_run
  19. def ask_initial(self, app_label):
  20. """Should we create an initial migration for the app?"""
  21. # If it was specified on the command line, definitely true
  22. if app_label in self.specified_apps:
  23. return True
  24. # Otherwise, we look to see if it has a migrations module
  25. # without any Python files in it, apart from __init__.py.
  26. # Apps from the new app template will have these; the Python
  27. # file check will ensure we skip South ones.
  28. try:
  29. app_config = apps.get_app_config(app_label)
  30. except LookupError: # It's a fake app.
  31. return self.defaults.get("ask_initial", False)
  32. migrations_import_path, _ = MigrationLoader.migrations_module(app_config.label)
  33. if migrations_import_path is None:
  34. # It's an application with migrations disabled.
  35. return self.defaults.get("ask_initial", False)
  36. try:
  37. migrations_module = importlib.import_module(migrations_import_path)
  38. except ImportError:
  39. return self.defaults.get("ask_initial", False)
  40. else:
  41. # getattr() needed on PY36 and older (replace with attribute access).
  42. if getattr(migrations_module, "__file__", None):
  43. filenames = os.listdir(os.path.dirname(migrations_module.__file__))
  44. elif hasattr(migrations_module, "__path__"):
  45. if len(migrations_module.__path__) > 1:
  46. return False
  47. filenames = os.listdir(list(migrations_module.__path__)[0])
  48. return not any(x.endswith(".py") for x in filenames if x != "__init__.py")
  49. def ask_not_null_addition(self, field_name, model_name):
  50. """Adding a NOT NULL field to a model."""
  51. # None means quit
  52. return None
  53. def ask_not_null_alteration(self, field_name, model_name):
  54. """Changing a NULL field to NOT NULL."""
  55. # None means quit
  56. return None
  57. def ask_rename(self, model_name, old_name, new_name, field_instance):
  58. """Was this field really renamed?"""
  59. return self.defaults.get("ask_rename", False)
  60. def ask_rename_model(self, old_model_state, new_model_state):
  61. """Was this model really renamed?"""
  62. return self.defaults.get("ask_rename_model", False)
  63. def ask_merge(self, app_label):
  64. """Do you really want to merge these migrations?"""
  65. return self.defaults.get("ask_merge", False)
  66. def ask_auto_now_add_addition(self, field_name, model_name):
  67. """Adding an auto_now_add field to a model."""
  68. # None means quit
  69. return None
  70. class InteractiveMigrationQuestioner(MigrationQuestioner):
  71. def _boolean_input(self, question, default=None):
  72. result = input("%s " % question)
  73. if not result and default is not None:
  74. return default
  75. while not result or result[0].lower() not in "yn":
  76. result = input("Please answer yes or no: ")
  77. return result[0].lower() == "y"
  78. def _choice_input(self, question, choices):
  79. print(question)
  80. for i, choice in enumerate(choices):
  81. print(" %s) %s" % (i + 1, choice))
  82. result = input("Select an option: ")
  83. while True:
  84. try:
  85. value = int(result)
  86. except ValueError:
  87. pass
  88. else:
  89. if 0 < value <= len(choices):
  90. return value
  91. result = input("Please select a valid option: ")
  92. def _ask_default(self, default=''):
  93. """
  94. Prompt for a default value.
  95. The ``default`` argument allows providing a custom default value (as a
  96. string) which will be shown to the user and used as the return value
  97. if the user doesn't provide any other input.
  98. """
  99. print("Please enter the default value now, as valid Python")
  100. if default:
  101. print(
  102. "You can accept the default '{}' by pressing 'Enter' or you "
  103. "can provide another value.".format(default)
  104. )
  105. print("The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now")
  106. print("Type 'exit' to exit this prompt")
  107. while True:
  108. if default:
  109. prompt = "[default: {}] >>> ".format(default)
  110. else:
  111. prompt = ">>> "
  112. code = input(prompt)
  113. if not code and default:
  114. code = default
  115. if not code:
  116. print("Please enter some code, or 'exit' (with no quotes) to exit.")
  117. elif code == "exit":
  118. sys.exit(1)
  119. else:
  120. try:
  121. return eval(code, {}, {'datetime': datetime, 'timezone': timezone})
  122. except (SyntaxError, NameError) as e:
  123. print("Invalid input: %s" % e)
  124. def ask_not_null_addition(self, field_name, model_name):
  125. """Adding a NOT NULL field to a model."""
  126. if not self.dry_run:
  127. choice = self._choice_input(
  128. "You are trying to add a non-nullable field '%s' to %s without a default; "
  129. "we can't do that (the database needs something to populate existing rows).\n"
  130. "Please select a fix:" % (field_name, model_name),
  131. [
  132. ("Provide a one-off default now (will be set on all existing "
  133. "rows with a null value for this column)"),
  134. "Quit, and let me add a default in models.py",
  135. ]
  136. )
  137. if choice == 2:
  138. sys.exit(3)
  139. else:
  140. return self._ask_default()
  141. return None
  142. def ask_not_null_alteration(self, field_name, model_name):
  143. """Changing a NULL field to NOT NULL."""
  144. if not self.dry_run:
  145. choice = self._choice_input(
  146. "You are trying to change the nullable field '%s' on %s to non-nullable "
  147. "without a default; we can't do that (the database needs something to "
  148. "populate existing rows).\n"
  149. "Please select a fix:" % (field_name, model_name),
  150. [
  151. ("Provide a one-off default now (will be set on all existing "
  152. "rows with a null value for this column)"),
  153. ("Ignore for now, and let me handle existing rows with NULL myself "
  154. "(e.g. because you added a RunPython or RunSQL operation to handle "
  155. "NULL values in a previous data migration)"),
  156. "Quit, and let me add a default in models.py",
  157. ]
  158. )
  159. if choice == 2:
  160. return NOT_PROVIDED
  161. elif choice == 3:
  162. sys.exit(3)
  163. else:
  164. return self._ask_default()
  165. return None
  166. def ask_rename(self, model_name, old_name, new_name, field_instance):
  167. """Was this field really renamed?"""
  168. msg = "Did you rename %s.%s to %s.%s (a %s)? [y/N]"
  169. return self._boolean_input(msg % (model_name, old_name, model_name, new_name,
  170. field_instance.__class__.__name__), False)
  171. def ask_rename_model(self, old_model_state, new_model_state):
  172. """Was this model really renamed?"""
  173. msg = "Did you rename the %s.%s model to %s? [y/N]"
  174. return self._boolean_input(msg % (old_model_state.app_label, old_model_state.name,
  175. new_model_state.name), False)
  176. def ask_merge(self, app_label):
  177. return self._boolean_input(
  178. "\nMerging will only work if the operations printed above do not conflict\n" +
  179. "with each other (working on different fields or models)\n" +
  180. "Do you want to merge these migration branches? [y/N]",
  181. False,
  182. )
  183. def ask_auto_now_add_addition(self, field_name, model_name):
  184. """Adding an auto_now_add field to a model."""
  185. if not self.dry_run:
  186. choice = self._choice_input(
  187. "You are trying to add the field '{}' with 'auto_now_add=True' "
  188. "to {} without a default; the database needs something to "
  189. "populate existing rows.\n".format(field_name, model_name),
  190. [
  191. "Provide a one-off default now (will be set on all "
  192. "existing rows)",
  193. "Quit, and let me add a default in models.py",
  194. ]
  195. )
  196. if choice == 2:
  197. sys.exit(3)
  198. else:
  199. return self._ask_default(default='timezone.now')
  200. return None
  201. class NonInteractiveMigrationQuestioner(MigrationQuestioner):
  202. def ask_not_null_addition(self, field_name, model_name):
  203. # We can't ask the user, so act like the user aborted.
  204. sys.exit(3)
  205. def ask_not_null_alteration(self, field_name, model_name):
  206. # We can't ask the user, so set as not provided.
  207. return NOT_PROVIDED
  208. def ask_auto_now_add_addition(self, field_name, model_name):
  209. # We can't ask the user, so act like the user aborted.
  210. sys.exit(3)