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.

migrate.py 16KB

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