Development of an internal social media platform with personalised dashboards for students
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.

autodetector.py 60KB

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