-
Notifications
You must be signed in to change notification settings - Fork 0
Remember instance refs and add safe rollback choices #530
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| """Move a database back to the migration leaves from an older release.""" | ||
|
|
||
| from pathlib import Path | ||
|
|
||
| from django.core.management.base import BaseCommand, CommandError, CommandParser | ||
| from django.db import connection | ||
| from django.db.migrations.executor import MigrationExecutor | ||
|
|
||
| MigrationTarget = tuple[str, str | None] | ||
|
|
||
|
|
||
| def read_migration_targets(path: Path) -> list[tuple[str, str]]: | ||
| targets: list[tuple[str, str]] = [] | ||
| for line_number, raw_line in enumerate( | ||
| path.read_text(encoding="utf-8").splitlines(), start=1 | ||
| ): | ||
| line = raw_line.strip() | ||
| if not line: | ||
| continue | ||
| parts = line.split("\t") | ||
| if len(parts) != 2 or not all(parts): | ||
| raise CommandError( | ||
| f"Invalid migration target at {path}:{line_number}: {raw_line!r}" | ||
| ) | ||
| targets.append((parts[0], parts[1])) | ||
| if not targets: | ||
| raise CommandError(f"No migration targets found in {path}") | ||
| return targets | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = "Plan or apply reverse migrations to an older release's leaf nodes." | ||
|
|
||
| def add_arguments(self, parser: CommandParser) -> None: | ||
| parser.add_argument("--targets-file", required=True) | ||
| parser.add_argument("--apply", action="store_true") | ||
|
|
||
| def handle(self, *args: object, **options: object) -> None: | ||
| targets_file = options["targets_file"] | ||
| apply_plan = options["apply"] | ||
| if not isinstance(targets_file, str): | ||
| raise CommandError("--targets-file must be a path") | ||
| if not isinstance(apply_plan, bool): | ||
| raise CommandError("--apply must be a boolean flag") | ||
|
|
||
| release_targets = read_migration_targets(Path(targets_file)) | ||
| target_apps = {app_label for app_label, _ in release_targets} | ||
| executor = MigrationExecutor(connection) | ||
| targets: list[MigrationTarget] = list(release_targets) | ||
| targets.extend( | ||
| (app_label, None) | ||
| for app_label in sorted(executor.loader.migrated_apps - target_apps) | ||
| ) | ||
|
|
||
| plan = executor.migration_plan(targets) | ||
| forward_migrations = [ | ||
| migration for migration, backwards in plan if not backwards | ||
| ] | ||
| if forward_migrations: | ||
| names = ", ".join( | ||
| f"{migration.app_label}.{migration.name}" | ||
| for migration in forward_migrations | ||
| ) | ||
| raise CommandError( | ||
| f"Target release would require forward migrations: {names}" | ||
| ) | ||
|
|
||
| irreversible = [ | ||
| migration | ||
| for migration, _ in plan | ||
| if not all(operation.reversible for operation in migration.operations) | ||
| ] | ||
| if irreversible: | ||
| names = ", ".join( | ||
| f"{migration.app_label}.{migration.name}" for migration in irreversible | ||
| ) | ||
| raise CommandError(f"Irreversible migrations in rollback plan: {names}") | ||
|
|
||
| if not plan: | ||
| self.stdout.write("No migration changes required.") | ||
| return | ||
|
|
||
| for migration, _ in plan: | ||
| self.stdout.write(f"UNAPPLY {migration.app_label}.{migration.name}") | ||
|
|
||
| if apply_plan: | ||
| executor.migrate(targets) | ||
| self.stdout.write(self.style.SUCCESS("Reverse migrations complete.")) | ||
| else: | ||
| self.stdout.write("Plan only; pass --apply to execute.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| from io import StringIO | ||
| from pathlib import Path | ||
| from tempfile import TemporaryDirectory | ||
| from unittest.mock import MagicMock, patch | ||
|
|
||
| from django.core.management.base import CommandError, OutputWrapper | ||
| from django.test import SimpleTestCase | ||
|
|
||
| from apps.workflow.management.commands.rollback_migrations import ( | ||
| Command, | ||
| read_migration_targets, | ||
| ) | ||
|
|
||
|
|
||
| class ReadMigrationTargetsTests(SimpleTestCase): | ||
| def test_reads_release_leaf_nodes(self) -> None: | ||
| with TemporaryDirectory() as temp_dir: | ||
| path = Path(temp_dir) / "targets.tsv" | ||
| path.write_text( | ||
| "company\t0007_people\njob\t0012_events\n", encoding="utf-8" | ||
| ) | ||
|
|
||
| self.assertEqual( | ||
| read_migration_targets(path), | ||
| [("company", "0007_people"), ("job", "0012_events")], | ||
| ) | ||
|
|
||
| def test_rejects_malformed_target(self) -> None: | ||
| with TemporaryDirectory() as temp_dir: | ||
| path = Path(temp_dir) / "targets.tsv" | ||
| path.write_text("company-only\n", encoding="utf-8") | ||
|
|
||
| with self.assertRaises(CommandError): | ||
| read_migration_targets(path) | ||
|
|
||
|
|
||
| class RollbackMigrationsCommandTests(SimpleTestCase): | ||
| def _targets_file(self, temp_dir: str) -> Path: | ||
| path = Path(temp_dir) / "targets.tsv" | ||
| path.write_text("company\t0007_people\n", encoding="utf-8") | ||
| return path | ||
|
|
||
| @patch("apps.workflow.management.commands.rollback_migrations.MigrationExecutor") | ||
| def test_empty_plan_reports_code_only_rollback( | ||
| self, executor_class: MagicMock | ||
| ) -> None: | ||
| executor = executor_class.return_value | ||
| executor.loader.migrated_apps = {"company"} | ||
| executor.migration_plan.return_value = [] | ||
| output = StringIO() | ||
| command = Command() | ||
| command.stdout = OutputWrapper(output) | ||
|
|
||
| with TemporaryDirectory() as temp_dir: | ||
| command.handle(targets_file=str(self._targets_file(temp_dir)), apply=False) | ||
|
|
||
| self.assertEqual(output.getvalue(), "No migration changes required.\n") | ||
| executor.migrate.assert_not_called() | ||
|
|
||
| @patch("apps.workflow.management.commands.rollback_migrations.MigrationExecutor") | ||
| def test_apply_executes_reversible_reverse_plan( | ||
| self, executor_class: MagicMock | ||
| ) -> None: | ||
| executor = executor_class.return_value | ||
| executor.loader.migrated_apps = {"company"} | ||
| migration = MagicMock() | ||
| migration.app_label = "company" | ||
| migration.name = "0008_new_field" | ||
| migration.operations = [MagicMock(reversible=True)] | ||
| executor.migration_plan.return_value = [(migration, True)] | ||
| output = StringIO() | ||
| command = Command() | ||
| command.stdout = OutputWrapper(output) | ||
|
|
||
| with TemporaryDirectory() as temp_dir: | ||
| command.handle(targets_file=str(self._targets_file(temp_dir)), apply=True) | ||
|
|
||
| self.assertIn("UNAPPLY company.0008_new_field", output.getvalue()) | ||
| executor.migrate.assert_called_once_with([("company", "0007_people")]) | ||
|
|
||
| @patch("apps.workflow.management.commands.rollback_migrations.MigrationExecutor") | ||
| def test_irreversible_reverse_plan_is_reported( | ||
| self, executor_class: MagicMock | ||
| ) -> None: | ||
| executor = executor_class.return_value | ||
| executor.loader.migrated_apps = {"company"} | ||
| migration = MagicMock() | ||
| migration.app_label = "company" | ||
| migration.name = "0008_irreversible" | ||
| migration.operations = [MagicMock(reversible=False)] | ||
| executor.migration_plan.return_value = [(migration, True)] | ||
|
|
||
| with ( | ||
| TemporaryDirectory() as temp_dir, | ||
| self.assertRaisesMessage( | ||
| CommandError, "Irreversible migrations in rollback plan" | ||
| ), | ||
| ): | ||
| Command().handle( | ||
| targets_file=str(self._targets_file(temp_dir)), apply=False | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.