autodetector.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. from __future__ import unicode_literals
  2. import re
  3. import datetime
  4. from django.utils import six
  5. from django.db import models
  6. from django.conf import settings
  7. from django.db.migrations import operations
  8. from django.db.migrations.migration import Migration
  9. from django.db.migrations.questioner import MigrationQuestioner
  10. from django.db.migrations.optimizer import MigrationOptimizer
  11. from django.db.migrations.operations.models import AlterModelOptions
  12. class MigrationAutodetector(object):
  13. """
  14. Takes a pair of ProjectStates, and compares them to see what the
  15. first would need doing to make it match the second (the second
  16. usually being the project's current state).
  17. Note that this naturally operates on entire projects at a time,
  18. as it's likely that changes interact (for example, you can't
  19. add a ForeignKey without having a migration to add the table it
  20. depends on first). A user interface may offer single-app usage
  21. if it wishes, with the caveat that it may not always be possible.
  22. """
  23. def __init__(self, from_state, to_state, questioner=None):
  24. self.from_state = from_state
  25. self.to_state = to_state
  26. self.questioner = questioner or MigrationQuestioner()
  27. def changes(self, graph, trim_to_apps=None, convert_apps=None):
  28. """
  29. Main entry point to produce a list of appliable changes.
  30. Takes a graph to base names on and an optional set of apps
  31. to try and restrict to (restriction is not guaranteed)
  32. """
  33. changes = self._detect_changes(convert_apps, graph)
  34. changes = self.arrange_for_graph(changes, graph)
  35. if trim_to_apps:
  36. changes = self._trim_to_apps(changes, trim_to_apps)
  37. return changes
  38. def deep_deconstruct(self, obj):
  39. """
  40. Recursive deconstruction for a field and its arguments.
  41. Used for full comparison for rename/alter; sometimes a single-level
  42. deconstruction will not compare correctly.
  43. """
  44. if not hasattr(obj, 'deconstruct'):
  45. return obj
  46. deconstructed = obj.deconstruct()
  47. if isinstance(obj, models.Field):
  48. # we have a field which also returns a name
  49. deconstructed = deconstructed[1:]
  50. path, args, kwargs = deconstructed
  51. return (
  52. path,
  53. [self.deep_deconstruct(value) for value in args],
  54. dict(
  55. (key, self.deep_deconstruct(value))
  56. for key, value in kwargs.items()
  57. ),
  58. )
  59. def only_relation_agnostic_fields(self, fields):
  60. """
  61. Return a definition of the fields that ignores field names and
  62. what related fields actually relate to.
  63. Used for detecting renames (as, of course, the related fields
  64. change during renames)
  65. """
  66. fields_def = []
  67. for name, field in fields:
  68. deconstruction = self.deep_deconstruct(field)
  69. if field.rel and field.rel.to:
  70. del deconstruction[2]['to']
  71. fields_def.append(deconstruction)
  72. return fields_def
  73. def _detect_changes(self, convert_apps=None, graph=None):
  74. """
  75. Returns a dict of migration plans which will achieve the
  76. change from from_state to to_state. The dict has app labels
  77. as keys and a list of migrations as values.
  78. The resulting migrations aren't specially named, but the names
  79. do matter for dependencies inside the set.
  80. convert_apps is the list of apps to convert to use migrations
  81. (i.e. to make initial migrations for, in the usual case)
  82. graph is an optional argument that, if provided, can help improve
  83. dependency generation and avoid potential circular dependencies.
  84. """
  85. # The first phase is generating all the operations for each app
  86. # and gathering them into a big per-app list.
  87. # We'll then go through that list later and order it and split
  88. # into migrations to resolve dependencies caused by M2Ms and FKs.
  89. self.generated_operations = {}
  90. # Prepare some old/new state and model lists, separating
  91. # proxy models and ignoring unmigrated apps.
  92. self.old_apps = self.from_state.render(ignore_swappable=True)
  93. self.new_apps = self.to_state.render()
  94. self.old_model_keys = []
  95. self.old_proxy_keys = []
  96. self.old_unmanaged_keys = []
  97. self.new_model_keys = []
  98. self.new_proxy_keys = []
  99. self.new_unmanaged_keys = []
  100. for al, mn in sorted(self.from_state.models.keys()):
  101. model = self.old_apps.get_model(al, mn)
  102. if not model._meta.managed:
  103. self.old_unmanaged_keys.append((al, mn))
  104. elif al not in self.from_state.real_apps:
  105. if model._meta.proxy:
  106. self.old_proxy_keys.append((al, mn))
  107. else:
  108. self.old_model_keys.append((al, mn))
  109. for al, mn in sorted(self.to_state.models.keys()):
  110. model = self.new_apps.get_model(al, mn)
  111. if not model._meta.managed:
  112. self.new_unmanaged_keys.append((al, mn))
  113. elif (
  114. al not in self.from_state.real_apps or
  115. (convert_apps and al in convert_apps)
  116. ):
  117. if model._meta.proxy:
  118. self.new_proxy_keys.append((al, mn))
  119. else:
  120. self.new_model_keys.append((al, mn))
  121. # Renames have to come first
  122. self.generate_renamed_models()
  123. # Prepare field lists, and prepare a list of the fields that used
  124. # through models in the old state so we can make dependencies
  125. # from the through model deletion to the field that uses it.
  126. self.kept_model_keys = set(self.old_model_keys).intersection(self.new_model_keys)
  127. self.kept_proxy_keys = set(self.old_proxy_keys).intersection(self.new_proxy_keys)
  128. self.kept_unmanaged_keys = set(self.old_unmanaged_keys).intersection(self.new_unmanaged_keys)
  129. self.through_users = {}
  130. self.old_field_keys = set()
  131. self.new_field_keys = set()
  132. for app_label, model_name in sorted(self.kept_model_keys):
  133. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  134. old_model_state = self.from_state.models[app_label, old_model_name]
  135. new_model_state = self.to_state.models[app_label, model_name]
  136. self.old_field_keys.update((app_label, model_name, x) for x, y in old_model_state.fields)
  137. self.new_field_keys.update((app_label, model_name, x) for x, y in new_model_state.fields)
  138. # Through model map generation
  139. for app_label, model_name in sorted(self.old_model_keys):
  140. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  141. old_model_state = self.from_state.models[app_label, old_model_name]
  142. for field_name, field in old_model_state.fields:
  143. old_field = self.old_apps.get_model(app_label, old_model_name)._meta.get_field_by_name(field_name)[0]
  144. if hasattr(old_field, "rel") and getattr(old_field.rel, "through", None) and not old_field.rel.through._meta.auto_created:
  145. through_key = (
  146. old_field.rel.through._meta.app_label,
  147. old_field.rel.through._meta.object_name.lower(),
  148. )
  149. self.through_users[through_key] = (app_label, old_model_name, field_name)
  150. # Generate non-rename model operations
  151. self.generate_deleted_models()
  152. self.generate_created_models()
  153. self.generate_deleted_proxies()
  154. self.generate_created_proxies()
  155. self.generate_deleted_unmanaged()
  156. self.generate_created_unmanaged()
  157. self.generate_altered_options()
  158. # Generate field operations
  159. self.generate_renamed_fields()
  160. self.generate_removed_fields()
  161. self.generate_added_fields()
  162. self.generate_altered_fields()
  163. self.generate_altered_unique_together()
  164. self.generate_altered_index_together()
  165. self.generate_altered_order_with_respect_to()
  166. # Now, reordering to make things possible. The order we have already
  167. # isn't bad, but we need to pull a few things around so FKs work nicely
  168. # inside the same app
  169. for app_label, ops in sorted(self.generated_operations.items()):
  170. for i in range(10000):
  171. found = False
  172. for i, op in enumerate(ops):
  173. for dep in op._auto_deps:
  174. if dep[0] == app_label:
  175. # Alright, there's a dependency on the same app.
  176. for j, op2 in enumerate(ops):
  177. if self.check_dependency(op2, dep) and j > i:
  178. ops = ops[:i] + ops[i + 1:j + 1] + [op] + ops[j + 1:]
  179. found = True
  180. break
  181. if found:
  182. break
  183. if found:
  184. break
  185. if not found:
  186. break
  187. else:
  188. raise ValueError("Infinite loop caught in operation dependency resolution")
  189. self.generated_operations[app_label] = ops
  190. # Now, we need to chop the lists of operations up into migrations with
  191. # dependencies on each other.
  192. # We do this by stepping up an app's list of operations until we
  193. # find one that has an outgoing dependency that isn't in another app's
  194. # migration yet (hasn't been chopped off its list). We then chop off the
  195. # operations before it into a migration and move onto the next app.
  196. # If we loop back around without doing anything, there's a circular
  197. # dependency (which _should_ be impossible as the operations are all
  198. # split at this point so they can't depend and be depended on)
  199. self.migrations = {}
  200. num_ops = sum(len(x) for x in self.generated_operations.values())
  201. chop_mode = False
  202. while num_ops:
  203. # On every iteration, we step through all the apps and see if there
  204. # is a completed set of operations.
  205. # If we find that a subset of the operations are complete we can
  206. # try to chop it off from the rest and continue, but we only
  207. # do this if we've already been through the list once before
  208. # without any chopping and nothing has changed.
  209. for app_label in sorted(self.generated_operations.keys()):
  210. chopped = []
  211. dependencies = set()
  212. for operation in list(self.generated_operations[app_label]):
  213. deps_satisfied = True
  214. operation_dependencies = set()
  215. for dep in operation._auto_deps:
  216. is_swappable_dep = False
  217. if dep[0] == "__setting__":
  218. # We need to temporarily resolve the swappable dependency to prevent
  219. # circular references. While keeping the dependency checks on the
  220. # resolved model we still add the swappable dependencies.
  221. # See #23322
  222. resolved_app_label, resolved_object_name = getattr(settings, dep[1]).split('.')
  223. original_dep = dep
  224. dep = (resolved_app_label, resolved_object_name.lower(), dep[2], dep[3])
  225. is_swappable_dep = True
  226. if dep[0] != app_label and dep[0] != "__setting__":
  227. # External app dependency. See if it's not yet
  228. # satisfied.
  229. for other_operation in self.generated_operations.get(dep[0], []):
  230. if self.check_dependency(other_operation, dep):
  231. deps_satisfied = False
  232. break
  233. if not deps_satisfied:
  234. break
  235. else:
  236. if is_swappable_dep:
  237. operation_dependencies.add((original_dep[0], original_dep[1]))
  238. elif dep[0] in self.migrations:
  239. operation_dependencies.add((dep[0], self.migrations[dep[0]][-1].name))
  240. else:
  241. # If we can't find the other app, we add a first/last dependency,
  242. # but only if we've already been through once and checked everything
  243. if chop_mode:
  244. # If the app already exists, we add a dependency on the last migration,
  245. # as we don't know which migration contains the target field.
  246. # If it's not yet migrated or has no migrations, we use __first__
  247. if graph and graph.leaf_nodes(dep[0]):
  248. operation_dependencies.add(graph.leaf_nodes(dep[0])[0])
  249. else:
  250. operation_dependencies.add((dep[0], "__first__"))
  251. else:
  252. deps_satisfied = False
  253. if deps_satisfied:
  254. chopped.append(operation)
  255. dependencies.update(operation_dependencies)
  256. self.generated_operations[app_label] = self.generated_operations[app_label][1:]
  257. else:
  258. break
  259. # Make a migration! Well, only if there's stuff to put in it
  260. if dependencies or chopped:
  261. if not self.generated_operations[app_label] or chop_mode:
  262. subclass = type(str("Migration"), (Migration,), {"operations": [], "dependencies": []})
  263. instance = subclass("auto_%i" % (len(self.migrations.get(app_label, [])) + 1), app_label)
  264. instance.dependencies = list(dependencies)
  265. instance.operations = chopped
  266. self.migrations.setdefault(app_label, []).append(instance)
  267. chop_mode = False
  268. else:
  269. self.generated_operations[app_label] = chopped + self.generated_operations[app_label]
  270. new_num_ops = sum(len(x) for x in self.generated_operations.values())
  271. if new_num_ops == num_ops:
  272. if not chop_mode:
  273. chop_mode = True
  274. else:
  275. raise ValueError("Cannot resolve operation dependencies: %r" % self.generated_operations)
  276. num_ops = new_num_ops
  277. # OK, add in internal dependencies among the migrations
  278. for app_label, migrations in self.migrations.items():
  279. for m1, m2 in zip(migrations, migrations[1:]):
  280. m2.dependencies.append((app_label, m1.name))
  281. # De-dupe dependencies
  282. for app_label, migrations in self.migrations.items():
  283. for migration in migrations:
  284. migration.dependencies = list(set(migration.dependencies))
  285. # Optimize migrations
  286. for app_label, migrations in self.migrations.items():
  287. for migration in migrations:
  288. migration.operations = MigrationOptimizer().optimize(migration.operations, app_label=app_label)
  289. return self.migrations
  290. def check_dependency(self, operation, dependency):
  291. """
  292. Checks if an operation dependency matches an operation.
  293. """
  294. # Created model
  295. if dependency[2] is None and dependency[3] is True:
  296. return (
  297. isinstance(operation, operations.CreateModel) and
  298. operation.name.lower() == dependency[1].lower()
  299. )
  300. # Created field
  301. elif dependency[2] is not None and dependency[3] is True:
  302. return (
  303. (
  304. isinstance(operation, operations.CreateModel) and
  305. operation.name.lower() == dependency[1].lower() and
  306. any(dependency[2] == x for x, y in operation.fields)
  307. ) or
  308. (
  309. isinstance(operation, operations.AddField) and
  310. operation.model_name.lower() == dependency[1].lower() and
  311. operation.name.lower() == dependency[2].lower()
  312. )
  313. )
  314. # Removed field
  315. elif dependency[2] is not None and dependency[3] is False:
  316. return (
  317. isinstance(operation, operations.RemoveField) and
  318. operation.model_name.lower() == dependency[1].lower() and
  319. operation.name.lower() == dependency[2].lower()
  320. )
  321. # Removed model
  322. elif dependency[2] is None and dependency[3] is False:
  323. return (
  324. isinstance(operation, operations.DeleteModel) and
  325. operation.name.lower() == dependency[1].lower()
  326. )
  327. # Field being altered
  328. elif dependency[2] is not None and dependency[3] == "alter":
  329. return (
  330. isinstance(operation, operations.AlterField) and
  331. operation.model_name.lower() == dependency[1].lower() and
  332. operation.name.lower() == dependency[2].lower()
  333. )
  334. # order_with_respect_to being unset for a field
  335. elif dependency[2] is not None and dependency[3] == "order_wrt_unset":
  336. return (
  337. isinstance(operation, operations.AlterOrderWithRespectTo) and
  338. operation.name.lower() == dependency[1].lower() and
  339. (operation.order_with_respect_to or "").lower() != dependency[2].lower()
  340. )
  341. # Unknown dependency. Raise an error.
  342. else:
  343. raise ValueError("Can't handle dependency %r" % (dependency, ))
  344. def add_operation(self, app_label, operation, dependencies=None, beginning=False):
  345. # Dependencies are (app_label, model_name, field_name, create/delete as True/False)
  346. operation._auto_deps = dependencies or []
  347. if beginning:
  348. self.generated_operations.setdefault(app_label, []).insert(0, operation)
  349. else:
  350. self.generated_operations.setdefault(app_label, []).append(operation)
  351. def swappable_first_key(self, item):
  352. """
  353. Sorting key function that places potential swappable models first in
  354. lists of created models (only real way to solve #22783)
  355. """
  356. try:
  357. model = self.new_apps.get_model(item[0], item[1])
  358. base_names = [base.__name__ for base in model.__bases__]
  359. string_version = "%s.%s" % (item[0], item[1])
  360. if (
  361. model._meta.swappable or
  362. "AbstractUser" in base_names or
  363. "AbstractBaseUser" in base_names or
  364. settings.AUTH_USER_MODEL.lower() == string_version.lower()
  365. ):
  366. return ("___" + item[0], "___" + item[1])
  367. except LookupError:
  368. pass
  369. return item
  370. def generate_renamed_models(self):
  371. """
  372. Finds any renamed models, and generates the operations for them,
  373. and removes the old entry from the model lists.
  374. Must be run before other model-level generation.
  375. """
  376. self.renamed_models = {}
  377. self.renamed_models_rel = {}
  378. added_models = set(self.new_model_keys) - set(self.old_model_keys)
  379. for app_label, model_name in sorted(added_models):
  380. model_state = self.to_state.models[app_label, model_name]
  381. model_fields_def = self.only_relation_agnostic_fields(model_state.fields)
  382. removed_models = set(self.old_model_keys) - set(self.new_model_keys)
  383. for rem_app_label, rem_model_name in removed_models:
  384. if rem_app_label == app_label:
  385. rem_model_state = self.from_state.models[rem_app_label, rem_model_name]
  386. rem_model_fields_def = self.only_relation_agnostic_fields(rem_model_state.fields)
  387. if model_fields_def == rem_model_fields_def:
  388. if self.questioner.ask_rename_model(rem_model_state, model_state):
  389. self.add_operation(
  390. app_label,
  391. operations.RenameModel(
  392. old_name=rem_model_state.name,
  393. new_name=model_state.name,
  394. )
  395. )
  396. self.renamed_models[app_label, model_name] = rem_model_name
  397. self.renamed_models_rel['%s.%s' % (rem_model_state.app_label, rem_model_state.name)] = '%s.%s' % (model_state.app_label, model_state.name)
  398. self.old_model_keys.remove((rem_app_label, rem_model_name))
  399. self.old_model_keys.append((app_label, model_name))
  400. break
  401. def generate_created_models(self):
  402. """
  403. Find all new models and make creation operations for them,
  404. and separate operations to create any foreign key or M2M relationships
  405. (we'll optimise these back in later if we can)
  406. We also defer any model options that refer to collections of fields
  407. that might be deferred (e.g. unique_together, index_together)
  408. """
  409. added_models = set(self.new_model_keys) - set(self.old_model_keys)
  410. for app_label, model_name in sorted(added_models, key=self.swappable_first_key, reverse=True):
  411. model_state = self.to_state.models[app_label, model_name]
  412. # Gather related fields
  413. related_fields = {}
  414. primary_key_rel = None
  415. for field in self.new_apps.get_model(app_label, model_name)._meta.local_fields:
  416. if field.rel:
  417. if field.rel.to:
  418. if field.primary_key:
  419. primary_key_rel = field.rel.to
  420. else:
  421. related_fields[field.name] = field
  422. # through will be none on M2Ms on swapped-out models;
  423. # we can treat lack of through as auto_created=True, though.
  424. if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
  425. related_fields[field.name] = field
  426. for field in self.new_apps.get_model(app_label, model_name)._meta.local_many_to_many:
  427. if field.rel.to:
  428. related_fields[field.name] = field
  429. if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
  430. related_fields[field.name] = field
  431. # Are there unique/index_together to defer?
  432. unique_together = model_state.options.pop('unique_together', None)
  433. index_together = model_state.options.pop('index_together', None)
  434. order_with_respect_to = model_state.options.pop('order_with_respect_to', None)
  435. # Depend on the deletion of any possible proxy version of us
  436. dependencies = [
  437. (app_label, model_name, None, False),
  438. ]
  439. # Depend on all bases
  440. for base in model_state.bases:
  441. if isinstance(base, six.string_types) and "." in base:
  442. base_app_label, base_name = base.split(".", 1)
  443. dependencies.append((base_app_label, base_name, None, True))
  444. # Depend on the other end of the primary key if it's a relation
  445. if primary_key_rel:
  446. dependencies.append((
  447. primary_key_rel._meta.app_label,
  448. primary_key_rel._meta.object_name,
  449. None,
  450. True
  451. ))
  452. # Generate creation operation
  453. self.add_operation(
  454. app_label,
  455. operations.CreateModel(
  456. name=model_state.name,
  457. fields=[d for d in model_state.fields if d[0] not in related_fields],
  458. options=model_state.options,
  459. bases=model_state.bases,
  460. ),
  461. dependencies=dependencies,
  462. beginning=True,
  463. )
  464. # Generate operations for each related field
  465. for name, field in sorted(related_fields.items()):
  466. # Account for FKs to swappable models
  467. swappable_setting = getattr(field, 'swappable_setting', None)
  468. if swappable_setting is not None:
  469. dep_app_label = "__setting__"
  470. dep_object_name = swappable_setting
  471. else:
  472. dep_app_label = field.rel.to._meta.app_label
  473. dep_object_name = field.rel.to._meta.object_name
  474. dependencies = [(dep_app_label, dep_object_name, None, True)]
  475. if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
  476. dependencies.append((
  477. field.rel.through._meta.app_label,
  478. field.rel.through._meta.object_name,
  479. None,
  480. True
  481. ))
  482. # Depend on our own model being created
  483. dependencies.append((app_label, model_name, None, True))
  484. # Make operation
  485. self.add_operation(
  486. app_label,
  487. operations.AddField(
  488. model_name=model_name,
  489. name=name,
  490. field=field,
  491. ),
  492. dependencies=list(set(dependencies)),
  493. )
  494. # Generate other opns
  495. related_dependencies = [
  496. (app_label, model_name, name, True)
  497. for name, field in sorted(related_fields.items())
  498. ]
  499. related_dependencies.append((app_label, model_name, None, True))
  500. if unique_together:
  501. self.add_operation(
  502. app_label,
  503. operations.AlterUniqueTogether(
  504. name=model_name,
  505. unique_together=unique_together,
  506. ),
  507. dependencies=related_dependencies
  508. )
  509. if index_together:
  510. self.add_operation(
  511. app_label,
  512. operations.AlterIndexTogether(
  513. name=model_name,
  514. index_together=index_together,
  515. ),
  516. dependencies=related_dependencies
  517. )
  518. if order_with_respect_to:
  519. self.add_operation(
  520. app_label,
  521. operations.AlterOrderWithRespectTo(
  522. name=model_name,
  523. order_with_respect_to=order_with_respect_to,
  524. ),
  525. dependencies=[
  526. (app_label, model_name, order_with_respect_to, True),
  527. (app_label, model_name, None, True),
  528. ]
  529. )
  530. def generate_created_proxies(self, unmanaged=False):
  531. """
  532. Makes CreateModel statements for proxy models.
  533. We use the same statements as that way there's less code duplication,
  534. but of course for proxy models we can skip all that pointless field
  535. stuff and just chuck out an operation.
  536. """
  537. if unmanaged:
  538. added = set(self.new_unmanaged_keys) - set(self.old_unmanaged_keys)
  539. else:
  540. added = set(self.new_proxy_keys) - set(self.old_proxy_keys)
  541. for app_label, model_name in sorted(added):
  542. model_state = self.to_state.models[app_label, model_name]
  543. if unmanaged:
  544. assert not model_state.options.get("managed", True)
  545. else:
  546. assert model_state.options.get("proxy", False)
  547. # Depend on the deletion of any possible non-proxy version of us
  548. dependencies = [
  549. (app_label, model_name, None, False),
  550. ]
  551. # Depend on all bases
  552. for base in model_state.bases:
  553. if isinstance(base, six.string_types) and "." in base:
  554. base_app_label, base_name = base.split(".", 1)
  555. dependencies.append((base_app_label, base_name, None, True))
  556. # Generate creation operation
  557. self.add_operation(
  558. app_label,
  559. operations.CreateModel(
  560. name=model_state.name,
  561. fields=[],
  562. options=model_state.options,
  563. bases=model_state.bases,
  564. ),
  565. # Depend on the deletion of any possible non-proxy version of us
  566. dependencies=dependencies,
  567. )
  568. def generate_created_unmanaged(self):
  569. """
  570. Similar to generate_created_proxies but for unmanaged
  571. (they are similar to us in that we need to supply them, but they don't
  572. affect the DB)
  573. """
  574. # Just re-use the same code in *_proxies
  575. self.generate_created_proxies(unmanaged=True)
  576. def generate_deleted_models(self):
  577. """
  578. Find all deleted models and make creation operations for them,
  579. and separate operations to delete any foreign key or M2M relationships
  580. (we'll optimise these back in later if we can)
  581. We also bring forward removal of any model options that refer to
  582. collections of fields - the inverse of generate_created_models.
  583. """
  584. deleted_models = set(self.old_model_keys) - set(self.new_model_keys)
  585. for app_label, model_name in sorted(deleted_models):
  586. model_state = self.from_state.models[app_label, model_name]
  587. model = self.old_apps.get_model(app_label, model_name)
  588. # Gather related fields
  589. related_fields = {}
  590. for field in model._meta.local_fields:
  591. if field.rel:
  592. if field.rel.to:
  593. related_fields[field.name] = field
  594. # through will be none on M2Ms on swapped-out models;
  595. # we can treat lack of through as auto_created=True, though.
  596. if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
  597. related_fields[field.name] = field
  598. for field in model._meta.local_many_to_many:
  599. if field.rel.to:
  600. related_fields[field.name] = field
  601. if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
  602. related_fields[field.name] = field
  603. # Generate option removal first
  604. unique_together = model_state.options.pop('unique_together', None)
  605. index_together = model_state.options.pop('index_together', None)
  606. if unique_together:
  607. self.add_operation(
  608. app_label,
  609. operations.AlterUniqueTogether(
  610. name=model_name,
  611. unique_together=None,
  612. )
  613. )
  614. if index_together:
  615. self.add_operation(
  616. app_label,
  617. operations.AlterIndexTogether(
  618. name=model_name,
  619. index_together=None,
  620. )
  621. )
  622. # Then remove each related field
  623. for name, field in sorted(related_fields.items()):
  624. self.add_operation(
  625. app_label,
  626. operations.RemoveField(
  627. model_name=model_name,
  628. name=name,
  629. )
  630. )
  631. # Finally, remove the model.
  632. # This depends on both the removal/alteration of all incoming fields
  633. # and the removal of all its own related fields, and if it's
  634. # a through model the field that references it.
  635. dependencies = []
  636. for related_object in model._meta.get_all_related_objects():
  637. dependencies.append((
  638. related_object.model._meta.app_label,
  639. related_object.model._meta.object_name,
  640. related_object.field.name,
  641. False,
  642. ))
  643. dependencies.append((
  644. related_object.model._meta.app_label,
  645. related_object.model._meta.object_name,
  646. related_object.field.name,
  647. "alter",
  648. ))
  649. for related_object in model._meta.get_all_related_many_to_many_objects():
  650. dependencies.append((
  651. related_object.model._meta.app_label,
  652. related_object.model._meta.object_name,
  653. related_object.field.name,
  654. False,
  655. ))
  656. for name, field in sorted(related_fields.items()):
  657. dependencies.append((app_label, model_name, name, False))
  658. # We're referenced in another field's through=
  659. through_user = self.through_users.get((app_label, model_state.name.lower()), None)
  660. if through_user:
  661. dependencies.append((through_user[0], through_user[1], through_user[2], False))
  662. # Finally, make the operation, deduping any dependencies
  663. self.add_operation(
  664. app_label,
  665. operations.DeleteModel(
  666. name=model_state.name,
  667. ),
  668. dependencies=list(set(dependencies)),
  669. )
  670. def generate_deleted_proxies(self, unmanaged=False):
  671. """
  672. Makes DeleteModel statements for proxy models.
  673. """
  674. if unmanaged:
  675. deleted = set(self.old_unmanaged_keys) - set(self.new_unmanaged_keys)
  676. else:
  677. deleted = set(self.old_proxy_keys) - set(self.new_proxy_keys)
  678. for app_label, model_name in sorted(deleted):
  679. model_state = self.from_state.models[app_label, model_name]
  680. if unmanaged:
  681. assert not model_state.options.get("managed", True)
  682. else:
  683. assert model_state.options.get("proxy", False)
  684. self.add_operation(
  685. app_label,
  686. operations.DeleteModel(
  687. name=model_state.name,
  688. ),
  689. )
  690. def generate_deleted_unmanaged(self):
  691. """
  692. Makes DeleteModel statements for unmanaged models
  693. """
  694. self.generate_deleted_proxies(unmanaged=True)
  695. def generate_renamed_fields(self):
  696. """
  697. Works out renamed fields
  698. """
  699. self.renamed_fields = {}
  700. for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys):
  701. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  702. old_model_state = self.from_state.models[app_label, old_model_name]
  703. field = self.new_apps.get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0]
  704. # Scan to see if this is actually a rename!
  705. field_dec = self.deep_deconstruct(field)
  706. for rem_app_label, rem_model_name, rem_field_name in sorted(self.old_field_keys - self.new_field_keys):
  707. if rem_app_label == app_label and rem_model_name == model_name:
  708. old_field_dec = self.deep_deconstruct(old_model_state.get_field_by_name(rem_field_name))
  709. if field.rel and field.rel.to and 'to' in old_field_dec[2]:
  710. old_rel_to = old_field_dec[2]['to']
  711. if old_rel_to in self.renamed_models_rel:
  712. old_field_dec[2]['to'] = self.renamed_models_rel[old_rel_to]
  713. if old_field_dec == field_dec:
  714. if self.questioner.ask_rename(model_name, rem_field_name, field_name, field):
  715. self.add_operation(
  716. app_label,
  717. operations.RenameField(
  718. model_name=model_name,
  719. old_name=rem_field_name,
  720. new_name=field_name,
  721. )
  722. )
  723. self.old_field_keys.remove((rem_app_label, rem_model_name, rem_field_name))
  724. self.old_field_keys.add((app_label, model_name, field_name))
  725. self.renamed_fields[app_label, model_name, field_name] = rem_field_name
  726. break
  727. def generate_added_fields(self):
  728. """
  729. Fields that have been added
  730. """
  731. for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys):
  732. field = self.new_apps.get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0]
  733. # Fields that are foreignkeys/m2ms depend on stuff
  734. dependencies = []
  735. if field.rel and field.rel.to:
  736. # Account for FKs to swappable models
  737. swappable_setting = getattr(field, 'swappable_setting', None)
  738. if swappable_setting is not None:
  739. dep_app_label = "__setting__"
  740. dep_object_name = swappable_setting
  741. else:
  742. dep_app_label = field.rel.to._meta.app_label
  743. dep_object_name = field.rel.to._meta.object_name
  744. dependencies = [(dep_app_label, dep_object_name, None, True)]
  745. if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
  746. dependencies.append((
  747. field.rel.through._meta.app_label,
  748. field.rel.through._meta.object_name,
  749. None,
  750. True
  751. ))
  752. # You can't just add NOT NULL fields with no default
  753. if not field.null and not field.has_default() and not isinstance(field, models.ManyToManyField):
  754. field = field.clone()
  755. field.default = self.questioner.ask_not_null_addition(field_name, model_name)
  756. self.add_operation(
  757. app_label,
  758. operations.AddField(
  759. model_name=model_name,
  760. name=field_name,
  761. field=field,
  762. preserve_default=False,
  763. ),
  764. dependencies=dependencies,
  765. )
  766. else:
  767. self.add_operation(
  768. app_label,
  769. operations.AddField(
  770. model_name=model_name,
  771. name=field_name,
  772. field=field,
  773. ),
  774. dependencies=dependencies,
  775. )
  776. def generate_removed_fields(self):
  777. """
  778. Fields that have been removed.
  779. """
  780. for app_label, model_name, field_name in sorted(self.old_field_keys - self.new_field_keys):
  781. self.add_operation(
  782. app_label,
  783. operations.RemoveField(
  784. model_name=model_name,
  785. name=field_name,
  786. ),
  787. # We might need to depend on the removal of an order_with_respect_to;
  788. # this is safely ignored if there isn't one
  789. dependencies=[(app_label, model_name, field_name, "order_wrt_unset")],
  790. )
  791. def generate_altered_fields(self):
  792. """
  793. Fields that have been altered.
  794. """
  795. for app_label, model_name, field_name in sorted(self.old_field_keys.intersection(self.new_field_keys)):
  796. # Did the field change?
  797. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  798. new_model_state = self.to_state.models[app_label, model_name]
  799. old_field_name = self.renamed_fields.get((app_label, model_name, field_name), field_name)
  800. old_field = self.old_apps.get_model(app_label, old_model_name)._meta.get_field_by_name(old_field_name)[0]
  801. new_field = self.new_apps.get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0]
  802. # Implement any model renames on relations; these are handled by RenameModel
  803. # so we need to exclude them from the comparison
  804. if hasattr(new_field, "rel") and getattr(new_field.rel, "to", None):
  805. rename_key = (
  806. new_field.rel.to._meta.app_label,
  807. new_field.rel.to._meta.object_name.lower(),
  808. )
  809. if rename_key in self.renamed_models:
  810. new_field.rel.to = old_field.rel.to
  811. old_field_dec = self.deep_deconstruct(old_field)
  812. new_field_dec = self.deep_deconstruct(new_field)
  813. if old_field_dec != new_field_dec:
  814. self.add_operation(
  815. app_label,
  816. operations.AlterField(
  817. model_name=model_name,
  818. name=field_name,
  819. field=new_model_state.get_field_by_name(field_name),
  820. )
  821. )
  822. def _generate_altered_foo_together(self, operation):
  823. option_name = operation.option_name
  824. for app_label, model_name in sorted(self.kept_model_keys):
  825. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  826. old_model_state = self.from_state.models[app_label, old_model_name]
  827. new_model_state = self.to_state.models[app_label, model_name]
  828. # We run the old version through the field renames to account for those
  829. if old_model_state.options.get(option_name) is None:
  830. old_value = None
  831. else:
  832. old_value = set([
  833. tuple(
  834. self.renamed_fields.get((app_label, model_name, n), n)
  835. for n in unique
  836. )
  837. for unique in old_model_state.options[option_name]
  838. ])
  839. if old_value != new_model_state.options.get(option_name):
  840. self.add_operation(
  841. app_label,
  842. operation(
  843. name=model_name,
  844. **{option_name: new_model_state.options.get(option_name)}
  845. )
  846. )
  847. def generate_altered_unique_together(self):
  848. self._generate_altered_foo_together(operations.AlterUniqueTogether)
  849. def generate_altered_index_together(self):
  850. self._generate_altered_foo_together(operations.AlterIndexTogether)
  851. def generate_altered_options(self):
  852. """
  853. Works out if any non-schema-affecting options have changed and
  854. makes an operation to represent them in state changes (in case Python
  855. code in migrations needs them)
  856. """
  857. models_to_check = self.kept_model_keys.union(self.kept_proxy_keys).union(self.kept_unmanaged_keys)
  858. for app_label, model_name in sorted(models_to_check):
  859. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  860. old_model_state = self.from_state.models[app_label, old_model_name]
  861. new_model_state = self.to_state.models[app_label, model_name]
  862. old_options = dict(
  863. option for option in old_model_state.options.items()
  864. if option[0] in AlterModelOptions.ALTER_OPTION_KEYS
  865. )
  866. new_options = dict(
  867. option for option in new_model_state.options.items()
  868. if option[0] in AlterModelOptions.ALTER_OPTION_KEYS
  869. )
  870. if old_options != new_options:
  871. self.add_operation(
  872. app_label,
  873. operations.AlterModelOptions(
  874. name=model_name,
  875. options=new_options,
  876. )
  877. )
  878. def generate_altered_order_with_respect_to(self):
  879. for app_label, model_name in sorted(self.kept_model_keys):
  880. old_model_name = self.renamed_models.get((app_label, model_name), model_name)
  881. old_model_state = self.from_state.models[app_label, old_model_name]
  882. new_model_state = self.to_state.models[app_label, model_name]
  883. if old_model_state.options.get("order_with_respect_to", None) != new_model_state.options.get("order_with_respect_to", None):
  884. # Make sure it comes second if we're adding
  885. # (removal dependency is part of RemoveField)
  886. dependencies = []
  887. if new_model_state.options.get("order_with_respect_to", None):
  888. dependencies.append((
  889. app_label,
  890. model_name,
  891. new_model_state.options["order_with_respect_to"],
  892. True,
  893. ))
  894. # Actually generate the operation
  895. self.add_operation(
  896. app_label,
  897. operations.AlterOrderWithRespectTo(
  898. name=model_name,
  899. order_with_respect_to=new_model_state.options.get('order_with_respect_to', None),
  900. ),
  901. dependencies=dependencies,
  902. )
  903. def arrange_for_graph(self, changes, graph):
  904. """
  905. Takes in a result from changes() and a MigrationGraph,
  906. and fixes the names and dependencies of the changes so they
  907. extend the graph from the leaf nodes for each app.
  908. """
  909. leaves = graph.leaf_nodes()
  910. name_map = {}
  911. for app_label, migrations in list(changes.items()):
  912. if not migrations:
  913. continue
  914. # Find the app label's current leaf node
  915. app_leaf = None
  916. for leaf in leaves:
  917. if leaf[0] == app_label:
  918. app_leaf = leaf
  919. break
  920. # Do they want an initial migration for this app?
  921. if app_leaf is None and not self.questioner.ask_initial(app_label):
  922. # They don't.
  923. for migration in migrations:
  924. name_map[(app_label, migration.name)] = (app_label, "__first__")
  925. del changes[app_label]
  926. continue
  927. # Work out the next number in the sequence
  928. if app_leaf is None:
  929. next_number = 1
  930. else:
  931. next_number = (self.parse_number(app_leaf[1]) or 0) + 1
  932. # Name each migration
  933. for i, migration in enumerate(migrations):
  934. if i == 0 and app_leaf:
  935. migration.dependencies.append(app_leaf)
  936. if i == 0 and not app_leaf:
  937. new_name = "0001_initial"
  938. else:
  939. new_name = "%04i_%s" % (
  940. next_number,
  941. self.suggest_name(migration.operations)[:100],
  942. )
  943. name_map[(app_label, migration.name)] = (app_label, new_name)
  944. next_number += 1
  945. migration.name = new_name
  946. # Now fix dependencies
  947. for app_label, migrations in changes.items():
  948. for migration in migrations:
  949. migration.dependencies = [name_map.get(d, d) for d in migration.dependencies]
  950. return changes
  951. def _trim_to_apps(self, changes, app_labels):
  952. """
  953. Takes changes from arrange_for_graph and set of app labels and
  954. returns a modified set of changes which trims out as many migrations
  955. that are not in app_labels as possible.
  956. Note that some other migrations may still be present, as they may be
  957. required dependencies.
  958. """
  959. # Gather other app dependencies in a first pass
  960. app_dependencies = {}
  961. for app_label, migrations in changes.items():
  962. for migration in migrations:
  963. for dep_app_label, name in migration.dependencies:
  964. app_dependencies.setdefault(app_label, set()).add(dep_app_label)
  965. required_apps = set(app_labels)
  966. # Keep resolving till there's no change
  967. old_required_apps = None
  968. while old_required_apps != required_apps:
  969. old_required_apps = set(required_apps)
  970. for app_label in list(required_apps):
  971. required_apps.update(app_dependencies.get(app_label, set()))
  972. # Remove all migrations that aren't needed
  973. for app_label in list(changes.keys()):
  974. if app_label not in required_apps:
  975. del changes[app_label]
  976. return changes
  977. @classmethod
  978. def suggest_name(cls, ops):
  979. """
  980. Given a set of operations, suggests a name for the migration
  981. they might represent. Names are not guaranteed to be unique,
  982. but we put some effort in to the fallback name to avoid VCS conflicts
  983. if we can.
  984. """
  985. if len(ops) == 1:
  986. if isinstance(ops[0], operations.CreateModel):
  987. return ops[0].name.lower()
  988. elif isinstance(ops[0], operations.DeleteModel):
  989. return "delete_%s" % ops[0].name.lower()
  990. elif isinstance(ops[0], operations.AddField):
  991. return "%s_%s" % (ops[0].model_name.lower(), ops[0].name.lower())
  992. elif isinstance(ops[0], operations.RemoveField):
  993. return "remove_%s_%s" % (ops[0].model_name.lower(), ops[0].name.lower())
  994. elif len(ops) > 1:
  995. if all(isinstance(o, operations.CreateModel) for o in ops):
  996. return "_".join(sorted(o.name.lower() for o in ops))
  997. return "auto_%s" % datetime.datetime.now().strftime("%Y%m%d_%H%M")
  998. @classmethod
  999. def parse_number(cls, name):
  1000. """
  1001. Given a migration name, tries to extract a number from the
  1002. beginning of it. If no number found, returns None.
  1003. """
  1004. if re.match(r"^\d+_", name):
  1005. return int(name.split("_")[0])
  1006. return None