autodetector.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. import re
  2. import sys
  3. from django.utils import datetime_safe
  4. from django.utils.six.moves import input
  5. from django.db.migrations import operations
  6. from django.db.migrations.migration import Migration
  7. from django.db.models.loading import cache
  8. class MigrationAutodetector(object):
  9. """
  10. Takes a pair of ProjectStates, and compares them to see what the
  11. first would need doing to make it match the second (the second
  12. usually being the project's current state).
  13. Note that this naturally operates on entire projects at a time,
  14. as it's likely that changes interact (for example, you can't
  15. add a ForeignKey without having a migration to add the table it
  16. depends on first). A user interface may offer single-app usage
  17. if it wishes, with the caveat that it may not always be possible.
  18. """
  19. def __init__(self, from_state, to_state, questioner=None):
  20. self.from_state = from_state
  21. self.to_state = to_state
  22. self.questioner = questioner or MigrationQuestioner()
  23. def changes(self):
  24. """
  25. Returns a dict of migration plans which will achieve the
  26. change from from_state to to_state. The dict has app labels
  27. as keys and a list of migrations as values.
  28. The resulting migrations aren't specially named, but the names
  29. do matter for dependencies inside the set.
  30. """
  31. # We'll store migrations as lists by app names for now
  32. self.migrations = {}
  33. old_app_cache = self.from_state.render()
  34. new_app_cache = self.to_state.render()
  35. # Adding models. Phase 1 is adding models with no outward relationships.
  36. added_models = set(self.to_state.models.keys()) - set(self.from_state.models.keys())
  37. pending_add = {}
  38. for app_label, model_name in added_models:
  39. model_state = self.to_state.models[app_label, model_name]
  40. # Are there any relationships out from this model? if so, punt it to the next phase.
  41. related_fields = []
  42. for field in new_app_cache.get_model(app_label, model_name)._meta.fields:
  43. if hasattr(field, "rel"):
  44. if hasattr(field.rel, "to"):
  45. related_fields.append((field.name, field.rel.to._meta.app_label.lower(), field.rel.to._meta.object_name.lower()))
  46. if hasattr(field.rel, "through") and not field.rel.though._meta.auto_created:
  47. related_fields.append((field.name, field.rel.through._meta.app_label.lower(), field.rel.through._meta.object_name.lower()))
  48. if related_fields:
  49. pending_add[app_label, model_name] = related_fields
  50. else:
  51. self.add_to_migration(
  52. app_label,
  53. operations.CreateModel(
  54. name = model_state.name,
  55. fields = model_state.fields,
  56. options = model_state.options,
  57. bases = model_state.bases,
  58. )
  59. )
  60. # Phase 2 is progressively adding pending models, splitting up into two
  61. # migrations if required.
  62. pending_new_fks = []
  63. while pending_add:
  64. # Is there one we can add that has all dependencies satisfied?
  65. satisfied = [(m, rf) for m, rf in pending_add.items() if all((al, mn) not in pending_add for f, al, mn in rf)]
  66. if satisfied:
  67. (app_label, model_name), related_fields = sorted(satisfied)[0]
  68. model_state = self.to_state.models[app_label, model_name]
  69. self.add_to_migration(
  70. app_label,
  71. operations.CreateModel(
  72. name = model_state.name,
  73. fields = model_state.fields,
  74. options = model_state.options,
  75. bases = model_state.bases,
  76. )
  77. )
  78. for field_name, other_app_label, other_model_name in related_fields:
  79. self.add_dependency(app_label, other_app_label)
  80. del pending_add[app_label, model_name]
  81. # Ah well, we'll need to split one. Pick deterministically.
  82. else:
  83. (app_label, model_name), related_fields = sorted(pending_add.items())[0]
  84. model_state = self.to_state.models[app_label, model_name]
  85. # Work out the fields that need splitting out
  86. bad_fields = dict((f, (al, mn)) for f, al, mn in related_fields if (al, mn) in pending_add)
  87. # Create the model, without those
  88. self.add_to_migration(
  89. app_label,
  90. operations.CreateModel(
  91. name = model_state.name,
  92. fields = [(n, f) for n, f in model_state.fields if n not in bad_fields],
  93. options = model_state.options,
  94. bases = model_state.bases,
  95. )
  96. )
  97. # Add the bad fields to be made in a phase 3
  98. for field_name, (other_app_label, other_model_name) in bad_fields.items():
  99. pending_new_fks.append((app_label, model_name, field_name, other_app_label))
  100. del pending_add[app_label, model_name]
  101. # Phase 3 is adding the final set of FKs as separate new migrations
  102. for app_label, model_name, field_name, other_app_label in pending_new_fks:
  103. model_state = self.to_state.models[app_label, model_name]
  104. self.add_to_migration(
  105. app_label,
  106. operations.AddField(
  107. model_name = model_name,
  108. name = field_name,
  109. field = model_state.get_field_by_name(field_name),
  110. ),
  111. new = True,
  112. )
  113. self.add_dependency(app_label, other_app_label)
  114. # Removing models
  115. removed_models = set(self.from_state.models.keys()) - set(self.to_state.models.keys())
  116. for app_label, model_name in removed_models:
  117. model_state = self.from_state.models[app_label, model_name]
  118. self.add_to_migration(
  119. app_label,
  120. operations.DeleteModel(
  121. model_state.name,
  122. )
  123. )
  124. # Changes within models
  125. kept_models = set(self.from_state.models.keys()).intersection(self.to_state.models.keys())
  126. for app_label, model_name in kept_models:
  127. old_model_state = self.from_state.models[app_label, model_name]
  128. new_model_state = self.to_state.models[app_label, model_name]
  129. # New fields
  130. old_field_names = set([x for x, y in old_model_state.fields])
  131. new_field_names = set([x for x, y in new_model_state.fields])
  132. for field_name in new_field_names - old_field_names:
  133. field = new_model_state.get_field_by_name(field_name)
  134. # Scan to see if this is actually a rename!
  135. field_dec = field.deconstruct()[1:]
  136. found_rename = False
  137. for removed_field_name in (old_field_names - new_field_names):
  138. if old_model_state.get_field_by_name(removed_field_name).deconstruct()[1:] == field_dec:
  139. if self.questioner.ask_rename(model_name, removed_field_name, field_name, field):
  140. self.add_to_migration(
  141. app_label,
  142. operations.RenameField(
  143. model_name = model_name,
  144. old_name = removed_field_name,
  145. new_name = field_name,
  146. )
  147. )
  148. old_field_names.remove(removed_field_name)
  149. new_field_names.remove(field_name)
  150. found_rename = True
  151. break
  152. if found_rename:
  153. continue
  154. # You can't just add NOT NULL fields with no default
  155. if not field.null and not field.has_default():
  156. field.default = self.questioner.ask_not_null_addition(field_name, model_name)
  157. self.add_to_migration(
  158. app_label,
  159. operations.AddField(
  160. model_name = model_name,
  161. name = field_name,
  162. field = field,
  163. )
  164. )
  165. # Old fields
  166. for field_name in old_field_names - new_field_names:
  167. self.add_to_migration(
  168. app_label,
  169. operations.RemoveField(
  170. model_name = model_name,
  171. name = field_name,
  172. )
  173. )
  174. # The same fields
  175. for field_name in old_field_names.intersection(new_field_names):
  176. # Did the field change?
  177. old_field_dec = old_model_state.get_field_by_name(field_name).deconstruct()
  178. new_field_dec = new_model_state.get_field_by_name(field_name).deconstruct()
  179. if old_field_dec != new_field_dec:
  180. self.add_to_migration(
  181. app_label,
  182. operations.AlterField(
  183. model_name = model_name,
  184. name = field_name,
  185. field = new_model_state.get_field_by_name(field_name),
  186. )
  187. )
  188. # unique_together changes
  189. if old_model_state.options.get("unique_together", set()) != new_model_state.options.get("unique_together", set()):
  190. self.add_to_migration(
  191. app_label,
  192. operations.AlterUniqueTogether(
  193. name = model_name,
  194. unique_together = new_model_state.options.get("unique_together", set()),
  195. )
  196. )
  197. # Alright, now add internal dependencies
  198. for app_label, migrations in self.migrations.items():
  199. for m1, m2 in zip(migrations, migrations[1:]):
  200. m2.dependencies.append((app_label, m1.name))
  201. # Clean up dependencies
  202. for app_label, migrations in self.migrations.items():
  203. for migration in migrations:
  204. migration.dependencies = list(set(migration.dependencies))
  205. return self.migrations
  206. def add_to_migration(self, app_label, operation, new=False):
  207. migrations = self.migrations.setdefault(app_label, [])
  208. if not migrations or new:
  209. subclass = type("Migration", (Migration,), {"operations": [], "dependencies": []})
  210. instance = subclass("auto_%i" % (len(migrations) + 1), app_label)
  211. migrations.append(instance)
  212. migrations[-1].operations.append(operation)
  213. def add_dependency(self, app_label, other_app_label):
  214. """
  215. Adds a dependency to app_label's newest migration on
  216. other_app_label's latest migration.
  217. """
  218. if self.migrations.get(other_app_label, []):
  219. dependency = (other_app_label, self.migrations[other_app_label][-1].name)
  220. else:
  221. dependency = (other_app_label, "__first__")
  222. self.migrations[app_label][-1].dependencies.append(dependency)
  223. def arrange_for_graph(self, changes, graph):
  224. """
  225. Takes in a result from changes() and a MigrationGraph,
  226. and fixes the names and dependencies of the changes so they
  227. extend the graph from the leaf nodes for each app.
  228. """
  229. leaves = graph.leaf_nodes()
  230. name_map = {}
  231. for app_label, migrations in list(changes.items()):
  232. if not migrations:
  233. continue
  234. # Find the app label's current leaf node
  235. app_leaf = None
  236. for leaf in leaves:
  237. if leaf[0] == app_label:
  238. app_leaf = leaf
  239. break
  240. # Do they want an initial migration for this app?
  241. if app_leaf is None and not self.questioner.ask_initial(app_label):
  242. # They don't.
  243. for migration in migrations:
  244. name_map[(app_label, migration.name)] = (app_label, "__first__")
  245. del changes[app_label]
  246. # Work out the next number in the sequence
  247. if app_leaf is None:
  248. next_number = 1
  249. else:
  250. next_number = (self.parse_number(app_leaf[1]) or 0) + 1
  251. # Name each migration
  252. for i, migration in enumerate(migrations):
  253. if i == 0 and app_leaf:
  254. migration.dependencies.append(app_leaf)
  255. if i == 0 and not app_leaf:
  256. new_name = "0001_initial"
  257. else:
  258. new_name = "%04i_%s" % (next_number, self.suggest_name(migration.operations))
  259. name_map[(app_label, migration.name)] = (app_label, new_name)
  260. migration.name = new_name
  261. # Now fix dependencies
  262. for app_label, migrations in changes.items():
  263. for migration in migrations:
  264. migration.dependencies = [name_map.get(d, d) for d in migration.dependencies]
  265. return changes
  266. def trim_to_apps(self, changes, app_labels):
  267. """
  268. Takes changes from arrange_for_graph and set of app labels and
  269. returns a modified set of changes which trims out as many migrations
  270. that are not in app_labels as possible.
  271. Note that some other migrations may still be present, as they may be
  272. required dependencies.
  273. """
  274. # Gather other app dependencies in a first pass
  275. app_dependencies = {}
  276. for app_label, migrations in changes.items():
  277. for migration in migrations:
  278. for dep_app_label, name in migration.dependencies:
  279. app_dependencies.setdefault(app_label, set()).add(dep_app_label)
  280. required_apps = set(app_labels)
  281. # Keep resolving till there's no change
  282. old_required_apps = None
  283. while old_required_apps != required_apps:
  284. old_required_apps = set(required_apps)
  285. for app_label in list(required_apps):
  286. required_apps.update(app_dependencies.get(app_label, set()))
  287. # Remove all migrations that aren't needed
  288. for app_label in list(changes.keys()):
  289. if app_label not in required_apps:
  290. del changes[app_label]
  291. return changes
  292. @classmethod
  293. def suggest_name(cls, ops):
  294. """
  295. Given a set of operations, suggests a name for the migration
  296. they might represent. Names not guaranteed to be unique; they
  297. must be prefixed by a number or date.
  298. """
  299. if len(ops) == 1:
  300. if isinstance(ops[0], operations.CreateModel):
  301. return ops[0].name.lower()
  302. elif isinstance(ops[0], operations.DeleteModel):
  303. return "delete_%s" % ops[0].name.lower()
  304. elif isinstance(ops[0], operations.AddField):
  305. return "%s_%s" % (ops[0].model_name.lower(), ops[0].name.lower())
  306. elif isinstance(ops[0], operations.RemoveField):
  307. return "remove_%s_%s" % (ops[0].model_name.lower(), ops[0].name.lower())
  308. elif all(isinstance(o, operations.CreateModel) for o in ops):
  309. return "_".join(sorted(o.name.lower() for o in ops))
  310. return "auto"
  311. @classmethod
  312. def parse_number(cls, name):
  313. """
  314. Given a migration name, tries to extract a number from the
  315. beginning of it. If no number found, returns None.
  316. """
  317. if re.match(r"^\d+_", name):
  318. return int(name.split("_")[0])
  319. return None
  320. class MigrationQuestioner(object):
  321. """
  322. Gives the autodetector responses to questions it might have.
  323. This base class has a built-in noninteractive mode, but the
  324. interactive subclass is what the command-line arguments will use.
  325. """
  326. def __init__(self, defaults=None):
  327. self.defaults = defaults or {}
  328. def ask_initial(self, app_label):
  329. "Should we create an initial migration for the app?"
  330. return self.defaults.get("ask_initial", False)
  331. def ask_not_null_addition(self, field_name, model_name):
  332. "Adding a NOT NULL field to a model"
  333. # None means quit
  334. return None
  335. def ask_rename(self, model_name, old_name, new_name, field_instance):
  336. "Was this field really renamed?"
  337. return self.defaults.get("ask_rename", False)
  338. class InteractiveMigrationQuestioner(MigrationQuestioner):
  339. def __init__(self, specified_apps=set()):
  340. self.specified_apps = specified_apps
  341. def _boolean_input(self, question, default=None):
  342. result = input("%s " % question)
  343. if not result and default is not None:
  344. return default
  345. while len(result) < 1 or result[0].lower() not in "yn":
  346. result = input("Please answer yes or no: ")
  347. return result[0].lower() == "y"
  348. def _choice_input(self, question, choices):
  349. print(question)
  350. for i, choice in enumerate(choices):
  351. print(" %s) %s" % (i + 1, choice))
  352. result = input("Select an option: ")
  353. while True:
  354. try:
  355. value = int(result)
  356. if 0 < value <= len(choices):
  357. return value
  358. except ValueError:
  359. pass
  360. result = input("Please select a valid option: ")
  361. def ask_initial(self, app_label):
  362. "Should we create an initial migration for the app?"
  363. # Don't ask for django.contrib apps
  364. app = cache.get_app(app_label)
  365. if app.__name__.startswith("django.contrib"):
  366. return False
  367. # If it was specified on the command line, definitely true
  368. if app_label in self.specified_apps:
  369. return True
  370. # Now ask
  371. return self._boolean_input("Do you want to enable migrations for app '%s'? [y/N]" % app_label, False)
  372. def ask_not_null_addition(self, field_name, model_name):
  373. "Adding a NOT NULL field to a model"
  374. choice = self._choice_input(
  375. "You are trying to add a non-nullable field '%s' to %s without a default;\n" % (field_name, model_name) +
  376. "this is not possible. Please select a fix:",
  377. [
  378. "Provide a one-off default now (will be set on all existing rows)",
  379. "Quit, and let me add a default in models.py",
  380. ]
  381. )
  382. if choice == 2:
  383. sys.exit(3)
  384. else:
  385. print("Please enter the default value now, as valid Python")
  386. print("The datetime module is available, so you can do e.g. datetime.date.today()")
  387. while True:
  388. code = input(">>> ")
  389. if not code:
  390. print("Please enter some code, or 'exit' (with no quotes) to exit.")
  391. elif code == "exit":
  392. sys.exit(1)
  393. else:
  394. try:
  395. return eval(code, {}, {"datetime": datetime_safe})
  396. except (SyntaxError, NameError) as e:
  397. print("Invalid input: %s" % e)
  398. else:
  399. break
  400. def ask_rename(self, model_name, old_name, new_name, field_instance):
  401. "Was this field really renamed?"
  402. return self._boolean_input("Did you rename %s.%s to %s.%s (a %s)? [y/N]" % (model_name, old_name, model_name, new_name, field_instance.__class__.__name__), False)