2013-09-07 00:05:50 +08:00
|
|
|
# encoding: utf8
|
|
|
|
from __future__ import unicode_literals
|
2013-06-08 01:47:17 +08:00
|
|
|
from optparse import make_option
|
2013-08-09 21:17:30 +08:00
|
|
|
from collections import OrderedDict
|
2013-08-10 00:36:16 +08:00
|
|
|
from importlib import import_module
|
2013-06-08 01:47:17 +08:00
|
|
|
import itertools
|
|
|
|
import traceback
|
|
|
|
|
2013-12-22 18:35:17 +08:00
|
|
|
from django.apps import app_cache
|
2013-06-08 01:47:17 +08:00
|
|
|
from django.core.management import call_command
|
2013-07-23 02:43:58 +08:00
|
|
|
from django.core.management.base import BaseCommand, CommandError
|
2013-08-10 00:34:35 +08:00
|
|
|
from django.core.management.color import no_style
|
2013-07-30 18:52:52 +08:00
|
|
|
from django.core.management.sql import custom_sql_for_model, emit_post_migrate_signal, emit_pre_migrate_signal
|
2013-12-12 06:31:34 +08:00
|
|
|
from django.db import connections, router, transaction, DEFAULT_DB_ALIAS
|
2013-06-08 01:47:17 +08:00
|
|
|
from django.db.migrations.executor import MigrationExecutor
|
2013-09-07 00:05:50 +08:00
|
|
|
from django.db.migrations.loader import MigrationLoader, AmbiguityError
|
2013-12-04 21:32:46 +08:00
|
|
|
from django.db.migrations.state import ProjectState
|
|
|
|
from django.db.migrations.autodetector import MigrationAutodetector
|
2013-07-26 23:39:44 +08:00
|
|
|
from django.utils.module_loading import module_has_submodule
|
2013-06-08 01:47:17 +08:00
|
|
|
|
|
|
|
|
2013-07-23 02:43:58 +08:00
|
|
|
class Command(BaseCommand):
|
|
|
|
option_list = BaseCommand.option_list + (
|
2013-06-08 01:47:17 +08:00
|
|
|
make_option('--noinput', action='store_false', dest='interactive', default=True,
|
|
|
|
help='Tells Django to NOT prompt the user for input of any kind.'),
|
|
|
|
make_option('--no-initial-data', action='store_false', dest='load_initial_data', default=True,
|
|
|
|
help='Tells Django not to load any initial data after database synchronization.'),
|
|
|
|
make_option('--database', action='store', dest='database',
|
|
|
|
default=DEFAULT_DB_ALIAS, help='Nominates a database to synchronize. '
|
|
|
|
'Defaults to the "default" database.'),
|
2013-07-26 23:47:00 +08:00
|
|
|
make_option('--fake', action='store_true', dest='fake', default=False,
|
|
|
|
help='Mark migrations as run without actually running them'),
|
2013-09-07 06:00:19 +08:00
|
|
|
make_option('--list', '-l', action='store_true', dest='list', default=False,
|
2013-09-07 00:05:50 +08:00
|
|
|
help='Show a list of all known migrations and which are applied'),
|
2013-06-08 01:47:17 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
help = "Updates database schema. Manages both apps with migrations and those without."
|
|
|
|
|
2013-07-23 02:43:58 +08:00
|
|
|
def handle(self, *args, **options):
|
2013-06-08 01:47:17 +08:00
|
|
|
|
|
|
|
self.verbosity = int(options.get('verbosity'))
|
|
|
|
self.interactive = options.get('interactive')
|
|
|
|
self.show_traceback = options.get('traceback')
|
|
|
|
self.load_initial_data = options.get('load_initial_data')
|
2013-06-19 22:36:22 +08:00
|
|
|
self.test_database = options.get('test_database', False)
|
2013-06-08 01:47:17 +08:00
|
|
|
|
|
|
|
# Import the 'management' module within each installed app, to register
|
|
|
|
# dispatcher events.
|
2013-12-19 22:57:23 +08:00
|
|
|
for app_config in app_cache.get_app_configs():
|
|
|
|
if module_has_submodule(app_config.app_module, "management"):
|
|
|
|
import_module('.management', app_config.name)
|
2013-06-08 01:47:17 +08:00
|
|
|
|
|
|
|
# Get the database we're operating from
|
|
|
|
db = options.get('database')
|
|
|
|
connection = connections[db]
|
|
|
|
|
2013-09-07 00:05:50 +08:00
|
|
|
# If they asked for a migration listing, quit main execution flow and show it
|
|
|
|
if options.get("list", False):
|
|
|
|
return self.show_migration_list(connection, args)
|
|
|
|
|
2013-06-08 01:47:17 +08:00
|
|
|
# Work out which apps have migrations and which do not
|
|
|
|
executor = MigrationExecutor(connection, self.migration_progress_callback)
|
|
|
|
|
2013-12-05 00:01:31 +08:00
|
|
|
# Before anything else, see if there's conflicting apps and drop out
|
|
|
|
# hard if there are any
|
|
|
|
conflicts = executor.loader.detect_conflicts()
|
|
|
|
if conflicts:
|
|
|
|
name_str = "; ".join(
|
|
|
|
"%s in %s" % (", ".join(names), app)
|
|
|
|
for app, names in conflicts.items()
|
|
|
|
)
|
|
|
|
raise CommandError("Conflicting migrations detected (%s).\nTo fix them run 'python manage.py makemigrations --merge'" % name_str)
|
|
|
|
|
2013-07-23 02:43:58 +08:00
|
|
|
# If they supplied command line arguments, work out what they mean.
|
|
|
|
run_syncdb = False
|
|
|
|
target_app_labels_only = True
|
|
|
|
if len(args) > 2:
|
|
|
|
raise CommandError("Too many command-line arguments (expecting 'appname' or 'appname migrationname')")
|
|
|
|
elif len(args) == 2:
|
|
|
|
app_label, migration_name = args
|
|
|
|
if app_label not in executor.loader.migrated_apps:
|
|
|
|
raise CommandError("App '%s' does not have migrations (you cannot selectively sync unmigrated apps)" % app_label)
|
|
|
|
if migration_name == "zero":
|
2013-07-25 20:52:35 +08:00
|
|
|
targets = [(app_label, None)]
|
2013-07-23 02:43:58 +08:00
|
|
|
else:
|
|
|
|
try:
|
|
|
|
migration = executor.loader.get_migration_by_prefix(app_label, migration_name)
|
|
|
|
except AmbiguityError:
|
|
|
|
raise CommandError("More than one migration matches '%s' in app '%s'. Please be more specific." % (app_label, migration_name))
|
|
|
|
except KeyError:
|
2013-10-16 19:00:07 +08:00
|
|
|
raise CommandError("Cannot find a migration matching '%s' from app '%s'." % (app_label, migration_name))
|
2013-07-25 20:52:35 +08:00
|
|
|
targets = [(app_label, migration.name)]
|
2013-07-23 02:43:58 +08:00
|
|
|
target_app_labels_only = False
|
|
|
|
elif len(args) == 1:
|
|
|
|
app_label = args[0]
|
|
|
|
if app_label not in executor.loader.migrated_apps:
|
|
|
|
raise CommandError("App '%s' does not have migrations (you cannot selectively sync unmigrated apps)" % app_label)
|
|
|
|
targets = [key for key in executor.loader.graph.leaf_nodes() if key[0] == app_label]
|
|
|
|
else:
|
|
|
|
targets = executor.loader.graph.leaf_nodes()
|
|
|
|
run_syncdb = True
|
|
|
|
|
2013-06-08 01:47:17 +08:00
|
|
|
plan = executor.migration_plan(targets)
|
|
|
|
|
2013-07-23 02:43:58 +08:00
|
|
|
# Print some useful info
|
2013-06-08 01:47:17 +08:00
|
|
|
if self.verbosity >= 1:
|
2013-07-23 02:43:58 +08:00
|
|
|
self.stdout.write(self.style.MIGRATE_HEADING("Operations to perform:"))
|
|
|
|
if run_syncdb:
|
|
|
|
self.stdout.write(self.style.MIGRATE_LABEL(" Synchronize unmigrated apps: ") + (", ".join(executor.loader.unmigrated_apps) or "(none)"))
|
|
|
|
if target_app_labels_only:
|
|
|
|
self.stdout.write(self.style.MIGRATE_LABEL(" Apply all migrations: ") + (", ".join(set(a for a, n in targets)) or "(none)"))
|
|
|
|
else:
|
|
|
|
if targets[0][1] is None:
|
|
|
|
self.stdout.write(self.style.MIGRATE_LABEL(" Unapply all migrations: ") + "%s" % (targets[0][0], ))
|
|
|
|
else:
|
|
|
|
self.stdout.write(self.style.MIGRATE_LABEL(" Target specific migration: ") + "%s, from %s" % (targets[0][1], targets[0][0]))
|
2013-06-08 01:47:17 +08:00
|
|
|
|
|
|
|
# Run the syncdb phase.
|
|
|
|
# If you ever manage to get rid of this, I owe you many, many drinks.
|
2013-07-30 18:52:52 +08:00
|
|
|
# Note that pre_migrate is called from inside here, as it needs
|
|
|
|
# the list of models about to be installed.
|
2013-07-23 02:43:58 +08:00
|
|
|
if run_syncdb:
|
2013-07-25 20:52:35 +08:00
|
|
|
if self.verbosity >= 1:
|
|
|
|
self.stdout.write(self.style.MIGRATE_HEADING("Synchronizing apps without migrations:"))
|
2013-07-30 18:52:52 +08:00
|
|
|
created_models = self.sync_apps(connection, executor.loader.unmigrated_apps)
|
|
|
|
else:
|
|
|
|
created_models = []
|
2013-06-08 01:47:17 +08:00
|
|
|
|
|
|
|
# Migrate!
|
|
|
|
if self.verbosity >= 1:
|
|
|
|
self.stdout.write(self.style.MIGRATE_HEADING("Running migrations:"))
|
|
|
|
if not plan:
|
|
|
|
if self.verbosity >= 1:
|
|
|
|
self.stdout.write(" No migrations needed.")
|
2013-12-04 21:32:46 +08:00
|
|
|
# If there's changes that aren't in migrations yet, tell them how to fix it.
|
|
|
|
autodetector = MigrationAutodetector(
|
|
|
|
executor.loader.graph.project_state(),
|
2013-12-12 06:31:34 +08:00
|
|
|
ProjectState.from_app_cache(app_cache),
|
2013-12-04 21:32:46 +08:00
|
|
|
)
|
|
|
|
changes = autodetector.changes(graph=executor.loader.graph)
|
|
|
|
if changes:
|
|
|
|
self.stdout.write(self.style.NOTICE(" Your models have changes that are not yet reflected in a migration, and so won't be applied."))
|
|
|
|
self.stdout.write(self.style.NOTICE(" Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them."))
|
2013-06-08 01:47:17 +08:00
|
|
|
else:
|
2013-07-26 23:47:00 +08:00
|
|
|
executor.migrate(targets, plan, fake=options.get("fake", False))
|
2013-06-08 01:47:17 +08:00
|
|
|
|
2013-07-30 18:52:52 +08:00
|
|
|
# Send the post_migrate signal, so individual apps can do whatever they need
|
|
|
|
# to do at this point.
|
|
|
|
emit_post_migrate_signal(created_models, self.verbosity, self.interactive, connection.alias)
|
|
|
|
|
2013-10-30 23:17:28 +08:00
|
|
|
def migration_progress_callback(self, action, migration, fake=False):
|
2013-06-08 01:47:17 +08:00
|
|
|
if self.verbosity >= 1:
|
|
|
|
if action == "apply_start":
|
2013-07-26 23:52:17 +08:00
|
|
|
self.stdout.write(" Applying %s..." % migration, ending="")
|
2013-06-08 01:47:17 +08:00
|
|
|
self.stdout.flush()
|
|
|
|
elif action == "apply_success":
|
2013-10-30 23:17:28 +08:00
|
|
|
if fake:
|
|
|
|
self.stdout.write(self.style.MIGRATE_SUCCESS(" FAKED"))
|
|
|
|
else:
|
|
|
|
self.stdout.write(self.style.MIGRATE_SUCCESS(" OK"))
|
2013-06-08 01:47:17 +08:00
|
|
|
elif action == "unapply_start":
|
2013-07-26 23:52:17 +08:00
|
|
|
self.stdout.write(" Unapplying %s..." % migration, ending="")
|
2013-06-08 01:47:17 +08:00
|
|
|
self.stdout.flush()
|
|
|
|
elif action == "unapply_success":
|
2013-10-30 23:17:28 +08:00
|
|
|
if fake:
|
|
|
|
self.stdout.write(self.style.MIGRATE_SUCCESS(" FAKED"))
|
|
|
|
else:
|
|
|
|
self.stdout.write(self.style.MIGRATE_SUCCESS(" OK"))
|
2013-06-08 01:47:17 +08:00
|
|
|
|
|
|
|
def sync_apps(self, connection, apps):
|
|
|
|
"Runs the old syncdb-style operation on a list of apps."
|
|
|
|
cursor = connection.cursor()
|
|
|
|
|
|
|
|
# Get a list of already installed *models* so that references work right.
|
|
|
|
tables = connection.introspection.table_names()
|
|
|
|
seen_models = connection.introspection.installed_models(tables)
|
|
|
|
created_models = set()
|
|
|
|
pending_references = {}
|
|
|
|
|
|
|
|
# Build the manifest of apps and models that are to be synchronized
|
|
|
|
all_models = [
|
2013-12-14 17:08:44 +08:00
|
|
|
(app_config.label,
|
|
|
|
router.get_migratable_models(app_config.models_module, connection.alias, include_auto_created=True))
|
2013-12-15 01:51:58 +08:00
|
|
|
for app_config in app_cache.get_app_configs(only_with_models_module=True)
|
2013-12-14 17:08:44 +08:00
|
|
|
if app_config.label in apps
|
2013-06-08 01:47:17 +08:00
|
|
|
]
|
|
|
|
|
|
|
|
def model_installed(model):
|
|
|
|
opts = model._meta
|
|
|
|
converter = connection.introspection.table_name_converter
|
|
|
|
# Note that if a model is unmanaged we short-circuit and never try to install it
|
|
|
|
return not ((converter(opts.db_table) in tables) or
|
|
|
|
(opts.auto_created and converter(opts.auto_created._meta.db_table) in tables))
|
|
|
|
|
2013-08-09 21:17:30 +08:00
|
|
|
manifest = OrderedDict(
|
2013-06-08 01:47:17 +08:00
|
|
|
(app_name, list(filter(model_installed, model_list)))
|
|
|
|
for app_name, model_list in all_models
|
|
|
|
)
|
|
|
|
|
2013-08-30 07:20:00 +08:00
|
|
|
create_models = set(itertools.chain(*manifest.values()))
|
2013-07-30 18:52:52 +08:00
|
|
|
emit_pre_migrate_signal(create_models, self.verbosity, self.interactive, connection.alias)
|
2013-06-08 01:47:17 +08:00
|
|
|
|
|
|
|
# Create the tables for each model
|
|
|
|
if self.verbosity >= 1:
|
|
|
|
self.stdout.write(" Creating tables...\n")
|
2013-07-26 23:39:44 +08:00
|
|
|
with transaction.atomic(using=connection.alias, savepoint=False):
|
2013-06-08 01:47:17 +08:00
|
|
|
for app_name, model_list in manifest.items():
|
|
|
|
for model in model_list:
|
|
|
|
# Create the model's database table, if it doesn't already exist.
|
|
|
|
if self.verbosity >= 3:
|
|
|
|
self.stdout.write(" Processing %s.%s model\n" % (app_name, model._meta.object_name))
|
2013-06-19 22:36:22 +08:00
|
|
|
sql, references = connection.creation.sql_create_model(model, no_style(), seen_models)
|
2013-06-08 01:47:17 +08:00
|
|
|
seen_models.add(model)
|
|
|
|
created_models.add(model)
|
|
|
|
for refto, refs in references.items():
|
|
|
|
pending_references.setdefault(refto, []).extend(refs)
|
|
|
|
if refto in seen_models:
|
2013-06-19 22:36:22 +08:00
|
|
|
sql.extend(connection.creation.sql_for_pending_references(refto, no_style(), pending_references))
|
|
|
|
sql.extend(connection.creation.sql_for_pending_references(model, no_style(), pending_references))
|
2013-06-08 01:47:17 +08:00
|
|
|
if self.verbosity >= 1 and sql:
|
|
|
|
self.stdout.write(" Creating table %s\n" % model._meta.db_table)
|
|
|
|
for statement in sql:
|
|
|
|
cursor.execute(statement)
|
|
|
|
tables.append(connection.introspection.table_name_converter(model._meta.db_table))
|
2013-07-26 23:47:00 +08:00
|
|
|
|
2013-07-26 23:39:44 +08:00
|
|
|
# We force a commit here, as that was the previous behaviour.
|
|
|
|
# If you can prove we don't need this, remove it.
|
|
|
|
transaction.set_dirty(using=connection.alias)
|
2013-06-08 01:47:17 +08:00
|
|
|
|
|
|
|
# The connection may have been closed by a syncdb handler.
|
|
|
|
cursor = connection.cursor()
|
|
|
|
|
|
|
|
# Install custom SQL for the app (but only if this
|
|
|
|
# is a model we've just created)
|
|
|
|
if self.verbosity >= 1:
|
|
|
|
self.stdout.write(" Installing custom SQL...\n")
|
|
|
|
for app_name, model_list in manifest.items():
|
|
|
|
for model in model_list:
|
|
|
|
if model in created_models:
|
2013-06-19 22:36:22 +08:00
|
|
|
custom_sql = custom_sql_for_model(model, no_style(), connection)
|
2013-06-08 01:47:17 +08:00
|
|
|
if custom_sql:
|
|
|
|
if self.verbosity >= 2:
|
|
|
|
self.stdout.write(" Installing custom SQL for %s.%s model\n" % (app_name, model._meta.object_name))
|
|
|
|
try:
|
|
|
|
with transaction.commit_on_success_unless_managed(using=connection.alias):
|
|
|
|
for sql in custom_sql:
|
|
|
|
cursor.execute(sql)
|
|
|
|
except Exception as e:
|
|
|
|
self.stderr.write(" Failed to install custom SQL for %s.%s model: %s\n" % (app_name, model._meta.object_name, e))
|
|
|
|
if self.show_traceback:
|
|
|
|
traceback.print_exc()
|
|
|
|
else:
|
|
|
|
if self.verbosity >= 3:
|
|
|
|
self.stdout.write(" No custom SQL for %s.%s model\n" % (app_name, model._meta.object_name))
|
|
|
|
|
|
|
|
if self.verbosity >= 1:
|
|
|
|
self.stdout.write(" Installing indexes...\n")
|
2013-07-30 18:52:52 +08:00
|
|
|
|
2013-06-08 01:47:17 +08:00
|
|
|
# Install SQL indices for all newly created models
|
|
|
|
for app_name, model_list in manifest.items():
|
|
|
|
for model in model_list:
|
|
|
|
if model in created_models:
|
2013-06-19 22:36:22 +08:00
|
|
|
index_sql = connection.creation.sql_indexes_for_model(model, no_style())
|
2013-06-08 01:47:17 +08:00
|
|
|
if index_sql:
|
|
|
|
if self.verbosity >= 2:
|
|
|
|
self.stdout.write(" Installing index for %s.%s model\n" % (app_name, model._meta.object_name))
|
|
|
|
try:
|
|
|
|
with transaction.commit_on_success_unless_managed(using=connection.alias):
|
|
|
|
for sql in index_sql:
|
|
|
|
cursor.execute(sql)
|
|
|
|
except Exception as e:
|
|
|
|
self.stderr.write(" Failed to install index for %s.%s model: %s\n" % (app_name, model._meta.object_name, e))
|
|
|
|
|
|
|
|
# Load initial_data fixtures (unless that has been disabled)
|
|
|
|
if self.load_initial_data:
|
|
|
|
call_command('loaddata', 'initial_data', verbosity=self.verbosity, database=connection.alias, skip_validation=True)
|
2013-07-30 18:52:52 +08:00
|
|
|
|
|
|
|
return created_models
|
2013-09-07 00:05:50 +08:00
|
|
|
|
|
|
|
def show_migration_list(self, connection, apps=None):
|
|
|
|
"""
|
|
|
|
Shows a list of all migrations on the system, or only those of
|
|
|
|
some named apps.
|
|
|
|
"""
|
|
|
|
# Load migrations from disk/DB
|
|
|
|
loader = MigrationLoader(connection)
|
|
|
|
graph = loader.graph
|
|
|
|
# If we were passed a list of apps, validate it
|
|
|
|
if apps:
|
|
|
|
invalid_apps = []
|
|
|
|
for app in apps:
|
2013-09-17 17:54:55 +08:00
|
|
|
if app not in loader.migrated_apps:
|
2013-09-07 00:05:50 +08:00
|
|
|
invalid_apps.append(app)
|
|
|
|
if invalid_apps:
|
|
|
|
raise CommandError("No migrations present for: %s" % (", ".join(invalid_apps)))
|
|
|
|
# Otherwise, show all apps in alphabetic order
|
|
|
|
else:
|
|
|
|
apps = sorted(loader.migrated_apps)
|
|
|
|
# For each app, print its migrations in order from oldest (roots) to
|
|
|
|
# newest (leaves).
|
|
|
|
for app in apps:
|
|
|
|
self.stdout.write(app, self.style.MIGRATE_LABEL)
|
|
|
|
shown = set()
|
|
|
|
for node in graph.leaf_nodes(app):
|
|
|
|
for plan_node in graph.forwards_plan(node):
|
|
|
|
if plan_node not in shown and plan_node[0] == app:
|
2013-10-16 19:00:07 +08:00
|
|
|
# Give it a nice title if it's a squashed one
|
|
|
|
title = plan_node[1]
|
|
|
|
if graph.nodes[plan_node].replaces:
|
|
|
|
title += " (%s squashed migrations)" % len(graph.nodes[plan_node].replaces)
|
|
|
|
# Mark it as applied/unapplied
|
2013-09-07 00:05:50 +08:00
|
|
|
if plan_node in loader.applied_migrations:
|
2013-10-16 19:00:07 +08:00
|
|
|
self.stdout.write(" [X] %s" % title)
|
2013-09-07 00:05:50 +08:00
|
|
|
else:
|
2013-10-16 19:00:07 +08:00
|
|
|
self.stdout.write(" [ ] %s" % title)
|
2013-09-07 00:05:50 +08:00
|
|
|
shown.add(plan_node)
|
|
|
|
# If we didn't print anything, then a small message
|
|
|
|
if not shown:
|
|
|
|
self.stdout.write(" (no migrations)", self.style.MIGRATE_FAILURE)
|