2
0

migrate.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. import time
  2. from importlib import import_module
  3. from django.apps import apps
  4. from django.core.checks import Tags, run_checks
  5. from django.core.management.base import (
  6. BaseCommand, CommandError, no_translations,
  7. )
  8. from django.core.management.sql import (
  9. emit_post_migrate_signal, emit_pre_migrate_signal,
  10. )
  11. from django.db import DEFAULT_DB_ALIAS, connections, router
  12. from django.db.migrations.autodetector import MigrationAutodetector
  13. from django.db.migrations.executor import MigrationExecutor
  14. from django.db.migrations.loader import AmbiguityError
  15. from django.db.migrations.state import ModelState, ProjectState
  16. from django.utils.module_loading import module_has_submodule
  17. from django.utils.text import Truncator
  18. class Command(BaseCommand):
  19. help = "Updates database schema. Manages both apps with migrations and those without."
  20. def add_arguments(self, parser):
  21. parser.add_argument(
  22. 'app_label', nargs='?',
  23. help='App label of an application to synchronize the state.',
  24. )
  25. parser.add_argument(
  26. 'migration_name', nargs='?',
  27. help='Database state will be brought to the state after that '
  28. 'migration. Use the name "zero" to unapply all migrations.',
  29. )
  30. parser.add_argument(
  31. '--noinput', '--no-input', action='store_false', dest='interactive',
  32. help='Tells Django to NOT prompt the user for input of any kind.',
  33. )
  34. parser.add_argument(
  35. '--database',
  36. default=DEFAULT_DB_ALIAS,
  37. help='Nominates a database to synchronize. Defaults to the "default" database.',
  38. )
  39. parser.add_argument(
  40. '--fake', action='store_true',
  41. help='Mark migrations as run without actually running them.',
  42. )
  43. parser.add_argument(
  44. '--fake-initial', action='store_true',
  45. help='Detect if tables already exist and fake-apply initial migrations if so. Make sure '
  46. 'that the current database schema matches your initial migration before using this '
  47. 'flag. Django will only check for an existing table name.',
  48. )
  49. parser.add_argument(
  50. '--plan', action='store_true',
  51. help='Shows a list of the migration actions that will be performed.',
  52. )
  53. parser.add_argument(
  54. '--run-syncdb', action='store_true',
  55. help='Creates tables for apps without migrations.',
  56. )
  57. def _run_checks(self, **kwargs):
  58. issues = run_checks(tags=[Tags.database])
  59. issues.extend(super()._run_checks(**kwargs))
  60. return issues
  61. @no_translations
  62. def handle(self, *args, **options):
  63. self.verbosity = options['verbosity']
  64. self.interactive = options['interactive']
  65. # Import the 'management' module within each installed app, to register
  66. # dispatcher events.
  67. for app_config in apps.get_app_configs():
  68. if module_has_submodule(app_config.module, "management"):
  69. import_module('.management', app_config.name)
  70. # Get the database we're operating from
  71. db = options['database']
  72. connection = connections[db]
  73. # Hook for backends needing any database preparation
  74. connection.prepare_database()
  75. # Work out which apps have migrations and which do not
  76. executor = MigrationExecutor(connection, self.migration_progress_callback)
  77. # Raise an error if any migrations are applied before their dependencies.
  78. executor.loader.check_consistent_history(connection)
  79. # Before anything else, see if there's conflicting apps and drop out
  80. # hard if there are any
  81. conflicts = executor.loader.detect_conflicts()
  82. if conflicts:
  83. name_str = "; ".join(
  84. "%s in %s" % (", ".join(names), app)
  85. for app, names in conflicts.items()
  86. )
  87. raise CommandError(
  88. "Conflicting migrations detected; multiple leaf nodes in the "
  89. "migration graph: (%s).\nTo fix them run "
  90. "'python manage.py makemigrations --merge'" % name_str
  91. )
  92. # If they supplied command line arguments, work out what they mean.
  93. run_syncdb = options['run_syncdb']
  94. target_app_labels_only = True
  95. if options['app_label']:
  96. # Validate app_label.
  97. app_label = options['app_label']
  98. try:
  99. apps.get_app_config(app_label)
  100. except LookupError as err:
  101. raise CommandError(str(err))
  102. if run_syncdb:
  103. if app_label in executor.loader.migrated_apps:
  104. raise CommandError("Can't use run_syncdb with app '%s' as it has migrations." % app_label)
  105. elif app_label not in executor.loader.migrated_apps:
  106. raise CommandError("App '%s' does not have migrations." % app_label)
  107. if options['app_label'] and options['migration_name']:
  108. migration_name = options['migration_name']
  109. if migration_name == "zero":
  110. targets = [(app_label, None)]
  111. else:
  112. try:
  113. migration = executor.loader.get_migration_by_prefix(app_label, migration_name)
  114. except AmbiguityError:
  115. raise CommandError(
  116. "More than one migration matches '%s' in app '%s'. "
  117. "Please be more specific." %
  118. (migration_name, app_label)
  119. )
  120. except KeyError:
  121. raise CommandError("Cannot find a migration matching '%s' from app '%s'." % (
  122. migration_name, app_label))
  123. targets = [(app_label, migration.name)]
  124. target_app_labels_only = False
  125. elif options['app_label']:
  126. targets = [key for key in executor.loader.graph.leaf_nodes() if key[0] == app_label]
  127. else:
  128. targets = executor.loader.graph.leaf_nodes()
  129. plan = executor.migration_plan(targets)
  130. if options['plan']:
  131. self.stdout.write('Planned operations:', self.style.MIGRATE_LABEL)
  132. if not plan:
  133. self.stdout.write(' No planned migration operations.')
  134. for migration, backwards in plan:
  135. self.stdout.write(str(migration), self.style.MIGRATE_HEADING)
  136. for operation in migration.operations:
  137. message, is_error = self.describe_operation(operation, backwards)
  138. style = self.style.WARNING if is_error else None
  139. self.stdout.write(' ' + message, style)
  140. return
  141. # At this point, ignore run_syncdb if there aren't any apps to sync.
  142. run_syncdb = options['run_syncdb'] and executor.loader.unmigrated_apps
  143. # Print some useful info
  144. if self.verbosity >= 1:
  145. self.stdout.write(self.style.MIGRATE_HEADING("Operations to perform:"))
  146. if run_syncdb:
  147. if options['app_label']:
  148. self.stdout.write(
  149. self.style.MIGRATE_LABEL(" Synchronize unmigrated app: %s" % app_label)
  150. )
  151. else:
  152. self.stdout.write(
  153. self.style.MIGRATE_LABEL(" Synchronize unmigrated apps: ") +
  154. (", ".join(sorted(executor.loader.unmigrated_apps)))
  155. )
  156. if target_app_labels_only:
  157. self.stdout.write(
  158. self.style.MIGRATE_LABEL(" Apply all migrations: ") +
  159. (", ".join(sorted({a for a, n in targets})) or "(none)")
  160. )
  161. else:
  162. if targets[0][1] is None:
  163. self.stdout.write(self.style.MIGRATE_LABEL(
  164. " Unapply all migrations: ") + "%s" % (targets[0][0],)
  165. )
  166. else:
  167. self.stdout.write(self.style.MIGRATE_LABEL(
  168. " Target specific migration: ") + "%s, from %s"
  169. % (targets[0][1], targets[0][0])
  170. )
  171. pre_migrate_state = executor._create_project_state(with_applied_migrations=True)
  172. pre_migrate_apps = pre_migrate_state.apps
  173. emit_pre_migrate_signal(
  174. self.verbosity, self.interactive, connection.alias, apps=pre_migrate_apps, plan=plan,
  175. )
  176. # Run the syncdb phase.
  177. if run_syncdb:
  178. if self.verbosity >= 1:
  179. self.stdout.write(self.style.MIGRATE_HEADING("Synchronizing apps without migrations:"))
  180. if options['app_label']:
  181. self.sync_apps(connection, [app_label])
  182. else:
  183. self.sync_apps(connection, executor.loader.unmigrated_apps)
  184. # Migrate!
  185. if self.verbosity >= 1:
  186. self.stdout.write(self.style.MIGRATE_HEADING("Running migrations:"))
  187. if not plan:
  188. if self.verbosity >= 1:
  189. self.stdout.write(" No migrations to apply.")
  190. # If there's changes that aren't in migrations yet, tell them how to fix it.
  191. autodetector = MigrationAutodetector(
  192. executor.loader.project_state(),
  193. ProjectState.from_apps(apps),
  194. )
  195. changes = autodetector.changes(graph=executor.loader.graph)
  196. if changes:
  197. self.stdout.write(self.style.NOTICE(
  198. " Your models have changes that are not yet reflected "
  199. "in a migration, and so won't be applied."
  200. ))
  201. self.stdout.write(self.style.NOTICE(
  202. " Run 'manage.py makemigrations' to make new "
  203. "migrations, and then re-run 'manage.py migrate' to "
  204. "apply them."
  205. ))
  206. fake = False
  207. fake_initial = False
  208. else:
  209. fake = options['fake']
  210. fake_initial = options['fake_initial']
  211. post_migrate_state = executor.migrate(
  212. targets, plan=plan, state=pre_migrate_state.clone(), fake=fake,
  213. fake_initial=fake_initial,
  214. )
  215. # post_migrate signals have access to all models. Ensure that all models
  216. # are reloaded in case any are delayed.
  217. post_migrate_state.clear_delayed_apps_cache()
  218. post_migrate_apps = post_migrate_state.apps
  219. # Re-render models of real apps to include relationships now that
  220. # we've got a final state. This wouldn't be necessary if real apps
  221. # models were rendered with relationships in the first place.
  222. with post_migrate_apps.bulk_update():
  223. model_keys = []
  224. for model_state in post_migrate_apps.real_models:
  225. model_key = model_state.app_label, model_state.name_lower
  226. model_keys.append(model_key)
  227. post_migrate_apps.unregister_model(*model_key)
  228. post_migrate_apps.render_multiple([
  229. ModelState.from_model(apps.get_model(*model)) for model in model_keys
  230. ])
  231. # Send the post_migrate signal, so individual apps can do whatever they need
  232. # to do at this point.
  233. emit_post_migrate_signal(
  234. self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan,
  235. )
  236. def migration_progress_callback(self, action, migration=None, fake=False):
  237. if self.verbosity >= 1:
  238. compute_time = self.verbosity > 1
  239. if action == "apply_start":
  240. if compute_time:
  241. self.start = time.monotonic()
  242. self.stdout.write(" Applying %s..." % migration, ending="")
  243. self.stdout.flush()
  244. elif action == "apply_success":
  245. elapsed = " (%.3fs)" % (time.monotonic() - self.start) if compute_time else ""
  246. if fake:
  247. self.stdout.write(self.style.SUCCESS(" FAKED" + elapsed))
  248. else:
  249. self.stdout.write(self.style.SUCCESS(" OK" + elapsed))
  250. elif action == "unapply_start":
  251. if compute_time:
  252. self.start = time.monotonic()
  253. self.stdout.write(" Unapplying %s..." % migration, ending="")
  254. self.stdout.flush()
  255. elif action == "unapply_success":
  256. elapsed = " (%.3fs)" % (time.monotonic() - self.start) if compute_time else ""
  257. if fake:
  258. self.stdout.write(self.style.SUCCESS(" FAKED" + elapsed))
  259. else:
  260. self.stdout.write(self.style.SUCCESS(" OK" + elapsed))
  261. elif action == "render_start":
  262. if compute_time:
  263. self.start = time.monotonic()
  264. self.stdout.write(" Rendering model states...", ending="")
  265. self.stdout.flush()
  266. elif action == "render_success":
  267. elapsed = " (%.3fs)" % (time.monotonic() - self.start) if compute_time else ""
  268. self.stdout.write(self.style.SUCCESS(" DONE" + elapsed))
  269. def sync_apps(self, connection, app_labels):
  270. """Run the old syncdb-style operation on a list of app_labels."""
  271. with connection.cursor() as cursor:
  272. tables = connection.introspection.table_names(cursor)
  273. # Build the manifest of apps and models that are to be synchronized.
  274. all_models = [
  275. (
  276. app_config.label,
  277. router.get_migratable_models(app_config, connection.alias, include_auto_created=False),
  278. )
  279. for app_config in apps.get_app_configs()
  280. if app_config.models_module is not None and app_config.label in app_labels
  281. ]
  282. def model_installed(model):
  283. opts = model._meta
  284. converter = connection.introspection.identifier_converter
  285. return not (
  286. (converter(opts.db_table) in tables) or
  287. (opts.auto_created and converter(opts.auto_created._meta.db_table) in tables)
  288. )
  289. manifest = {
  290. app_name: list(filter(model_installed, model_list))
  291. for app_name, model_list in all_models
  292. }
  293. # Create the tables for each model
  294. if self.verbosity >= 1:
  295. self.stdout.write(" Creating tables...\n")
  296. with connection.schema_editor() as editor:
  297. for app_name, model_list in manifest.items():
  298. for model in model_list:
  299. # Never install unmanaged models, etc.
  300. if not model._meta.can_migrate(connection):
  301. continue
  302. if self.verbosity >= 3:
  303. self.stdout.write(
  304. " Processing %s.%s model\n" % (app_name, model._meta.object_name)
  305. )
  306. if self.verbosity >= 1:
  307. self.stdout.write(" Creating table %s\n" % model._meta.db_table)
  308. editor.create_model(model)
  309. # Deferred SQL is executed when exiting the editor's context.
  310. if self.verbosity >= 1:
  311. self.stdout.write(" Running deferred SQL...\n")
  312. @staticmethod
  313. def describe_operation(operation, backwards):
  314. """Return a string that describes a migration operation for --plan."""
  315. prefix = ''
  316. if hasattr(operation, 'code'):
  317. code = operation.reverse_code if backwards else operation.code
  318. action = code.__doc__ if code else ''
  319. elif hasattr(operation, 'sql'):
  320. action = operation.reverse_sql if backwards else operation.sql
  321. else:
  322. action = ''
  323. if backwards:
  324. prefix = 'Undo '
  325. if action is None:
  326. action = 'IRREVERSIBLE'
  327. is_error = True
  328. else:
  329. action = str(action).replace('\n', '')
  330. is_error = False
  331. if action:
  332. action = ' -> ' + action
  333. truncated = Truncator(action)
  334. return prefix + operation.describe() + truncated.chars(40), is_error