loader.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import pkgutil
  2. import sys
  3. from importlib import import_module, reload
  4. from django.apps import apps
  5. from django.conf import settings
  6. from django.db.migrations.graph import MigrationGraph
  7. from django.db.migrations.recorder import MigrationRecorder
  8. from .exceptions import (
  9. AmbiguityError, BadMigrationError, InconsistentMigrationHistory,
  10. NodeNotFoundError,
  11. )
  12. MIGRATIONS_MODULE_NAME = 'migrations'
  13. class MigrationLoader:
  14. """
  15. Load migration files from disk and their status from the database.
  16. Migration files are expected to live in the "migrations" directory of
  17. an app. Their names are entirely unimportant from a code perspective,
  18. but will probably follow the 1234_name.py convention.
  19. On initialization, this class will scan those directories, and open and
  20. read the Python files, looking for a class called Migration, which should
  21. inherit from django.db.migrations.Migration. See
  22. django.db.migrations.migration for what that looks like.
  23. Some migrations will be marked as "replacing" another set of migrations.
  24. These are loaded into a separate set of migrations away from the main ones.
  25. If all the migrations they replace are either unapplied or missing from
  26. disk, then they are injected into the main set, replacing the named migrations.
  27. Any dependency pointers to the replaced migrations are re-pointed to the
  28. new migration.
  29. This does mean that this class MUST also talk to the database as well as
  30. to disk, but this is probably fine. We're already not just operating
  31. in memory.
  32. """
  33. def __init__(
  34. self, connection, load=True, ignore_no_migrations=False,
  35. replace_migrations=True,
  36. ):
  37. self.connection = connection
  38. self.disk_migrations = None
  39. self.applied_migrations = None
  40. self.ignore_no_migrations = ignore_no_migrations
  41. self.replace_migrations = replace_migrations
  42. if load:
  43. self.build_graph()
  44. @classmethod
  45. def migrations_module(cls, app_label):
  46. """
  47. Return the path to the migrations module for the specified app_label
  48. and a boolean indicating if the module is specified in
  49. settings.MIGRATION_MODULE.
  50. """
  51. if app_label in settings.MIGRATION_MODULES:
  52. return settings.MIGRATION_MODULES[app_label], True
  53. else:
  54. app_package_name = apps.get_app_config(app_label).name
  55. return '%s.%s' % (app_package_name, MIGRATIONS_MODULE_NAME), False
  56. def load_disk(self):
  57. """Load the migrations from all INSTALLED_APPS from disk."""
  58. self.disk_migrations = {}
  59. self.unmigrated_apps = set()
  60. self.migrated_apps = set()
  61. for app_config in apps.get_app_configs():
  62. # Get the migrations module directory
  63. module_name, explicit = self.migrations_module(app_config.label)
  64. if module_name is None:
  65. self.unmigrated_apps.add(app_config.label)
  66. continue
  67. was_loaded = module_name in sys.modules
  68. try:
  69. module = import_module(module_name)
  70. except ModuleNotFoundError as e:
  71. if (
  72. (explicit and self.ignore_no_migrations) or
  73. (not explicit and MIGRATIONS_MODULE_NAME in e.name.split('.'))
  74. ):
  75. self.unmigrated_apps.add(app_config.label)
  76. continue
  77. raise
  78. else:
  79. # Module is not a package (e.g. migrations.py).
  80. if not hasattr(module, '__path__'):
  81. self.unmigrated_apps.add(app_config.label)
  82. continue
  83. # Empty directories are namespaces. Namespace packages have no
  84. # __file__ and don't use a list for __path__. See
  85. # https://docs.python.org/3/reference/import.html#namespace-packages
  86. if (
  87. getattr(module, '__file__', None) is None and
  88. not isinstance(module.__path__, list)
  89. ):
  90. self.unmigrated_apps.add(app_config.label)
  91. continue
  92. # Force a reload if it's already loaded (tests need this)
  93. if was_loaded:
  94. reload(module)
  95. self.migrated_apps.add(app_config.label)
  96. migration_names = {
  97. name for _, name, is_pkg in pkgutil.iter_modules(module.__path__)
  98. if not is_pkg and name[0] not in '_~'
  99. }
  100. # Load migrations
  101. for migration_name in migration_names:
  102. migration_path = '%s.%s' % (module_name, migration_name)
  103. try:
  104. migration_module = import_module(migration_path)
  105. except ImportError as e:
  106. if 'bad magic number' in str(e):
  107. raise ImportError(
  108. "Couldn't import %r as it appears to be a stale "
  109. ".pyc file." % migration_path
  110. ) from e
  111. else:
  112. raise
  113. if not hasattr(migration_module, "Migration"):
  114. raise BadMigrationError(
  115. "Migration %s in app %s has no Migration class" % (migration_name, app_config.label)
  116. )
  117. self.disk_migrations[app_config.label, migration_name] = migration_module.Migration(
  118. migration_name,
  119. app_config.label,
  120. )
  121. def get_migration(self, app_label, name_prefix):
  122. """Return the named migration or raise NodeNotFoundError."""
  123. return self.graph.nodes[app_label, name_prefix]
  124. def get_migration_by_prefix(self, app_label, name_prefix):
  125. """
  126. Return the migration(s) which match the given app label and name_prefix.
  127. """
  128. # Do the search
  129. results = []
  130. for migration_app_label, migration_name in self.disk_migrations:
  131. if migration_app_label == app_label and migration_name.startswith(name_prefix):
  132. results.append((migration_app_label, migration_name))
  133. if len(results) > 1:
  134. raise AmbiguityError(
  135. "There is more than one migration for '%s' with the prefix '%s'" % (app_label, name_prefix)
  136. )
  137. elif not results:
  138. raise KeyError("There no migrations for '%s' with the prefix '%s'" % (app_label, name_prefix))
  139. else:
  140. return self.disk_migrations[results[0]]
  141. def check_key(self, key, current_app):
  142. if (key[1] != "__first__" and key[1] != "__latest__") or key in self.graph:
  143. return key
  144. # Special-case __first__, which means "the first migration" for
  145. # migrated apps, and is ignored for unmigrated apps. It allows
  146. # makemigrations to declare dependencies on apps before they even have
  147. # migrations.
  148. if key[0] == current_app:
  149. # Ignore __first__ references to the same app (#22325)
  150. return
  151. if key[0] in self.unmigrated_apps:
  152. # This app isn't migrated, but something depends on it.
  153. # The models will get auto-added into the state, though
  154. # so we're fine.
  155. return
  156. if key[0] in self.migrated_apps:
  157. try:
  158. if key[1] == "__first__":
  159. return self.graph.root_nodes(key[0])[0]
  160. else: # "__latest__"
  161. return self.graph.leaf_nodes(key[0])[0]
  162. except IndexError:
  163. if self.ignore_no_migrations:
  164. return None
  165. else:
  166. raise ValueError("Dependency on app with no migrations: %s" % key[0])
  167. raise ValueError("Dependency on unknown app: %s" % key[0])
  168. def add_internal_dependencies(self, key, migration):
  169. """
  170. Internal dependencies need to be added first to ensure `__first__`
  171. dependencies find the correct root node.
  172. """
  173. for parent in migration.dependencies:
  174. # Ignore __first__ references to the same app.
  175. if parent[0] == key[0] and parent[1] != '__first__':
  176. self.graph.add_dependency(migration, key, parent, skip_validation=True)
  177. def add_external_dependencies(self, key, migration):
  178. for parent in migration.dependencies:
  179. # Skip internal dependencies
  180. if key[0] == parent[0]:
  181. continue
  182. parent = self.check_key(parent, key[0])
  183. if parent is not None:
  184. self.graph.add_dependency(migration, key, parent, skip_validation=True)
  185. for child in migration.run_before:
  186. child = self.check_key(child, key[0])
  187. if child is not None:
  188. self.graph.add_dependency(migration, child, key, skip_validation=True)
  189. def build_graph(self):
  190. """
  191. Build a migration dependency graph using both the disk and database.
  192. You'll need to rebuild the graph if you apply migrations. This isn't
  193. usually a problem as generally migration stuff runs in a one-shot process.
  194. """
  195. # Load disk data
  196. self.load_disk()
  197. # Load database data
  198. if self.connection is None:
  199. self.applied_migrations = {}
  200. else:
  201. recorder = MigrationRecorder(self.connection)
  202. self.applied_migrations = recorder.applied_migrations()
  203. # To start, populate the migration graph with nodes for ALL migrations
  204. # and their dependencies. Also make note of replacing migrations at this step.
  205. self.graph = MigrationGraph()
  206. self.replacements = {}
  207. for key, migration in self.disk_migrations.items():
  208. self.graph.add_node(key, migration)
  209. # Replacing migrations.
  210. if migration.replaces:
  211. self.replacements[key] = migration
  212. for key, migration in self.disk_migrations.items():
  213. # Internal (same app) dependencies.
  214. self.add_internal_dependencies(key, migration)
  215. # Add external dependencies now that the internal ones have been resolved.
  216. for key, migration in self.disk_migrations.items():
  217. self.add_external_dependencies(key, migration)
  218. # Carry out replacements where possible and if enabled.
  219. if self.replace_migrations:
  220. for key, migration in self.replacements.items():
  221. # Get applied status of each of this migration's replacement
  222. # targets.
  223. applied_statuses = [(target in self.applied_migrations) for target in migration.replaces]
  224. # The replacing migration is only marked as applied if all of
  225. # its replacement targets are.
  226. if all(applied_statuses):
  227. self.applied_migrations[key] = migration
  228. else:
  229. self.applied_migrations.pop(key, None)
  230. # A replacing migration can be used if either all or none of
  231. # its replacement targets have been applied.
  232. if all(applied_statuses) or (not any(applied_statuses)):
  233. self.graph.remove_replaced_nodes(key, migration.replaces)
  234. else:
  235. # This replacing migration cannot be used because it is
  236. # partially applied. Remove it from the graph and remap
  237. # dependencies to it (#25945).
  238. self.graph.remove_replacement_node(key, migration.replaces)
  239. # Ensure the graph is consistent.
  240. try:
  241. self.graph.validate_consistency()
  242. except NodeNotFoundError as exc:
  243. # Check if the missing node could have been replaced by any squash
  244. # migration but wasn't because the squash migration was partially
  245. # applied before. In that case raise a more understandable exception
  246. # (#23556).
  247. # Get reverse replacements.
  248. reverse_replacements = {}
  249. for key, migration in self.replacements.items():
  250. for replaced in migration.replaces:
  251. reverse_replacements.setdefault(replaced, set()).add(key)
  252. # Try to reraise exception with more detail.
  253. if exc.node in reverse_replacements:
  254. candidates = reverse_replacements.get(exc.node, set())
  255. is_replaced = any(candidate in self.graph.nodes for candidate in candidates)
  256. if not is_replaced:
  257. tries = ', '.join('%s.%s' % c for c in candidates)
  258. raise NodeNotFoundError(
  259. "Migration {0} depends on nonexistent node ('{1}', '{2}'). "
  260. "Django tried to replace migration {1}.{2} with any of [{3}] "
  261. "but wasn't able to because some of the replaced migrations "
  262. "are already applied.".format(
  263. exc.origin, exc.node[0], exc.node[1], tries
  264. ),
  265. exc.node
  266. ) from exc
  267. raise
  268. self.graph.ensure_not_cyclic()
  269. def check_consistent_history(self, connection):
  270. """
  271. Raise InconsistentMigrationHistory if any applied migrations have
  272. unapplied dependencies.
  273. """
  274. recorder = MigrationRecorder(connection)
  275. applied = recorder.applied_migrations()
  276. for migration in applied:
  277. # If the migration is unknown, skip it.
  278. if migration not in self.graph.nodes:
  279. continue
  280. for parent in self.graph.node_map[migration].parents:
  281. if parent not in applied:
  282. # Skip unapplied squashed migrations that have all of their
  283. # `replaces` applied.
  284. if parent in self.replacements:
  285. if all(m in applied for m in self.replacements[parent].replaces):
  286. continue
  287. raise InconsistentMigrationHistory(
  288. "Migration {}.{} is applied before its dependency "
  289. "{}.{} on database '{}'.".format(
  290. migration[0], migration[1], parent[0], parent[1],
  291. connection.alias,
  292. )
  293. )
  294. def detect_conflicts(self):
  295. """
  296. Look through the loaded graph and detect any conflicts - apps
  297. with more than one leaf migration. Return a dict of the app labels
  298. that conflict with the migration names that conflict.
  299. """
  300. seen_apps = {}
  301. conflicting_apps = set()
  302. for app_label, migration_name in self.graph.leaf_nodes():
  303. if app_label in seen_apps:
  304. conflicting_apps.add(app_label)
  305. seen_apps.setdefault(app_label, set()).add(migration_name)
  306. return {app_label: sorted(seen_apps[app_label]) for app_label in conflicting_apps}
  307. def project_state(self, nodes=None, at_end=True):
  308. """
  309. Return a ProjectState object representing the most recent state
  310. that the loaded migrations represent.
  311. See graph.make_state() for the meaning of "nodes" and "at_end".
  312. """
  313. return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps))
  314. def collect_sql(self, plan):
  315. """
  316. Take a migration plan and return a list of collected SQL statements
  317. that represent the best-efforts version of that plan.
  318. """
  319. statements = []
  320. state = None
  321. for migration, backwards in plan:
  322. with self.connection.schema_editor(collect_sql=True, atomic=migration.atomic) as schema_editor:
  323. if state is None:
  324. state = self.project_state((migration.app_label, migration.name), at_end=False)
  325. if not backwards:
  326. state = migration.apply(state, schema_editor, collect_sql=True)
  327. else:
  328. state = migration.unapply(state, schema_editor, collect_sql=True)
  329. statements.extend(schema_editor.collected_sql)
  330. return statements