2013-06-19 23:23:52 +08:00
|
|
|
import os
|
2015-01-28 20:35:27 +08:00
|
|
|
import sys
|
2015-10-21 08:39:48 +08:00
|
|
|
import warnings
|
2015-01-28 20:35:27 +08:00
|
|
|
from itertools import takewhile
|
2013-06-19 22:36:22 +08:00
|
|
|
|
2013-12-24 19:25:17 +08:00
|
|
|
from django.apps import apps
|
2013-12-05 00:01:31 +08:00
|
|
|
from django.core.management.base import BaseCommand, CommandError
|
2014-05-09 01:39:09 +08:00
|
|
|
from django.db.migrations import Migration
|
2013-12-05 00:01:31 +08:00
|
|
|
from django.db.migrations.autodetector import MigrationAutodetector
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.db.migrations.loader import MigrationLoader
|
|
|
|
from django.db.migrations.questioner import (
|
|
|
|
InteractiveMigrationQuestioner, MigrationQuestioner,
|
2015-03-07 20:53:13 +08:00
|
|
|
NonInteractiveMigrationQuestioner,
|
2015-01-28 20:35:27 +08:00
|
|
|
)
|
2013-06-19 22:36:22 +08:00
|
|
|
from django.db.migrations.state import ProjectState
|
2013-06-19 23:23:52 +08:00
|
|
|
from django.db.migrations.writer import MigrationWriter
|
2015-10-21 08:39:48 +08:00
|
|
|
from django.utils.deprecation import RemovedInDjango20Warning
|
2014-06-20 03:24:59 +08:00
|
|
|
from django.utils.six import iteritems
|
2014-11-13 07:06:12 +08:00
|
|
|
from django.utils.six.moves import zip
|
2013-06-19 22:36:22 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Command(BaseCommand):
|
|
|
|
help = "Creates new migration(s) for apps."
|
2014-06-07 04:39:33 +08:00
|
|
|
|
|
|
|
def add_arguments(self, parser):
|
|
|
|
parser.add_argument('args', metavar='app_label', nargs='*',
|
|
|
|
help='Specify the app label(s) to create migrations for.')
|
|
|
|
parser.add_argument('--dry-run', action='store_true', dest='dry_run', default=False,
|
|
|
|
help="Just show what migrations would be made; don't actually write them.")
|
|
|
|
parser.add_argument('--merge', action='store_true', dest='merge', default=False,
|
|
|
|
help="Enable fixing of migration conflicts.")
|
|
|
|
parser.add_argument('--empty', action='store_true', dest='empty', default=False,
|
|
|
|
help="Create an empty migration.")
|
2015-09-07 21:17:55 +08:00
|
|
|
parser.add_argument('--noinput', '--no-input',
|
|
|
|
action='store_false', dest='interactive', default=True,
|
2014-06-20 07:50:01 +08:00
|
|
|
help='Tells Django to NOT prompt the user for input of any kind.')
|
2014-08-19 21:24:31 +08:00
|
|
|
parser.add_argument('-n', '--name', action='store', dest='name', default=None,
|
|
|
|
help="Use this name for migration file(s).")
|
2014-11-11 12:41:55 +08:00
|
|
|
parser.add_argument('-e', '--exit', action='store_true', dest='exit_code', default=False,
|
2015-10-21 08:39:48 +08:00
|
|
|
help='Exit with error code 1 if no changes needing migrations are found. '
|
|
|
|
'Deprecated, use the --check option instead.')
|
|
|
|
parser.add_argument('--check', action='store_true', dest='check_changes',
|
|
|
|
help='Exit with a non-zero status if model changes are missing migrations.')
|
2013-06-19 22:36:22 +08:00
|
|
|
|
|
|
|
def handle(self, *app_labels, **options):
|
2014-06-07 04:39:33 +08:00
|
|
|
self.verbosity = options.get('verbosity')
|
2013-06-19 22:36:22 +08:00
|
|
|
self.interactive = options.get('interactive')
|
2013-12-04 21:55:20 +08:00
|
|
|
self.dry_run = options.get('dry_run', False)
|
2013-12-05 00:01:31 +08:00
|
|
|
self.merge = options.get('merge', False)
|
2014-02-13 01:16:40 +08:00
|
|
|
self.empty = options.get('empty', False)
|
2015-05-14 02:51:18 +08:00
|
|
|
self.migration_name = options.get('name')
|
2014-11-11 12:41:55 +08:00
|
|
|
self.exit_code = options.get('exit_code', False)
|
2015-10-21 08:39:48 +08:00
|
|
|
check_changes = options['check_changes']
|
|
|
|
|
|
|
|
if self.exit_code:
|
|
|
|
warnings.warn(
|
|
|
|
"The --exit option is deprecated in favor of the --check option.",
|
|
|
|
RemovedInDjango20Warning
|
|
|
|
)
|
2013-06-19 22:36:22 +08:00
|
|
|
|
|
|
|
# Make sure the app they asked for exists
|
|
|
|
app_labels = set(app_labels)
|
2013-08-11 03:02:55 +08:00
|
|
|
bad_app_labels = set()
|
2013-06-19 22:36:22 +08:00
|
|
|
for app_label in app_labels:
|
|
|
|
try:
|
2013-12-24 19:25:17 +08:00
|
|
|
apps.get_app_config(app_label)
|
2013-12-14 18:11:52 +08:00
|
|
|
except LookupError:
|
2013-08-11 03:02:55 +08:00
|
|
|
bad_app_labels.add(app_label)
|
|
|
|
if bad_app_labels:
|
|
|
|
for app_label in bad_app_labels:
|
|
|
|
self.stderr.write("App '%s' could not be found. Is it in INSTALLED_APPS?" % app_label)
|
|
|
|
sys.exit(2)
|
2013-06-19 22:36:22 +08:00
|
|
|
|
2014-05-07 13:41:59 +08:00
|
|
|
# Load the current graph state. Pass in None for the connection so
|
|
|
|
# the loader doesn't try to resolve replaced migrations from DB.
|
2014-06-17 00:58:35 +08:00
|
|
|
loader = MigrationLoader(None, ignore_no_migrations=True)
|
2013-06-19 22:36:22 +08:00
|
|
|
|
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 and they don't want to merge
|
|
|
|
conflicts = loader.detect_conflicts()
|
2014-06-20 03:24:59 +08:00
|
|
|
|
|
|
|
# If app_labels is specified, filter out conflicting migrations for unspecified apps
|
|
|
|
if app_labels:
|
2014-12-07 05:00:09 +08:00
|
|
|
conflicts = {
|
|
|
|
app_label: conflict for app_label, conflict in iteritems(conflicts)
|
2014-06-20 03:24:59 +08:00
|
|
|
if app_label in app_labels
|
2014-12-07 05:00:09 +08:00
|
|
|
}
|
2014-06-20 03:24:59 +08:00
|
|
|
|
2013-12-05 00:01:31 +08:00
|
|
|
if conflicts and not self.merge:
|
|
|
|
name_str = "; ".join(
|
|
|
|
"%s in %s" % (", ".join(names), app)
|
|
|
|
for app, names in conflicts.items()
|
|
|
|
)
|
2014-09-04 20:15:09 +08:00
|
|
|
raise CommandError(
|
2015-08-21 06:56:57 +08:00
|
|
|
"Conflicting migrations detected; multiple leaf nodes in the "
|
|
|
|
"migration graph: (%s).\nTo fix them run "
|
2014-09-04 20:15:09 +08:00
|
|
|
"'python manage.py makemigrations --merge'" % name_str
|
|
|
|
)
|
2013-12-05 00:01:31 +08:00
|
|
|
|
|
|
|
# If they want to merge and there's nothing to merge, then politely exit
|
|
|
|
if self.merge and not conflicts:
|
|
|
|
self.stdout.write("No conflicts detected to merge.")
|
|
|
|
return
|
|
|
|
|
|
|
|
# If they want to merge and there is something to merge, then
|
|
|
|
# divert into the merge code
|
|
|
|
if self.merge and conflicts:
|
|
|
|
return self.handle_merge(loader, conflicts)
|
|
|
|
|
2015-03-07 20:53:13 +08:00
|
|
|
if self.interactive:
|
|
|
|
questioner = InteractiveMigrationQuestioner(specified_apps=app_labels, dry_run=self.dry_run)
|
|
|
|
else:
|
|
|
|
questioner = NonInteractiveMigrationQuestioner(specified_apps=app_labels, dry_run=self.dry_run)
|
2014-02-13 01:16:40 +08:00
|
|
|
# Set up autodetector
|
2013-06-19 22:36:22 +08:00
|
|
|
autodetector = MigrationAutodetector(
|
2014-05-01 03:25:12 +08:00
|
|
|
loader.project_state(),
|
2013-12-24 19:25:17 +08:00
|
|
|
ProjectState.from_apps(apps),
|
2015-03-07 20:53:13 +08:00
|
|
|
questioner,
|
2013-06-19 22:36:22 +08:00
|
|
|
)
|
2014-02-13 01:16:40 +08:00
|
|
|
|
|
|
|
# If they want to make an empty migration, make one for each app
|
|
|
|
if self.empty:
|
|
|
|
if not app_labels:
|
|
|
|
raise CommandError("You must supply at least one app label when using --empty.")
|
|
|
|
# Make a fake changes() result we can pass to arrange_for_graph
|
2014-12-07 05:00:09 +08:00
|
|
|
changes = {
|
|
|
|
app: [Migration("custom", app)]
|
2014-02-13 01:16:40 +08:00
|
|
|
for app in app_labels
|
2014-12-07 05:00:09 +08:00
|
|
|
}
|
2014-08-19 21:24:31 +08:00
|
|
|
changes = autodetector.arrange_for_graph(
|
|
|
|
changes=changes,
|
|
|
|
graph=loader.graph,
|
|
|
|
migration_name=self.migration_name,
|
|
|
|
)
|
2014-02-13 01:16:40 +08:00
|
|
|
self.write_migration_files(changes)
|
|
|
|
return
|
|
|
|
|
|
|
|
# Detect changes
|
2014-06-09 08:12:27 +08:00
|
|
|
changes = autodetector.changes(
|
|
|
|
graph=loader.graph,
|
|
|
|
trim_to_apps=app_labels or None,
|
|
|
|
convert_apps=app_labels or None,
|
2014-08-19 21:24:31 +08:00
|
|
|
migration_name=self.migration_name,
|
2014-06-09 08:12:27 +08:00
|
|
|
)
|
2013-06-19 22:36:22 +08:00
|
|
|
|
2014-11-11 12:41:55 +08:00
|
|
|
if not changes:
|
|
|
|
# No changes? Tell them.
|
|
|
|
if self.verbosity >= 1:
|
|
|
|
if len(app_labels) == 1:
|
|
|
|
self.stdout.write("No changes detected in app '%s'" % app_labels.pop())
|
|
|
|
elif len(app_labels) > 1:
|
|
|
|
self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels)))
|
|
|
|
else:
|
|
|
|
self.stdout.write("No changes detected")
|
|
|
|
|
|
|
|
if self.exit_code:
|
|
|
|
sys.exit(1)
|
2015-10-21 08:39:48 +08:00
|
|
|
else:
|
|
|
|
self.write_migration_files(changes)
|
|
|
|
if check_changes:
|
|
|
|
sys.exit(1)
|
2014-02-13 01:16:40 +08:00
|
|
|
|
|
|
|
def write_migration_files(self, changes):
|
|
|
|
"""
|
|
|
|
Takes a changes dict and writes them out as migration files.
|
|
|
|
"""
|
2013-08-22 05:27:46 +08:00
|
|
|
directory_created = {}
|
2013-12-05 22:10:58 +08:00
|
|
|
for app_label, app_migrations in changes.items():
|
2013-09-01 23:42:43 +08:00
|
|
|
if self.verbosity >= 1:
|
|
|
|
self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label) + "\n")
|
2013-12-05 22:10:58 +08:00
|
|
|
for migration in app_migrations:
|
2013-06-19 23:23:52 +08:00
|
|
|
# Describe the migration
|
|
|
|
writer = MigrationWriter(migration)
|
2013-09-01 23:42:43 +08:00
|
|
|
if self.verbosity >= 1:
|
|
|
|
self.stdout.write(" %s:\n" % (self.style.MIGRATE_LABEL(writer.filename),))
|
|
|
|
for operation in migration.operations:
|
|
|
|
self.stdout.write(" - %s\n" % operation.describe())
|
2013-12-04 21:55:20 +08:00
|
|
|
if not self.dry_run:
|
2014-05-27 04:09:17 +08:00
|
|
|
# Write the migrations file to the disk.
|
2013-12-04 21:55:20 +08:00
|
|
|
migrations_directory = os.path.dirname(writer.path)
|
2015-05-14 02:51:18 +08:00
|
|
|
if not directory_created.get(app_label):
|
2013-12-04 21:55:20 +08:00
|
|
|
if not os.path.isdir(migrations_directory):
|
|
|
|
os.mkdir(migrations_directory)
|
|
|
|
init_path = os.path.join(migrations_directory, "__init__.py")
|
|
|
|
if not os.path.isfile(init_path):
|
|
|
|
open(init_path, "w").close()
|
|
|
|
# We just do this once per app
|
|
|
|
directory_created[app_label] = True
|
|
|
|
migration_string = writer.as_string()
|
|
|
|
with open(writer.path, "wb") as fh:
|
|
|
|
fh.write(migration_string)
|
2014-05-27 04:09:17 +08:00
|
|
|
elif self.verbosity == 3:
|
|
|
|
# Alternatively, makemigrations --dry-run --verbosity 3
|
|
|
|
# will output the migrations to stdout rather than saving
|
|
|
|
# the file to the disk.
|
2014-09-04 20:15:09 +08:00
|
|
|
self.stdout.write(self.style.MIGRATE_HEADING(
|
|
|
|
"Full migrations file '%s':" % writer.filename) + "\n"
|
|
|
|
)
|
2014-05-27 04:09:17 +08:00
|
|
|
self.stdout.write("%s\n" % writer.as_string())
|
2013-12-05 00:01:31 +08:00
|
|
|
|
|
|
|
def handle_merge(self, loader, conflicts):
|
|
|
|
"""
|
|
|
|
Handles merging together conflicted migrations interactively,
|
|
|
|
if it's safe; otherwise, advises on how to fix it.
|
|
|
|
"""
|
|
|
|
if self.interactive:
|
|
|
|
questioner = InteractiveMigrationQuestioner()
|
|
|
|
else:
|
2014-06-20 07:50:01 +08:00
|
|
|
questioner = MigrationQuestioner(defaults={'ask_merge': True})
|
2015-08-09 21:53:09 +08:00
|
|
|
|
2013-12-05 00:01:31 +08:00
|
|
|
for app_label, migration_names in conflicts.items():
|
|
|
|
# Grab out the migrations in question, and work out their
|
|
|
|
# common ancestor.
|
|
|
|
merge_migrations = []
|
|
|
|
for migration_name in migration_names:
|
|
|
|
migration = loader.get_migration(app_label, migration_name)
|
2015-08-09 21:53:09 +08:00
|
|
|
migration.ancestry = [
|
|
|
|
mig for mig in loader.graph.forwards_plan((app_label, migration_name))
|
|
|
|
if mig[0] == migration.app_label
|
|
|
|
]
|
2013-12-05 00:01:31 +08:00
|
|
|
merge_migrations.append(migration)
|
2014-11-13 07:06:12 +08:00
|
|
|
all_items_equal = lambda seq: all(item == seq[0] for item in seq[1:])
|
|
|
|
merge_migrations_generations = zip(*[m.ancestry for m in merge_migrations])
|
|
|
|
common_ancestor_count = sum(1 for common_ancestor_generation
|
|
|
|
in takewhile(all_items_equal, merge_migrations_generations))
|
|
|
|
if not common_ancestor_count:
|
2013-12-05 00:01:31 +08:00
|
|
|
raise ValueError("Could not find common ancestor of %s" % migration_names)
|
|
|
|
# Now work out the operations along each divergent branch
|
|
|
|
for migration in merge_migrations:
|
2014-11-13 07:06:12 +08:00
|
|
|
migration.branch = migration.ancestry[common_ancestor_count:]
|
|
|
|
migrations_ops = (loader.get_migration(node_app, node_name).operations
|
|
|
|
for node_app, node_name in migration.branch)
|
|
|
|
migration.merged_operations = sum(migrations_ops, [])
|
2013-12-05 00:01:31 +08:00
|
|
|
# In future, this could use some of the Optimizer code
|
|
|
|
# (can_optimize_through) to automatically see if they're
|
|
|
|
# mergeable. For now, we always just prompt the user.
|
|
|
|
if self.verbosity > 0:
|
|
|
|
self.stdout.write(self.style.MIGRATE_HEADING("Merging %s" % app_label))
|
|
|
|
for migration in merge_migrations:
|
|
|
|
self.stdout.write(self.style.MIGRATE_LABEL(" Branch %s" % migration.name))
|
|
|
|
for operation in migration.merged_operations:
|
|
|
|
self.stdout.write(" - %s\n" % operation.describe())
|
|
|
|
if questioner.ask_merge(app_label):
|
|
|
|
# If they still want to merge it, then write out an empty
|
|
|
|
# file depending on the migrations needing merging.
|
|
|
|
numbers = [
|
|
|
|
MigrationAutodetector.parse_number(migration.name)
|
|
|
|
for migration in merge_migrations
|
|
|
|
]
|
|
|
|
try:
|
2014-12-07 05:00:09 +08:00
|
|
|
biggest_number = max(x for x in numbers if x is not None)
|
2013-12-05 00:01:31 +08:00
|
|
|
except ValueError:
|
|
|
|
biggest_number = 1
|
2014-05-09 01:39:09 +08:00
|
|
|
subclass = type("Migration", (Migration, ), {
|
2013-12-05 00:01:31 +08:00
|
|
|
"dependencies": [(app_label, migration.name) for migration in merge_migrations],
|
|
|
|
})
|
|
|
|
new_migration = subclass("%04i_merge" % (biggest_number + 1), app_label)
|
|
|
|
writer = MigrationWriter(new_migration)
|
2015-03-03 06:13:14 +08:00
|
|
|
|
|
|
|
if not self.dry_run:
|
|
|
|
# Write the merge migrations file to the disk
|
|
|
|
with open(writer.path, "wb") as fh:
|
|
|
|
fh.write(writer.as_string())
|
|
|
|
if self.verbosity > 0:
|
|
|
|
self.stdout.write("\nCreated new merge migration %s" % writer.path)
|
|
|
|
elif self.verbosity == 3:
|
|
|
|
# Alternatively, makemigrations --merge --dry-run --verbosity 3
|
|
|
|
# will output the merge migrations to stdout rather than saving
|
|
|
|
# the file to the disk.
|
|
|
|
self.stdout.write(self.style.MIGRATE_HEADING(
|
|
|
|
"Full merge migrations file '%s':" % writer.filename) + "\n"
|
|
|
|
)
|
|
|
|
self.stdout.write("%s\n" % writer.as_string())
|