From 9e6d6316977d5668a1d2d1f77b861b2b9323dcdf Mon Sep 17 00:00:00 2001 From: andrewdotn Date: Tue, 2 Nov 2021 00:13:42 -0600 Subject: [PATCH] Fixed #33246 -- Made squashmigrations raise CommandError when squashed_name already exists. --- django/core/management/commands/squashmigrations.py | 6 ++++++ tests/migrations/test_commands.py | 9 +++++++++ 2 files changed, 15 insertions(+) diff --git a/django/core/management/commands/squashmigrations.py b/django/core/management/commands/squashmigrations.py index 65da95a19b..80fdc0cbc1 100644 --- a/django/core/management/commands/squashmigrations.py +++ b/django/core/management/commands/squashmigrations.py @@ -1,3 +1,5 @@ +import os + from django.apps import apps from django.conf import settings from django.core.management.base import BaseCommand, CommandError @@ -184,6 +186,10 @@ class Command(BaseCommand): # Write out the new migration file writer = MigrationWriter(new_migration, include_header) + if os.path.exists(writer.path): + raise CommandError( + f'Migration {new_migration.name} already exists. Use a different name.' + ) with open(writer.path, "w", encoding='utf-8') as fh: fh.write(writer.as_string()) diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py index 02e2a1ee11..9755af9f6d 100644 --- a/tests/migrations/test_commands.py +++ b/tests/migrations/test_commands.py @@ -2082,6 +2082,15 @@ class SquashMigrationsTests(MigrationTestBase): squashed_migration_file = os.path.join(migration_dir, '0001_%s.py' % squashed_name) self.assertTrue(os.path.exists(squashed_migration_file)) + def test_squashed_name_exists(self): + msg = 'Migration 0001_initial already exists. Use a different name.' + with self.temporary_migration_module(module='migrations.test_migrations'): + with self.assertRaisesMessage(CommandError, msg): + call_command( + 'squashmigrations', 'migrations', '0001', '0002', + squashed_name='initial', interactive=False, verbosity=0, + ) + class AppLabelErrorTests(TestCase): """