Public repository: timo / mitch

Reader

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

Cleanup

public

Cleanup
Changeset778866b59fee4aacae75569eab8695900e3b1f54
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parentsed2ab756922e
Children
Pushlog
by timo via ssh

modified src/mitch/cli/deploy.py +178 −102

@@ -1,13 +1,14 @@
11
 from enum import Enum
2
-from typing import Annotated
2
+from typing import Annotated, Callable, Iterable
33
 from pathlib import Path
44
 
55
 from rich.prompt import Confirm
66
 import typer
77
 import rich
88
 
9
+from ..migration import Migration
910
 from ..repository import Repository
10
-from ..runner import Runner
11
+from ..runner import Runner, DeploymentStatus
1112
 from ..helpers import connection_for
1213
 from ..watcher import EventType
1314
 
@@ -19,6 +20,163 @@
1920
 
2021
 
2122
 app = typer.Typer()
23
+
24
+
25
+def _resolve_if_modified_policy(
26
+    if_modified: IfModifiedOption | None,
27
+    watch: bool,
28
+) -> IfModifiedOption:
29
+    if if_modified is not None:
30
+        return if_modified
31
+    if watch:
32
+        return IfModifiedOption.REDEPLOY
33
+
34
+    console = rich.get_console()
35
+    if console.is_interactive and console.is_terminal:
36
+        return IfModifiedOption.PROMPT
37
+    return IfModifiedOption.ABORT
38
+
39
+
40
+def _collect_redeploy_migrations(
41
+    runner: Runner,
42
+    covered_migrations: set[Migration],
43
+    if_modified: IfModifiedOption,
44
+) -> set[Migration]:
45
+    if if_modified == IfModifiedOption.IGNORE:
46
+        return set()
47
+
48
+    redeploy = set(
49
+        migration
50
+        for migration in covered_migrations
51
+        if runner.deployment_status(migration) == "modified"
52
+    )
53
+
54
+    if redeploy and if_modified == IfModifiedOption.ABORT:
55
+        rich.print("[red]Error:[/red] The following migrations have been modified since their last deployment:")
56
+        for migration in redeploy:
57
+            rich.print(f" - Migration '{migration.id}'")
58
+        raise typer.Abort("Aborting due to modified migrations.")
59
+
60
+    if redeploy and if_modified == IfModifiedOption.PROMPT:
61
+        for migration in redeploy.copy():
62
+            rich.print(
63
+                f"[yellow]Warning:[/yellow] Migration '{migration.id}' has been modified since it was last deployed."
64
+            )
65
+            match Confirm.ask(
66
+                "(r)evert and redeploy, (i)gnore, or (e)exit?",
67
+                choices=["r", "i", "e"],
68
+                default="e",
69
+            ):
70
+                case "r":
71
+                    continue
72
+                case "i":
73
+                    redeploy.remove(migration)
74
+                case "e":
75
+                    raise typer.Abort()
76
+
77
+    return redeploy
78
+
79
+
80
+def _revert_with_feedback(
81
+    runner: Runner,
82
+    migrations: list[Migration],
83
+    message_builder: Callable[[Migration, DeploymentStatus], str],
84
+) -> None:
85
+    runner.revert_migrations(
86
+        migrations,
87
+        before_each=lambda migration, status: rich.print(
88
+            message_builder(migration, status)
89
+        ),
90
+    )
91
+
92
+
93
+def _deploy_with_feedback(
94
+    runner: Runner,
95
+    migrations: list[Migration],
96
+    message_builder: Callable[[Migration, DeploymentStatus], str],
97
+) -> None:
98
+    runner.deploy_migrations(
99
+        migrations,
100
+        before_each=lambda migration, status: rich.print(
101
+            message_builder(migration, status)
102
+        ),
103
+    )
104
+
105
+
106
+def _apply_planned_migrations(
107
+    repo: Repository,
108
+    runner: Runner,
109
+    covered_migrations: set[Migration],
110
+    redeploy: set[Migration],
111
+) -> None:
112
+    to_revert = list(repo.with_dependants(redeploy))
113
+    _revert_with_feedback(
114
+        runner,
115
+        to_revert,
116
+        lambda migration, status: (
117
+            f"[blue]Reverting:[/blue] {status} migration '{migration.id}' due to modifications after deployment."
118
+        ),
119
+    )
120
+
121
+    pending = {
122
+        migration
123
+        for migration in covered_migrations
124
+        if runner.deployment_status(migration) == "pending"
125
+    }
126
+    to_apply = list(repo.with_dependencies(pending | redeploy))
127
+    _deploy_with_feedback(
128
+        runner,
129
+        to_apply,
130
+        lambda migration, status: (
131
+            f"[green]Deploying:[/green] Migration '{migration.id}' ({status})"
132
+        ),
133
+    )
134
+
135
+
136
+def _process_watch_changes(
137
+    repo: Repository,
138
+    runner: Runner,
139
+    covered_migrations: set[Migration],
140
+    changes: Iterable[tuple[EventType, Path]],
141
+    allow_new_migrations: bool,
142
+) -> None:
143
+    # Reload repository after receiving events so created files are visible in the index.
144
+    repo.reload()
145
+
146
+    applied_and_modified = set()
147
+    added_and_pending = set()
148
+    for action, path in changes:
149
+        if action == EventType.MODIFIED and (
150
+            path.name.endswith(".up.sql") or path.name.endswith(".config.toml")
151
+        ):
152
+            migration = repo.by_path(path)
153
+            if migration not in covered_migrations:
154
+                continue
155
+            if runner.deployment_status(migration) in ("modified", "applied"):
156
+                applied_and_modified.add(migration)
157
+
158
+        if allow_new_migrations and action == EventType.CREATED and path.name.endswith(".up.sql"):
159
+            migration = repo.by_path(path)
160
+            if runner.deployment_status(migration) == "pending":
161
+                added_and_pending.add(migration)
162
+
163
+    to_revert = list(repo.with_dependants(applied_and_modified))
164
+    _revert_with_feedback(
165
+        runner,
166
+        to_revert,
167
+        lambda migration, status: (
168
+            f"[blue]Reverted:[/blue] Migration '{migration.id}' ({status})"
169
+        ),
170
+    )
171
+
172
+    to_apply = list(repo.with_dependencies(applied_and_modified | added_and_pending))
173
+    _deploy_with_feedback(
174
+        runner,
175
+        to_apply,
176
+        lambda migration, status: (
177
+            f"[green]Deployed:[/green] Migration '{migration.id}' ({status})"
178
+        ),
179
+    )
22180
 
23181
 
24182
 @app.command(name="add")
@@ -47,112 +205,30 @@
47205
 
48206
     repo = Repository(root)
49207
     covered_migrations = set(repo.by_ids_with_dependencies(migration_ids))
50
-
51
-    # Choose default behavior for modified migrations based on whether watch mode is enabled...
52
-    if if_modified is None and watch:
53
-        if_modified = IfModifiedOption.REDEPLOY
54
-    
55
-    # ...and whether we're in an interactive terminal.
56
-    if if_modified is None:
57
-        console = rich.get_console()
58
-        if console.is_interactive and console.is_terminal:
59
-            if_modified = IfModifiedOption.PROMPT
60
-        else:
61
-            if_modified = IfModifiedOption.ABORT
208
+    allow_new_migrations = ctx.info_name == "up"
209
+
210
+    if_modified = _resolve_if_modified_policy(if_modified, watch)
62211
 
63212
     with connection_for(database_url) as connection:
64213
         runner = Runner(connection)
65
-
66
-        # If the option is to ignore modifications, we won't redeploy any modified migrations.
67
-        if if_modified == IfModifiedOption.IGNORE:
68
-            redeploy = set()
69
-        
70
-        # In other cases, we prepare to redeploy all modified migrations, 
71
-        # but for the prompt case we will confirm with the user before actually doing it. 
72
-        else:
73
-            redeploy = set(m for m in covered_migrations if runner.deployment_status(m) == 'modified')
74
-
75
-        # Abort if there are modified migrations and the option is set to abort. Especially on CI where prompting is not possible.
76
-        if redeploy and if_modified == IfModifiedOption.ABORT:
77
-            rich.print("[red]Error:[/red] The following migrations have been modified since their last deployment:")
78
-            for m in redeploy:
79
-                rich.print(f" - Migration '{m.id}'")
80
-            raise typer.Abort("Aborting due to modified migrations.")
81
-
82
-        # If prompting is enabled, ask the user what to do with each modified migration.
83
-        if redeploy and if_modified == IfModifiedOption.PROMPT:
84
-            for migration in redeploy.copy():
85
-                rich.print(f"[yellow]Warning:[/yellow] Migration '{migration.id}' has been modified since it was last deployed.")
86
-                match Confirm.ask(f"(r)evert and redeploy, (i)gnore, or (e)exit?", choices=["r", "i", "e"], default="e"):
87
-                    case "r":
88
-                        continue
89
-                    case "i":
90
-                        redeploy.remove(migration)
91
-                    case "e":
92
-                        raise typer.Abort()
93
-
94
-        # Revert modified migrations and their dependants before redeploying.
95
-        to_revert = list(repo.with_dependants(redeploy))
96
-        runner.revert_migrations(
97
-            to_revert,
98
-            before_each=lambda migration, status: rich.print(
99
-                f"[blue]Reverting:[/blue] {status} migration '{migration.id}' due to modifications after deployment."
100
-            ),
101
-        )
102
-
103
-        # Deploy pending migrations, including redeployments for modified ones.
104
-        pending = set(m for m in covered_migrations if runner.deployment_status(m) == 'pending')
105
-        to_apply = list(repo.with_dependencies(pending | redeploy))
106
-        runner.deploy_migrations(
107
-            to_apply,
108
-            before_each=lambda migration, status: rich.print(
109
-                f"[green]Deploying:[/green] Migration '{migration.id}' ({status})"
110
-            ),
111
-        )
112
-
113
-        if watch:
114
-            incoming_changes = repo.watch_for_changes()
115
-        
116
-        while watch:
214
+        redeploy = _collect_redeploy_migrations(runner, covered_migrations, if_modified)
215
+        _apply_planned_migrations(repo, runner, covered_migrations, redeploy)
216
+
217
+        if not watch:
218
+            return
219
+
220
+        incoming_changes = repo.watch_for_changes()
221
+        while True:
117222
             try:
118
-                changes = next(incoming_changes)  # pyright: ignore[reportPossiblyUnboundVariable]
223
+                changes = next(incoming_changes)
119224
             except StopIteration:
120225
                 break
121
-
122
-            # Reload repository after receiving events so created files are visible in the index.
123
-            repo.reload()
124
-
125
-            # Collect modified and added migrations from the incoming changes.
126
-            applied_and_modified = set()
127
-            added_and_pending = set()
128
-            for action, path in changes:
129
-                if action == EventType.MODIFIED and (path.name.endswith(".up.sql") or path.name.endswith(".config.toml")):
130
-                    migration = repo.by_path(path)
131
-                    if migration not in covered_migrations:
132
-                        continue
133
-
134
-                    if runner.deployment_status(migration) in ('modified', 'applied'):
135
-                        applied_and_modified.add(migration)
136
-                
137
-                if ctx.info_name in ('up',) and action == EventType.CREATED and path.name.endswith(".up.sql"):
138
-                    migration = repo.by_path(path)
139
-                    if runner.deployment_status(migration) == 'pending':
140
-                        added_and_pending.add(migration)
141
-
142
-            to_revert = list(repo.with_dependants(applied_and_modified))
143
-            runner.revert_migrations(
144
-                to_revert,
145
-                before_each=lambda migration, status: rich.print(
146
-                    f"[blue]Reverted:[/blue] Migration '{migration.id}' ({status})"
147
-                ),
148
-            )
149
-            
150
-            to_be_applied = list(repo.with_dependencies(applied_and_modified | added_and_pending))
151
-            runner.deploy_migrations(
152
-                to_be_applied,
153
-                before_each=lambda migration, status: rich.print(
154
-                    f"[green]Deployed:[/green] Migration '{migration.id}' ({status})"
155
-                ),
226
+            _process_watch_changes(
227
+                repo,
228
+                runner,
229
+                covered_migrations,
230
+                changes,
231
+                allow_new_migrations,
156232
             )
157233
 
158234
 

modified src/mitch/runner.py +58 −50

@@ -3,7 +3,7 @@
33
 from pathlib import Path
44
 from datetime import datetime, timezone
55
 from contextlib import nullcontext
6
-from typing import Iterable, Callable
6
+from typing import Iterable, Callable, Literal, TypeAlias
77
 
88
 from sqlalchemy.engine import Connection
99
 import sqlalchemy as sa
@@ -11,6 +11,8 @@
1111
 
1212
 from .migration import Migration
1313
 from .helpers import batch_transactional_migrations
14
+
15
+DeploymentStatus: TypeAlias = Literal["pending", "applied", "modified"]
1416
 
1517
 
1618
 class Runner:
@@ -134,7 +136,7 @@
134136
             else:
135137
                 transaction.commit()
136138
 
137
-    def deployment_status(self, migration: Migration) -> str:
139
+    def deployment_status(self, migration: Migration) -> DeploymentStatus:
138140
         deployment = self.connection.execute(
139141
             self.migration_table
140142
                 .select()
@@ -182,34 +184,7 @@
182184
             case 'modified':
183185
                 raise RuntimeError(f"Migration {migration.id} has been modified since it was applied.")
184186
             case 'pending':
185
-                sql = migration.up_script.read_text(encoding="utf-8")
186
-                statements = list(self._split_statements(sql))
187
-
188
-                raw_hash = sha1(sql.encode('utf-8')).hexdigest()
189
-                normalized_hash = sha1('; '.join(statements).encode('utf-8')).hexdigest()
190
-
191
-                for statement in statements:
192
-                    self.connection.execute(sa.text(statement))
193
-
194
-                applied_at = datetime.now(timezone.utc)
195
-                self._pending_work.append(f'applied migration {migration.id}')
196
-
197
-                self.connection.execute(
198
-                    self.migration_table.insert().values(
199
-                        id=migration.id,
200
-                        raw_hash=raw_hash,
201
-                        normalized_hash=normalized_hash,
202
-                        applied_at=applied_at
203
-                    )
204
-                )
205
-
206
-                self.connection.execute(
207
-                    self.audit_table.insert().values(
208
-                        migration_id=migration.id,
209
-                        action='applied',
210
-                        timestamp=applied_at
211
-                    )
212
-                    )
187
+                self._apply_migration(migration)
213188
 
214189
     
215190
     def revert_migration(self, migration: Migration) -> None:
@@ -217,27 +192,60 @@
217192
             case 'pending':
218193
                 pass  # No action needed
219194
             case 'applied' | 'modified':
220
-                for statement in self._statements_from_file(migration.down_script):
221
-                    self.connection.execute(sa.text(statement))
222
-
223
-                self._pending_work.append(f'reverted migration {migration.id}')
224
-
225
-                self.connection.execute(
226
-                    self.migration_table.delete().where(self.migration_table.c.id == migration.id)
227
-                )
228
-
229
-                self.connection.execute(
230
-                    self.audit_table.insert().values(
231
-                        migration_id=migration.id,
232
-                        action='reverted',
233
-                        timestamp=datetime.now(timezone.utc)
234
-                    )
235
-                )
195
+                self._revert_migration(migration)
196
+
197
+    def _apply_migration(self, migration: Migration) -> None:
198
+        sql = migration.up_script.read_text(encoding="utf-8")
199
+        statements = list(self._split_statements(sql))
200
+
201
+        raw_hash = sha1(sql.encode('utf-8')).hexdigest()
202
+        normalized_hash = sha1('; '.join(statements).encode('utf-8')).hexdigest()
203
+
204
+        for statement in statements:
205
+            self.connection.execute(sa.text(statement))
206
+
207
+        applied_at = datetime.now(timezone.utc)
208
+        self._pending_work.append(f'applied migration {migration.id}')
209
+
210
+        self.connection.execute(
211
+            self.migration_table.insert().values(
212
+                id=migration.id,
213
+                raw_hash=raw_hash,
214
+                normalized_hash=normalized_hash,
215
+                applied_at=applied_at
216
+            )
217
+        )
218
+
219
+        self.connection.execute(
220
+            self.audit_table.insert().values(
221
+                migration_id=migration.id,
222
+                action='applied',
223
+                timestamp=applied_at
224
+            )
225
+        )
226
+
227
+    def _revert_migration(self, migration: Migration) -> None:
228
+        for statement in self._statements_from_file(migration.down_script):
229
+            self.connection.execute(sa.text(statement))
230
+
231
+        self._pending_work.append(f'reverted migration {migration.id}')
232
+
233
+        self.connection.execute(
234
+            self.migration_table.delete().where(self.migration_table.c.id == migration.id)
235
+        )
236
+
237
+        self.connection.execute(
238
+            self.audit_table.insert().values(
239
+                migration_id=migration.id,
240
+                action='reverted',
241
+                timestamp=datetime.now(timezone.utc)
242
+            )
243
+        )
236244
 
237245
     def deploy_migrations(
238246
         self,
239247
         migrations: Iterable[Migration],
240
-        before_each: Callable[[Migration, str], None] | None = None,
248
+        before_each: Callable[[Migration, DeploymentStatus], None] | None = None,
241249
     ) -> None:
242250
         for batch in batch_transactional_migrations(migrations):
243251
             self.autocommit = not batch.transactional
@@ -248,12 +256,12 @@
248256
                         continue
249257
                     if before_each is not None:
250258
                         before_each(migration, status)
251
-                    self.apply_migration(migration)
259
+                    self._apply_migration(migration)
252260
 
253261
     def revert_migrations(
254262
         self,
255263
         migrations: Iterable[Migration],
256
-        before_each: Callable[[Migration, str], None] | None = None,
264
+        before_each: Callable[[Migration, DeploymentStatus], None] | None = None,
257265
     ) -> None:
258266
         for batch in batch_transactional_migrations(migrations):
259267
             self.autocommit = not batch.transactional
@@ -264,4 +272,4 @@
264272
                         continue
265273
                     if before_each is not None:
266274
                         before_each(migration, status)
267
-                    self.revert_migration(migration)
275
+                    self._revert_migration(migration)