Public repository: timo / mitch

Reader

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

mitch / tests / test_rework.py · 19.9 KB · at 76a2c3d332a1 · raw

Outline: 41 definitions
1
"""Rework, rebuild, ordering constraints and the ID-based checkout plan (GitLab issue #2).
2
3
All tests drive mitch through the CLI against SQLite files and git repositories under tmp_path.
4
"""
5
6
import sqlite3
7
import subprocess
8
from pathlib import Path
9
10
from typer.testing import CliRunner
11
12
from mitch.cli import app
13
14
runner = CliRunner()
15
16
17
def mitch(*args: str):
18
    return runner.invoke(app, list(args))
19
20
21
def git(cwd: Path, *args: str) -> str:
22
    result = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, check=False)
23
    assert result.returncode == 0, result.stderr or result.stdout
24
    return result.stdout.strip()
25
26
27
def init_repo(path: Path) -> str:
28
    git(path, "init")
29
    git(path, "config", "user.email", "test@example.com")
30
    git(path, "config", "user.name", "Test User")
31
    return path.name
32
33
34
def commit_all(path: Path, message: str) -> None:
35
    git(path, "add", "-A")
36
    git(path, "commit", "-m", message)
37
38
39
def write_migration(root: Path, stem: str, up: str, down: str | None = None, config: str | None = None) -> None:
40
    (root / f"{stem}.up.sql").write_text(up, encoding="utf-8")
41
    if down is not None:
42
        (root / f"{stem}.down.sql").write_text(down, encoding="utf-8")
43
    if config is not None:
44
        (root / f"{stem}.config.toml").write_text(config, encoding="utf-8")
45
46
47
def new_project(path: Path, project_id: str = "app") -> Path:
48
    path.mkdir(parents=True, exist_ok=True)
49
    (path / "mitch.toml").write_text(f'[project]\nid = "{project_id}"\n', encoding="utf-8")
50
    return path
51
52
53
def db_url(tmp_path: Path) -> str:
54
    return f"sqlite:///{tmp_path / 'test.db'}"
55
56
57
def audit(tmp_path: Path) -> list[tuple[str, str]]:
58
    """(migration ID, action) in the order they happened."""
59
    with sqlite3.connect(tmp_path / "test.db") as connection:
60
        return connection.execute("SELECT migration_id, action FROM mitch_migration_audit ORDER BY id").fetchall()
61
62
63
def applied_ids(tmp_path: Path) -> set[str]:
64
    with sqlite3.connect(tmp_path / "test.db") as connection:
65
        return {row[0] for row in connection.execute("SELECT id FROM mitch_migrations")}
66
67
68
FUNCTION_V1 = "DROP VIEW IF EXISTS answer; CREATE VIEW answer AS SELECT 41 AS value;"
69
FUNCTION_V2 = "DROP VIEW IF EXISTS answer; CREATE VIEW answer AS SELECT 42 AS value;"
70
71
72
def test_checkout_back_across_a_rework_reverts_only_the_new_version(tmp_path):
73
    root = new_project(tmp_path / "repo")
74
    init_repo(root)
75
    write_migration(root, "answer", FUNCTION_V1, "DROP VIEW answer;")
76
    write_migration(
77
        root, "reader", "CREATE TABLE reader (id int);", "DROP TABLE reader;", 'dependencies = ["answer"]\n'
78
    )
79
    commit_all(root, "before rework")
80
    base = git(root, "branch", "--show-current")
81
82
    git(root, "checkout", "-b", "reworked")
83
    write_migration(root, "answer@1", FUNCTION_V1, "DROP VIEW answer;", 'id = "answer"\n')
84
    write_migration(root, "answer", FUNCTION_V2, FUNCTION_V1, 'id = "answer@2"\ndependencies = ["answer"]\n')
85
    commit_all(root, "rework answer")
86
    assert mitch("up", "-p", str(root), "-d", db_url(tmp_path)).exit_code == 0
87
    assert applied_ids(tmp_path) == {"answer", "reader", "answer@2"}
88
    history_before = len(audit(tmp_path))
89
90
    result = mitch("checkout", base, "-p", str(root), "-d", db_url(tmp_path))
91
92
    assert result.exit_code == 0, result.output
93
    assert audit(tmp_path)[history_before:] == [("answer@2", "reverted")]
94
    assert applied_ids(tmp_path) == {"answer", "reader"}
95
96
97
# ---------------------------------------------------------------- ordering constraints
98
99
100
def table(name: str) -> tuple[str, str]:
101
    return f"CREATE TABLE {name} (id int);", f"DROP TABLE {name};"
102
103
104
def test_ordering_constraint_runs_a_migration_after_another_in_the_same_run(tmp_path):
105
    root = new_project(tmp_path / "app")
106
    # Without the constraint, "early" would sort first by creation time.
107
    write_migration(root, "late", *table("late"), "created_at = 2026-02-01\n")
108
    write_migration(root, "early", *table("early"), 'created_at = 2026-01-01\nafter = ["late"]\n')
109
110
    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))
111
112
    assert result.exit_code == 0, result.output
113
    assert [m for m, _ in audit(tmp_path)] == ["late", "early"]
114
115
116
def test_ordering_constraint_does_not_pull_in_its_target(tmp_path):
117
    root = new_project(tmp_path / "app")
118
    write_migration(root, "optional", *table("optional"))
119
    write_migration(root, "main", *table("main"), 'after = ["optional"]\n')
120
121
    result = mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path))
122
123
    assert result.exit_code == 0, result.output
124
    assert applied_ids(tmp_path) == {"main"}
125
126
127
def test_cycle_of_dependency_and_ordering_constraint_is_an_error(tmp_path):
128
    root = new_project(tmp_path / "app")
129
    write_migration(root, "a", *table("a"), 'after = ["b"]\n')
130
    write_migration(root, "b", *table("b"), 'dependencies = ["a"]\n')
131
132
    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))
133
134
    assert result.exit_code == 1
135
    assert "cycle" in result.output
136
137
138
def test_late_target_of_ordering_constraint_is_applied_with_a_warning(tmp_path):
139
    root = new_project(tmp_path / "app")
140
    write_migration(root, "optional", *table("optional"))
141
    write_migration(root, "main", *table("main"), 'after = ["optional"]\n')
142
    mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path))
143
144
    result = mitch("add", "optional", "-p", str(root), "-d", db_url(tmp_path))
145
146
    assert result.exit_code == 0, result.output
147
    assert "Warning" in result.output and "main" in result.output
148
    assert audit(tmp_path) == [("main", "applied"), ("optional", "applied")]
149
150
151
def test_restore_order_reverts_and_reapplies_around_a_late_target(tmp_path):
152
    root = new_project(tmp_path / "app")
153
    write_migration(root, "optional", *table("optional"))
154
    write_migration(root, "main", *table("main"), 'after = ["optional"]\n')
155
    mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path))
156
157
    result = mitch("add", "optional", "--restore-order", "-p", str(root), "-d", db_url(tmp_path))
158
159
    assert result.exit_code == 0, result.output
160
    assert audit(tmp_path)[1:] == [("main", "reverted"), ("optional", "applied"), ("main", "applied")]
161
162
163
def test_late_target_is_detected_through_the_recorded_constraint_of_a_project_not_loaded(tmp_path):
164
    users = new_project(tmp_path / "users", "org.example.users")
165
    write_migration(users, "create-users", *table("users"))
166
    reports = new_project(tmp_path / "reports", "org.example.reports")
167
    (reports / "mitch.toml").write_text(
168
        '[project]\nid = "org.example.reports"\n\n[projects]\nu = "../users"\n', encoding="utf-8"
169
    )
170
    write_migration(reports, "report", *table("report"), 'after = ["u:create-users"]\n')
171
    mitch("up", "-p", str(reports), "-d", db_url(tmp_path))
172
    assert applied_ids(tmp_path) == {"report"}
173
174
    result = mitch("up", "-p", str(users), "-d", db_url(tmp_path))
175
176
    assert result.exit_code == 0, result.output
177
    assert "Warning" in result.output and "org.example.reports:report" in result.output
178
179
180
# ---------------------------------------------------------------- rebuild
181
182
183
def _view_project(tmp_path: Path, dependant_down: str | None = "DROP VIEW w;", extra_dependant: bool = False) -> Path:
184
    """base table, view v (migration x), view w on v (migration d, depends on x)."""
185
    root = new_project(tmp_path / "app")
186
    write_migration(root, "base", "CREATE TABLE base (id int, name text);", "DROP TABLE base;")
187
    write_migration(
188
        root, "x", "CREATE VIEW v AS SELECT id, name FROM base;", "DROP VIEW v;", 'dependencies = ["base"]\n'
189
    )
190
    write_migration(
191
        root, "d", "CREATE VIEW w AS SELECT id FROM v; SELECT id FROM w;", dependant_down, 'dependencies = ["x"]\n'
192
    )
193
    if extra_dependant:
194
        write_migration(
195
            root, "optional", "CREATE VIEW o AS SELECT id FROM v;", "DROP VIEW o;", 'dependencies = ["x"]\n'
196
        )
197
    return root
198
199
200
def _write_rebuilder(
201
    root: Path, up: str = "DROP VIEW v; CREATE VIEW v AS SELECT id FROM base;", extra: str = ""
202
) -> None:
203
    write_migration(
204
        root,
205
        "m",
206
        up,
207
        "DROP VIEW v; CREATE VIEW v AS SELECT id, name FROM base;",
208
        f'dependencies = ["x"]\nrebuild_dependants_of = ["x"]\n{extra}',
209
    )
210
211
212
def test_rebuild_reverts_applied_dependants_applies_the_migration_and_reapplies_them(tmp_path):
213
    root = _view_project(tmp_path, extra_dependant=True)
214
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
215
    _write_rebuilder(root)
216
217
    result = mitch("add", "m", "-p", str(root), "-d", db_url(tmp_path))
218
219
    assert result.exit_code == 0, result.output
220
    assert audit(tmp_path)[3:] == [("d", "reverted"), ("m", "applied"), ("d", "applied")]
221
    assert "optional" not in applied_ids(tmp_path)
222
223
224
def test_rebuild_is_refused_when_a_dependant_has_no_down_script(tmp_path):
225
    root = _view_project(tmp_path, dependant_down=None)
226
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
227
    _write_rebuilder(root)
228
229
    result = mitch("add", "m", "-p", str(root), "-d", db_url(tmp_path))
230
231
    assert result.exit_code == 1
232
    assert "no down script" in result.output and "d" in result.output
233
    assert "m" not in applied_ids(tmp_path)
234
235
236
def test_rebuild_is_refused_when_a_dependant_belongs_to_a_project_that_is_not_loaded(tmp_path):
237
    root = _view_project(tmp_path)
238
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
239
    other = new_project(tmp_path / "other", "org.example.other")
240
    (other / "mitch.toml").write_text(
241
        '[project]\nid = "org.example.other"\n\n[projects]\napp = "../app"\n', encoding="utf-8"
242
    )
243
    write_migration(other, "uses-v", "CREATE VIEW u AS SELECT id FROM v;", "DROP VIEW u;", 'dependencies = ["app:x"]\n')
244
    mitch("up", "-p", str(other), "-d", db_url(tmp_path))
245
    _write_rebuilder(root)
246
247
    result = mitch("add", "m", "-p", str(root), "-d", db_url(tmp_path))
248
249
    assert result.exit_code == 1
250
    assert "org.example.other:uses-v" in result.output
251
    assert "m" not in applied_ids(tmp_path)
252
253
254
def test_rebuild_with_non_transactional_participant_needs_allow_autocommit(tmp_path):
255
    root = _view_project(tmp_path)
256
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
257
    _write_rebuilder(root, extra="transactional = false\n")
258
259
    refused = mitch("add", "m", "-p", str(root), "-d", db_url(tmp_path))
260
    allowed = mitch("add", "m", "--allow-autocommit", "-p", str(root), "-d", db_url(tmp_path))
261
262
    assert refused.exit_code == 1 and "--allow-autocommit" in refused.output
263
    assert allowed.exit_code == 0, allowed.output
264
    assert {"m", "d"} <= applied_ids(tmp_path)
265
266
267
def test_failed_autocommit_rebuild_prints_the_command_to_resume(tmp_path):
268
    root = _view_project(tmp_path)
269
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
270
    # The new v lacks the column w selects, so re-applying d fails after m was committed.
271
    _write_rebuilder(root, up="DROP VIEW v; CREATE VIEW v AS SELECT name FROM base;", extra="transactional = false\n")
272
273
    result = mitch("add", "m", "--allow-autocommit", "-p", str(root), "-d", db_url(tmp_path))
274
275
    assert result.exit_code == 1
276
    assert "mitch add d" in result.output
277
278
279
def test_database_error_during_rebuild_hints_at_an_undeclared_dependency(tmp_path):
280
    root = _view_project(tmp_path, dependant_down="DROP VIEW does_not_exist;")
281
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
282
    _write_rebuilder(root)
283
284
    result = mitch("add", "m", "-p", str(root), "-d", db_url(tmp_path))
285
286
    assert result.exit_code == 1
287
    assert "undeclared" in result.output
288
    assert applied_ids(tmp_path) == {"base", "x", "d"}
289
290
291
# ---------------------------------------------------------------- rework command
292
293
import tomllib  # noqa: E402
294
295
296
def _config(path: Path) -> dict:
297
    return tomllib.loads(path.read_text(encoding="utf-8"))
298
299
300
def _reworkable(tmp_path: Path) -> Path:
301
    """answer (idempotent view), reader and audit-reader depending on it, plus an unrelated table."""
302
    root = new_project(tmp_path / "app")
303
    write_migration(
304
        root,
305
        "answer",
306
        FUNCTION_V1,
307
        "DROP VIEW answer;",
308
        "created_at = 2026-01-01\nidempotent = true\ntransactional = true\n",
309
    )
310
    write_migration(root, "reader", *table("reader"), 'dependencies = ["answer"]\n')
311
    write_migration(root, "audit-reader", *table("audit_reader"), 'dependencies = ["reader"]\n')
312
    write_migration(root, "unrelated", *table("unrelated"))
313
    return root
314
315
316
def test_rework_archives_the_current_version_under_its_id_and_prepares_the_new_one(tmp_path):
317
    root = _reworkable(tmp_path)
318
319
    result = mitch("rework", "answer", "-p", str(root))
320
321
    assert result.exit_code == 0, result.output
322
    assert (root / "answer@1.up.sql").read_text(encoding="utf-8") == FUNCTION_V1
323
    assert (root / "answer@1.down.sql").read_text(encoding="utf-8") == "DROP VIEW answer;"
324
    archived = _config(root / "answer@1.config.toml")
325
    assert archived["id"] == "answer" and archived["idempotent"] is True
326
    assert str(archived["created_at"]) == "2026-01-01"
327
328
    assert (root / "answer.up.sql").read_text(encoding="utf-8") == FUNCTION_V1
329
    assert (root / "answer.down.sql").read_text(encoding="utf-8") == FUNCTION_V1
330
    new = _config(root / "answer.config.toml")
331
    assert new["id"] == "answer@2"
332
    assert new["dependencies"] == ["answer"]
333
    assert new["after"] == ["audit-reader", "reader"]
334
    assert new["idempotent"] is True and new["transactional"] is True
335
    assert str(new["created_at"]) != "2026-01-01"
336
    assert '# rebuild_dependants_of = ["answer"]' in (root / "answer.config.toml").read_text(encoding="utf-8")
337
338
339
def test_rework_again_archives_the_newest_version(tmp_path):
340
    root = _reworkable(tmp_path)
341
    mitch("rework", "answer", "-p", str(root))
342
343
    result = mitch("rework", "answer", "-p", str(root))
344
345
    assert result.exit_code == 0, result.output
346
    assert _config(root / "answer@2.config.toml")["id"] == "answer@2"
347
    assert _config(root / "answer.config.toml")["id"] == "answer@3"
348
    assert _config(root / "answer.config.toml")["dependencies"] == ["answer@2"]
349
    assert _config(root / "answer.config.toml")["after"] == ["audit-reader", "reader"]
350
    assert '# rebuild_dependants_of = ["answer", "answer@2"]' in (root / "answer.config.toml").read_text(
351
        encoding="utf-8"
352
    )
353
    assert _config(root / "answer@1.config.toml")["id"] == "answer"
354
355
356
def test_rework_of_unknown_migration_fails_without_creating_files(tmp_path):
357
    root = _reworkable(tmp_path)
358
    before = sorted(p.name for p in root.iterdir())
359
360
    result = mitch("rework", "nope", "-p", str(root))
361
362
    assert result.exit_code == 1
363
    assert sorted(p.name for p in root.iterdir()) == before
364
365
366
def test_rework_rejects_migrations_of_linked_projects(tmp_path):
367
    root = _reworkable(tmp_path)
368
    users = new_project(root / "users", "org.example.users")
369
    write_migration(users, "create-users", *table("users"))
370
371
    result = mitch("rework", "users:create-users", "-p", str(root))
372
373
    assert result.exit_code == 1
374
    assert not (users / "create-users@1.up.sql").exists()
375
376
377
def test_rework_gives_old_and_fresh_deployments_the_same_history(tmp_path):
378
    root = _reworkable(tmp_path)
379
    old_db, fresh_db = tmp_path / "old.db", tmp_path / "fresh.db"
380
    assert mitch("up", "-p", str(root), "-d", f"sqlite:///{old_db}").exit_code == 0
381
    mitch("rework", "answer", "-p", str(root))
382
    (root / "answer.up.sql").write_text(FUNCTION_V2, encoding="utf-8")
383
384
    assert mitch("up", "-p", str(root), "-d", f"sqlite:///{old_db}").exit_code == 0
385
    assert mitch("up", "-p", str(root), "-d", f"sqlite:///{fresh_db}").exit_code == 0
386
387
    def history(db: Path) -> list[str]:
388
        with sqlite3.connect(db) as connection:
389
            rows = connection.execute("SELECT migration_id FROM mitch_migration_audit ORDER BY id").fetchall()
390
        return [row[0] for row in rows if row[0] != "unrelated"]
391
392
    assert history(old_db) == history(fresh_db) == ["answer", "reader", "audit-reader", "answer@2"]
393
394
395
def test_applying_a_reworked_version_does_not_roll_out_optional_dependants(tmp_path):
396
    root = _reworkable(tmp_path)
397
    mitch("rework", "answer", "-p", str(root))
398
399
    result = mitch("add", "answer@2", "-p", str(root), "-d", db_url(tmp_path))
400
401
    assert result.exit_code == 0, result.output
402
    assert applied_ids(tmp_path) == {"answer", "answer@2"}
403
404
405
def test_status_suggests_rework_for_an_edited_idempotent_migration(tmp_path):
406
    root = _reworkable(tmp_path)
407
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
408
    (root / "answer.up.sql").write_text(FUNCTION_V2, encoding="utf-8")
409
410
    result = mitch("status", "--no-ci", "-p", str(root), "-d", db_url(tmp_path))
411
412
    assert result.exit_code == 0
413
    assert "M answer" in result.output
414
    assert "mitch rework answer" in result.output
415
416
417
def test_status_and_log_group_versions_of_a_migration(tmp_path):
418
    root = _reworkable(tmp_path)
419
    write_migration(root, "answer-cache", *table("answer_cache"))
420
    mitch("rework", "answer", "-p", str(root))
421
422
    status = mitch("status", "--no-ci", "-p", str(root), "-d", db_url(tmp_path))
423
    lines = [line[2:] for line in status.output.splitlines() if line.startswith("A ")]
424
    assert lines.index("answer@2") == lines.index("answer") + 1
425
426
    mitch("up", "-p", str(root), "-d", db_url(tmp_path))
427
    log = mitch("log", "-p", str(root), "-d", db_url(tmp_path))
428
    assert log.output.index("answer@2") < log.output.index("reader")
429
    assert log.output.index("reader") < log.output.index("audit-reader")
430
431
432
# ---------------------------------------------------------------- review findings
433
434
435
def test_restore_order_still_rebuilds_dependants(tmp_path):
436
    root = _view_project(tmp_path)
437
    write_migration(root, "optional", *table("optional"))
438
    write_migration(root, "late", *table("late"), 'after = ["optional"]\n')
439
    mitch("add", "d", "late", "-p", str(root), "-d", db_url(tmp_path))
440
    _write_rebuilder(root)
441
442
    result = mitch("add", "optional", "m", "--restore-order", "-p", str(root), "-d", db_url(tmp_path))
443
444
    assert result.exit_code == 0, result.output
445
    assert ("d", "reverted") in audit(tmp_path)
446
447
448
def test_allow_autocommit_keeps_a_fully_transactional_rebuild_atomic(tmp_path):
449
    root = _view_project(tmp_path)
450
    mitch("add", "d", "-p", str(root), "-d", db_url(tmp_path))
451
    _write_rebuilder(root, up="DROP VIEW v; SELECT missing FROM nowhere;")
452
453
    result = mitch("add", "m", "--allow-autocommit", "-p", str(root), "-d", db_url(tmp_path))
454
455
    assert result.exit_code == 1
456
    assert applied_ids(tmp_path) == {"base", "x", "d"}
457
    assert ("d", "reverted") not in audit(tmp_path)
458
459
460
def _rework_branches(tmp_path: Path) -> tuple[Path, str]:
461
    """A repository whose current branch is before the rework and branch `reworked` after it."""
462
    root = _reworkable(tmp_path)
463
    init_repo(root)
464
    commit_all(root, "before rework")
465
    base = git(root, "branch", "--show-current")
466
    git(root, "checkout", "-b", "reworked")
467
    assert mitch("rework", "answer", "-p", str(root)).exit_code == 0
468
    (root / "answer.up.sql").write_text(FUNCTION_V2, encoding="utf-8")
469
    commit_all(root, "rework answer")
470
    git(root, "checkout", base)
471
    return root, base
472
473
474
def test_checkout_forward_across_a_rework_reverts_nothing_and_leaves_the_new_version_pending(tmp_path):
475
    root, _ = _rework_branches(tmp_path)
476
    assert mitch("up", "-p", str(root), "-d", db_url(tmp_path)).exit_code == 0
477
    history_before = len(audit(tmp_path))
478
479
    result = mitch("checkout", "reworked", "-p", str(root), "-d", db_url(tmp_path))
480
481
    assert result.exit_code == 0, result.output
482
    assert len(audit(tmp_path)) == history_before
483
    assert "answer@2" not in applied_ids(tmp_path)
484
485
486
def test_stash_of_a_rework_in_progress_reverts_only_the_new_version(tmp_path):
487
    root = _reworkable(tmp_path)
488
    init_repo(root)
489
    commit_all(root, "before rework")
490
    mitch("rework", "answer", "-p", str(root))
491
    (root / "answer.up.sql").write_text(FUNCTION_V2, encoding="utf-8")
492
    assert mitch("up", "-p", str(root), "-d", db_url(tmp_path)).exit_code == 0
493
    history_before = len(audit(tmp_path))
494
495
    result = mitch("stash", "-p", str(root), "-d", db_url(tmp_path))
496
497
    assert result.exit_code == 0, result.output
498
    assert audit(tmp_path)[history_before:] == [("answer@2", "reverted")]
499
    assert "answer@2" not in applied_ids(tmp_path)