:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(hogli): share rollback and apply logic across migration commands (#89686)
posthog[bot]0e738f26169c
diff --git a/tools/hogli-commands/hogli_commands/migrations.py b/tools/hogli-commands/hogli_commands/migrations.pyindex 52a89c5f61d7..8972fdd1122d 100644--- a/tools/hogli-commands/hogli_commands/migrations.py+++ b/tools/hogli-commands/hogli_commands/migrations.py@@ -28,7 +28,7 @@ import osimport reimport sysimport subprocess-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom pathlib import Pathfrom urllib.parse import quote@@ -82,6 +82,24 @@ class MigrationDiff:synced: list[MigrationInfo] = field(default_factory=list)+@dataclass(frozen=True, kw_only=True)+class OrphanRollbackPlan:+ """Orphaned migrations split by whether a cached file can drive a real rollback."""++ # Cached: the migration file is available, so Django can undo the schema changes+ cached: list[MigrationInfo]+ # Uncached: only the django_migrations record can be removed, and --force is required+ uncached: list[MigrationInfo]+++@dataclass(frozen=True, kw_only=True)+class GitRecoveryResult:+ """Uncached migrations split by whether git history could supply their file."""++ newly_cached: list[MigrationInfo]+ still_uncached: list[MigrationInfo]++def _cache_migration(app: str, name: str, source_path: Path) -> bool:"""Cache a migration file for later rollback with CLI feedback."""try:@@ -331,16 +349,16 @@ def _rollback_migration_with_cache(app: str, name: str, dry_run: bool = False) -return False-def _fetch_uncached_from_git(uncached: list[MigrationInfo], cached: list[MigrationInfo]) -> list[MigrationInfo]:+def _fetch_uncached_from_git(uncached: list[MigrationInfo]) -> GitRecoveryResult:"""Try to fetch uncached migrations from git history.- Moves successfully fetched migrations from uncached to cached list.- Returns the list of migrations that are still uncached.+ Returns the migrations that are now cached, and the ones that are still uncached."""if not uncached:- return []+ return GitRecoveryResult(newly_cached=[], still_uncached=[])click.echo("Attempting to fetch uncached migrations from git…\n")+ newly_cached: list[MigrationInfo] = []still_uncached: list[MigrationInfo] = []for m in uncached:@@ -349,7 +367,7 @@ def _fetch_uncached_from_git(uncached: list[MigrationInfo], cached: list[Migraticlick.echo(f" Fetching {m.app}.{m.name} from {branch}…")if _fetch_and_cache_migration_from_git(m.app, m.name, branch):click.secho(f" ✓ Cached {m.app}.{m.name}", fg="green")- cached.append(m)+ newly_cached.append(m)else:click.secho(f" ✗ Could not fetch {m.app}.{m.name}", fg="red")still_uncached.append(m)@@ -358,7 +376,7 @@ def _fetch_uncached_from_git(uncached: list[MigrationInfo], cached: list[Migratistill_uncached.append(m)click.echo()- return still_uncached+ return GitRecoveryResult(newly_cached=newly_cached, still_uncached=still_uncached)def _show_manual_rollback_instructions(uncached: list[MigrationInfo], command_name: str) -> None:@@ -384,7 +402,7 @@ def _show_manual_rollback_instructions(uncached: list[MigrationInfo], command_naclick.echo()click.echo("After manual rollback, run 'hogli migrations:sync' again.\n")- click.echo("Or use --force to skip schema rollback (just removes DB records):")+ click.echo("Or use --force to continue, removing only the DB records for those migrations:")click.secho(f" hogli {command_name} --force\n", fg="yellow")raise SystemExit(1)@@ -576,92 +594,93 @@ def _apply_migrations(pending: list[MigrationInfo] | None = None, dry_run: boolreturn MigrationResult(success=True)[email protected](name="migrations:status", help="Show migration diff between database and code")-def migrations_status() -> None:- """Show which migrations are orphaned, pending, or synced."""- click.echo("\nAnalyzing migrations…\n")-- diff = _compute_migration_diff()-- if diff.orphaned:- click.secho("Orphaned migrations (in DB but not in code):", fg="yellow", bold=True)- click.echo(" These were likely applied on another branch.\n")- for m in diff.orphaned:- click.echo(f" {m.app}: {m.name}")- click.echo()-- if diff.pending:- click.secho("Pending migrations (in code but not applied):", fg="blue", bold=True)- click.echo(" These need to be applied.\n")- for m in diff.pending:- click.echo(f" {m.app}: {m.name}")- click.echo()-- if not diff.orphaned and not diff.pending:- click.secho("✓ Migrations are in sync", fg="green", bold=True)- click.echo(f" {len(diff.synced)} migration(s) applied and present in code.")- else:- click.echo("Run 'hogli migrations:sync' to fix, or use 'down'/'up' individually.")--[email protected](name="migrations:down", help="Roll back orphaned migrations")[email protected]("--dry-run", "-n", is_flag=True, help="Show what would be done without executing")[email protected]("--yes", "-y", is_flag=True, help="Skip confirmation prompts")[email protected]("--force", "-f", is_flag=True, help="Force removal without schema rollback (just deletes DB records)")-def migrations_down(dry_run: bool, yes: bool, force: bool) -> None:- """Roll back migrations that are applied but don't exist in code."""- click.echo("\nAnalyzing migrations…\n")-+def _echo_dry_run_banner(dry_run: bool) -> None:if dry_run:click.secho("[DRY RUN MODE - No changes will be made]\n", fg="yellow")- diff = _compute_migration_diff()- if not diff.orphaned:- click.secho("✓ No orphaned migrations to roll back", fg="green")- return+def _echo_step_header(title: str, color: str) -> None:+ click.echo("\n" + "─" * 40)+ click.secho(title, fg=color, bold=True)+- # Categorize orphaned migrations by whether we can roll them back+def _classify_orphans(orphaned: list[MigrationInfo]) -> OrphanRollbackPlan:+ """Split orphaned migrations by whether their file is in the migration cache."""cached: list[MigrationInfo] = []uncached: list[MigrationInfo] = []-- for m in diff.orphaned:+ for m in orphaned:if _get_cached_migration(m.app, m.name):cached.append(m)else:uncached.append(m)+ return OrphanRollbackPlan(cached=cached, uncached=uncached)+++def _echo_orphaned_migrations(orphaned: list[MigrationInfo], plan: OrphanRollbackPlan) -> None:+ """List the orphans in the order the diff found them, each labeled with its cache status.++ The plan holds the same migrations but grouped by cache status, so it only supplies+ the label here. Iterating the plan instead would regroup the printed list.+ """+ if not orphaned:+ return- # Show what we foundclick.secho("Orphaned migrations to roll back:", fg="yellow", bold=True)- for m in diff.orphaned:- cache_status = "cached" if m in cached else "not cached"+ for m in orphaned:+ cache_status = "cached" if m in plan.cached else "not cached"click.echo(f" {m.app}: {m.name} ({cache_status})")click.echo()- # Try to fetch uncached migrations from git- if uncached and not force:- uncached = _fetch_uncached_from_git(uncached, cached)-- # If there are still uncached migrations and not forcing, show instructions- if uncached and not force:- _show_manual_rollback_instructions(uncached, "migrations:down")-- # Proceed with rollback- if not yes and not dry_run:- if force and uncached:- click.secho(- "\n⚠ WARNING: --force will only remove DB records.\n"- "Schema changes from these migrations will remain!\n",- fg="red",- )- if not click.confirm("Proceed?", default=False):- click.echo("Aborted.")- raise SystemExit(1)- # Roll back cached migrations properly- if cached:+def _echo_pending_migrations(pending: list[MigrationInfo]) -> None:+ if not pending:+ return++ click.secho("Pending migrations to apply:", fg="blue", bold=True)+ for m in pending:+ click.echo(f" {m.app}: {m.name}")+ click.echo()+++def _recover_uncached_orphans(plan: OrphanRollbackPlan, force: bool, command_name: str) -> OrphanRollbackPlan:+ """Fill the cache from git history so uncached orphans can still be rolled back.++ Migrations that stay uncached stop the command, because removing their records+ leaves their schema changes behind. --force accepts that trade and skips the search.+ """+ if force or not plan.uncached:+ return plan++ recovery = _fetch_uncached_from_git(plan.uncached)+ plan = replace(plan, cached=[*plan.cached, *recovery.newly_cached], uncached=recovery.still_uncached)+ if plan.uncached:+ _show_manual_rollback_instructions(plan.uncached, command_name)+ return plan+++def _confirm_or_exit(+ prompt: str, default: bool, dry_run: bool, yes: bool, force: bool, plan: OrphanRollbackPlan+) -> None:+ """Ask before changing the database. A dry run and --yes both skip the prompt."""+ if yes or dry_run:+ return++ if force and plan.uncached:+ click.secho(+ "\n⚠ WARNING: --force will only remove DB records for uncached migrations.\n"+ "Schema changes from those migrations will remain!\n",+ fg="red",+ )+ if not click.confirm(prompt, default=default):+ click.echo("Aborted.")+ raise SystemExit(1)+++def _execute_orphan_rollback(plan: OrphanRollbackPlan, force: bool, dry_run: bool) -> None:+ """Roll back cached orphans, then remove records for uncached ones under --force."""+ if plan.cached:click.echo("\nRolling back cached migrations…")- for m in cached:+ for m in plan.cached:click.echo(f" Rolling back {m.app}.{m.name}…")if not _rollback_migration_with_cache(m.app, m.name, dry_run=dry_run):click.secho(f" Failed to roll back {m.app}.{m.name}", fg="red")@@ -669,16 +688,12 @@ def migrations_down(dry_run: bool, yes: bool, force: bool) -> None:if not dry_run:click.secho(f" ✓ Rolled back {m.app}.{m.name}", fg="green")- # For uncached migrations (only if --force), just remove DB records- if uncached and force:+ if plan.uncached and force:click.echo("\nRemoving uncached migration records (schema changes remain)…")- if not _remove_orphaned_migrations(uncached, dry_run=dry_run):+ if not _remove_orphaned_migrations(plan.uncached, dry_run=dry_run):click.secho("Failed to remove orphaned migrations", fg="red")raise SystemExit(1)- click.echo()- click.secho("✓ Orphaned migrations handled", fg="green", bold=True)-def _handle_duplicate_error(result: MigrationResult, pending: list[MigrationInfo], dry_run: bool, yes: bool) -> bool:"""Handle duplicate column/table errors by offering to fake the migration.@@ -732,15 +747,97 @@ def _handle_duplicate_error(result: MigrationResult, pending: list[MigrationInforeturn False+def _apply_pending_migrations(pending: list[MigrationInfo], dry_run: bool, yes: bool) -> None:+ """Apply pending migrations, offering to fake any migration whose schema already exists.++ Each faked migration leaves the rest of the list unapplied, so the run repeats+ until Django reports success or an error we cannot recover from.+ """+ remaining = list(pending)++ while True:+ result = _apply_migrations(pending=remaining, dry_run=dry_run)+ if result.success:+ return++ recoverable = result.error_type in ("duplicate_column", "duplicate_table")+ if recoverable and _handle_duplicate_error(result, remaining, dry_run, yes):+ click.echo("\nRetrying remaining migrations…\n")+ continue++ if not recoverable:+ click.secho("Failed to apply migrations", fg="red")+ if result.error_message:+ click.echo(f"\n{result.error_message}")+ raise SystemExit(1)++[email protected](name="migrations:status", help="Show migration diff between database and code")+def migrations_status() -> None:+ """Show which migrations are orphaned, pending, or synced."""+ click.echo("\nAnalyzing migrations…\n")++ diff = _compute_migration_diff()++ if diff.orphaned:+ click.secho("Orphaned migrations (in DB but not in code):", fg="yellow", bold=True)+ click.echo(" These were likely applied on another branch.\n")+ for m in diff.orphaned:+ click.echo(f" {m.app}: {m.name}")+ click.echo()++ if diff.pending:+ click.secho("Pending migrations (in code but not applied):", fg="blue", bold=True)+ click.echo(" These need to be applied.\n")+ for m in diff.pending:+ click.echo(f" {m.app}: {m.name}")+ click.echo()++ if not diff.orphaned and not diff.pending:+ click.secho("✓ Migrations are in sync", fg="green", bold=True)+ click.echo(f" {len(diff.synced)} migration(s) applied and present in code.")+ else:+ click.echo("Run 'hogli migrations:sync' to fix, or use 'down'/'up' individually.")++[email protected](name="migrations:down", help="Roll back orphaned migrations")[email protected]("--dry-run", "-n", is_flag=True, help="Show what would be done without executing")[email protected]("--yes", "-y", is_flag=True, help="Skip confirmation prompts")+ "--force",+ "-f",+ is_flag=True,+ help="Continue when some migrations can't be rolled back, removing only their DB records",+)+def migrations_down(dry_run: bool, yes: bool, force: bool) -> None:+ """Roll back migrations that are applied but don't exist in code."""+ click.echo("\nAnalyzing migrations…\n")+ _echo_dry_run_banner(dry_run)++ diff = _compute_migration_diff()++ if not diff.orphaned:+ click.secho("✓ No orphaned migrations to roll back", fg="green")+ return++ plan = _classify_orphans(diff.orphaned)+ _echo_orphaned_migrations(diff.orphaned, plan)+ plan = _recover_uncached_orphans(plan, force=force, command_name="migrations:down")++ _confirm_or_exit("Proceed?", default=False, dry_run=dry_run, yes=yes, force=force, plan=plan)+ _execute_orphan_rollback(plan, force=force, dry_run=dry_run)++ click.echo()+ click.secho("✓ Orphaned migrations handled", fg="green", bold=True)++@click.command(name="migrations:up", help="Apply pending migrations")@click.option("--dry-run", "-n", is_flag=True, help="Show what would be done without executing")@click.option("--yes", "-y", is_flag=True, help="Auto-confirm faking migrations with duplicate schema")def migrations_up(dry_run: bool, yes: bool) -> None:"""Apply migrations that exist in code but aren't applied."""click.echo("\nApplying pending migrations…\n")-- if dry_run:- click.secho("[DRY RUN MODE - No changes will be made]\n", fg="yellow")+ _echo_dry_run_banner(dry_run)diff = _compute_migration_diff()@@ -748,33 +845,8 @@ def migrations_up(dry_run: bool, yes: bool) -> None:click.secho("✓ No pending migrations to apply", fg="green")return- click.secho("Pending migrations to apply:", fg="blue", bold=True)- for m in diff.pending:- click.echo(f" {m.app}: {m.name}")- click.echo()-- pending = list(diff.pending) # Make a mutable copy-- while True:- result = _apply_migrations(pending=pending, dry_run=dry_run)-- if result.success:- break-- # Check for recoverable duplicate schema errors- if result.error_type in ("duplicate_column", "duplicate_table"):- if _handle_duplicate_error(result, pending, dry_run, yes):- # User chose to fake, retry remaining migrations- click.echo("\nRetrying remaining migrations…\n")- continue- else:- raise SystemExit(1)- else:- # Non-recoverable error- click.secho("Failed to apply migrations", fg="red")- if result.error_message:- click.echo(f"\n{result.error_message}")- raise SystemExit(1)+ _echo_pending_migrations(diff.pending)+ _apply_pending_migrations(diff.pending, dry_run=dry_run, yes=yes)if not dry_run:click.secho("✓ Migrations applied and cached", fg="green", bold=True)@@ -797,9 +869,7 @@ def migrations_sync(dry_run: bool, yes: bool, force: bool) -> None:hogli migrations:sync"""click.echo("\nAnalyzing migrations…\n")-- if dry_run:- click.secho("[DRY RUN MODE - No changes will be made]\n", fg="yellow")+ _echo_dry_run_banner(dry_run)diff = _compute_migration_diff()@@ -808,100 +878,21 @@ def migrations_sync(dry_run: bool, yes: bool, force: bool) -> None:click.echo(f" {len(diff.synced)} migration(s) applied and present in code.")return- # Categorize orphaned migrations- cached: list[MigrationInfo] = []- uncached: list[MigrationInfo] = []+ plan = _classify_orphans(diff.orphaned)+ _echo_orphaned_migrations(diff.orphaned, plan)+ _echo_pending_migrations(diff.pending)+ plan = _recover_uncached_orphans(plan, force=force, command_name="migrations:sync")- for m in diff.orphaned:- if _get_cached_migration(m.app, m.name):- cached.append(m)- else:- uncached.append(m)+ _confirm_or_exit("Proceed with sync?", default=True, dry_run=dry_run, yes=yes, force=force, plan=plan)- # Show what will happenif diff.orphaned:- click.secho("Orphaned migrations to roll back:", fg="yellow", bold=True)- for m in diff.orphaned:- cache_status = "cached" if m in cached else "not cached"- click.echo(f" {m.app}: {m.name} ({cache_status})")- click.echo()+ _echo_step_header("Step 1: Rolling back orphaned migrations", "yellow")+ _execute_orphan_rollback(plan, force=force, dry_run=dry_run)if diff.pending:- click.secho("Pending migrations to apply:", fg="blue", bold=True)- for m in diff.pending:- click.echo(f" {m.app}: {m.name}")+ _echo_step_header("Step 2: Applying pending migrations", "blue")click.echo()-- # Try to fetch uncached migrations from git- if uncached and not force:- uncached = _fetch_uncached_from_git(uncached, cached)-- # If there are still uncached migrations and not forcing, show instructions- if uncached and not force:- _show_manual_rollback_instructions(uncached, "migrations:sync")-- if not yes and not dry_run:- if force and uncached:- click.secho(- "\n⚠ WARNING: --force will only remove DB records for uncached migrations.\n"- "Schema changes from those migrations will remain!\n",- fg="red",- )- if not click.confirm("Proceed with sync?", default=True):- click.echo("Aborted.")- raise SystemExit(1)-- # Step 1: Roll back orphaned migrations- if diff.orphaned:- click.echo("\n" + "─" * 40)- click.secho("Step 1: Rolling back orphaned migrations", fg="yellow", bold=True)- click.echo()-- # Roll back cached migrations properly- for m in cached:- click.echo(f" Rolling back {m.app}.{m.name}…")- if not _rollback_migration_with_cache(m.app, m.name, dry_run=dry_run):- click.secho(f" Failed to roll back {m.app}.{m.name}", fg="red")- raise SystemExit(1)- if not dry_run:- click.secho(f" ✓ Rolled back {m.app}.{m.name}", fg="green")-- # Remove uncached migrations (only records, if --force)- if uncached and force:- click.echo("\n Removing uncached migration records…")- if not _remove_orphaned_migrations(uncached, dry_run=dry_run):- click.secho("Failed to remove orphaned migrations", fg="red")- raise SystemExit(1)-- # Step 2: Apply pending- if diff.pending:- click.echo("\n" + "─" * 40)- click.secho("Step 2: Applying pending migrations", fg="blue", bold=True)- click.echo()-- pending = list(diff.pending) # Make a mutable copy-- while True:- result = _apply_migrations(pending=pending, dry_run=dry_run)-- if result.success:- break-- # Check for recoverable duplicate schema errors- if result.error_type in ("duplicate_column", "duplicate_table"):- if _handle_duplicate_error(result, pending, dry_run, yes):- # User chose to fake, retry remaining migrations- click.echo("\nRetrying remaining migrations…\n")- continue- else:- raise SystemExit(1)- else:- # Non-recoverable error- click.secho("Failed to apply migrations", fg="red")- if result.error_message:- click.echo(f"\n{result.error_message}")- raise SystemExit(1)-+ _apply_pending_migrations(diff.pending, dry_run=dry_run, yes=yes)if not dry_run:click.secho(" ✓ Migrations applied and cached", fg="green")diff --git a/tools/hogli-commands/hogli_commands/tests/test_migration_commands.py b/tools/hogli-commands/hogli_commands/tests/test_migration_commands.pynew file mode 100644index 000000000000..fc3e15bd6e6a--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_migration_commands.py@@ -0,0 +1,227 @@+from __future__ import annotations++from collections.abc import Sequence++import pytest++import click+import hogli_commands.migrations as migrations+from click.testing import CliRunner+++def _label(info: migrations.MigrationInfo) -> str:+ return f"{info.app}.{info.name}"+++def _info(label: str) -> migrations.MigrationInfo:+ app, name = label.split(".")+ return migrations.MigrationInfo(app=app, name=name)+++# Stands in for every boundary the migration commands can change state through.+class Harness:+ def __init__(self) -> None:+ self.orphaned: list[migrations.MigrationInfo] = []+ self.pending: list[migrations.MigrationInfo] = []+ self.cached: set[str] = set()+ # Uncached orphans that the git search can recover into the cache+ self.git_recovered: set[str] = set()+ self.rollback_failures: set[str] = set()+ self.apply_results: list[migrations.MigrationResult] = []+ # What the command asked the boundaries to do, with the dry-run flag it passed+ self.rollbacks: list[tuple[str, bool]] = []+ self.removals: list[tuple[list[str], bool]] = []+ self.applies: list[tuple[list[str], bool]] = []++ def set_state(self, orphaned: Sequence[str] = (), pending: Sequence[str] = ()) -> None:+ self.orphaned = [_info(label) for label in orphaned]+ self.pending = [_info(label) for label in pending]+++def harness(monkeypatch: pytest.MonkeyPatch) -> Harness:+ h = Harness()++ def rollback(app: str, name: str, dry_run: bool = False) -> bool:+ h.rollbacks.append((f"{app}.{name}", dry_run))+ return f"{app}.{name}" not in h.rollback_failures++ def remove(orphaned: list[migrations.MigrationInfo], dry_run: bool = False) -> bool:+ h.removals.append(([_label(m) for m in orphaned], dry_run))+ return True++ def apply(+ pending: list[migrations.MigrationInfo] | None = None, dry_run: bool = False+ ) -> migrations.MigrationResult:+ h.applies.append(([_label(m) for m in pending or []], dry_run))+ if h.apply_results:+ return h.apply_results.pop(0)+ return migrations.MigrationResult(success=True)++ monkeypatch.setattr(+ migrations,+ "_compute_migration_diff",+ lambda: migrations.MigrationDiff(orphaned=list(h.orphaned), pending=list(h.pending)),+ )+ monkeypatch.setattr(migrations, "_get_cached_migration", lambda app, name: f"{app}.{name}" in h.cached)+ monkeypatch.setattr(migrations, "_rollback_migration_with_cache", rollback)+ monkeypatch.setattr(migrations, "_remove_orphaned_migrations", remove)+ monkeypatch.setattr(migrations, "_apply_migrations", apply)++ def fetch_from_git(uncached: list[migrations.MigrationInfo]) -> migrations.GitRecoveryResult:+ return migrations.GitRecoveryResult(+ newly_cached=[m for m in uncached if _label(m) in h.git_recovered],+ still_uncached=[m for m in uncached if _label(m) not in h.git_recovered],+ )++ monkeypatch.setattr(migrations, "_fetch_uncached_from_git", fetch_from_git)+ monkeypatch.setattr(migrations, "_find_migration_branch", lambda app, name: None)+ monkeypatch.setattr(migrations, "_fake_migration", lambda app, name: True)+ monkeypatch.setattr(migrations, "get_managed_app_paths", lambda root: {})+ # Nothing in these tests may reach Postgres+ monkeypatch.setattr(migrations, "_get_migrations_in_db", lambda: {})+ return h+++ "command,args",+ [+ (migrations.migrations_down, ["--dry-run"]),+ (migrations.migrations_sync, ["--dry-run"]),+ (migrations.migrations_up, ["--dry-run"]),+ ],+)+def test_dry_run_only_plans(harness: Harness, command: click.Command, args: list[str]) -> None:+ harness.set_state(orphaned=["posthog.0002_orphan"], pending=["posthog.0003_new"])+ harness.cached = {"posthog.0002_orphan"}++ result = CliRunner().invoke(command, args)++ assert result.exit_code == 0+ assert all(dry_run for _, dry_run in harness.rollbacks)+ assert all(dry_run for _, dry_run in harness.applies)+ assert harness.removals == []+++ "command,args",+ [+ (migrations.migrations_down, []),+ (migrations.migrations_sync, []),+ ],+)+def test_declining_the_prompt_changes_nothing(harness: Harness, command: click.Command, args: list[str]) -> None:+ harness.set_state(orphaned=["posthog.0002_orphan"], pending=["posthog.0003_new"])+ harness.cached = {"posthog.0002_orphan"}++ result = CliRunner().invoke(command, args, input="n\n")++ assert result.exit_code == 1+ assert "Aborted." in result.output+ assert harness.rollbacks == []+ assert harness.applies == []+++def test_uncached_orphan_without_force_stops_before_any_change(harness: Harness) -> None:+ harness.set_state(orphaned=["posthog.0002_orphan"])++ result = CliRunner().invoke(migrations.migrations_sync, ["--yes"])++ assert result.exit_code == 1+ assert "cannot be auto-rolled back" in result.output+ assert harness.rollbacks == []+ assert harness.removals == []+++def test_force_removes_records_for_uncached_orphans_only(harness: Harness) -> None:+ harness.set_state(orphaned=["posthog.0002_orphan", "posthog.0004_gone"])+ harness.cached = {"posthog.0002_orphan"}++ result = CliRunner().invoke(migrations.migrations_down, ["--force", "--yes"])++ assert result.exit_code == 0+ assert harness.rollbacks == [("posthog.0002_orphan", False)]+ assert harness.removals == [(["posthog.0004_gone"], False)]+++def test_force_dry_run_plans_the_record_removal_without_doing_it(harness: Harness) -> None:+ harness.set_state(orphaned=["posthog.0004_gone"])++ result = CliRunner().invoke(migrations.migrations_down, ["--force", "--dry-run"])++ assert result.exit_code == 0+ assert harness.removals == [(["posthog.0004_gone"], True)]+ assert harness.rollbacks == []+++def test_git_recovered_orphan_is_rolled_back_not_record_deleted(harness: Harness) -> None:+ harness.set_state(orphaned=["posthog.0002_orphan", "posthog.0004_gone"])+ harness.cached = {"posthog.0002_orphan"}+ harness.git_recovered = {"posthog.0004_gone"}++ result = CliRunner().invoke(migrations.migrations_down, ["--yes"])++ assert result.exit_code == 0+ assert harness.rollbacks == [("posthog.0002_orphan", False), ("posthog.0004_gone", False)]+ assert harness.removals == []+++def test_failed_rollback_stops_before_applying_pending(harness: Harness) -> None:+ harness.set_state(orphaned=["posthog.0002_orphan"], pending=["posthog.0003_new"])+ harness.cached = {"posthog.0002_orphan"}+ harness.rollback_failures = {"posthog.0002_orphan"}++ result = CliRunner().invoke(migrations.migrations_sync, ["--yes"])++ assert result.exit_code == 1+ assert "Failed to roll back posthog.0002_orphan" in result.output+ assert harness.applies == []+++ "command,args",+ [+ (migrations.migrations_up, ["--yes"]),+ (migrations.migrations_sync, ["--yes"]),+ ],+)+def test_duplicate_schema_is_faked_then_dropped_from_the_retry(+ harness: Harness, command: click.Command, args: list[str]+) -> None:+ harness.set_state(pending=["posthog.0003_new", "posthog.0005_later"])+ harness.apply_results = [+ migrations.MigrationResult(+ success=False,+ error_type="duplicate_column",+ error_message='column "foo" of relation "posthog_team" already exists',+ failed_migration=("posthog", "0003_new"),+ )+ ]++ result = CliRunner().invoke(command, args)++ assert result.exit_code == 0+ assert [pending for pending, _ in harness.applies] == [+ ["posthog.0003_new", "posthog.0005_later"],+ ["posthog.0005_later"],+ ]+++ "command,args",+ [+ (migrations.migrations_up, ["--yes"]),+ (migrations.migrations_sync, ["--yes"]),+ ],+)+def test_unrecoverable_apply_error_reports_and_exits(harness: Harness, command: click.Command, args: list[str]) -> None:+ harness.set_state(pending=["posthog.0003_new"])+ harness.apply_results = [+ migrations.MigrationResult(success=False, error_type="other", error_message="relation does not exist")+ ]++ result = CliRunner().invoke(command, args)++ assert result.exit_code == 1+ assert "Failed to apply migrations" in result.output+ assert "relation does not exist" in result.output