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.

executor.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. from django.apps.registry import apps as global_apps
  2. from django.db import migrations, router
  3. from .exceptions import InvalidMigrationPlan
  4. from .loader import MigrationLoader
  5. from .recorder import MigrationRecorder
  6. from .state import ProjectState
  7. class MigrationExecutor:
  8. """
  9. End-to-end migration execution - load migrations and run them up or down
  10. to a specified set of targets.
  11. """
  12. def __init__(self, connection, progress_callback=None):
  13. self.connection = connection
  14. self.loader = MigrationLoader(self.connection)
  15. self.recorder = MigrationRecorder(self.connection)
  16. self.progress_callback = progress_callback
  17. def migration_plan(self, targets, clean_start=False):
  18. """
  19. Given a set of targets, return a list of (Migration instance, backwards?).
  20. """
  21. plan = []
  22. if clean_start:
  23. applied = set()
  24. else:
  25. applied = set(self.loader.applied_migrations)
  26. for target in targets:
  27. # If the target is (app_label, None), that means unmigrate everything
  28. if target[1] is None:
  29. for root in self.loader.graph.root_nodes():
  30. if root[0] == target[0]:
  31. for migration in self.loader.graph.backwards_plan(root):
  32. if migration in applied:
  33. plan.append((self.loader.graph.nodes[migration], True))
  34. applied.remove(migration)
  35. # If the migration is already applied, do backwards mode,
  36. # otherwise do forwards mode.
  37. elif target in applied:
  38. # Don't migrate backwards all the way to the target node (that
  39. # may roll back dependencies in other apps that don't need to
  40. # be rolled back); instead roll back through target's immediate
  41. # child(ren) in the same app, and no further.
  42. next_in_app = sorted(
  43. n for n in
  44. self.loader.graph.node_map[target].children
  45. if n[0] == target[0]
  46. )
  47. for node in next_in_app:
  48. for migration in self.loader.graph.backwards_plan(node):
  49. if migration in applied:
  50. plan.append((self.loader.graph.nodes[migration], True))
  51. applied.remove(migration)
  52. else:
  53. for migration in self.loader.graph.forwards_plan(target):
  54. if migration not in applied:
  55. plan.append((self.loader.graph.nodes[migration], False))
  56. applied.add(migration)
  57. return plan
  58. def _create_project_state(self, with_applied_migrations=False):
  59. """
  60. Create a project state including all the applications without
  61. migrations and applied migrations if with_applied_migrations=True.
  62. """
  63. state = ProjectState(real_apps=list(self.loader.unmigrated_apps))
  64. if with_applied_migrations:
  65. # Create the forwards plan Django would follow on an empty database
  66. full_plan = self.migration_plan(self.loader.graph.leaf_nodes(), clean_start=True)
  67. applied_migrations = {
  68. self.loader.graph.nodes[key] for key in self.loader.applied_migrations
  69. if key in self.loader.graph.nodes
  70. }
  71. for migration, _ in full_plan:
  72. if migration in applied_migrations:
  73. migration.mutate_state(state, preserve=False)
  74. return state
  75. def migrate(self, targets, plan=None, state=None, fake=False, fake_initial=False):
  76. """
  77. Migrate the database up to the given targets.
  78. Django first needs to create all project states before a migration is
  79. (un)applied and in a second step run all the database operations.
  80. """
  81. # The django_migrations table must be present to record applied
  82. # migrations.
  83. self.recorder.ensure_schema()
  84. if plan is None:
  85. plan = self.migration_plan(targets)
  86. # Create the forwards plan Django would follow on an empty database
  87. full_plan = self.migration_plan(self.loader.graph.leaf_nodes(), clean_start=True)
  88. all_forwards = all(not backwards for mig, backwards in plan)
  89. all_backwards = all(backwards for mig, backwards in plan)
  90. if not plan:
  91. if state is None:
  92. # The resulting state should include applied migrations.
  93. state = self._create_project_state(with_applied_migrations=True)
  94. elif all_forwards == all_backwards:
  95. # This should only happen if there's a mixed plan
  96. raise InvalidMigrationPlan(
  97. "Migration plans with both forwards and backwards migrations "
  98. "are not supported. Please split your migration process into "
  99. "separate plans of only forwards OR backwards migrations.",
  100. plan
  101. )
  102. elif all_forwards:
  103. if state is None:
  104. # The resulting state should still include applied migrations.
  105. state = self._create_project_state(with_applied_migrations=True)
  106. state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  107. else:
  108. # No need to check for `elif all_backwards` here, as that condition
  109. # would always evaluate to true.
  110. state = self._migrate_all_backwards(plan, full_plan, fake=fake)
  111. self.check_replacements()
  112. return state
  113. def _migrate_all_forwards(self, state, plan, full_plan, fake, fake_initial):
  114. """
  115. Take a list of 2-tuples of the form (migration instance, False) and
  116. apply them in the order they occur in the full_plan.
  117. """
  118. migrations_to_run = {m[0] for m in plan}
  119. for migration, _ in full_plan:
  120. if not migrations_to_run:
  121. # We remove every migration that we applied from these sets so
  122. # that we can bail out once the last migration has been applied
  123. # and don't always run until the very end of the migration
  124. # process.
  125. break
  126. if migration in migrations_to_run:
  127. if 'apps' not in state.__dict__:
  128. if self.progress_callback:
  129. self.progress_callback("render_start")
  130. state.apps # Render all -- performance critical
  131. if self.progress_callback:
  132. self.progress_callback("render_success")
  133. state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  134. migrations_to_run.remove(migration)
  135. return state
  136. def _migrate_all_backwards(self, plan, full_plan, fake):
  137. """
  138. Take a list of 2-tuples of the form (migration instance, True) and
  139. unapply them in reverse order they occur in the full_plan.
  140. Since unapplying a migration requires the project state prior to that
  141. migration, Django will compute the migration states before each of them
  142. in a first run over the plan and then unapply them in a second run over
  143. the plan.
  144. """
  145. migrations_to_run = {m[0] for m in plan}
  146. # Holds all migration states prior to the migrations being unapplied
  147. states = {}
  148. state = self._create_project_state()
  149. applied_migrations = {
  150. self.loader.graph.nodes[key] for key in self.loader.applied_migrations
  151. if key in self.loader.graph.nodes
  152. }
  153. if self.progress_callback:
  154. self.progress_callback("render_start")
  155. for migration, _ in full_plan:
  156. if not migrations_to_run:
  157. # We remove every migration that we applied from this set so
  158. # that we can bail out once the last migration has been applied
  159. # and don't always run until the very end of the migration
  160. # process.
  161. break
  162. if migration in migrations_to_run:
  163. if 'apps' not in state.__dict__:
  164. state.apps # Render all -- performance critical
  165. # The state before this migration
  166. states[migration] = state
  167. # The old state keeps as-is, we continue with the new state
  168. state = migration.mutate_state(state, preserve=True)
  169. migrations_to_run.remove(migration)
  170. elif migration in applied_migrations:
  171. # Only mutate the state if the migration is actually applied
  172. # to make sure the resulting state doesn't include changes
  173. # from unrelated migrations.
  174. migration.mutate_state(state, preserve=False)
  175. if self.progress_callback:
  176. self.progress_callback("render_success")
  177. for migration, _ in plan:
  178. self.unapply_migration(states[migration], migration, fake=fake)
  179. applied_migrations.remove(migration)
  180. # Generate the post migration state by starting from the state before
  181. # the last migration is unapplied and mutating it to include all the
  182. # remaining applied migrations.
  183. last_unapplied_migration = plan[-1][0]
  184. state = states[last_unapplied_migration]
  185. for index, (migration, _) in enumerate(full_plan):
  186. if migration == last_unapplied_migration:
  187. for migration, _ in full_plan[index:]:
  188. if migration in applied_migrations:
  189. migration.mutate_state(state, preserve=False)
  190. break
  191. return state
  192. def collect_sql(self, plan):
  193. """
  194. Take a migration plan and return a list of collected SQL statements
  195. that represent the best-efforts version of that plan.
  196. """
  197. statements = []
  198. state = None
  199. for migration, backwards in plan:
  200. with self.connection.schema_editor(collect_sql=True, atomic=migration.atomic) as schema_editor:
  201. if state is None:
  202. state = self.loader.project_state((migration.app_label, migration.name), at_end=False)
  203. if not backwards:
  204. state = migration.apply(state, schema_editor, collect_sql=True)
  205. else:
  206. state = migration.unapply(state, schema_editor, collect_sql=True)
  207. statements.extend(schema_editor.collected_sql)
  208. return statements
  209. def apply_migration(self, state, migration, fake=False, fake_initial=False):
  210. """Run a migration forwards."""
  211. migration_recorded = False
  212. if self.progress_callback:
  213. self.progress_callback("apply_start", migration, fake)
  214. if not fake:
  215. if fake_initial:
  216. # Test to see if this is an already-applied initial migration
  217. applied, state = self.detect_soft_applied(state, migration)
  218. if applied:
  219. fake = True
  220. if not fake:
  221. # Alright, do it normally
  222. with self.connection.schema_editor(atomic=migration.atomic) as schema_editor:
  223. state = migration.apply(state, schema_editor)
  224. self.record_migration(migration)
  225. migration_recorded = True
  226. if not migration_recorded:
  227. self.record_migration(migration)
  228. # Report progress
  229. if self.progress_callback:
  230. self.progress_callback("apply_success", migration, fake)
  231. return state
  232. def record_migration(self, migration):
  233. # For replacement migrations, record individual statuses
  234. if migration.replaces:
  235. for app_label, name in migration.replaces:
  236. self.recorder.record_applied(app_label, name)
  237. else:
  238. self.recorder.record_applied(migration.app_label, migration.name)
  239. def unapply_migration(self, state, migration, fake=False):
  240. """Run a migration backwards."""
  241. if self.progress_callback:
  242. self.progress_callback("unapply_start", migration, fake)
  243. if not fake:
  244. with self.connection.schema_editor(atomic=migration.atomic) as schema_editor:
  245. state = migration.unapply(state, schema_editor)
  246. # For replacement migrations, record individual statuses
  247. if migration.replaces:
  248. for app_label, name in migration.replaces:
  249. self.recorder.record_unapplied(app_label, name)
  250. else:
  251. self.recorder.record_unapplied(migration.app_label, migration.name)
  252. # Report progress
  253. if self.progress_callback:
  254. self.progress_callback("unapply_success", migration, fake)
  255. return state
  256. def check_replacements(self):
  257. """
  258. Mark replacement migrations applied if their replaced set all are.
  259. Do this unconditionally on every migrate, rather than just when
  260. migrations are applied or unapplied, to correctly handle the case
  261. when a new squash migration is pushed to a deployment that already had
  262. all its replaced migrations applied. In this case no new migration will
  263. be applied, but the applied state of the squashed migration must be
  264. maintained.
  265. """
  266. applied = self.recorder.applied_migrations()
  267. for key, migration in self.loader.replacements.items():
  268. all_applied = all(m in applied for m in migration.replaces)
  269. if all_applied and key not in applied:
  270. self.recorder.record_applied(*key)
  271. def detect_soft_applied(self, project_state, migration):
  272. """
  273. Test whether a migration has been implicitly applied - that the
  274. tables or columns it would create exist. This is intended only for use
  275. on initial migrations (as it only looks for CreateModel and AddField).
  276. """
  277. def should_skip_detecting_model(migration, model):
  278. """
  279. No need to detect tables for proxy models, unmanaged models, or
  280. models that can't be migrated on the current database.
  281. """
  282. return (
  283. model._meta.proxy or not model._meta.managed or not
  284. router.allow_migrate(
  285. self.connection.alias, migration.app_label,
  286. model_name=model._meta.model_name,
  287. )
  288. )
  289. if migration.initial is None:
  290. # Bail if the migration isn't the first one in its app
  291. if any(app == migration.app_label for app, name in migration.dependencies):
  292. return False, project_state
  293. elif migration.initial is False:
  294. # Bail if it's NOT an initial migration
  295. return False, project_state
  296. if project_state is None:
  297. after_state = self.loader.project_state((migration.app_label, migration.name), at_end=True)
  298. else:
  299. after_state = migration.mutate_state(project_state)
  300. apps = after_state.apps
  301. found_create_model_migration = False
  302. found_add_field_migration = False
  303. with self.connection.cursor() as cursor:
  304. existing_table_names = self.connection.introspection.table_names(cursor)
  305. # Make sure all create model and add field operations are done
  306. for operation in migration.operations:
  307. if isinstance(operation, migrations.CreateModel):
  308. model = apps.get_model(migration.app_label, operation.name)
  309. if model._meta.swapped:
  310. # We have to fetch the model to test with from the
  311. # main app cache, as it's not a direct dependency.
  312. model = global_apps.get_model(model._meta.swapped)
  313. if should_skip_detecting_model(migration, model):
  314. continue
  315. if model._meta.db_table not in existing_table_names:
  316. return False, project_state
  317. found_create_model_migration = True
  318. elif isinstance(operation, migrations.AddField):
  319. model = apps.get_model(migration.app_label, operation.model_name)
  320. if model._meta.swapped:
  321. # We have to fetch the model to test with from the
  322. # main app cache, as it's not a direct dependency.
  323. model = global_apps.get_model(model._meta.swapped)
  324. if should_skip_detecting_model(migration, model):
  325. continue
  326. table = model._meta.db_table
  327. field = model._meta.get_field(operation.name)
  328. # Handle implicit many-to-many tables created by AddField.
  329. if field.many_to_many:
  330. if field.remote_field.through._meta.db_table not in existing_table_names:
  331. return False, project_state
  332. else:
  333. found_add_field_migration = True
  334. continue
  335. column_names = [
  336. column.name for column in
  337. self.connection.introspection.get_table_description(self.connection.cursor(), table)
  338. ]
  339. if field.column not in column_names:
  340. return False, project_state
  341. found_add_field_migration = True
  342. # If we get this far and we found at least one CreateModel or AddField migration,
  343. # the migration is considered implicitly applied.
  344. return (found_create_model_migration or found_add_field_migration), after_state