Public repository: timo / mitch

Reader

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

Use watchdog properly, rename commands apply->up, deploy->add, unapply->drop

public

Use watchdog properly, rename commands apply->up, deploy->add, unapply->drop
Changeset78239ca0d1e6607eee927c446b891f6dcb1ff9e3
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents8dee25b9bb42
Children
Pushlog
by timo via ssh

modified src/mitch/cli/deploy.py +41 −180

@@ -1,10 +1,6 @@
1
-from collections import defaultdict
21
 from enum import Enum
3
-from typing import Annotated, Iterable, Callable
2
+from typing import Annotated
43
 from pathlib import Path
5
-from contextlib import nullcontext
6
-from threading import Event
7
-from time import monotonic, sleep
84
 
95
 from rich.prompt import Confirm
106
 import typer
@@ -12,7 +8,7 @@
128
 
139
 from ..repository import Repository
1410
 from ..runner import Runner
15
-from ..helpers import batch_transactional_migrations, create_engine, connection_for
11
+from ..helpers import connection_for
1612
 from ..watcher import EventType
1713
 
1814
 class IfModifiedOption(str, Enum):
@@ -25,163 +21,8 @@
2521
 app = typer.Typer()
2622
 
2723
 
28
-def _is_migration_file(path: Path) -> bool:
29
-    name = path.name
30
-    return (
31
-        name.endswith(".up.sql")
32
-        or name.endswith(".down.sql")
33
-        or name.endswith(".config.toml")
34
-    )
35
-
36
-
37
-def _deploy_all_migrations(
38
-    root: Path,
39
-    database_url: str | None,
40
-    if_modified: IfModifiedOption,
41
-) -> None:
42
-    repo = Repository(root)
43
-    migration_ids = [m.id for m in repo.migrations]
44
-    _deploy_migrations(repo, migration_ids, database_url, if_modified)
45
-
46
-
47
-def _watch_migrations(
48
-    root: Path,
49
-    on_change: Callable[[], None],
50
-    keep_going: bool,
51
-    debounce_seconds: float = 0.5,
52
-) -> None:
53
-    try:
54
-        from watchdog.events import FileSystemEventHandler
55
-        from watchdog.observers import Observer
56
-    except ModuleNotFoundError as exc:
57
-        typer.echo("Error: --watch requires the 'watchdog' package.", err=True)
58
-        raise typer.Exit(1) from exc
59
-
60
-    change_event = Event()
61
-    last_change = 0.0
62
-
63
-    def trigger_change() -> None:
64
-        nonlocal last_change
65
-        last_change = monotonic()
66
-        change_event.set()
67
-
68
-    class MigrationWatchHandler(FileSystemEventHandler):
69
-        def on_any_event(self, event) -> None:
70
-            if event.is_directory:
71
-                return
72
-            if _is_migration_file(Path(event.src_path)):
73
-                trigger_change()
74
-                return
75
-            dest_path = getattr(event, "dest_path", None)
76
-            if dest_path and _is_migration_file(Path(dest_path)):
77
-                trigger_change()
78
-
79
-    handler = MigrationWatchHandler()
80
-    observer = Observer()
81
-    observer.schedule(handler, str(root), recursive=True)
82
-    observer.start()
83
-    rich.print("[blue]Watching for migration changes...[/blue]")
84
-
85
-    try:
86
-        while True:
87
-            change_event.wait()
88
-
89
-            while True:
90
-                change_event.clear()
91
-                sleep(debounce_seconds)
92
-                if monotonic() - last_change >= debounce_seconds:
93
-                    break
94
-
95
-            try:
96
-                on_change()
97
-            except typer.Exit:
98
-                raise
99
-            except Exception as exc:
100
-                rich.print(f"[red]Error:[/red] {exc}")
101
-                if not keep_going:
102
-                    raise
103
-    except KeyboardInterrupt:
104
-        pass
105
-    finally:
106
-        observer.stop()
107
-        observer.join()
108
-
109
-
110
-def _deploy_migrations(
111
-    repo: Repository,
112
-    migration_ids: Iterable[str],
113
-    database_url: str | None,
114
-    if_modified: IfModifiedOption,
115
-) -> None:
116
-    migration_ids = list(migration_ids)
117
-    engine = create_engine(database_url)
118
-
119
-    # Fetch due migrations
120
-    due_migrations = list(repo.by_ids_with_dependencies(migration_ids))
121
-
122
-    with engine.connect() as connection:
123
-        runner = Runner(connection)
124
-
125
-        # Check for modified migrations
126
-        modified_migrations = [m for m in due_migrations if runner.deployment_status(m) == 'modified']
127
-        migrations_to_redeploy = []
128
-        migrations_to_ignore = set()
129
-
130
-        match if_modified:
131
-            case IfModifiedOption.REDEPLOY:
132
-                migrations_to_redeploy = modified_migrations[:]
133
-            case IfModifiedOption.IGNORE:
134
-                migrations_to_ignore.update(modified_migrations)
135
-            case IfModifiedOption.PROMPT:
136
-                for m in modified_migrations:
137
-                    rich.print(f"[yellow]Warning:[/yellow] Migration '{m.id}' has been modified since it was last deployed.")
138
-                    match Confirm.ask(f"(r)evert and redeploy, (i)gnore, or (e)exit?", choices=["r", "i", "e"], default="e"):
139
-                        case "r":
140
-                            migrations_to_redeploy.append(m)
141
-                        case "i":
142
-                            migrations_to_ignore.add(m)
143
-                        case "e":
144
-                            raise typer.Exit(0)
145
-            case _:
146
-                raise typer.Exit(1, f"Unknown if_modified option: {if_modified}")
147
-
148
-        # Revert modified migrations if needed.
149
-        migrations_to_revert = list(repo.by_ids_with_dependants([m.id for m in migrations_to_redeploy]))
150
-
151
-        # Ask for confirmation if there are dependants to revert.
152
-        dependants_to_revert = [m for m in migrations_to_revert if m not in migrations_to_redeploy]
153
-        if dependants_to_revert:
154
-            rich.print("[yellow]Warning:[/yellow] The following dependant migrations will also be reverted:")
155
-            for m in dependants_to_revert:
156
-                rich.print(f" - Migration '{m.id}'")
157
-            if not Confirm.ask("Do you want to continue?", default=False):
158
-                raise typer.Exit(0)
159
-
160
-        for m in migrations_to_revert:
161
-            rich.print(f"[blue]Reverting:[/blue] Migration '{m.id}'")
162
-            runner.revert_migration(m)
163
-
164
-        # Prepare to redeploy modified migrations, together with the
165
-        if migrations_to_revert:
166
-            due_ids = set(migration_ids) | {m.id for m in migrations_to_revert}
167
-            due_migrations = list(repo.by_ids_with_dependencies(due_ids))
168
-
169
-        # Deploy due and reverted migrations
170
-        for batch in batch_transactional_migrations(due_migrations):
171
-            runner.autocommit = not batch.transactional
172
-            with runner.transaction() if batch.transactional else nullcontext():
173
-                for m in batch.migrations:
174
-                    if m in migrations_to_ignore:
175
-                        rich.print(f"[cyan]Ignoring:[/cyan] Migration '{m.id}'")
176
-                        continue
177
-                    rich.print(f"[green]Deploying:[/green] Migration '{m.id}'")
178
-                    runner.apply_migration(m)
179
-
180
-    engine.dispose()
181
-
182
-
183
-@app.command()
184
-def pick(
24
+@app.command(name="add")
25
+def add(
18526
     ctx: typer.Context,
18627
     migration_ids: list[str],
18728
     root: Annotated[Path, typer.Option("--repository", "-r", help="Repository directory.", default_factory=lambda: Path.cwd(), dir_okay=True, file_okay=False, exists=True)],
@@ -202,7 +43,7 @@
20243
         typer.Option("--watch", help="Watch the repository and re-run deployments on changes."),
20344
     ] = False,
20445
 ) -> None:
205
-    """Deploy all migrations in the repository."""
46
+    """Deploy the specified migrations in the repository."""
20647
 
20748
     repo = Repository(root)
20849
     covered_migrations = set(repo.by_ids_with_dependencies(migration_ids))
@@ -251,27 +92,40 @@
25192
                         raise typer.Abort()
25293
 
25394
         # Revert modified migrations and their dependants before redeploying.
254
-        for migration in repo.with_dependants(redeploy):
255
-            rich.print(f"[blue]Reverting:[/blue] Migration '{migration.id}' due to modifications after deployment.")
256
-            runner.revert_migration(migration)
95
+        to_revert = list(repo.with_dependants(redeploy))
96
+        runner.revert_migrations(
97
+            to_revert,
98
+            before_each=lambda migration: rich.print(
99
+                f"[blue]Reverting:[/blue] Migration '{migration.id}' due to modifications after deployment."
100
+            ),
101
+        )
257102
 
258103
         # Deploy pending migrations, including redeployments for modified ones.
259104
         pending = set(m for m in covered_migrations if runner.deployment_status(m) == 'pending')
260
-        for migration in repo.with_dependencies(pending | redeploy):
261
-            rich.print(f"[green]Deploying:[/green] Migration '{migration.id}'")
262
-            runner.apply_migration(migration)
105
+        to_apply = list(repo.with_dependencies(pending | redeploy))
106
+        runner.deploy_migrations(
107
+            to_apply,
108
+            before_each=lambda migration: rich.print(
109
+                f"[green]Deploying:[/green] Migration '{migration.id}'"
110
+            ),
111
+        )
263112
 
264113
         if watch:
265114
             incoming_changes = repo.watch_for_changes()
266115
         
267116
         while watch:
268
-            # Reload repository to reflect any file changes, including new migrations or deleted ones.
269
-            repo.reload()  
117
+            try:
118
+                changes = next(incoming_changes)  # pyright: ignore[reportPossiblyUnboundVariable]
119
+            except StopIteration:
120
+                break
121
+
122
+            # Reload repository after receiving events so created files are visible in the index.
123
+            repo.reload()
270124
 
271125
             # Collect modified and added migrations from the incoming changes.
272126
             applied_and_modified = set()
273127
             added_and_pending = set()
274
-            for action, path in next(incoming_changes):  # pyright: ignore[reportPossiblyUnboundVariable]
128
+            for action, path in changes:
275129
                 if action == EventType.MODIFIED and (path.name.endswith(".up.sql") or path.name.endswith(".config.toml")):
276130
                     migration = repo.by_path(path)
277131
                     if migration not in covered_migrations:
@@ -285,14 +139,21 @@
285139
                     if runner.deployment_status(migration) == 'pending':
286140
                         added_and_pending.add(migration)
287141
 
288
-            for m in repo.with_dependants(applied_and_modified):
289
-                runner.revert_migration(m)
290
-                rich.print(f"[blue]Reverted:[/blue] Migration '{m.id}'")
142
+            to_revert = list(repo.with_dependants(applied_and_modified))
143
+            runner.revert_migrations(
144
+                to_revert,
145
+                before_each=lambda migration: rich.print(
146
+                    f"[blue]Reverted:[/blue] Migration '{migration.id}'"
147
+                ),
148
+            )
291149
             
292150
             to_be_applied = list(repo.with_dependencies(applied_and_modified | added_and_pending))
293
-            for m in to_be_applied:
294
-                runner.apply_migration(m)
295
-                rich.print(f"[green]Deployed:[/green] Migration '{m.id}'")
151
+            runner.deploy_migrations(
152
+                to_be_applied,
153
+                before_each=lambda migration: rich.print(
154
+                    f"[green]Deployed:[/green] Migration '{migration.id}'"
155
+                ),
156
+            )
296157
 
297158
 
298159
 @app.command()
@@ -319,4 +180,4 @@
319180
     """Deploy all migrations in the repository."""
320181
 
321182
     repo = Repository(root)
322
-    pick(ctx, [m.id for m in repo.migrations], root, database_url, if_modified, watch)
183
+    add(ctx, [m.id for m in repo.migrations], root, database_url, if_modified, watch)

modified src/mitch/cli/revert.py +9 −17

@@ -1,26 +1,19 @@
1
-from enum import Enum
2
-from typing import Annotated, Iterable, Callable
1
+from typing import Annotated
32
 from pathlib import Path
4
-from contextlib import nullcontext
5
-from threading import Event
6
-from time import monotonic, sleep
7
-import os
83
 
9
-from rich.prompt import Confirm
10
-import sqlalchemy as sa
114
 import typer
125
 import rich
136
 
147
 from ..repository import Repository
158
 from ..runner import Runner
16
-from ..helpers import batch_transactional_migrations, create_engine
9
+from ..helpers import create_engine
1710
 
1811
 
1912
 app = typer.Typer(help="Revert migrations in the repository.")
2013
 
2114
 
2215
 @app.command(name="down")
23
-@app.command(name="unapply")
16
+@app.command(name="drop")
2417
 def down(
2518
     root: Annotated[Path, typer.Option("--repository", "-r", help="Repository directory.", default_factory=lambda: Path.cwd(), dir_okay=True, file_okay=False, exists=True)],
2619
     database_url: Annotated[str | None, typer.Option("--database", "-d", help="Database URL. Can also be set via MITCH_DATABASE_URL or DATABASE_URL environment variable.")] = None,
@@ -32,12 +25,11 @@
3225
         runner = Runner(connection)
3326
         ids = [m.id for m in repo.migrations]
3427
         applied_migrations = list(m for m in repo.by_ids_with_dependants(ids) if runner.deployment_status(m) in ('applied', 'modified'))
35
-
36
-        for batch in batch_transactional_migrations(applied_migrations):
37
-            runner.autocommit = not batch.transactional
38
-            with runner.transaction() if batch.transactional else nullcontext():
39
-                for m in batch.migrations:
40
-                    rich.print(f"[blue]Reverting:[/blue] Migration '{m.id}'")
41
-                    runner.revert_migration(m)
28
+        runner.revert_migrations(
29
+            applied_migrations,
30
+            before_each=lambda migration: rich.print(
31
+                f"[blue]Reverting:[/blue] Migration '{migration.id}'"
32
+            ),
33
+        )
4234
 
4335
     engine.dispose()

modified src/mitch/runner.py +30 −1

@@ -2,12 +2,15 @@
22
 from contextlib import contextmanager
33
 from pathlib import Path
44
 from datetime import datetime, timezone
5
+from contextlib import nullcontext
6
+from typing import Iterable, Callable
57
 
68
 from sqlalchemy.engine import Connection
79
 import sqlalchemy as sa
810
 import sqlparse
911
 
1012
 from .migration import Migration
13
+from .helpers import batch_transactional_migrations
1114
 
1215
 
1316
 class Runner:
@@ -206,7 +209,7 @@
206209
                         action='applied',
207210
                         timestamp=applied_at
208211
                     )
209
-                )
212
+                    )
210213
 
211214
     
212215
     def revert_migration(self, migration: Migration) -> None:
@@ -230,3 +233,29 @@
230233
                         timestamp=datetime.now(timezone.utc)
231234
                     )
232235
                 )
236
+
237
+    def deploy_migrations(
238
+        self,
239
+        migrations: Iterable[Migration],
240
+        before_each: Callable[[Migration], None] | None = None,
241
+    ) -> None:
242
+        for batch in batch_transactional_migrations(migrations):
243
+            self.autocommit = not batch.transactional
244
+            with self.transaction() if batch.transactional else nullcontext():
245
+                for migration in batch.migrations:
246
+                    if before_each is not None:
247
+                        before_each(migration)
248
+                    self.apply_migration(migration)
249
+
250
+    def revert_migrations(
251
+        self,
252
+        migrations: Iterable[Migration],
253
+        before_each: Callable[[Migration], None] | None = None,
254
+    ) -> None:
255
+        for batch in batch_transactional_migrations(migrations):
256
+            self.autocommit = not batch.transactional
257
+            with self.transaction() if batch.transactional else nullcontext():
258
+                for migration in batch.migrations:
259
+                    if before_each is not None:
260
+                        before_each(migration)
261
+                    self.revert_migration(migration)

modified tests/test_cli.py +10 −10

@@ -5,16 +5,17 @@
55
 from typer.testing import CliRunner
66
 
77
 from mitch.cli import app
8
-from mitch.cli import deploy as deploy_module
8
+from mitch.repository import Repository
9
+from mitch.watcher import EventType
910
 
1011
 runner = CliRunner()
1112
 
1213
 
13
-def test_deploy_help():
14
-    result = runner.invoke(app, ["deploy", "--help"])
14
+def test_add_help():
15
+    result = runner.invoke(app, ["add", "--help"])
1516
 
1617
     assert result.exit_code == 0
17
-    assert "Deploy the specified migrations." in result.output
18
+    assert "Deploy the specified migrations in the repository." in result.output
1819
 
1920
 
2021
 def test_up_help_includes_watch_options():
@@ -22,17 +23,16 @@
2223
 
2324
     assert result.exit_code == 0
2425
     assert "--watch" in result.output
25
-    assert "--watch-keep-going" in result.output
2626
 
2727
 
28
-def test_deploy_applies_migration_to_sqlite(tmp_path):
28
+def test_add_applies_migration_to_sqlite(tmp_path):
2929
     db_path = tmp_path / "test.db"
3030
     database_url = f"sqlite:///{db_path}"
3131
 
3232
     result = runner.invoke(
3333
         app,
3434
         [
35
-            "deploy",
35
+            "add",
3636
             "001-init",
3737
             "--repository",
3838
             "tests/migrations",
@@ -129,14 +129,14 @@
129129
     db_path = tmp_path / "test.db"
130130
     database_url = f"sqlite:///{db_path}"
131131
 
132
-    def fake_watch(root, on_change, keep_going, debounce_seconds=0.5):
132
+    def fake_watch_for_changes(self):
133133
         (repo_path / "002-add.up.sql").write_text(
134134
             "ALTER TABLE some_table ADD COLUMN extra int;",
135135
             encoding="utf-8",
136136
         )
137
-        on_change()
137
+        yield [(EventType.CREATED, repo_path / "002-add.up.sql")]
138138
 
139
-    monkeypatch.setattr(deploy_module, "_watch_migrations", fake_watch)
139
+    monkeypatch.setattr(Repository, "watch_for_changes", fake_watch_for_changes)
140140
 
141141
     result = runner.invoke(
142142
         app,

modified tests/test_runner.py +59 −0

@@ -65,6 +65,65 @@
6565
     assert table[0] == 'some_table'
6666
 
6767
 
68
+def test_runner_deploy_migrations_batches_and_commits(tmp_path):
69
+    db_path = tmp_path / "runner-deploy.db"
70
+    engine = create_engine(f"sqlite:///{db_path}")
71
+
72
+    up_script = tmp_path / "001-create.up.sql"
73
+    up_script.write_text("CREATE TABLE deployed_with_batching (id int);", encoding="utf-8")
74
+    migration = Migration(id="001-create", up_script=up_script)
75
+
76
+    with engine.connect() as connection:
77
+        runner = Runner(connection)
78
+        runner.deploy_migrations([migration])
79
+
80
+    with engine.connect() as connection:
81
+        row = connection.execute(
82
+            sa.text("SELECT id FROM mitch_migrations WHERE id = '001-create'")
83
+        ).first()
84
+        table = connection.execute(
85
+            sa.text(
86
+                "SELECT name FROM sqlite_schema WHERE type='table' AND name='deployed_with_batching'"
87
+            )
88
+        ).first()
89
+
90
+    engine.dispose()
91
+
92
+    assert row is not None
93
+    assert table is not None
94
+
95
+
96
+def test_runner_revert_migrations_batches_and_commits(tmp_path):
97
+    db_path = tmp_path / "runner-revert.db"
98
+    engine = create_engine(f"sqlite:///{db_path}")
99
+
100
+    up_script = tmp_path / "001-create.up.sql"
101
+    down_script = tmp_path / "001-create.down.sql"
102
+    up_script.write_text("CREATE TABLE reverted_with_batching (id int);", encoding="utf-8")
103
+    down_script.write_text("DROP TABLE reverted_with_batching;", encoding="utf-8")
104
+    migration = Migration(id="001-create", up_script=up_script, down_script=down_script)
105
+
106
+    with engine.connect() as connection:
107
+        runner = Runner(connection)
108
+        runner.deploy_migrations([migration])
109
+        runner.revert_migrations([migration])
110
+
111
+    with engine.connect() as connection:
112
+        row = connection.execute(
113
+            sa.text("SELECT id FROM mitch_migrations WHERE id = '001-create'")
114
+        ).first()
115
+        table = connection.execute(
116
+            sa.text(
117
+                "SELECT name FROM sqlite_schema WHERE type='table' AND name='reverted_with_batching'"
118
+            )
119
+        ).first()
120
+
121
+    engine.dispose()
122
+
123
+    assert row is None
124
+    assert table is None
125
+
126
+
68127
 def test_runner_split_statements_drops_empty(runner):
69128
     statements = list(runner._split_statements("\n-- only a comment\n     \n"))
70129
     assert statements == []