Public repository: timo / mitch

Reader

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

mitch / tests / test_rebuild_postgres.py · 5.5 KB · at 76a2c3d332a1 · raw

Outline: 9 definitions
1
"""Rebuild against a real PostgreSQL, which tracks dependencies between views, materialized views and policies.
2
3
Runs only when MITCH_TEST_POSTGRES_URL points to a server where the user may create databases, for example
4
`postgresql+psycopg2:///postgres`. Each test gets a fresh database.
5
"""
6
7
import os
8
import uuid
9
from pathlib import Path
10
11
import pytest
12
import sqlalchemy as sa
13
from sqlalchemy.engine import make_url
14
from typer.testing import CliRunner
15
16
from mitch.cli import app
17
18
ADMIN_URL = os.getenv("MITCH_TEST_POSTGRES_URL")
19
pytestmark = pytest.mark.skipif(not ADMIN_URL, reason="MITCH_TEST_POSTGRES_URL is not set")
20
21
runner = CliRunner()
22
23
24
@pytest.fixture
25
def database_url():
26
    name = f"mitch_test_{uuid.uuid4().hex[:12]}"
27
    admin = sa.create_engine(ADMIN_URL, isolation_level="AUTOCOMMIT")
28
    with admin.connect() as connection:
29
        connection.execute(sa.text(f"CREATE DATABASE {name} TEMPLATE template0"))
30
    try:
31
        yield make_url(ADMIN_URL).set(database=name).render_as_string(hide_password=False)
32
    finally:
33
        with admin.connect() as connection:
34
            connection.execute(sa.text(f"DROP DATABASE IF EXISTS {name} WITH (FORCE)"))
35
        admin.dispose()
36
37
38
def mitch(*args: str):
39
    return runner.invoke(app, list(args))
40
41
42
def write_migration(root: Path, stem: str, up: str, down: str, config: str = "") -> None:
43
    (root / f"{stem}.up.sql").write_text(up, encoding="utf-8")
44
    (root / f"{stem}.down.sql").write_text(down, encoding="utf-8")
45
    if config:
46
        (root / f"{stem}.config.toml").write_text(config, encoding="utf-8")
47
48
49
def relations(database_url: str) -> set[str]:
50
    engine = sa.create_engine(database_url)
51
    with engine.connect() as connection:
52
        rows = connection.execute(
53
            sa.text("SELECT relname FROM pg_class JOIN pg_namespace n ON n.oid = relnamespace WHERE nspname = 'public'")
54
        )
55
        names = {row[0] for row in rows}
56
        policies = {row[0] for row in connection.execute(sa.text("SELECT policyname FROM pg_policies"))}
57
    engine.dispose()
58
    return names | {f"policy:{p}" for p in policies}
59
60
61
def view_columns(database_url: str, view: str) -> list[str]:
62
    engine = sa.create_engine(database_url)
63
    with engine.connect() as connection:
64
        rows = connection.execute(
65
            sa.text(
66
                "SELECT column_name FROM information_schema.columns WHERE table_name = :view ORDER BY ordinal_position"
67
            ),
68
            {"view": view},
69
        )
70
        columns = [row[0] for row in rows]
71
    engine.dispose()
72
    return columns
73
74
75
@pytest.fixture
76
def project(tmp_path: Path) -> Path:
77
    """A table, a view on it (x), and a materialized view and a policy built on the view."""
78
    root = tmp_path / "app"
79
    root.mkdir()
80
    (root / "mitch.toml").write_text('[project]\nid = "app"\n', encoding="utf-8")
81
    write_migration(root, "base", "CREATE TABLE t (id int, name text);", "DROP TABLE t;")
82
    write_migration(root, "x", "CREATE VIEW v AS SELECT id, name FROM t;", "DROP VIEW v;", 'dependencies = ["base"]\n')
83
    write_migration(
84
        root,
85
        "summary",
86
        "CREATE MATERIALIZED VIEW mv AS SELECT id FROM v;",
87
        "DROP MATERIALIZED VIEW mv;",
88
        'dependencies = ["x"]\n',
89
    )
90
    write_migration(
91
        root,
92
        "visible-rows",
93
        "ALTER TABLE t ENABLE ROW LEVEL SECURITY; CREATE POLICY visible ON t USING (id IN (SELECT id FROM v));",
94
        "DROP POLICY visible ON t; ALTER TABLE t DISABLE ROW LEVEL SECURITY;",
95
        'dependencies = ["x"]\n',
96
    )
97
    return root
98
99
100
DROP_NAME_COLUMN = "DROP VIEW v; CREATE VIEW v AS SELECT id FROM t;"
101
RESTORE_NAME_COLUMN = "DROP VIEW v; CREATE VIEW v AS SELECT id, name FROM t;"
102
103
104
def test_view_with_dependent_objects_cannot_lose_a_column_without_rebuild(project, database_url):
105
    assert mitch("up", "-p", str(project), "-d", database_url).exit_code == 0
106
    write_migration(project, "slim-v", DROP_NAME_COLUMN, RESTORE_NAME_COLUMN, 'dependencies = ["x"]\n')
107
108
    result = mitch("add", "slim-v", "-p", str(project), "-d", database_url)
109
110
    assert result.exit_code != 0
111
    assert view_columns(database_url, "v") == ["id", "name"]
112
113
114
def test_rebuild_reverts_and_reapplies_materialized_view_and_policy_around_the_changed_view(project, database_url):
115
    assert mitch("up", "-p", str(project), "-d", database_url).exit_code == 0
116
    write_migration(
117
        project,
118
        "slim-v",
119
        DROP_NAME_COLUMN,
120
        RESTORE_NAME_COLUMN,
121
        'dependencies = ["x"]\nrebuild_dependants_of = ["x"]\n',
122
    )
123
124
    result = mitch("add", "slim-v", "-p", str(project), "-d", database_url)
125
126
    assert result.exit_code == 0, result.output
127
    assert view_columns(database_url, "v") == ["id"]
128
    assert {"mv", "policy:visible"} <= relations(database_url)
129
130
131
def test_undeclared_dependency_makes_the_rebuild_fail_with_a_hint_and_roll_back(project, database_url):
132
    # Runs after x, but does not declare that it depends on it.
133
    write_migration(
134
        project,
135
        "sneaky",
136
        "CREATE VIEW s AS SELECT name FROM v;",
137
        "DROP VIEW s;",
138
        'dependencies = ["base"]\nafter = ["x"]\n',
139
    )
140
    assert mitch("up", "-p", str(project), "-d", database_url).exit_code == 0
141
    write_migration(
142
        project,
143
        "slim-v",
144
        DROP_NAME_COLUMN,
145
        RESTORE_NAME_COLUMN,
146
        'dependencies = ["x"]\nrebuild_dependants_of = ["x"]\n',
147
    )
148
149
    result = mitch("add", "slim-v", "-p", str(project), "-d", database_url)
150
151
    assert result.exit_code == 1
152
    assert "undeclared" in result.output
153
    assert view_columns(database_url, "v") == ["id", "name"]
154
    assert {"mv", "policy:visible", "s"} <= relations(database_url)