Use watchdog properly, rename commands apply->up, deploy->add, unapply->drop
public
Use watchdog properly, rename commands apply->up, deploy->add, unapply->drop
| Changeset | 78239ca0d1e6607eee927c446b891f6dcb1ff9e3 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | 8dee25b9bb42 |
| Children | |
| Pushlog | by timo via ssh |
modified src/mitch/cli/deploy.py +41 −180
| @@ -1,10 +1,6 @@ | ||
| 1 | -from collections import defaultdict | |
| 2 | 1 | from enum import Enum |
| 3 | -from typing import Annotated, Iterable, Callable | |
| 2 | +from typing import Annotated | |
| 4 | 3 | from pathlib import Path |
| 5 | -from contextlib import nullcontext | |
| 6 | -from threading import Event | |
| 7 | -from time import monotonic, sleep | |
| 8 | 4 | |
| 9 | 5 | from rich.prompt import Confirm |
| 10 | 6 | import typer |
| @@ -12,7 +8,7 @@ | ||
| 12 | 8 | |
| 13 | 9 | from ..repository import Repository |
| 14 | 10 | from ..runner import Runner |
| 15 | -from ..helpers import batch_transactional_migrations, create_engine, connection_for | |
| 11 | +from ..helpers import connection_for | |
| 16 | 12 | from ..watcher import EventType |
| 17 | 13 | |
| 18 | 14 | class IfModifiedOption(str, Enum): |
| @@ -25,163 +21,8 @@ | ||
| 25 | 21 | app = typer.Typer() |
| 26 | 22 | |
| 27 | 23 | |
| 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( | |
| 185 | 26 | ctx: typer.Context, |
| 186 | 27 | migration_ids: list[str], |
| 187 | 28 | 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 @@ | ||
| 202 | 43 | typer.Option("--watch", help="Watch the repository and re-run deployments on changes."), |
| 203 | 44 | ] = False, |
| 204 | 45 | ) -> None: |
| 205 | - """Deploy all migrations in the repository.""" | |
| 46 | + """Deploy the specified migrations in the repository.""" | |
| 206 | 47 | |
| 207 | 48 | repo = Repository(root) |
| 208 | 49 | covered_migrations = set(repo.by_ids_with_dependencies(migration_ids)) |
| @@ -251,27 +92,40 @@ | ||
| 251 | 92 | raise typer.Abort() |
| 252 | 93 | |
| 253 | 94 | # 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 | + ) | |
| 257 | 102 | |
| 258 | 103 | # Deploy pending migrations, including redeployments for modified ones. |
| 259 | 104 | 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 | + ) | |
| 263 | 112 | |
| 264 | 113 | if watch: |
| 265 | 114 | incoming_changes = repo.watch_for_changes() |
| 266 | 115 | |
| 267 | 116 | 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() | |
| 270 | 124 | |
| 271 | 125 | # Collect modified and added migrations from the incoming changes. |
| 272 | 126 | applied_and_modified = set() |
| 273 | 127 | added_and_pending = set() |
| 274 | - for action, path in next(incoming_changes): # pyright: ignore[reportPossiblyUnboundVariable] | |
| 128 | + for action, path in changes: | |
| 275 | 129 | if action == EventType.MODIFIED and (path.name.endswith(".up.sql") or path.name.endswith(".config.toml")): |
| 276 | 130 | migration = repo.by_path(path) |
| 277 | 131 | if migration not in covered_migrations: |
| @@ -285,14 +139,21 @@ | ||
| 285 | 139 | if runner.deployment_status(migration) == 'pending': |
| 286 | 140 | added_and_pending.add(migration) |
| 287 | 141 | |
| 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 | + ) | |
| 291 | 149 | |
| 292 | 150 | 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 | + ) | |
| 296 | 157 | |
| 297 | 158 | |
| 298 | 159 | @app.command() |
| @@ -319,4 +180,4 @@ | ||
| 319 | 180 | """Deploy all migrations in the repository.""" |
| 320 | 181 | |
| 321 | 182 | 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 | |
| 3 | 2 | from pathlib import Path |
| 4 | -from contextlib import nullcontext | |
| 5 | -from threading import Event | |
| 6 | -from time import monotonic, sleep | |
| 7 | -import os | |
| 8 | 3 | |
| 9 | -from rich.prompt import Confirm | |
| 10 | -import sqlalchemy as sa | |
| 11 | 4 | import typer |
| 12 | 5 | import rich |
| 13 | 6 | |
| 14 | 7 | from ..repository import Repository |
| 15 | 8 | from ..runner import Runner |
| 16 | -from ..helpers import batch_transactional_migrations, create_engine | |
| 9 | +from ..helpers import create_engine | |
| 17 | 10 | |
| 18 | 11 | |
| 19 | 12 | app = typer.Typer(help="Revert migrations in the repository.") |
| 20 | 13 | |
| 21 | 14 | |
| 22 | 15 | @app.command(name="down") |
| 23 | -@app.command(name="unapply") | |
| 16 | +@app.command(name="drop") | |
| 24 | 17 | def down( |
| 25 | 18 | root: Annotated[Path, typer.Option("--repository", "-r", help="Repository directory.", default_factory=lambda: Path.cwd(), dir_okay=True, file_okay=False, exists=True)], |
| 26 | 19 | 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 @@ | ||
| 32 | 25 | runner = Runner(connection) |
| 33 | 26 | ids = [m.id for m in repo.migrations] |
| 34 | 27 | 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 | + ) | |
| 42 | 34 | |
| 43 | 35 | engine.dispose() |
modified src/mitch/runner.py +30 −1
| @@ -2,12 +2,15 @@ | ||
| 2 | 2 | from contextlib import contextmanager |
| 3 | 3 | from pathlib import Path |
| 4 | 4 | from datetime import datetime, timezone |
| 5 | +from contextlib import nullcontext | |
| 6 | +from typing import Iterable, Callable | |
| 5 | 7 | |
| 6 | 8 | from sqlalchemy.engine import Connection |
| 7 | 9 | import sqlalchemy as sa |
| 8 | 10 | import sqlparse |
| 9 | 11 | |
| 10 | 12 | from .migration import Migration |
| 13 | +from .helpers import batch_transactional_migrations | |
| 11 | 14 | |
| 12 | 15 | |
| 13 | 16 | class Runner: |
| @@ -206,7 +209,7 @@ | ||
| 206 | 209 | action='applied', |
| 207 | 210 | timestamp=applied_at |
| 208 | 211 | ) |
| 209 | - ) | |
| 212 | + ) | |
| 210 | 213 | |
| 211 | 214 | |
| 212 | 215 | def revert_migration(self, migration: Migration) -> None: |
| @@ -230,3 +233,29 @@ | ||
| 230 | 233 | timestamp=datetime.now(timezone.utc) |
| 231 | 234 | ) |
| 232 | 235 | ) |
| 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 @@ | ||
| 5 | 5 | from typer.testing import CliRunner |
| 6 | 6 | |
| 7 | 7 | 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 | |
| 9 | 10 | |
| 10 | 11 | runner = CliRunner() |
| 11 | 12 | |
| 12 | 13 | |
| 13 | -def test_deploy_help(): | |
| 14 | - result = runner.invoke(app, ["deploy", "--help"]) | |
| 14 | +def test_add_help(): | |
| 15 | + result = runner.invoke(app, ["add", "--help"]) | |
| 15 | 16 | |
| 16 | 17 | 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 | |
| 18 | 19 | |
| 19 | 20 | |
| 20 | 21 | def test_up_help_includes_watch_options(): |
| @@ -22,17 +23,16 @@ | ||
| 22 | 23 | |
| 23 | 24 | assert result.exit_code == 0 |
| 24 | 25 | assert "--watch" in result.output |
| 25 | - assert "--watch-keep-going" in result.output | |
| 26 | 26 | |
| 27 | 27 | |
| 28 | -def test_deploy_applies_migration_to_sqlite(tmp_path): | |
| 28 | +def test_add_applies_migration_to_sqlite(tmp_path): | |
| 29 | 29 | db_path = tmp_path / "test.db" |
| 30 | 30 | database_url = f"sqlite:///{db_path}" |
| 31 | 31 | |
| 32 | 32 | result = runner.invoke( |
| 33 | 33 | app, |
| 34 | 34 | [ |
| 35 | - "deploy", | |
| 35 | + "add", | |
| 36 | 36 | "001-init", |
| 37 | 37 | "--repository", |
| 38 | 38 | "tests/migrations", |
| @@ -129,14 +129,14 @@ | ||
| 129 | 129 | db_path = tmp_path / "test.db" |
| 130 | 130 | database_url = f"sqlite:///{db_path}" |
| 131 | 131 | |
| 132 | - def fake_watch(root, on_change, keep_going, debounce_seconds=0.5): | |
| 132 | + def fake_watch_for_changes(self): | |
| 133 | 133 | (repo_path / "002-add.up.sql").write_text( |
| 134 | 134 | "ALTER TABLE some_table ADD COLUMN extra int;", |
| 135 | 135 | encoding="utf-8", |
| 136 | 136 | ) |
| 137 | - on_change() | |
| 137 | + yield [(EventType.CREATED, repo_path / "002-add.up.sql")] | |
| 138 | 138 | |
| 139 | - monkeypatch.setattr(deploy_module, "_watch_migrations", fake_watch) | |
| 139 | + monkeypatch.setattr(Repository, "watch_for_changes", fake_watch_for_changes) | |
| 140 | 140 | |
| 141 | 141 | result = runner.invoke( |
| 142 | 142 | app, |
modified tests/test_runner.py +59 −0
| @@ -65,6 +65,65 @@ | ||
| 65 | 65 | assert table[0] == 'some_table' |
| 66 | 66 | |
| 67 | 67 | |
| 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 | + | |
| 68 | 127 | def test_runner_split_statements_drops_empty(runner): |
| 69 | 128 | statements = list(runner._split_statements("\n-- only a comment\n \n")) |
| 70 | 129 | assert statements == [] |