Public repository: timo / mitch

Reader

A migration stitcher (therefore mitch) for PostgreSQL, SQLite, MariaDB, and others

Add CLI commands up and apply

public

Add CLI commands up and apply
Changeset1eca48d44eecd6806bfa59d654c11c4163d13da8
Author (claimed)Timo Stolz <timo.stolz@nullachtvierzehn.de>,
Parentsfe6f12450197
Children
Pushlog
by timo via ssh

modified src/mitch/cli/deploy.py +55 −24

@@ -1,5 +1,5 @@
11
 from enum import Enum
2
-from typing import Annotated
2
+from typing import Annotated, Iterable
33
 from pathlib import Path
44
 from contextlib import nullcontext
55
 import os
@@ -21,38 +21,39 @@
2121
 
2222
 app = typer.Typer()
2323
 
24
-@app.command()
25
-def deploy(
26
-    migration_ids: list[str],
27
-    root: Annotated[Path, typer.Option("--repository", "-r", help="Repository directory.", default_factory=lambda: Path.cwd(), dir_okay=True, file_okay=False, exists=True)],
28
-    database_url: Annotated[str | None, typer.Option("--database", "-d", help="Database connection URL.")] = None,
29
-    if_modified: Annotated[IfModifiedOption, typer.Option("--if-modified", "-m", help="Action to take if a migration has been modified since its last deployment.", case_sensitive=False, show_choices=True)] = IfModifiedOption.PROMPT,
30
-) -> None:
31
-    """Deploy the specified migrations.
3224
 
33
-    Args:
34
-        migration_ids: The IDs of the migrations to deploy.
35
-    """
36
-
37
-    # Resolve database URL
25
+def _resolve_database_url(database_url: str | None) -> str:
3826
     resolved_database_url = database_url or os.getenv("MITCH_DATABASE_URL") or os.getenv("DATABASE_URL")
3927
     if not resolved_database_url:
40
-        typer.echo("Error: Database URL must be provided via --database option or MITCH_DATABASE_URL/DATABASE_URL environment variable.", err=True)
28
+        typer.echo(
29
+            "Error: Database URL must be provided via --database option or MITCH_DATABASE_URL/DATABASE_URL environment variable.",
30
+            err=True,
31
+        )
4132
         raise typer.Exit(1)
33
+    return resolved_database_url
34
+
35
+
36
+def _deploy_migrations(
37
+    repo: Repository,
38
+    migration_ids: Iterable[str],
39
+    database_url: str | None,
40
+    if_modified: IfModifiedOption,
41
+) -> None:
42
+    migration_ids = list(migration_ids)
43
+    resolved_database_url = _resolve_database_url(database_url)
4244
     engine = sa.create_engine(resolved_database_url)
43
-    
45
+
4446
     # Fetch due migrations
45
-    repo = Repository(root)
4647
     due_migrations = list(repo.by_ids_with_dependencies(migration_ids))
47
-    
48
+
4849
     with engine.connect() as connection:
4950
         runner = Runner(connection)
50
-        
51
+
5152
         # Check for modified migrations
5253
         modified_migrations = [m for m in due_migrations if runner.deployment_status(m) == 'modified']
5354
         migrations_to_redeploy = []
5455
         migrations_to_ignore = set()
55
-        
56
+
5657
         match if_modified:
5758
             case IfModifiedOption.REDEPLOY:
5859
                 migrations_to_redeploy = modified_migrations[:]
@@ -82,16 +83,16 @@
8283
                 rich.print(f" - Migration '{m.id}'")
8384
             if not Confirm.ask("Do you want to continue?", default=False):
8485
                 raise typer.Exit(0)
85
-        
86
+
8687
         for m in migrations_to_revert:
8788
             rich.print(f"[blue]Reverting:[/blue] Migration '{m.id}'")
8889
             runner.revert_migration(m)
8990
 
90
-        # Prepare to redeploy modified migrations, together with the 
91
+        # Prepare to redeploy modified migrations, together with the
9192
         if migrations_to_revert:
9293
             due_ids = set(migration_ids) | {m.id for m in migrations_to_revert}
9394
             due_migrations = list(repo.by_ids_with_dependencies(due_ids))
94
-        
95
+
9596
         # Deploy due and reverted migrations
9697
         for batch in batch_transactional_migrations(due_migrations):
9798
             runner.autocommit = not batch.transactional
@@ -102,5 +103,35 @@
102103
                         continue
103104
                     rich.print(f"[green]Deploying:[/green] Migration '{m.id}'")
104105
                     runner.apply_migration(m)
105
-    
106
+
106107
     engine.dispose()
108
+
109
+
110
+@app.command()
111
+def deploy(
112
+    migration_ids: list[str],
113
+    root: Annotated[Path, typer.Option("--repository", "-r", help="Repository directory.", default_factory=lambda: Path.cwd(), dir_okay=True, file_okay=False, exists=True)],
114
+    database_url: Annotated[str | None, typer.Option("--database", "-d", help="Database connection URL.")] = None,
115
+    if_modified: Annotated[IfModifiedOption, typer.Option("--if-modified", "-m", help="Action to take if a migration has been modified since its last deployment.", case_sensitive=False, show_choices=True)] = IfModifiedOption.PROMPT,
116
+) -> None:
117
+    """Deploy the specified migrations.
118
+
119
+    Args:
120
+        migration_ids: The IDs of the migrations to deploy.
121
+    """
122
+
123
+    repo = Repository(root)
124
+    _deploy_migrations(repo, migration_ids, database_url, if_modified)
125
+
126
+
127
+@app.command(name="up")
128
+@app.command(name="apply", help="Alias for up.")
129
+def up(
130
+    root: Annotated[Path, typer.Option("--repository", "-r", help="Repository directory.", default_factory=lambda: Path.cwd(), dir_okay=True, file_okay=False, exists=True)],
131
+    database_url: Annotated[str | None, typer.Option("--database", "-d", help="Database connection URL.")] = None,
132
+    if_modified: Annotated[IfModifiedOption, typer.Option("--if-modified", "-m", help="Action to take if a migration has been modified since its last deployment.", case_sensitive=False, show_choices=True)] = IfModifiedOption.PROMPT,
133
+) -> None:
134
+    """Deploy all migrations in the repository."""
135
+    repo = Repository(root)
136
+    migration_ids = [m.id for m in repo.migrations]
137
+    _deploy_migrations(repo, migration_ids, database_url, if_modified)

modified tests/test_cli.py +28 −0

@@ -42,3 +42,31 @@
4242
         ).fetchone()
4343
 
4444
     assert row is not None
45
+
46
+
47
+def test_up_applies_all_migrations_to_sqlite(tmp_path):
48
+    db_path = tmp_path / "test.db"
49
+    database_url = f"sqlite:///{db_path}"
50
+
51
+    result = runner.invoke(
52
+        app,
53
+        [
54
+            "up",
55
+            "--repository",
56
+            "tests/migrations",
57
+            "--database",
58
+            database_url,
59
+            "--if-modified",
60
+            "ignore",
61
+        ],
62
+    )
63
+
64
+    assert result.exit_code == 0
65
+    assert "Deploying:" in result.output
66
+
67
+    with sqlite3.connect(db_path) as connection:
68
+        rows = connection.execute(
69
+            "SELECT id FROM mitch_migrations ORDER BY id",
70
+        ).fetchall()
71
+
72
+    assert [row[0] for row in rows] == ["001-init", "002-add-column"]