Debian Codegraph @

django/db/migrations/questioner.py

raw
1 import datetime
2 import importlib
3 import os
4 import sys
5
6 from django.apps import apps
7 from django.core.management.base import OutputWrapper
8 from django.db.models import NOT_PROVIDED
9 from django.utils import timezone
10 from django.utils.version import get_docs_version
11
12 from .loader import MigrationLoader
13
14
15 class MigrationQuestioner:
16 """
17 Give the autodetector responses to questions it might have.
18 This base class has a built-in noninteractive mode, but the
19 interactive subclass is what the command-line arguments will use.
20 """
21
22 def __init__(self, defaults=None, specified_apps=None, dry_run=None):
23 self.defaults = defaults or {}
24 self.specified_apps = specified_apps or set()
25 self.dry_run = dry_run
26
27 def ask_initial(self, app_label):
28 """Should we create an initial migration for the app?"""
29 # If it was specified on the command line, definitely true
30 if app_label in self.specified_apps:
31 return True
32 # Otherwise, we look to see if it has a migrations module
33 # without any Python files in it, apart from __init__.py.
34 # Apps from the new app template will have these; the Python
35 # file check will ensure we skip South ones.
36 try:
37 app_config = apps.get_app_config(app_label)
38 except LookupError: # It's a fake app.
39 return self.defaults.get("ask_initial", False)
40 migrations_import_path, _ = MigrationLoader.migrations_module(app_config.label)
41 if migrations_import_path is None:
42 # It's an application with migrations disabled.
43 return self.defaults.get("ask_initial", False)
44 try:
45 migrations_module = importlib.import_module(migrations_import_path)
46 except ImportError:
47 return self.defaults.get("ask_initial", False)
48 else:
49 if getattr(migrations_module, "__file__", None):
50 filenames = os.listdir(os.path.dirname(migrations_module.__file__))
51 elif hasattr(migrations_module, "__path__"):
52 if len(migrations_module.__path__) > 1:
53 return False
54 filenames = os.listdir(list(migrations_module.__path__)[0])
55 return not any(x.endswith(".py") for x in filenames if x != "__init__.py")
56
57 def ask_not_null_addition(self, field_name, model_name):
58 """Adding a NOT NULL field to a model."""
59 # None means quit
60 return None
61
62 def ask_not_null_alteration(self, field_name, model_name):
63 """Changing a NULL field to NOT NULL."""
64 # None means quit
65 return None
66
67 def ask_rename(self, model_name, old_name, new_name, field_instance):
68 """Was this field really renamed?"""
69 return self.defaults.get("ask_rename", False)
70
71 def ask_rename_model(self, old_model_state, new_model_state):
72 """Was this model really renamed?"""
73 return self.defaults.get("ask_rename_model", False)
74
75 def ask_merge(self, app_label):
76 """Should these migrations really be merged?"""
77 return self.defaults.get("ask_merge", False)
78
79 def ask_auto_now_add_addition(self, field_name, model_name):
80 """Adding an auto_now_add field to a model."""
81 # None means quit
82 return None
83
84 def ask_unique_callable_default_addition(self, field_name, model_name):
85 """Adding a unique field with a callable default."""
86 # None means continue.
87 return None
88
89
90 class InteractiveMigrationQuestioner(MigrationQuestioner):
91 def __init__(
92 self, defaults=None, specified_apps=None, dry_run=None, prompt_output=None
93 ):
94 super().__init__(
95 defaults=defaults, specified_apps=specified_apps, dry_run=dry_run
96 )
97 self.prompt_output = prompt_output or OutputWrapper(sys.stdout)
98
99 def _boolean_input(self, question, default=None):
100 self.prompt_output.write(f"{question} ", ending="")
101 result = input()
102 if not result and default is not None:
103 return default
104 while not result or result[0].lower() not in "yn":
105 self.prompt_output.write("Please answer yes or no: ", ending="")
106 result = input()
107 return result[0].lower() == "y"
108
109 def _choice_input(self, question, choices):
110 self.prompt_output.write(f"{question}")
111 for i, choice in enumerate(choices):
112 self.prompt_output.write(" %s) %s" % (i + 1, choice))
113 self.prompt_output.write("Select an option: ", ending="")
114 while True:
115 try:
116 result = input()
117 value = int(result)
118 except ValueError:
119 pass
120 except KeyboardInterrupt:
121 self.prompt_output.write("\nCancelled.")
122 sys.exit(1)
123 else:
124 if 0 < value <= len(choices):
125 return value
126 self.prompt_output.write("Please select a valid option: ", ending="")
127
128 def _ask_default(self, default=""):
129 """
130 Prompt for a default value.
131
132 The ``default`` argument allows providing a custom default value (as a
133 string) which will be shown to the user and used as the return value
134 if the user doesn't provide any other input.
135 """
136 self.prompt_output.write("Please enter the default value as valid Python.")
137 if default:
138 self.prompt_output.write(
139 f"Accept the default '{default}' by pressing 'Enter' or "
140 f"provide another value."
141 )
142 self.prompt_output.write(
143 "The datetime and django.utils.timezone modules are available, so "
144 "it is possible to provide e.g. timezone.now as a value."
145 )
146 self.prompt_output.write("Type 'exit' to exit this prompt")
147 while True:
148 if default:
149 prompt = "[default: {}] >>> ".format(default)
150 else:
151 prompt = ">>> "
152 self.prompt_output.write(prompt, ending="")
153 try:
154 code = input()
155 except KeyboardInterrupt:
156 self.prompt_output.write("\nCancelled.")
157 sys.exit(1)
158 if not code and default:
159 code = default
160 if not code:
161 self.prompt_output.write(
162 "Please enter some code, or 'exit' (without quotes) to exit."
163 )
164 elif code == "exit":
165 sys.exit(1)
166 else:
167 try:
168 return eval(code, {}, {"datetime": datetime, "timezone": timezone})
169 except Exception as e:
170 self.prompt_output.write(f"{e.__class__.__name__}: {e}")
171
172 def ask_not_null_addition(self, field_name, model_name):
173 """Adding a NOT NULL field to a model."""
174 if not self.dry_run:
175 choice = self._choice_input(
176 f"It is impossible to add a non-nullable field '{field_name}' "
177 f"to {model_name} without specifying a default. This is "
178 f"because the database needs something to populate existing "
179 f"rows.\n"
180 f"Please select a fix:",
181 [
182 (
183 "Provide a one-off default now (will be set on all existing "
184 "rows with a null value for this column)"
185 ),
186 "Quit and manually define a default value in models.py.",
187 ],
188 )
189 if choice == 2:
190 sys.exit(3)
191 else:
192 return self._ask_default()
193 return None
194
195 def ask_not_null_alteration(self, field_name, model_name):
196 """Changing a NULL field to NOT NULL."""
197 if not self.dry_run:
198 choice = self._choice_input(
199 f"It is impossible to change a nullable field '{field_name}' "
200 f"on {model_name} to non-nullable without providing a "
201 f"default. This is because the database needs something to "
202 f"populate existing rows.\n"
203 f"Please select a fix:",
204 [
205 (
206 "Provide a one-off default now (will be set on all existing "
207 "rows with a null value for this column)"
208 ),
209 "Ignore for now. Existing rows that contain NULL values "
210 "will have to be handled manually, for example with a "
211 "RunPython or RunSQL operation.",
212 "Quit and manually define a default value in models.py.",
213 ],
214 )
215 if choice == 2:
216 return NOT_PROVIDED
217 elif choice == 3:
218 sys.exit(3)
219 else:
220 return self._ask_default()
221 return None
222
223 def ask_rename(self, model_name, old_name, new_name, field_instance):
224 """Was this field really renamed?"""
225 msg = "Was %s.%s renamed to %s.%s (a %s)? [y/N]"
226 return self._boolean_input(
227 msg
228 % (
229 model_name,
230 old_name,
231 model_name,
232 new_name,
233 field_instance.__class__.__name__,
234 ),
235 False,
236 )
237
238 def ask_rename_model(self, old_model_state, new_model_state):
239 """Was this model really renamed?"""
240 msg = "Was the model %s.%s renamed to %s? [y/N]"
241 return self._boolean_input(
242 msg
243 % (old_model_state.app_label, old_model_state.name, new_model_state.name),
244 False,
245 )
246
247 def ask_merge(self, app_label):
248 return self._boolean_input(
249 "\nMerging will only work if the operations printed above do not conflict\n"
250 + "with each other (working on different fields or models)\n"
251 + "Should these migration branches be merged? [y/N]",
252 False,
253 )
254
255 def ask_auto_now_add_addition(self, field_name, model_name):
256 """Adding an auto_now_add field to a model."""
257 if not self.dry_run:
258 choice = self._choice_input(
259 f"It is impossible to add the field '{field_name}' with "
260 f"'auto_now_add=True' to {model_name} without providing a "
261 f"default. This is because the database needs something to "
262 f"populate existing rows.\n",
263 [
264 "Provide a one-off default now which will be set on all "
265 "existing rows",
266 "Quit and manually define a default value in models.py.",
267 ],
268 )
269 if choice == 2:
270 sys.exit(3)
271 else:
272 return self._ask_default(default="timezone.now")
273 return None
274
275 def ask_unique_callable_default_addition(self, field_name, model_name):
276 """Adding a unique field with a callable default."""
277 if not self.dry_run:
278 version = get_docs_version()
279 choice = self._choice_input(
280 f"Callable default on unique field {model_name}.{field_name} "
281 f"will not generate unique values upon migrating.\n"
282 f"Please choose how to proceed:\n",
283 [
284 f"Continue making this migration as the first step in "
285 f"writing a manual migration to generate unique values "
286 f"described here: "
287 f"https://docs.djangoproject.com/en/{version}/howto/"
288 f"writing-migrations/#migrations-that-add-unique-fields.",
289 "Quit and edit field options in models.py.",
290 ],
291 )
292 if choice == 2:
293 sys.exit(3)
294 return None
295
296
297 class NonInteractiveMigrationQuestioner(MigrationQuestioner):
298 def __init__(
299 self,
300 defaults=None,
301 specified_apps=None,
302 dry_run=None,
303 verbosity=1,
304 log=None,
305 ):
306 self.verbosity = verbosity
307 self.log = log
308 super().__init__(
309 defaults=defaults,
310 specified_apps=specified_apps,
311 dry_run=dry_run,
312 )
313
314 def log_lack_of_migration(self, field_name, model_name, reason):
315 if self.verbosity > 0:
316 self.log(
317 f"Field '{field_name}' on model '{model_name}' not migrated: "
318 f"{reason}."
319 )
320
321 def ask_not_null_addition(self, field_name, model_name):
322 # We can't ask the user, so act like the user aborted.
323 self.log_lack_of_migration(
324 field_name,
325 model_name,
326 "it is impossible to add a non-nullable field without specifying "
327 "a default",
328 )
329 sys.exit(3)
330
331 def ask_not_null_alteration(self, field_name, model_name):
332 # We can't ask the user, so set as not provided.
333 self.log(
334 f"Field '{field_name}' on model '{model_name}' given a default of "
335 f"NOT PROVIDED and must be corrected."
336 )
337 return NOT_PROVIDED
338
339 def ask_auto_now_add_addition(self, field_name, model_name):
340 # We can't ask the user, so act like the user aborted.
341 self.log_lack_of_migration(
342 field_name,
343 model_name,
344 "it is impossible to add a field with 'auto_now_add=True' without "
345 "specifying a default",
346 )
347 sys.exit(3)