2013-06-19 23:23:52 +08:00
|
|
|
import os
|
2015-01-28 20:35:27 +08:00
|
|
|
import sys
|
2020-04-26 02:54:20 +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
|
2016-09-02 04:19:29 +08:00
|
|
|
from django.conf import settings
|
2013-02-04 21:35:52 +08:00
|
|
|
from django.core.management.base import (
|
|
|
|
BaseCommand, CommandError, no_translations,
|
|
|
|
)
|
2020-04-26 02:54:20 +08:00
|
|
|
from django.db import DEFAULT_DB_ALIAS, OperationalError, connections, router
|
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
|
2016-05-11 20:19:19 +08:00
|
|
|
from django.db.migrations.utils import get_migration_name_timestamp
|
2013-06-19 23:23:52 +08:00
|
|
|
from django.db.migrations.writer import MigrationWriter
|
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):
|
2016-03-29 06:33:29 +08:00
|
|
|
parser.add_argument(
|
|
|
|
'args', metavar='app_label', nargs='*',
|
|
|
|
help='Specify the app label(s) to create migrations for.',
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
2018-07-03 05:54:57 +08:00
|
|
|
'--dry-run', action='store_true',
|
2016-03-29 06:33:29 +08:00
|
|
|
help="Just show what migrations would be made; don't actually write them.",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
2018-07-03 05:54:57 +08:00
|
|
|
'--merge', action='store_true',
|
2016-03-29 06:33:29 +08:00
|
|
|
help="Enable fixing of migration conflicts.",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
2018-07-03 05:54:57 +08:00
|
|
|
'--empty', action='store_true',
|
2016-03-29 06:33:29 +08:00
|
|
|
help="Create an empty migration.",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
2017-04-02 08:03:56 +08:00
|
|
|
'--noinput', '--no-input', action='store_false', dest='interactive',
|
2016-03-29 06:33:29 +08:00
|
|
|
help='Tells Django to NOT prompt the user for input of any kind.',
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
2018-07-03 05:54:57 +08:00
|
|
|
'-n', '--name',
|
2016-03-29 06:33:29 +08:00
|
|
|
help="Use this name for migration file(s).",
|
|
|
|
)
|
2018-12-19 19:41:31 +08:00
|
|
|
parser.add_argument(
|
|
|
|
'--no-header', action='store_false', dest='include_header',
|
|
|
|
help='Do not add header comments to new migration file(s).',
|
|
|
|
)
|
2016-03-29 06:33:29 +08:00
|
|
|
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
|
|
|
|
2013-02-04 21:35:52 +08:00
|
|
|
@no_translations
|
2013-06-19 22:36:22 +08:00
|
|
|
def handle(self, *app_labels, **options):
|
2016-03-03 10:01:36 +08:00
|
|
|
self.verbosity = options['verbosity']
|
|
|
|
self.interactive = options['interactive']
|
|
|
|
self.dry_run = options['dry_run']
|
|
|
|
self.merge = options['merge']
|
|
|
|
self.empty = options['empty']
|
|
|
|
self.migration_name = options['name']
|
2018-10-19 14:56:33 +08:00
|
|
|
if self.migration_name and not self.migration_name.isidentifier():
|
|
|
|
raise CommandError('The migration name must be a valid Python identifier.')
|
2018-12-19 19:41:31 +08:00
|
|
|
self.include_header = options['include_header']
|
2015-10-21 08:39:48 +08:00
|
|
|
check_changes = options['check_changes']
|
|
|
|
|
2013-06-19 22:36:22 +08:00
|
|
|
# Make sure the app they asked for exists
|
|
|
|
app_labels = set(app_labels)
|
2018-06-19 15:34:25 +08:00
|
|
|
has_bad_labels = False
|
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)
|
2018-06-19 15:34:25 +08:00
|
|
|
except LookupError as err:
|
|
|
|
self.stderr.write(str(err))
|
|
|
|
has_bad_labels = True
|
|
|
|
if has_bad_labels:
|
2013-08-11 03:02:55 +08:00
|
|
|
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
|
|
|
|
2016-04-02 20:46:59 +08:00
|
|
|
# Raise an error if any migrations are applied before their dependencies.
|
2017-06-02 07:08:59 +08:00
|
|
|
consistency_check_labels = {config.label for config in apps.get_app_configs()}
|
2016-09-02 04:19:29 +08:00
|
|
|
# Non-default databases are only checked if database routers used.
|
|
|
|
aliases_to_check = connections if settings.DATABASE_ROUTERS else [DEFAULT_DB_ALIAS]
|
|
|
|
for alias in sorted(aliases_to_check):
|
|
|
|
connection = connections[alias]
|
2016-10-13 09:19:56 +08:00
|
|
|
if (connection.settings_dict['ENGINE'] != 'django.db.backends.dummy' and any(
|
|
|
|
# At least one model must be migrated to the database.
|
|
|
|
router.allow_migrate(connection.alias, app_label, model_name=model._meta.object_name)
|
|
|
|
for app_label in consistency_check_labels
|
2016-11-09 23:27:19 +08:00
|
|
|
for model in apps.get_app_config(app_label).get_models()
|
2016-10-13 09:19:56 +08:00
|
|
|
)):
|
2020-04-26 02:54:20 +08:00
|
|
|
try:
|
|
|
|
loader.check_consistent_history(connection)
|
|
|
|
except OperationalError as error:
|
|
|
|
warnings.warn(
|
|
|
|
"Got an error checking a consistent migration history "
|
2020-06-07 07:05:39 +08:00
|
|
|
"performed for database connection '%s': %s"
|
2020-04-26 02:54:20 +08:00
|
|
|
% (alias, error),
|
|
|
|
RuntimeWarning,
|
|
|
|
)
|
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 = {
|
2017-01-07 19:11:46 +08:00
|
|
|
app_label: conflict for app_label, conflict in conflicts.items()
|
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:
|
2017-11-30 00:54:34 +08:00
|
|
|
if app_labels:
|
|
|
|
if len(app_labels) == 1:
|
|
|
|
self.stdout.write("No changes detected in app '%s'" % app_labels.pop())
|
|
|
|
else:
|
|
|
|
self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels)))
|
2014-11-11 12:41:55 +08:00
|
|
|
else:
|
|
|
|
self.stdout.write("No changes detected")
|
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):
|
|
|
|
"""
|
2017-01-26 03:02:33 +08:00
|
|
|
Take a changes dict and write them out as migration files.
|
2014-02-13 01:16:40 +08:00
|
|
|
"""
|
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:
|
2020-04-25 21:51:17 +08:00
|
|
|
self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label))
|
2013-12-05 22:10:58 +08:00
|
|
|
for migration in app_migrations:
|
2013-06-19 23:23:52 +08:00
|
|
|
# Describe the migration
|
2018-12-19 19:41:31 +08:00
|
|
|
writer = MigrationWriter(migration, self.include_header)
|
2013-09-01 23:42:43 +08:00
|
|
|
if self.verbosity >= 1:
|
2015-11-07 21:43:06 +08:00
|
|
|
# Display a relative path if it's below the current working
|
|
|
|
# directory, or an absolute path otherwise.
|
2016-11-09 07:06:17 +08:00
|
|
|
try:
|
|
|
|
migration_string = os.path.relpath(writer.path)
|
|
|
|
except ValueError:
|
|
|
|
migration_string = writer.path
|
2015-11-07 21:43:06 +08:00
|
|
|
if migration_string.startswith('..'):
|
|
|
|
migration_string = writer.path
|
2020-04-25 21:51:17 +08:00
|
|
|
self.stdout.write(' %s\n' % self.style.MIGRATE_LABEL(migration_string))
|
2013-09-01 23:42:43 +08:00
|
|
|
for operation in migration.operations:
|
2020-04-25 21:51:17 +08:00
|
|
|
self.stdout.write(' - %s' % 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):
|
2019-01-31 23:12:55 +08:00
|
|
|
os.makedirs(migrations_directory, exist_ok=True)
|
2013-12-04 21:55:20 +08:00
|
|
|
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()
|
2017-01-19 05:05:41 +08:00
|
|
|
with open(writer.path, "w", encoding='utf-8') as fh:
|
2013-12-04 21:55:20 +08:00
|
|
|
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(
|
2020-04-25 21:51:17 +08:00
|
|
|
"Full migrations file '%s':" % writer.filename
|
|
|
|
))
|
|
|
|
self.stdout.write(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)
|
2016-01-24 00:47:07 +08:00
|
|
|
|
|
|
|
def all_items_equal(seq):
|
|
|
|
return all(item == seq[0] for item in seq[1:])
|
|
|
|
|
2017-04-26 12:04:10 +08:00
|
|
|
merge_migrations_generations = zip(*(m.ancestry for m in merge_migrations))
|
2014-11-13 07:06:12 +08:00
|
|
|
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:
|
2020-04-25 21:51:17 +08:00
|
|
|
self.stdout.write(' - %s' % operation.describe())
|
2013-12-05 00:01:31 +08:00
|
|
|
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
|
2017-12-29 04:07:29 +08:00
|
|
|
subclass = type("Migration", (Migration,), {
|
2013-12-05 00:01:31 +08:00
|
|
|
"dependencies": [(app_label, migration.name) for migration in merge_migrations],
|
|
|
|
})
|
2020-07-07 08:08:25 +08:00
|
|
|
parts = ['%04i' % (biggest_number + 1)]
|
|
|
|
if self.migration_name:
|
|
|
|
parts.append(self.migration_name)
|
|
|
|
else:
|
|
|
|
parts.append('merge')
|
|
|
|
leaf_names = '_'.join(sorted(migration.name for migration in merge_migrations))
|
|
|
|
if len(leaf_names) > 47:
|
|
|
|
parts.append(get_migration_name_timestamp())
|
|
|
|
else:
|
|
|
|
parts.append(leaf_names)
|
|
|
|
migration_name = '_'.join(parts)
|
2016-05-11 20:19:19 +08:00
|
|
|
new_migration = subclass(migration_name, app_label)
|
2018-12-19 19:41:31 +08:00
|
|
|
writer = MigrationWriter(new_migration, self.include_header)
|
2015-03-03 06:13:14 +08:00
|
|
|
|
|
|
|
if not self.dry_run:
|
|
|
|
# Write the merge migrations file to the disk
|
2017-01-19 05:05:41 +08:00
|
|
|
with open(writer.path, "w", encoding='utf-8') as fh:
|
2015-03-03 06:13:14 +08:00
|
|
|
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(
|
2020-04-25 21:51:17 +08:00
|
|
|
"Full merge migrations file '%s':" % writer.filename
|
|
|
|
))
|
|
|
|
self.stdout.write(writer.as_string())
|