autodetector.py 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884
  1. import functools
  2. import re
  3. from collections import defaultdict, namedtuple
  4. from enum import Enum
  5. from graphlib import TopologicalSorter
  6. from itertools import chain
  7. from django.conf import settings
  8. from django.db import models
  9. from django.db.migrations import operations
  10. from django.db.migrations.migration import Migration
  11. from django.db.migrations.operations.models import AlterModelOptions
  12. from django.db.migrations.optimizer import MigrationOptimizer
  13. from django.db.migrations.questioner import MigrationQuestioner
  14. from django.db.migrations.utils import (
  15. COMPILED_REGEX_TYPE,
  16. RegexObject,
  17. resolve_relation,
  18. )
  19. from django.utils.functional import cached_property
  20. class OperationDependency(
  21. namedtuple("OperationDependency", "app_label model_name field_name type")
  22. ):
  23. class Type(Enum):
  24. CREATE = 0
  25. REMOVE = 1
  26. ALTER = 2
  27. REMOVE_ORDER_WRT = 3
  28. ALTER_FOO_TOGETHER = 4
  29. @cached_property
  30. def model_name_lower(self):
  31. return self.model_name.lower()
  32. @cached_property
  33. def field_name_lower(self):
  34. return self.field_name.lower()
  35. class MigrationAutodetector:
  36. """
  37. Take a pair of ProjectStates and compare them to see what the first would
  38. need doing to make it match the second (the second usually being the
  39. project's current state).
  40. Note that this naturally operates on entire projects at a time,
  41. as it's likely that changes interact (for example, you can't
  42. add a ForeignKey without having a migration to add the table it
  43. depends on first). A user interface may offer single-app usage
  44. if it wishes, with the caveat that it may not always be possible.
  45. """
  46. def __init__(self, from_state, to_state, questioner=None):
  47. self.from_state = from_state
  48. self.to_state = to_state
  49. self.questioner = questioner or MigrationQuestioner()
  50. self.existing_apps = {app for app, model in from_state.models}
  51. def changes(self, graph, trim_to_apps=None, convert_apps=None, migration_name=None):
  52. """
  53. Main entry point to produce a list of applicable changes.
  54. Take a graph to base names on and an optional set of apps
  55. to try and restrict to (restriction is not guaranteed)
  56. """
  57. changes = self._detect_changes(convert_apps, graph)
  58. changes = self.arrange_for_graph(changes, graph, migration_name)
  59. if trim_to_apps:
  60. changes = self._trim_to_apps(changes, trim_to_apps)
  61. return changes
  62. def deep_deconstruct(self, obj):
  63. """
  64. Recursive deconstruction for a field and its arguments.
  65. Used for full comparison for rename/alter; sometimes a single-level
  66. deconstruction will not compare correctly.
  67. """
  68. if isinstance(obj, list):
  69. return [self.deep_deconstruct(value) for value in obj]
  70. elif isinstance(obj, tuple):
  71. return tuple(self.deep_deconstruct(value) for value in obj)
  72. elif isinstance(obj, dict):
  73. return {key: self.deep_deconstruct(value) for key, value in obj.items()}
  74. elif isinstance(obj, functools.partial):
  75. return (
  76. obj.func,
  77. self.deep_deconstruct(obj.args),
  78. self.deep_deconstruct(obj.keywords),
  79. )
  80. elif isinstance(obj, COMPILED_REGEX_TYPE):
  81. return RegexObject(obj)
  82. elif isinstance(obj, type):
  83. # If this is a type that implements 'deconstruct' as an instance method,
  84. # avoid treating this as being deconstructible itself - see #22951
  85. return obj
  86. elif hasattr(obj, "deconstruct"):
  87. deconstructed = obj.deconstruct()
  88. if isinstance(obj, models.Field):
  89. # we have a field which also returns a name
  90. deconstructed = deconstructed[1:]
  91. path, args, kwargs = deconstructed
  92. return (
  93. path,
  94. [self.deep_deconstruct(value) for value in args],
  95. {key: self.deep_deconstruct(value) for key, value in kwargs.items()},
  96. )
  97. else:
  98. return obj
  99. def only_relation_agnostic_fields(self, fields):
  100. """
  101. Return a definition of the fields that ignores field names and
  102. what related fields actually relate to. Used for detecting renames (as
  103. the related fields change during renames).
  104. """
  105. fields_def = []
  106. for name, field in sorted(fields.items()):
  107. deconstruction = self.deep_deconstruct(field)
  108. if field.remote_field and field.remote_field.model:
  109. deconstruction[2].pop("to", None)
  110. fields_def.append(deconstruction)
  111. return fields_def
  112. def _detect_changes(self, convert_apps=None, graph=None):
  113. """
  114. Return a dict of migration plans which will achieve the
  115. change from from_state to to_state. The dict has app labels
  116. as keys and a list of migrations as values.
  117. The resulting migrations aren't specially named, but the names
  118. do matter for dependencies inside the set.
  119. convert_apps is the list of apps to convert to use migrations
  120. (i.e. to make initial migrations for, in the usual case)
  121. graph is an optional argument that, if provided, can help improve
  122. dependency generation and avoid potential circular dependencies.
  123. """
  124. # The first phase is generating all the operations for each app
  125. # and gathering them into a big per-app list.
  126. # Then go through that list, order it, and split into migrations to
  127. # resolve dependencies caused by M2Ms and FKs.
  128. self.generated_operations = {}
  129. self.altered_indexes = {}
  130. self.altered_constraints = {}
  131. self.renamed_fields = {}
  132. # Prepare some old/new state and model lists, separating
  133. # proxy models and ignoring unmigrated apps.
  134. self.old_model_keys = set()
  135. self.old_proxy_keys = set()
  136. self.old_unmanaged_keys = set()
  137. self.new_model_keys = set()
  138. self.new_proxy_keys = set()
  139. self.new_unmanaged_keys = set()
  140. for (app_label, model_name), model_state in self.from_state.models.items():
  141. if not model_state.options.get("managed", True):
  142. self.old_unmanaged_keys.add((app_label, model_name))
  143. elif app_label not in self.from_state.real_apps:
  144. if model_state.options.get("proxy"):
  145. self.old_proxy_keys.add((app_label, model_name))
  146. else:
  147. self.old_model_keys.add((app_label, model_name))
  148. for (app_label, model_name), model_state in self.to_state.models.items():
  149. if not model_state.options.get("managed", True):
  150. self.new_unmanaged_keys.add((app_label, model_name))
  151. elif app_label not in self.from_state.real_apps or (
  152. convert_apps and app_label in convert_apps
  153. ):
  154. if model_state.options.get("proxy"):
  155. self.new_proxy_keys.add((app_label, model_name))
  156. else:
  157. self.new_model_keys.add((app_label, model_name))
  158. self.from_state.resolve_fields_and_relations()
  159. self.to_state.resolve_fields_and_relations()
  160. # Renames have to come first
  161. self.generate_renamed_models()
  162. # Prepare lists of fields and generate through model map
  163. self._prepare_field_lists()
  164. self._generate_through_model_map()
  165. # Generate non-rename model operations
  166. self.generate_deleted_models()
  167. self.generate_created_models()
  168. self.generate_deleted_proxies()
  169. self.generate_created_proxies()
  170. self.generate_altered_options()
  171. self.generate_altered_managers()
  172. self.generate_altered_db_table_comment()
  173. # Create the renamed fields and store them in self.renamed_fields.
  174. # They are used by create_altered_indexes(), generate_altered_fields(),
  175. # generate_removed_altered_index/unique_together(), and
  176. # generate_altered_index/unique_together().
  177. self.create_renamed_fields()
  178. # Create the altered indexes and store them in self.altered_indexes.
  179. # This avoids the same computation in generate_removed_indexes()
  180. # and generate_added_indexes().
  181. self.create_altered_indexes()
  182. self.create_altered_constraints()
  183. # Generate index removal operations before field is removed
  184. self.generate_removed_constraints()
  185. self.generate_removed_indexes()
  186. # Generate field renaming operations.
  187. self.generate_renamed_fields()
  188. self.generate_renamed_indexes()
  189. # Generate removal of foo together.
  190. self.generate_removed_altered_unique_together()
  191. # Generate field operations.
  192. self.generate_removed_fields()
  193. self.generate_added_fields()
  194. self.generate_altered_fields()
  195. self.generate_altered_order_with_respect_to()
  196. self.generate_altered_unique_together()
  197. self.generate_added_indexes()
  198. self.generate_added_constraints()
  199. self.generate_altered_db_table()
  200. self._sort_migrations()
  201. self._build_migration_list(graph)
  202. self._optimize_migrations()
  203. return self.migrations
  204. def _prepare_field_lists(self):
  205. """
  206. Prepare field lists and a list of the fields that used through models
  207. in the old state so dependencies can be made from the through model
  208. deletion to the field that uses it.
  209. """
  210. self.kept_model_keys = self.old_model_keys & self.new_model_keys
  211. self.kept_proxy_keys = self.old_proxy_keys & self.new_proxy_keys
  212. self.kept_unmanaged_keys = self.old_unmanaged_keys & self.new_unmanaged_keys
  213. self.through_users = {}
  214. self.old_field_keys = {
  215. (app_label, model_name, field_name)
  216. for app_label, model_name in self.kept_model_keys
  217. for field_name in self.from_state.models[
  218. app_label, self.renamed_models.get((app_label, model_name), model_name)
  219. ].fields
  220. }
  221. self.new_field_keys = {
  222. (app_label, model_name, field_name)
  223. for app_label, model_name in self.kept_model_keys
  224. for field_name in self.to_state.models[app_label, model_name].fields
  225. }
  226. def _generate_through_model_map(self):
  227. """Through model map generation."""
  228. for app_label, model_name in sorted(self.old_model_keys):
  229. old_model_name = self.renamed_models.get(
  230. (app_label, model_name), model_name
  231. )
  232. old_model_state = self.from_state.models[app_label, old_model_name]
  233. for field_name, field in old_model_state.fields.items():
  234. if hasattr(field, "remote_field") and getattr(
  235. field.remote_field, "through", None
  236. ):
  237. through_key = resolve_relation(
  238. field.remote_field.through, app_label, model_name
  239. )
  240. self.through_users[through_key] = (
  241. app_label,
  242. old_model_name,
  243. field_name,
  244. )
  245. @staticmethod
  246. def _resolve_dependency(dependency):
  247. """
  248. Return the resolved dependency and a boolean denoting whether or not
  249. it was swappable.
  250. """
  251. if dependency.app_label != "__setting__":
  252. return dependency, False
  253. resolved_app_label, resolved_object_name = getattr(
  254. settings, dependency.model_name
  255. ).split(".")
  256. return (
  257. OperationDependency(
  258. resolved_app_label,
  259. resolved_object_name.lower(),
  260. dependency.field_name,
  261. dependency.type,
  262. ),
  263. True,
  264. )
  265. def _build_migration_list(self, graph=None):
  266. """
  267. Chop the lists of operations up into migrations with dependencies on
  268. each other. Do this by going through an app's list of operations until
  269. one is found that has an outgoing dependency that isn't in another
  270. app's migration yet (hasn't been chopped off its list). Then chop off
  271. the operations before it into a migration and move onto the next app.
  272. If the loops completes without doing anything, there's a circular
  273. dependency (which _should_ be impossible as the operations are
  274. all split at this point so they can't depend and be depended on).
  275. """
  276. self.migrations = {}
  277. num_ops = sum(len(x) for x in self.generated_operations.values())
  278. chop_mode = False
  279. while num_ops:
  280. # On every iteration, we step through all the apps and see if there
  281. # is a completed set of operations.
  282. # If we find that a subset of the operations are complete we can
  283. # try to chop it off from the rest and continue, but we only
  284. # do this if we've already been through the list once before
  285. # without any chopping and nothing has changed.
  286. for app_label in sorted(self.generated_operations):
  287. chopped = []
  288. dependencies = set()
  289. for operation in list(self.generated_operations[app_label]):
  290. deps_satisfied = True
  291. operation_dependencies = set()
  292. for dep in operation._auto_deps:
  293. # Temporarily resolve the swappable dependency to
  294. # prevent circular references. While keeping the
  295. # dependency checks on the resolved model, add the
  296. # swappable dependencies.
  297. original_dep = dep
  298. dep, is_swappable_dep = self._resolve_dependency(dep)
  299. if dep.app_label != app_label:
  300. # External app dependency. See if it's not yet
  301. # satisfied.
  302. for other_operation in self.generated_operations.get(
  303. dep.app_label, []
  304. ):
  305. if self.check_dependency(other_operation, dep):
  306. deps_satisfied = False
  307. break
  308. if not deps_satisfied:
  309. break
  310. else:
  311. if is_swappable_dep:
  312. operation_dependencies.add(
  313. (
  314. original_dep.app_label,
  315. original_dep.model_name,
  316. )
  317. )
  318. elif dep.app_label in self.migrations:
  319. operation_dependencies.add(
  320. (
  321. dep.app_label,
  322. self.migrations[dep.app_label][-1].name,
  323. )
  324. )
  325. else:
  326. # If we can't find the other app, we add a
  327. # first/last dependency, but only if we've
  328. # already been through once and checked
  329. # everything.
  330. if chop_mode:
  331. # If the app already exists, we add a
  332. # dependency on the last migration, as
  333. # we don't know which migration
  334. # contains the target field. If it's
  335. # not yet migrated or has no
  336. # migrations, we use __first__.
  337. if graph and graph.leaf_nodes(dep.app_label):
  338. operation_dependencies.add(
  339. graph.leaf_nodes(dep.app_label)[0]
  340. )
  341. else:
  342. operation_dependencies.add(
  343. (dep.app_label, "__first__")
  344. )
  345. else:
  346. deps_satisfied = False
  347. if deps_satisfied:
  348. chopped.append(operation)
  349. dependencies.update(operation_dependencies)
  350. del self.generated_operations[app_label][0]
  351. else:
  352. break
  353. # Make a migration! Well, only if there's stuff to put in it
  354. if dependencies or chopped:
  355. if not self.generated_operations[app_label] or chop_mode:
  356. subclass = type(
  357. "Migration",
  358. (Migration,),
  359. {"operations": [], "dependencies": []},
  360. )
  361. instance = subclass(
  362. "auto_%i" % (len(self.migrations.get(app_label, [])) + 1),
  363. app_label,
  364. )
  365. instance.dependencies = list(dependencies)
  366. instance.operations = chopped
  367. instance.initial = app_label not in self.existing_apps
  368. self.migrations.setdefault(app_label, []).append(instance)
  369. chop_mode = False
  370. else:
  371. self.generated_operations[app_label] = (
  372. chopped + self.generated_operations[app_label]
  373. )
  374. new_num_ops = sum(len(x) for x in self.generated_operations.values())
  375. if new_num_ops == num_ops:
  376. if not chop_mode:
  377. chop_mode = True
  378. else:
  379. raise ValueError(
  380. "Cannot resolve operation dependencies: %r"
  381. % self.generated_operations
  382. )
  383. num_ops = new_num_ops
  384. def _sort_migrations(self):
  385. """
  386. Reorder to make things possible. Reordering may be needed so FKs work
  387. nicely inside the same app.
  388. """
  389. for app_label, ops in sorted(self.generated_operations.items()):
  390. ts = TopologicalSorter()
  391. for op in ops:
  392. ts.add(op)
  393. for dep in op._auto_deps:
  394. # Resolve intra-app dependencies to handle circular
  395. # references involving a swappable model.
  396. dep = self._resolve_dependency(dep)[0]
  397. if dep.app_label != app_label:
  398. continue
  399. ts.add(op, *(x for x in ops if self.check_dependency(x, dep)))
  400. self.generated_operations[app_label] = list(ts.static_order())
  401. def _optimize_migrations(self):
  402. # Add in internal dependencies among the migrations
  403. for app_label, migrations in self.migrations.items():
  404. for m1, m2 in zip(migrations, migrations[1:]):
  405. m2.dependencies.append((app_label, m1.name))
  406. # De-dupe dependencies
  407. for migrations in self.migrations.values():
  408. for migration in migrations:
  409. migration.dependencies = list(set(migration.dependencies))
  410. # Optimize migrations
  411. for app_label, migrations in self.migrations.items():
  412. for migration in migrations:
  413. migration.operations = MigrationOptimizer().optimize(
  414. migration.operations, app_label
  415. )
  416. def check_dependency(self, operation, dependency):
  417. """
  418. Return True if the given operation depends on the given dependency,
  419. False otherwise.
  420. """
  421. # Created model
  422. if (
  423. dependency.field_name is None
  424. and dependency.type == OperationDependency.Type.CREATE
  425. ):
  426. return (
  427. isinstance(operation, operations.CreateModel)
  428. and operation.name_lower == dependency.model_name_lower
  429. )
  430. # Created field
  431. elif (
  432. dependency.field_name is not None
  433. and dependency.type == OperationDependency.Type.CREATE
  434. ):
  435. return (
  436. isinstance(operation, operations.CreateModel)
  437. and operation.name_lower == dependency.model_name_lower
  438. and any(dependency.field_name == x for x, y in operation.fields)
  439. ) or (
  440. isinstance(operation, operations.AddField)
  441. and operation.model_name_lower == dependency.model_name_lower
  442. and operation.name_lower == dependency.field_name_lower
  443. )
  444. # Removed field
  445. elif (
  446. dependency.field_name is not None
  447. and dependency.type == OperationDependency.Type.REMOVE
  448. ):
  449. return (
  450. isinstance(operation, operations.RemoveField)
  451. and operation.model_name_lower == dependency.model_name_lower
  452. and operation.name_lower == dependency.field_name_lower
  453. )
  454. # Removed model
  455. elif (
  456. dependency.field_name is None
  457. and dependency.type == OperationDependency.Type.REMOVE
  458. ):
  459. return (
  460. isinstance(operation, operations.DeleteModel)
  461. and operation.name_lower == dependency.model_name_lower
  462. )
  463. # Field being altered
  464. elif (
  465. dependency.field_name is not None
  466. and dependency.type == OperationDependency.Type.ALTER
  467. ):
  468. return (
  469. isinstance(operation, operations.AlterField)
  470. and operation.model_name_lower == dependency.model_name_lower
  471. and operation.name_lower == dependency.field_name_lower
  472. )
  473. # order_with_respect_to being unset for a field
  474. elif (
  475. dependency.field_name is not None
  476. and dependency.type == OperationDependency.Type.REMOVE_ORDER_WRT
  477. ):
  478. return (
  479. isinstance(operation, operations.AlterOrderWithRespectTo)
  480. and operation.name_lower == dependency.model_name_lower
  481. and (operation.order_with_respect_to or "").lower()
  482. != dependency.field_name_lower
  483. )
  484. # Field is removed and part of an index/unique_together
  485. elif (
  486. dependency.field_name is not None
  487. and dependency.type == OperationDependency.Type.ALTER_FOO_TOGETHER
  488. ):
  489. return (
  490. isinstance(
  491. operation,
  492. (operations.AlterUniqueTogether, operations.AlterIndexTogether),
  493. )
  494. and operation.name_lower == dependency.model_name_lower
  495. )
  496. # Unknown dependency. Raise an error.
  497. else:
  498. raise ValueError("Can't handle dependency %r" % (dependency,))
  499. def add_operation(self, app_label, operation, dependencies=None, beginning=False):
  500. # Dependencies are
  501. # (app_label, model_name, field_name, create/delete as True/False)
  502. operation._auto_deps = dependencies or []
  503. if beginning:
  504. self.generated_operations.setdefault(app_label, []).insert(0, operation)
  505. else:
  506. self.generated_operations.setdefault(app_label, []).append(operation)
  507. def swappable_first_key(self, item):
  508. """
  509. Place potential swappable models first in lists of created models (only
  510. real way to solve #22783).
  511. """
  512. try:
  513. model_state = self.to_state.models[item]
  514. base_names = {
  515. base if isinstance(base, str) else base.__name__
  516. for base in model_state.bases
  517. }
  518. string_version = "%s.%s" % (item[0], item[1])
  519. if (
  520. model_state.options.get("swappable")
  521. or "AbstractUser" in base_names
  522. or "AbstractBaseUser" in base_names
  523. or settings.AUTH_USER_MODEL.lower() == string_version.lower()
  524. ):
  525. return ("___" + item[0], "___" + item[1])
  526. except LookupError:
  527. pass
  528. return item
  529. def generate_renamed_models(self):
  530. """
  531. Find any renamed models, generate the operations for them, and remove
  532. the old entry from the model lists. Must be run before other
  533. model-level generation.
  534. """
  535. self.renamed_models = {}
  536. self.renamed_models_rel = {}
  537. added_models = self.new_model_keys - self.old_model_keys
  538. for app_label, model_name in sorted(added_models):
  539. model_state = self.to_state.models[app_label, model_name]
  540. model_fields_def = self.only_relation_agnostic_fields(model_state.fields)
  541. removed_models = self.old_model_keys - self.new_model_keys
  542. for rem_app_label, rem_model_name in removed_models:
  543. if rem_app_label == app_label:
  544. rem_model_state = self.from_state.models[
  545. rem_app_label, rem_model_name
  546. ]
  547. rem_model_fields_def = self.only_relation_agnostic_fields(
  548. rem_model_state.fields
  549. )
  550. if model_fields_def == rem_model_fields_def:
  551. if self.questioner.ask_rename_model(
  552. rem_model_state, model_state
  553. ):
  554. dependencies = []
  555. fields = list(model_state.fields.values()) + [
  556. field.remote_field
  557. for relations in self.to_state.relations[
  558. app_label, model_name
  559. ].values()
  560. for field in relations.values()
  561. ]
  562. for field in fields:
  563. if field.is_relation:
  564. dependencies.extend(
  565. self._get_dependencies_for_foreign_key(
  566. app_label,
  567. model_name,
  568. field,
  569. self.to_state,
  570. )
  571. )
  572. self.add_operation(
  573. app_label,
  574. operations.RenameModel(
  575. old_name=rem_model_state.name,
  576. new_name=model_state.name,
  577. ),
  578. dependencies=dependencies,
  579. )
  580. self.renamed_models[app_label, model_name] = rem_model_name
  581. renamed_models_rel_key = "%s.%s" % (
  582. rem_model_state.app_label,
  583. rem_model_state.name_lower,
  584. )
  585. self.renamed_models_rel[renamed_models_rel_key] = (
  586. "%s.%s"
  587. % (
  588. model_state.app_label,
  589. model_state.name_lower,
  590. )
  591. )
  592. self.old_model_keys.remove((rem_app_label, rem_model_name))
  593. self.old_model_keys.add((app_label, model_name))
  594. break
  595. def generate_created_models(self):
  596. """
  597. Find all new models (both managed and unmanaged) and make create
  598. operations for them as well as separate operations to create any
  599. foreign key or M2M relationships (these are optimized later, if
  600. possible).
  601. Defer any model options that refer to collections of fields that might
  602. be deferred (e.g. unique_together).
  603. """
  604. old_keys = self.old_model_keys | self.old_unmanaged_keys
  605. added_models = self.new_model_keys - old_keys
  606. added_unmanaged_models = self.new_unmanaged_keys - old_keys
  607. all_added_models = chain(
  608. sorted(added_models, key=self.swappable_first_key, reverse=True),
  609. sorted(added_unmanaged_models, key=self.swappable_first_key, reverse=True),
  610. )
  611. for app_label, model_name in all_added_models:
  612. model_state = self.to_state.models[app_label, model_name]
  613. # Gather related fields
  614. related_fields = {}
  615. primary_key_rel = None
  616. for field_name, field in model_state.fields.items():
  617. if field.remote_field:
  618. if field.remote_field.model:
  619. if field.primary_key:
  620. primary_key_rel = field.remote_field.model
  621. elif not field.remote_field.parent_link:
  622. related_fields[field_name] = field
  623. if getattr(field.remote_field, "through", None):
  624. related_fields[field_name] = field
  625. # Are there indexes/unique_together to defer?
  626. indexes = model_state.options.pop("indexes")
  627. constraints = model_state.options.pop("constraints")
  628. unique_together = model_state.options.pop("unique_together", None)
  629. order_with_respect_to = model_state.options.pop(
  630. "order_with_respect_to", None
  631. )
  632. # Depend on the deletion of any possible proxy version of us
  633. dependencies = [
  634. OperationDependency(
  635. app_label, model_name, None, OperationDependency.Type.REMOVE
  636. ),
  637. ]
  638. # Depend on all bases
  639. for base in model_state.bases:
  640. if isinstance(base, str) and "." in base:
  641. base_app_label, base_name = base.split(".", 1)
  642. dependencies.append(
  643. OperationDependency(
  644. base_app_label,
  645. base_name,
  646. None,
  647. OperationDependency.Type.CREATE,
  648. )
  649. )
  650. # Depend on the removal of base fields if the new model has
  651. # a field with the same name.
  652. old_base_model_state = self.from_state.models.get(
  653. (base_app_label, base_name)
  654. )
  655. new_base_model_state = self.to_state.models.get(
  656. (base_app_label, base_name)
  657. )
  658. if old_base_model_state and new_base_model_state:
  659. removed_base_fields = (
  660. set(old_base_model_state.fields)
  661. .difference(
  662. new_base_model_state.fields,
  663. )
  664. .intersection(model_state.fields)
  665. )
  666. for removed_base_field in removed_base_fields:
  667. dependencies.append(
  668. OperationDependency(
  669. base_app_label,
  670. base_name,
  671. removed_base_field,
  672. OperationDependency.Type.REMOVE,
  673. )
  674. )
  675. # Depend on the other end of the primary key if it's a relation
  676. if primary_key_rel:
  677. dependencies.append(
  678. OperationDependency(
  679. *resolve_relation(primary_key_rel, app_label, model_name),
  680. None,
  681. OperationDependency.Type.CREATE,
  682. ),
  683. )
  684. # Generate creation operation
  685. self.add_operation(
  686. app_label,
  687. operations.CreateModel(
  688. name=model_state.name,
  689. fields=[
  690. d
  691. for d in model_state.fields.items()
  692. if d[0] not in related_fields
  693. ],
  694. options=model_state.options,
  695. bases=model_state.bases,
  696. managers=model_state.managers,
  697. ),
  698. dependencies=dependencies,
  699. beginning=True,
  700. )
  701. # Don't add operations which modify the database for unmanaged models
  702. if not model_state.options.get("managed", True):
  703. continue
  704. # Generate operations for each related field
  705. for name, field in sorted(related_fields.items()):
  706. dependencies = self._get_dependencies_for_foreign_key(
  707. app_label,
  708. model_name,
  709. field,
  710. self.to_state,
  711. )
  712. # Depend on our own model being created
  713. dependencies.append(
  714. OperationDependency(
  715. app_label, model_name, None, OperationDependency.Type.CREATE
  716. )
  717. )
  718. # Make operation
  719. self.add_operation(
  720. app_label,
  721. operations.AddField(
  722. model_name=model_name,
  723. name=name,
  724. field=field,
  725. ),
  726. dependencies=list(set(dependencies)),
  727. )
  728. # Generate other opns
  729. if order_with_respect_to:
  730. self.add_operation(
  731. app_label,
  732. operations.AlterOrderWithRespectTo(
  733. name=model_name,
  734. order_with_respect_to=order_with_respect_to,
  735. ),
  736. dependencies=[
  737. OperationDependency(
  738. app_label,
  739. model_name,
  740. order_with_respect_to,
  741. OperationDependency.Type.CREATE,
  742. ),
  743. OperationDependency(
  744. app_label, model_name, None, OperationDependency.Type.CREATE
  745. ),
  746. ],
  747. )
  748. related_dependencies = [
  749. OperationDependency(
  750. app_label, model_name, name, OperationDependency.Type.CREATE
  751. )
  752. for name in sorted(related_fields)
  753. ]
  754. related_dependencies.append(
  755. OperationDependency(
  756. app_label, model_name, None, OperationDependency.Type.CREATE
  757. )
  758. )
  759. for index in indexes:
  760. self.add_operation(
  761. app_label,
  762. operations.AddIndex(
  763. model_name=model_name,
  764. index=index,
  765. ),
  766. dependencies=related_dependencies,
  767. )
  768. for constraint in constraints:
  769. self.add_operation(
  770. app_label,
  771. operations.AddConstraint(
  772. model_name=model_name,
  773. constraint=constraint,
  774. ),
  775. dependencies=related_dependencies,
  776. )
  777. if unique_together:
  778. self.add_operation(
  779. app_label,
  780. operations.AlterUniqueTogether(
  781. name=model_name,
  782. unique_together=unique_together,
  783. ),
  784. dependencies=related_dependencies,
  785. )
  786. # Fix relationships if the model changed from a proxy model to a
  787. # concrete model.
  788. relations = self.to_state.relations
  789. if (app_label, model_name) in self.old_proxy_keys:
  790. for related_model_key, related_fields in relations[
  791. app_label, model_name
  792. ].items():
  793. related_model_state = self.to_state.models[related_model_key]
  794. for related_field_name, related_field in related_fields.items():
  795. self.add_operation(
  796. related_model_state.app_label,
  797. operations.AlterField(
  798. model_name=related_model_state.name,
  799. name=related_field_name,
  800. field=related_field,
  801. ),
  802. dependencies=[
  803. OperationDependency(
  804. app_label,
  805. model_name,
  806. None,
  807. OperationDependency.Type.CREATE,
  808. )
  809. ],
  810. )
  811. def generate_created_proxies(self):
  812. """
  813. Make CreateModel statements for proxy models. Use the same statements
  814. as that way there's less code duplication, but for proxy models it's
  815. safe to skip all the pointless field stuff and chuck out an operation.
  816. """
  817. added = self.new_proxy_keys - self.old_proxy_keys
  818. for app_label, model_name in sorted(added):
  819. model_state = self.to_state.models[app_label, model_name]
  820. assert model_state.options.get("proxy")
  821. # Depend on the deletion of any possible non-proxy version of us
  822. dependencies = [
  823. OperationDependency(
  824. app_label, model_name, None, OperationDependency.Type.REMOVE
  825. ),
  826. ]
  827. # Depend on all bases
  828. for base in model_state.bases:
  829. if isinstance(base, str) and "." in base:
  830. base_app_label, base_name = base.split(".", 1)
  831. dependencies.append(
  832. OperationDependency(
  833. base_app_label,
  834. base_name,
  835. None,
  836. OperationDependency.Type.CREATE,
  837. )
  838. )
  839. # Generate creation operation
  840. self.add_operation(
  841. app_label,
  842. operations.CreateModel(
  843. name=model_state.name,
  844. fields=[],
  845. options=model_state.options,
  846. bases=model_state.bases,
  847. managers=model_state.managers,
  848. ),
  849. # Depend on the deletion of any possible non-proxy version of us
  850. dependencies=dependencies,
  851. )
  852. def generate_deleted_models(self):
  853. """
  854. Find all deleted models (managed and unmanaged) and make delete
  855. operations for them as well as separate operations to delete any
  856. foreign key or M2M relationships (these are optimized later, if
  857. possible).
  858. Also bring forward removal of any model options that refer to
  859. collections of fields - the inverse of generate_created_models().
  860. """
  861. new_keys = self.new_model_keys | self.new_unmanaged_keys
  862. deleted_models = self.old_model_keys - new_keys
  863. deleted_unmanaged_models = self.old_unmanaged_keys - new_keys
  864. all_deleted_models = chain(
  865. sorted(deleted_models), sorted(deleted_unmanaged_models)
  866. )
  867. for app_label, model_name in all_deleted_models:
  868. model_state = self.from_state.models[app_label, model_name]
  869. # Gather related fields
  870. related_fields = {}
  871. for field_name, field in model_state.fields.items():
  872. if field.remote_field:
  873. if field.remote_field.model:
  874. related_fields[field_name] = field
  875. if getattr(field.remote_field, "through", None):
  876. related_fields[field_name] = field
  877. # Generate option removal first
  878. unique_together = model_state.options.pop("unique_together", None)
  879. if unique_together:
  880. self.add_operation(
  881. app_label,
  882. operations.AlterUniqueTogether(
  883. name=model_name,
  884. unique_together=None,
  885. ),
  886. )
  887. # Then remove each related field
  888. for name in sorted(related_fields):
  889. self.add_operation(
  890. app_label,
  891. operations.RemoveField(
  892. model_name=model_name,
  893. name=name,
  894. ),
  895. )
  896. # Finally, remove the model.
  897. # This depends on both the removal/alteration of all incoming fields
  898. # and the removal of all its own related fields, and if it's
  899. # a through model the field that references it.
  900. dependencies = []
  901. relations = self.from_state.relations
  902. for (
  903. related_object_app_label,
  904. object_name,
  905. ), relation_related_fields in relations[app_label, model_name].items():
  906. for field_name, field in relation_related_fields.items():
  907. dependencies.append(
  908. OperationDependency(
  909. related_object_app_label,
  910. object_name,
  911. field_name,
  912. OperationDependency.Type.REMOVE,
  913. ),
  914. )
  915. if not field.many_to_many:
  916. dependencies.append(
  917. OperationDependency(
  918. related_object_app_label,
  919. object_name,
  920. field_name,
  921. OperationDependency.Type.ALTER,
  922. ),
  923. )
  924. for name in sorted(related_fields):
  925. dependencies.append(
  926. OperationDependency(
  927. app_label, model_name, name, OperationDependency.Type.REMOVE
  928. )
  929. )
  930. # We're referenced in another field's through=
  931. through_user = self.through_users.get((app_label, model_state.name_lower))
  932. if through_user:
  933. dependencies.append(
  934. OperationDependency(*through_user, OperationDependency.Type.REMOVE),
  935. )
  936. # Finally, make the operation, deduping any dependencies
  937. self.add_operation(
  938. app_label,
  939. operations.DeleteModel(
  940. name=model_state.name,
  941. ),
  942. dependencies=list(set(dependencies)),
  943. )
  944. def generate_deleted_proxies(self):
  945. """Make DeleteModel options for proxy models."""
  946. deleted = self.old_proxy_keys - self.new_proxy_keys
  947. for app_label, model_name in sorted(deleted):
  948. model_state = self.from_state.models[app_label, model_name]
  949. assert model_state.options.get("proxy")
  950. self.add_operation(
  951. app_label,
  952. operations.DeleteModel(
  953. name=model_state.name,
  954. ),
  955. )
  956. def create_renamed_fields(self):
  957. """Work out renamed fields."""
  958. self.renamed_operations = []
  959. old_field_keys = self.old_field_keys.copy()
  960. for app_label, model_name, field_name in sorted(
  961. self.new_field_keys - old_field_keys
  962. ):
  963. old_model_name = self.renamed_models.get(
  964. (app_label, model_name), model_name
  965. )
  966. old_model_state = self.from_state.models[app_label, old_model_name]
  967. new_model_state = self.to_state.models[app_label, model_name]
  968. field = new_model_state.get_field(field_name)
  969. # Scan to see if this is actually a rename!
  970. field_dec = self.deep_deconstruct(field)
  971. for rem_app_label, rem_model_name, rem_field_name in sorted(
  972. old_field_keys - self.new_field_keys
  973. ):
  974. if rem_app_label == app_label and rem_model_name == model_name:
  975. old_field = old_model_state.get_field(rem_field_name)
  976. old_field_dec = self.deep_deconstruct(old_field)
  977. if (
  978. field.remote_field
  979. and field.remote_field.model
  980. and "to" in old_field_dec[2]
  981. ):
  982. old_rel_to = old_field_dec[2]["to"]
  983. if old_rel_to in self.renamed_models_rel:
  984. old_field_dec[2]["to"] = self.renamed_models_rel[old_rel_to]
  985. old_field.set_attributes_from_name(rem_field_name)
  986. old_db_column = old_field.get_attname_column()[1]
  987. if old_field_dec == field_dec or (
  988. # Was the field renamed and db_column equal to the
  989. # old field's column added?
  990. old_field_dec[0:2] == field_dec[0:2]
  991. and dict(old_field_dec[2], db_column=old_db_column)
  992. == field_dec[2]
  993. ):
  994. if self.questioner.ask_rename(
  995. model_name, rem_field_name, field_name, field
  996. ):
  997. self.renamed_operations.append(
  998. (
  999. rem_app_label,
  1000. rem_model_name,
  1001. old_field.db_column,
  1002. rem_field_name,
  1003. app_label,
  1004. model_name,
  1005. field,
  1006. field_name,
  1007. )
  1008. )
  1009. old_field_keys.remove(
  1010. (rem_app_label, rem_model_name, rem_field_name)
  1011. )
  1012. old_field_keys.add((app_label, model_name, field_name))
  1013. self.renamed_fields[app_label, model_name, field_name] = (
  1014. rem_field_name
  1015. )
  1016. break
  1017. def generate_renamed_fields(self):
  1018. """Generate RenameField operations."""
  1019. for (
  1020. rem_app_label,
  1021. rem_model_name,
  1022. rem_db_column,
  1023. rem_field_name,
  1024. app_label,
  1025. model_name,
  1026. field,
  1027. field_name,
  1028. ) in self.renamed_operations:
  1029. # A db_column mismatch requires a prior noop AlterField for the
  1030. # subsequent RenameField to be a noop on attempts at preserving the
  1031. # old name.
  1032. if rem_db_column != field.db_column:
  1033. altered_field = field.clone()
  1034. altered_field.name = rem_field_name
  1035. self.add_operation(
  1036. app_label,
  1037. operations.AlterField(
  1038. model_name=model_name,
  1039. name=rem_field_name,
  1040. field=altered_field,
  1041. ),
  1042. )
  1043. self.add_operation(
  1044. app_label,
  1045. operations.RenameField(
  1046. model_name=model_name,
  1047. old_name=rem_field_name,
  1048. new_name=field_name,
  1049. ),
  1050. )
  1051. self.old_field_keys.remove((rem_app_label, rem_model_name, rem_field_name))
  1052. self.old_field_keys.add((app_label, model_name, field_name))
  1053. def generate_added_fields(self):
  1054. """Make AddField operations."""
  1055. for app_label, model_name, field_name in sorted(
  1056. self.new_field_keys - self.old_field_keys
  1057. ):
  1058. self._generate_added_field(app_label, model_name, field_name)
  1059. def _generate_added_field(self, app_label, model_name, field_name):
  1060. field = self.to_state.models[app_label, model_name].get_field(field_name)
  1061. # Adding a field always depends at least on its removal.
  1062. dependencies = [
  1063. OperationDependency(
  1064. app_label, model_name, field_name, OperationDependency.Type.REMOVE
  1065. )
  1066. ]
  1067. # Fields that are foreignkeys/m2ms depend on stuff.
  1068. if field.remote_field and field.remote_field.model:
  1069. dependencies.extend(
  1070. self._get_dependencies_for_foreign_key(
  1071. app_label,
  1072. model_name,
  1073. field,
  1074. self.to_state,
  1075. )
  1076. )
  1077. # You can't just add NOT NULL fields with no default or fields
  1078. # which don't allow empty strings as default.
  1079. time_fields = (models.DateField, models.DateTimeField, models.TimeField)
  1080. preserve_default = (
  1081. field.null
  1082. or field.has_default()
  1083. or field.db_default is not models.NOT_PROVIDED
  1084. or field.many_to_many
  1085. or (field.blank and field.empty_strings_allowed)
  1086. or (isinstance(field, time_fields) and field.auto_now)
  1087. )
  1088. if not preserve_default:
  1089. field = field.clone()
  1090. if isinstance(field, time_fields) and field.auto_now_add:
  1091. field.default = self.questioner.ask_auto_now_add_addition(
  1092. field_name, model_name
  1093. )
  1094. else:
  1095. field.default = self.questioner.ask_not_null_addition(
  1096. field_name, model_name
  1097. )
  1098. if (
  1099. field.unique
  1100. and field.default is not models.NOT_PROVIDED
  1101. and callable(field.default)
  1102. ):
  1103. self.questioner.ask_unique_callable_default_addition(field_name, model_name)
  1104. self.add_operation(
  1105. app_label,
  1106. operations.AddField(
  1107. model_name=model_name,
  1108. name=field_name,
  1109. field=field,
  1110. preserve_default=preserve_default,
  1111. ),
  1112. dependencies=dependencies,
  1113. )
  1114. def generate_removed_fields(self):
  1115. """Make RemoveField operations."""
  1116. for app_label, model_name, field_name in sorted(
  1117. self.old_field_keys - self.new_field_keys
  1118. ):
  1119. self._generate_removed_field(app_label, model_name, field_name)
  1120. def _generate_removed_field(self, app_label, model_name, field_name):
  1121. self.add_operation(
  1122. app_label,
  1123. operations.RemoveField(
  1124. model_name=model_name,
  1125. name=field_name,
  1126. ),
  1127. # We might need to depend on the removal of an
  1128. # order_with_respect_to or index/unique_together operation;
  1129. # this is safely ignored if there isn't one
  1130. dependencies=[
  1131. OperationDependency(
  1132. app_label,
  1133. model_name,
  1134. field_name,
  1135. OperationDependency.Type.REMOVE_ORDER_WRT,
  1136. ),
  1137. OperationDependency(
  1138. app_label,
  1139. model_name,
  1140. field_name,
  1141. OperationDependency.Type.ALTER_FOO_TOGETHER,
  1142. ),
  1143. ],
  1144. )
  1145. def generate_altered_fields(self):
  1146. """
  1147. Make AlterField operations, or possibly RemovedField/AddField if alter
  1148. isn't possible.
  1149. """
  1150. for app_label, model_name, field_name in sorted(
  1151. self.old_field_keys & self.new_field_keys
  1152. ):
  1153. # Did the field change?
  1154. old_model_name = self.renamed_models.get(
  1155. (app_label, model_name), model_name
  1156. )
  1157. old_field_name = self.renamed_fields.get(
  1158. (app_label, model_name, field_name), field_name
  1159. )
  1160. old_field = self.from_state.models[app_label, old_model_name].get_field(
  1161. old_field_name
  1162. )
  1163. new_field = self.to_state.models[app_label, model_name].get_field(
  1164. field_name
  1165. )
  1166. dependencies = []
  1167. # Implement any model renames on relations; these are handled by RenameModel
  1168. # so we need to exclude them from the comparison
  1169. if hasattr(new_field, "remote_field") and getattr(
  1170. new_field.remote_field, "model", None
  1171. ):
  1172. rename_key = resolve_relation(
  1173. new_field.remote_field.model, app_label, model_name
  1174. )
  1175. if rename_key in self.renamed_models:
  1176. new_field.remote_field.model = old_field.remote_field.model
  1177. # Handle ForeignKey which can only have a single to_field.
  1178. remote_field_name = getattr(new_field.remote_field, "field_name", None)
  1179. if remote_field_name:
  1180. to_field_rename_key = rename_key + (remote_field_name,)
  1181. if to_field_rename_key in self.renamed_fields:
  1182. # Repoint both model and field name because to_field
  1183. # inclusion in ForeignKey.deconstruct() is based on
  1184. # both.
  1185. new_field.remote_field.model = old_field.remote_field.model
  1186. new_field.remote_field.field_name = (
  1187. old_field.remote_field.field_name
  1188. )
  1189. # Handle ForeignObjects which can have multiple from_fields/to_fields.
  1190. from_fields = getattr(new_field, "from_fields", None)
  1191. if from_fields:
  1192. from_rename_key = (app_label, model_name)
  1193. new_field.from_fields = tuple(
  1194. [
  1195. self.renamed_fields.get(
  1196. from_rename_key + (from_field,), from_field
  1197. )
  1198. for from_field in from_fields
  1199. ]
  1200. )
  1201. new_field.to_fields = tuple(
  1202. [
  1203. self.renamed_fields.get(rename_key + (to_field,), to_field)
  1204. for to_field in new_field.to_fields
  1205. ]
  1206. )
  1207. if old_from_fields := getattr(old_field, "from_fields", None):
  1208. old_field.from_fields = tuple(old_from_fields)
  1209. old_field.to_fields = tuple(old_field.to_fields)
  1210. dependencies.extend(
  1211. self._get_dependencies_for_foreign_key(
  1212. app_label,
  1213. model_name,
  1214. new_field,
  1215. self.to_state,
  1216. )
  1217. )
  1218. if hasattr(new_field, "remote_field") and getattr(
  1219. new_field.remote_field, "through", None
  1220. ):
  1221. rename_key = resolve_relation(
  1222. new_field.remote_field.through, app_label, model_name
  1223. )
  1224. if rename_key in self.renamed_models:
  1225. new_field.remote_field.through = old_field.remote_field.through
  1226. old_field_dec = self.deep_deconstruct(old_field)
  1227. new_field_dec = self.deep_deconstruct(new_field)
  1228. # If the field was confirmed to be renamed it means that only
  1229. # db_column was allowed to change which generate_renamed_fields()
  1230. # already accounts for by adding an AlterField operation.
  1231. if old_field_dec != new_field_dec and old_field_name == field_name:
  1232. both_m2m = old_field.many_to_many and new_field.many_to_many
  1233. neither_m2m = not old_field.many_to_many and not new_field.many_to_many
  1234. if both_m2m or neither_m2m:
  1235. # Either both fields are m2m or neither is
  1236. preserve_default = True
  1237. if (
  1238. old_field.null
  1239. and not new_field.null
  1240. and not new_field.has_default()
  1241. and new_field.db_default is models.NOT_PROVIDED
  1242. and not new_field.many_to_many
  1243. ):
  1244. field = new_field.clone()
  1245. new_default = self.questioner.ask_not_null_alteration(
  1246. field_name, model_name
  1247. )
  1248. if new_default is not models.NOT_PROVIDED:
  1249. field.default = new_default
  1250. preserve_default = False
  1251. else:
  1252. field = new_field
  1253. self.add_operation(
  1254. app_label,
  1255. operations.AlterField(
  1256. model_name=model_name,
  1257. name=field_name,
  1258. field=field,
  1259. preserve_default=preserve_default,
  1260. ),
  1261. dependencies=dependencies,
  1262. )
  1263. else:
  1264. # We cannot alter between m2m and concrete fields
  1265. self._generate_removed_field(app_label, model_name, field_name)
  1266. self._generate_added_field(app_label, model_name, field_name)
  1267. def create_altered_indexes(self):
  1268. option_name = operations.AddIndex.option_name
  1269. self.renamed_index_together_values = defaultdict(list)
  1270. for app_label, model_name in sorted(self.kept_model_keys):
  1271. old_model_name = self.renamed_models.get(
  1272. (app_label, model_name), model_name
  1273. )
  1274. old_model_state = self.from_state.models[app_label, old_model_name]
  1275. new_model_state = self.to_state.models[app_label, model_name]
  1276. old_indexes = old_model_state.options[option_name]
  1277. new_indexes = new_model_state.options[option_name]
  1278. added_indexes = [idx for idx in new_indexes if idx not in old_indexes]
  1279. removed_indexes = [idx for idx in old_indexes if idx not in new_indexes]
  1280. renamed_indexes = []
  1281. # Find renamed indexes.
  1282. remove_from_added = []
  1283. remove_from_removed = []
  1284. for new_index in added_indexes:
  1285. new_index_dec = new_index.deconstruct()
  1286. new_index_name = new_index_dec[2].pop("name")
  1287. for old_index in removed_indexes:
  1288. old_index_dec = old_index.deconstruct()
  1289. old_index_name = old_index_dec[2].pop("name")
  1290. # Indexes are the same except for the names.
  1291. if (
  1292. new_index_dec == old_index_dec
  1293. and new_index_name != old_index_name
  1294. ):
  1295. renamed_indexes.append((old_index_name, new_index_name, None))
  1296. remove_from_added.append(new_index)
  1297. remove_from_removed.append(old_index)
  1298. # Find index_together changed to indexes.
  1299. for (
  1300. old_value,
  1301. new_value,
  1302. index_together_app_label,
  1303. index_together_model_name,
  1304. dependencies,
  1305. ) in self._get_altered_foo_together_operations(
  1306. operations.AlterIndexTogether.option_name
  1307. ):
  1308. if (
  1309. app_label != index_together_app_label
  1310. or model_name != index_together_model_name
  1311. ):
  1312. continue
  1313. removed_values = old_value.difference(new_value)
  1314. for removed_index_together in removed_values:
  1315. renamed_index_together_indexes = []
  1316. for new_index in added_indexes:
  1317. _, args, kwargs = new_index.deconstruct()
  1318. # Ensure only 'fields' are defined in the Index.
  1319. if (
  1320. not args
  1321. and new_index.fields == list(removed_index_together)
  1322. and set(kwargs) == {"name", "fields"}
  1323. ):
  1324. renamed_index_together_indexes.append(new_index)
  1325. if len(renamed_index_together_indexes) == 1:
  1326. renamed_index = renamed_index_together_indexes[0]
  1327. remove_from_added.append(renamed_index)
  1328. renamed_indexes.append(
  1329. (None, renamed_index.name, removed_index_together)
  1330. )
  1331. self.renamed_index_together_values[
  1332. index_together_app_label, index_together_model_name
  1333. ].append(removed_index_together)
  1334. # Remove renamed indexes from the lists of added and removed
  1335. # indexes.
  1336. added_indexes = [
  1337. idx for idx in added_indexes if idx not in remove_from_added
  1338. ]
  1339. removed_indexes = [
  1340. idx for idx in removed_indexes if idx not in remove_from_removed
  1341. ]
  1342. self.altered_indexes.update(
  1343. {
  1344. (app_label, model_name): {
  1345. "added_indexes": added_indexes,
  1346. "removed_indexes": removed_indexes,
  1347. "renamed_indexes": renamed_indexes,
  1348. }
  1349. }
  1350. )
  1351. def generate_added_indexes(self):
  1352. for (app_label, model_name), alt_indexes in self.altered_indexes.items():
  1353. dependencies = self._get_dependencies_for_model(app_label, model_name)
  1354. for index in alt_indexes["added_indexes"]:
  1355. self.add_operation(
  1356. app_label,
  1357. operations.AddIndex(
  1358. model_name=model_name,
  1359. index=index,
  1360. ),
  1361. dependencies=dependencies,
  1362. )
  1363. def generate_removed_indexes(self):
  1364. for (app_label, model_name), alt_indexes in self.altered_indexes.items():
  1365. for index in alt_indexes["removed_indexes"]:
  1366. self.add_operation(
  1367. app_label,
  1368. operations.RemoveIndex(
  1369. model_name=model_name,
  1370. name=index.name,
  1371. ),
  1372. )
  1373. def generate_renamed_indexes(self):
  1374. for (app_label, model_name), alt_indexes in self.altered_indexes.items():
  1375. for old_index_name, new_index_name, old_fields in alt_indexes[
  1376. "renamed_indexes"
  1377. ]:
  1378. self.add_operation(
  1379. app_label,
  1380. operations.RenameIndex(
  1381. model_name=model_name,
  1382. new_name=new_index_name,
  1383. old_name=old_index_name,
  1384. old_fields=old_fields,
  1385. ),
  1386. )
  1387. def create_altered_constraints(self):
  1388. option_name = operations.AddConstraint.option_name
  1389. for app_label, model_name in sorted(self.kept_model_keys):
  1390. old_model_name = self.renamed_models.get(
  1391. (app_label, model_name), model_name
  1392. )
  1393. old_model_state = self.from_state.models[app_label, old_model_name]
  1394. new_model_state = self.to_state.models[app_label, model_name]
  1395. old_constraints = old_model_state.options[option_name]
  1396. new_constraints = new_model_state.options[option_name]
  1397. add_constraints = [c for c in new_constraints if c not in old_constraints]
  1398. rem_constraints = [c for c in old_constraints if c not in new_constraints]
  1399. self.altered_constraints.update(
  1400. {
  1401. (app_label, model_name): {
  1402. "added_constraints": add_constraints,
  1403. "removed_constraints": rem_constraints,
  1404. }
  1405. }
  1406. )
  1407. def generate_added_constraints(self):
  1408. for (
  1409. app_label,
  1410. model_name,
  1411. ), alt_constraints in self.altered_constraints.items():
  1412. dependencies = self._get_dependencies_for_model(app_label, model_name)
  1413. for constraint in alt_constraints["added_constraints"]:
  1414. self.add_operation(
  1415. app_label,
  1416. operations.AddConstraint(
  1417. model_name=model_name,
  1418. constraint=constraint,
  1419. ),
  1420. dependencies=dependencies,
  1421. )
  1422. def generate_removed_constraints(self):
  1423. for (
  1424. app_label,
  1425. model_name,
  1426. ), alt_constraints in self.altered_constraints.items():
  1427. for constraint in alt_constraints["removed_constraints"]:
  1428. self.add_operation(
  1429. app_label,
  1430. operations.RemoveConstraint(
  1431. model_name=model_name,
  1432. name=constraint.name,
  1433. ),
  1434. )
  1435. @staticmethod
  1436. def _get_dependencies_for_foreign_key(app_label, model_name, field, project_state):
  1437. remote_field_model = None
  1438. if hasattr(field.remote_field, "model"):
  1439. remote_field_model = field.remote_field.model
  1440. else:
  1441. relations = project_state.relations[app_label, model_name]
  1442. for (remote_app_label, remote_model_name), fields in relations.items():
  1443. if any(
  1444. field == related_field.remote_field
  1445. for related_field in fields.values()
  1446. ):
  1447. remote_field_model = f"{remote_app_label}.{remote_model_name}"
  1448. break
  1449. # Account for FKs to swappable models
  1450. swappable_setting = getattr(field, "swappable_setting", None)
  1451. if swappable_setting is not None:
  1452. dep_app_label = "__setting__"
  1453. dep_object_name = swappable_setting
  1454. else:
  1455. dep_app_label, dep_object_name = resolve_relation(
  1456. remote_field_model,
  1457. app_label,
  1458. model_name,
  1459. )
  1460. dependencies = [
  1461. OperationDependency(
  1462. dep_app_label, dep_object_name, None, OperationDependency.Type.CREATE
  1463. )
  1464. ]
  1465. if getattr(field.remote_field, "through", None):
  1466. through_app_label, through_object_name = resolve_relation(
  1467. field.remote_field.through,
  1468. app_label,
  1469. model_name,
  1470. )
  1471. dependencies.append(
  1472. OperationDependency(
  1473. through_app_label,
  1474. through_object_name,
  1475. None,
  1476. OperationDependency.Type.CREATE,
  1477. )
  1478. )
  1479. return dependencies
  1480. def _get_dependencies_for_model(self, app_label, model_name):
  1481. """Return foreign key dependencies of the given model."""
  1482. dependencies = []
  1483. model_state = self.to_state.models[app_label, model_name]
  1484. for field in model_state.fields.values():
  1485. if field.is_relation:
  1486. dependencies.extend(
  1487. self._get_dependencies_for_foreign_key(
  1488. app_label,
  1489. model_name,
  1490. field,
  1491. self.to_state,
  1492. )
  1493. )
  1494. return dependencies
  1495. def _get_altered_foo_together_operations(self, option_name):
  1496. for app_label, model_name in sorted(self.kept_model_keys):
  1497. old_model_name = self.renamed_models.get(
  1498. (app_label, model_name), model_name
  1499. )
  1500. old_model_state = self.from_state.models[app_label, old_model_name]
  1501. new_model_state = self.to_state.models[app_label, model_name]
  1502. # We run the old version through the field renames to account for those
  1503. old_value = old_model_state.options.get(option_name)
  1504. old_value = (
  1505. {
  1506. tuple(
  1507. self.renamed_fields.get((app_label, model_name, n), n)
  1508. for n in unique
  1509. )
  1510. for unique in old_value
  1511. }
  1512. if old_value
  1513. else set()
  1514. )
  1515. new_value = new_model_state.options.get(option_name)
  1516. new_value = set(new_value) if new_value else set()
  1517. if old_value != new_value:
  1518. dependencies = []
  1519. for foo_togethers in new_value:
  1520. for field_name in foo_togethers:
  1521. field = new_model_state.get_field(field_name)
  1522. if field.remote_field and field.remote_field.model:
  1523. dependencies.extend(
  1524. self._get_dependencies_for_foreign_key(
  1525. app_label,
  1526. model_name,
  1527. field,
  1528. self.to_state,
  1529. )
  1530. )
  1531. yield (
  1532. old_value,
  1533. new_value,
  1534. app_label,
  1535. model_name,
  1536. dependencies,
  1537. )
  1538. def _generate_removed_altered_foo_together(self, operation):
  1539. for (
  1540. old_value,
  1541. new_value,
  1542. app_label,
  1543. model_name,
  1544. dependencies,
  1545. ) in self._get_altered_foo_together_operations(operation.option_name):
  1546. if operation == operations.AlterIndexTogether:
  1547. old_value = {
  1548. value
  1549. for value in old_value
  1550. if value
  1551. not in self.renamed_index_together_values[app_label, model_name]
  1552. }
  1553. removal_value = new_value.intersection(old_value)
  1554. if removal_value or old_value:
  1555. self.add_operation(
  1556. app_label,
  1557. operation(
  1558. name=model_name, **{operation.option_name: removal_value}
  1559. ),
  1560. dependencies=dependencies,
  1561. )
  1562. def generate_removed_altered_unique_together(self):
  1563. self._generate_removed_altered_foo_together(operations.AlterUniqueTogether)
  1564. def _generate_altered_foo_together(self, operation):
  1565. for (
  1566. old_value,
  1567. new_value,
  1568. app_label,
  1569. model_name,
  1570. dependencies,
  1571. ) in self._get_altered_foo_together_operations(operation.option_name):
  1572. removal_value = new_value.intersection(old_value)
  1573. if new_value != removal_value:
  1574. self.add_operation(
  1575. app_label,
  1576. operation(name=model_name, **{operation.option_name: new_value}),
  1577. dependencies=dependencies,
  1578. )
  1579. def generate_altered_unique_together(self):
  1580. self._generate_altered_foo_together(operations.AlterUniqueTogether)
  1581. def generate_altered_db_table(self):
  1582. models_to_check = self.kept_model_keys.union(
  1583. self.kept_proxy_keys, self.kept_unmanaged_keys
  1584. )
  1585. for app_label, model_name in sorted(models_to_check):
  1586. old_model_name = self.renamed_models.get(
  1587. (app_label, model_name), model_name
  1588. )
  1589. old_model_state = self.from_state.models[app_label, old_model_name]
  1590. new_model_state = self.to_state.models[app_label, model_name]
  1591. old_db_table_name = old_model_state.options.get("db_table")
  1592. new_db_table_name = new_model_state.options.get("db_table")
  1593. if old_db_table_name != new_db_table_name:
  1594. self.add_operation(
  1595. app_label,
  1596. operations.AlterModelTable(
  1597. name=model_name,
  1598. table=new_db_table_name,
  1599. ),
  1600. )
  1601. def generate_altered_db_table_comment(self):
  1602. models_to_check = self.kept_model_keys.union(
  1603. self.kept_proxy_keys, self.kept_unmanaged_keys
  1604. )
  1605. for app_label, model_name in sorted(models_to_check):
  1606. old_model_name = self.renamed_models.get(
  1607. (app_label, model_name), model_name
  1608. )
  1609. old_model_state = self.from_state.models[app_label, old_model_name]
  1610. new_model_state = self.to_state.models[app_label, model_name]
  1611. old_db_table_comment = old_model_state.options.get("db_table_comment")
  1612. new_db_table_comment = new_model_state.options.get("db_table_comment")
  1613. if old_db_table_comment != new_db_table_comment:
  1614. self.add_operation(
  1615. app_label,
  1616. operations.AlterModelTableComment(
  1617. name=model_name,
  1618. table_comment=new_db_table_comment,
  1619. ),
  1620. )
  1621. def generate_altered_options(self):
  1622. """
  1623. Work out if any non-schema-affecting options have changed and make an
  1624. operation to represent them in state changes (in case Python code in
  1625. migrations needs them).
  1626. """
  1627. models_to_check = self.kept_model_keys.union(
  1628. self.kept_proxy_keys,
  1629. self.kept_unmanaged_keys,
  1630. # unmanaged converted to managed
  1631. self.old_unmanaged_keys & self.new_model_keys,
  1632. # managed converted to unmanaged
  1633. self.old_model_keys & self.new_unmanaged_keys,
  1634. )
  1635. for app_label, model_name in sorted(models_to_check):
  1636. old_model_name = self.renamed_models.get(
  1637. (app_label, model_name), model_name
  1638. )
  1639. old_model_state = self.from_state.models[app_label, old_model_name]
  1640. new_model_state = self.to_state.models[app_label, model_name]
  1641. old_options = {
  1642. key: value
  1643. for key, value in old_model_state.options.items()
  1644. if key in AlterModelOptions.ALTER_OPTION_KEYS
  1645. }
  1646. new_options = {
  1647. key: value
  1648. for key, value in new_model_state.options.items()
  1649. if key in AlterModelOptions.ALTER_OPTION_KEYS
  1650. }
  1651. if old_options != new_options:
  1652. self.add_operation(
  1653. app_label,
  1654. operations.AlterModelOptions(
  1655. name=model_name,
  1656. options=new_options,
  1657. ),
  1658. )
  1659. def generate_altered_order_with_respect_to(self):
  1660. for app_label, model_name in sorted(self.kept_model_keys):
  1661. old_model_name = self.renamed_models.get(
  1662. (app_label, model_name), model_name
  1663. )
  1664. old_model_state = self.from_state.models[app_label, old_model_name]
  1665. new_model_state = self.to_state.models[app_label, model_name]
  1666. if old_model_state.options.get(
  1667. "order_with_respect_to"
  1668. ) != new_model_state.options.get("order_with_respect_to"):
  1669. # Make sure it comes second if we're adding
  1670. # (removal dependency is part of RemoveField)
  1671. dependencies = []
  1672. if new_model_state.options.get("order_with_respect_to"):
  1673. dependencies.append(
  1674. OperationDependency(
  1675. app_label,
  1676. model_name,
  1677. new_model_state.options["order_with_respect_to"],
  1678. OperationDependency.Type.CREATE,
  1679. )
  1680. )
  1681. # Actually generate the operation
  1682. self.add_operation(
  1683. app_label,
  1684. operations.AlterOrderWithRespectTo(
  1685. name=model_name,
  1686. order_with_respect_to=new_model_state.options.get(
  1687. "order_with_respect_to"
  1688. ),
  1689. ),
  1690. dependencies=dependencies,
  1691. )
  1692. def generate_altered_managers(self):
  1693. for app_label, model_name in sorted(self.kept_model_keys):
  1694. old_model_name = self.renamed_models.get(
  1695. (app_label, model_name), model_name
  1696. )
  1697. old_model_state = self.from_state.models[app_label, old_model_name]
  1698. new_model_state = self.to_state.models[app_label, model_name]
  1699. if old_model_state.managers != new_model_state.managers:
  1700. self.add_operation(
  1701. app_label,
  1702. operations.AlterModelManagers(
  1703. name=model_name,
  1704. managers=new_model_state.managers,
  1705. ),
  1706. )
  1707. def arrange_for_graph(self, changes, graph, migration_name=None):
  1708. """
  1709. Take a result from changes() and a MigrationGraph, and fix the names
  1710. and dependencies of the changes so they extend the graph from the leaf
  1711. nodes for each app.
  1712. """
  1713. leaves = graph.leaf_nodes()
  1714. name_map = {}
  1715. for app_label, migrations in list(changes.items()):
  1716. if not migrations:
  1717. continue
  1718. # Find the app label's current leaf node
  1719. app_leaf = None
  1720. for leaf in leaves:
  1721. if leaf[0] == app_label:
  1722. app_leaf = leaf
  1723. break
  1724. # Do they want an initial migration for this app?
  1725. if app_leaf is None and not self.questioner.ask_initial(app_label):
  1726. # They don't.
  1727. for migration in migrations:
  1728. name_map[(app_label, migration.name)] = (app_label, "__first__")
  1729. del changes[app_label]
  1730. continue
  1731. # Work out the next number in the sequence
  1732. if app_leaf is None:
  1733. next_number = 1
  1734. else:
  1735. next_number = (self.parse_number(app_leaf[1]) or 0) + 1
  1736. # Name each migration
  1737. for i, migration in enumerate(migrations):
  1738. if i == 0 and app_leaf:
  1739. migration.dependencies.append(app_leaf)
  1740. new_name_parts = ["%04i" % next_number]
  1741. if migration_name:
  1742. new_name_parts.append(migration_name)
  1743. elif i == 0 and not app_leaf:
  1744. new_name_parts.append("initial")
  1745. else:
  1746. new_name_parts.append(migration.suggest_name()[:100])
  1747. new_name = "_".join(new_name_parts)
  1748. name_map[(app_label, migration.name)] = (app_label, new_name)
  1749. next_number += 1
  1750. migration.name = new_name
  1751. # Now fix dependencies
  1752. for migrations in changes.values():
  1753. for migration in migrations:
  1754. migration.dependencies = [
  1755. name_map.get(d, d) for d in migration.dependencies
  1756. ]
  1757. return changes
  1758. def _trim_to_apps(self, changes, app_labels):
  1759. """
  1760. Take changes from arrange_for_graph() and set of app labels, and return
  1761. a modified set of changes which trims out as many migrations that are
  1762. not in app_labels as possible. Note that some other migrations may
  1763. still be present as they may be required dependencies.
  1764. """
  1765. # Gather other app dependencies in a first pass
  1766. app_dependencies = {}
  1767. for app_label, migrations in changes.items():
  1768. for migration in migrations:
  1769. for dep_app_label, name in migration.dependencies:
  1770. app_dependencies.setdefault(app_label, set()).add(dep_app_label)
  1771. required_apps = set(app_labels)
  1772. # Keep resolving till there's no change
  1773. old_required_apps = None
  1774. while old_required_apps != required_apps:
  1775. old_required_apps = set(required_apps)
  1776. required_apps.update(
  1777. *[app_dependencies.get(app_label, ()) for app_label in required_apps]
  1778. )
  1779. # Remove all migrations that aren't needed
  1780. for app_label in list(changes):
  1781. if app_label not in required_apps:
  1782. del changes[app_label]
  1783. return changes
  1784. @classmethod
  1785. def parse_number(cls, name):
  1786. """
  1787. Given a migration name, try to extract a number from the beginning of
  1788. it. For a squashed migration such as '0001_squashed_0004…', return the
  1789. second number. If no number is found, return None.
  1790. """
  1791. if squashed_match := re.search(r".*_squashed_(\d+)", name):
  1792. return int(squashed_match[1])
  1793. match = re.match(r"^\d+", name)
  1794. if match:
  1795. return int(match[0])
  1796. return None