Public repository: timo / mitch

Reader

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

fix: address review of rework and rebuild

public

fix: address review of rework and rebuild

- rebuild also under --restore-order
- --allow-autocommit gives up atomicity only when a participant is
  non-transactional; atomic() is reentrant
- rework targets the whole version chain: `after` and the rebuild
  template cover dependants of every earlier version
- log groups versions but keeps apply order otherwise
- test checkout forward and stash across a rework

Refs #2
Changesetcdbf8a3138cac969e05ab2e5047cda9b13828021
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents9e2f6a8c057f
Children
Pushlog
by timo via ssh

modified src/mitch/cli/deploy.py +11 −4

@@ -192,6 +192,13 @@
192192
     return set(to_revert), requested
193193
 
194194
 
195
+def _all_or_nothing(runner: Runner, migrations: Iterable[Migration], allow_autocommit: bool):
196
+    """One transaction, unless autocommit is allowed and actually needed by a non-transactional migration."""
197
+    if allow_autocommit and any(not m.transactional for m in migrations):
198
+        return nullcontext()
199
+    return runner.atomic()
200
+
201
+
195202
 def _rebuild(
196203
     project: Project,
197204
     runner: Runner,
@@ -212,7 +219,7 @@
212219
     requested = {m for m in dependants if not runner.is_pulled_in(m)}
213220
 
214221
     try:
215
-        with runner.atomic() if not allow_autocommit else nullcontext():
222
+        with _all_or_nothing(runner, [migration, *dependants], allow_autocommit):
216223
             _revert_with_feedback(
217224
                 runner,
218225
                 dependants,
@@ -291,11 +298,11 @@
291298
 
292299
     late = _late_arrivals(runner, to_apply)
293300
     if late and restore_order:
294
-        transactional = not allow_autocommit
295
-        with runner.atomic() if transactional else nullcontext():
301
+        with _all_or_nothing(runner, project.all_migrations, allow_autocommit):
296302
             reverted, requested = _restore_order(project, runner, to_apply, late, allow_autocommit)
297303
             requested_before |= requested
298
-            deploy(list(project.with_dependencies(set(to_apply) | reverted)))
304
+            reordered = list(project.with_dependencies(set(to_apply) | reverted))
305
+            _deploy_with_rebuilds(project, runner, reordered, deploy, allow_autocommit)
299306
     else:
300307
         for migration, keys in late.items():
301308
             rich.print(

modified src/mitch/cli/log.py +13 −8

@@ -10,7 +10,7 @@
1010
 from ..helpers import connection_for
1111
 from ..project import Project
1212
 from ..runner import Runner
13
-from ..versions import grouping_key
13
+from ..versions import split_version
1414
 
1515
 app = typer.Typer(help="Show applied migrations in the project.")
1616
 
@@ -67,14 +67,19 @@
6767
             for migration in project.required_migrations()
6868
             if not project.is_own(migration)
6969
         }
70
-        # Versions of a reworked migration are listed together (ADR cli/rework/...); otherwise in apply order.
70
+        rows_in_apply_order = [
71
+            row
72
+            for row in runner.applied_records()
73
+            if row.project_id == own_local_id or (row.project_id, row.id) in required_linked_by_local_key
74
+        ]
75
+        # Versions of a reworked migration are listed together, where the first of them was applied;
76
+        # everything else keeps its apply order.
77
+        first_position: dict[tuple[int, str], int] = {}
78
+        for position, row in enumerate(rows_in_apply_order):
79
+            first_position.setdefault((row.project_id, split_version(row.id)[0]), position)
7180
         rows = sorted(
72
-            (
73
-                row
74
-                for row in runner.applied_records()
75
-                if row.project_id == own_local_id or (row.project_id, row.id) in required_linked_by_local_key
76
-            ),
77
-            key=lambda row: grouping_key(row.id)[:1],
81
+            rows_in_apply_order,
82
+            key=lambda row: (first_position[(row.project_id, split_version(row.id)[0])], split_version(row.id)[1]),
7883
         )
7984
 
8085
         if not rows:

modified src/mitch/cli/rework.py +5 −3

@@ -10,7 +10,7 @@
1010
 from .. import toml_writer
1111
 from ..errors import CannotReworkLinkedMigrationError, MissingMigrationError
1212
 from ..project import Project
13
-from ..versions import newest_version, split_version, version_id
13
+from ..versions import newest_version, split_version, version_id, versions_of
1414
 
1515
 app = typer.Typer(help="Rework an existing migration.")
1616
 
@@ -49,6 +49,8 @@
4949
     current = newest_version(project.migrations, base)
5050
     if current is None:
5151
         raise MissingMigrationError(migration_id)
52
+    # All versions so far: what built on any of them must run before the new version and may need a rebuild.
53
+    versions = sorted(versions_of(project.migrations, base), key=lambda m: split_version(m.id)[1])
5254
     _, current_version = split_version(current.id)
5355
     new_id = version_id(base, current_version + 1)
5456
 
@@ -67,7 +69,7 @@
6769
     )
6870
 
6971
     # Turn the files at the original path into the new version.
70
-    dependants = [m for m in project.with_dependants([current]) if m != current and project.is_own(m)]
72
+    dependants = [m for m in project.with_dependants(versions) if m not in versions and project.is_own(m)]
7173
     new_config = {
7274
         "id": new_id,
7375
         "created_at": datetime.now(timezone.utc).replace(microsecond=0),
@@ -77,7 +79,7 @@
7779
         "idempotent": current.idempotent,
7880
     }
7981
     _sibling(current.up_script, path_stem, ".config.toml").write_text(
80
-        toml_writer.dumps(new_config, comments=[f"rebuild_dependants_of = {toml_writer.value([current.id])}"]),
82
+        toml_writer.dumps(new_config, comments=[f"rebuild_dependants_of = {toml_writer.value([v.id for v in versions])}"]),
8183
         encoding="utf-8",
8284
     )
8385
     # Reverting the new version must restore the archived one, which stays applied.

modified src/mitch/runner.py +3 −0

@@ -186,6 +186,9 @@
186186
     @contextmanager
187187
     def atomic(self):
188188
         """Run everything inside in one transaction, including reverts and applies that open their own."""
189
+        if self._atomic:
190
+            yield self
191
+            return
189192
         self._commit_transaction_if_open_but_empty()
190193
         with self.connection.begin():
191194
             self._atomic = True

modified src/mitch/versions.py +5 −2

@@ -26,6 +26,9 @@
2626
     return (base, version, migration_id)
2727
 
2828
 
29
+def versions_of(migrations: Iterable[Migration], base: str) -> list[Migration]:
30
+    return [m for m in migrations if split_version(m.id)[0] == base]
31
+
32
+
2933
 def newest_version(migrations: Iterable[Migration], base: str) -> Migration | None:
30
-    versions = [m for m in migrations if split_version(m.id)[0] == base]
31
-    return max(versions, key=lambda m: split_version(m.id)[1], default=None)
34
+    return max(versions_of(migrations, base), key=lambda m: split_version(m.id)[1], default=None)

modified tests/test_rework.py +75 −1

@@ -328,6 +328,8 @@
328328
     assert _config(root / "answer@2.config.toml")["id"] == "answer@2"
329329
     assert _config(root / "answer.config.toml")["id"] == "answer@3"
330330
     assert _config(root / "answer.config.toml")["dependencies"] == ["answer@2"]
331
+    assert _config(root / "answer.config.toml")["after"] == ["audit-reader", "reader"]
332
+    assert '# rebuild_dependants_of = ["answer", "answer@2"]' in (root / "answer.config.toml").read_text(encoding="utf-8")
331333
     assert _config(root / "answer@1.config.toml")["id"] == "answer"
332334
 
333335
 
@@ -403,4 +405,76 @@
403405
 
404406
     mitch("up", "-p", str(root), "-d", db_url(tmp_path))
405407
     log = mitch("log", "-p", str(root), "-d", db_url(tmp_path))
406
-    assert log.output.index("answer@2") < log.output.index("answer-cache")
408
+    assert log.output.index("answer@2") < log.output.index("reader")
409
+    assert log.output.index("reader") < log.output.index("audit-reader")
410
+
411
+
412
+
413
+# ---------------------------------------------------------------- review findings
414
+
415
+
416
+def test_restore_order_still_rebuilds_dependants(tmp_path):
417
+    root = _view_project(tmp_path)
418
+    write_migration(root, "optional", *table("optional"))
419
+    write_migration(root, "late", *table("late"), 'after = ["optional"]\n')
420
+    mitch("add", "d", "late", "-p", str(root), "-d", db_url(tmp_path))
421
+    _write_rebuilder(root)
422
+
423
+    result = mitch("add", "optional", "m", "--restore-order", "-p", str(root), "-d", db_url(tmp_path))
424
+
425
+    assert result.exit_code == 0, result.output
426
+    assert ("d", "reverted") in audit(tmp_path)
427
+
428
+
429
+def test_allow_autocommit_keeps_a_fully_transactional_rebuild_atomic(tmp_path):
430
+    root = _view_project(tmp_path)
431
+    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
432
+    _write_rebuilder(root, up="DROP VIEW v; SELECT missing FROM nowhere;")
433
+
434
+    result = mitch("add", "m", "--allow-autocommit", "-p", str(root), "-d", db_url(tmp_path))
435
+
436
+    assert result.exit_code == 1
437
+    assert applied_ids(tmp_path) == {"base", "x", "d"}
438
+    assert ("d", "reverted") not in audit(tmp_path)
439
+
440
+
441
+def _rework_branches(tmp_path: Path) -> tuple[Path, str]:
442
+    """A repository whose current branch is before the rework and branch `reworked` after it."""
443
+    root = _reworkable(tmp_path)
444
+    init_repo(root)
445
+    commit_all(root, "before rework")
446
+    base = git(root, "branch", "--show-current")
447
+    git(root, "checkout", "-b", "reworked")
448
+    assert mitch("rework", "answer", "-p", str(root)).exit_code == 0
449
+    (root / "answer.up.sql").write_text(FUNCTION_V2, encoding="utf-8")
450
+    commit_all(root, "rework answer")
451
+    git(root, "checkout", base)
452
+    return root, base
453
+
454
+
455
+def test_checkout_forward_across_a_rework_reverts_nothing_and_leaves_the_new_version_pending(tmp_path):
456
+    root, _ = _rework_branches(tmp_path)
457
+    assert mitch("up", "-p", str(root), "-d", db_url(tmp_path)).exit_code == 0
458
+    history_before = len(audit(tmp_path))
459
+
460
+    result = mitch("checkout", "reworked", "-p", str(root), "-d", db_url(tmp_path))
461
+
462
+    assert result.exit_code == 0, result.output
463
+    assert len(audit(tmp_path)) == history_before
464
+    assert "answer@2" not in applied_ids(tmp_path)
465
+
466
+
467
+def test_stash_of_a_rework_in_progress_reverts_only_the_new_version(tmp_path):
468
+    root = _reworkable(tmp_path)
469
+    init_repo(root)
470
+    commit_all(root, "before rework")
471
+    mitch("rework", "answer", "-p", str(root))
472
+    (root / "answer.up.sql").write_text(FUNCTION_V2, encoding="utf-8")
473
+    assert mitch("up", "-p", str(root), "-d", db_url(tmp_path)).exit_code == 0
474
+    history_before = len(audit(tmp_path))
475
+
476
+    result = mitch("stash", "-p", str(root), "-d", db_url(tmp_path))
477
+
478
+    assert result.exit_code == 0, result.output
479
+    assert audit(tmp_path)[history_before:] == [("answer@2", "reverted")]
480
+    assert "answer@2" not in applied_ids(tmp_path)