Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,23 @@

Changes are recorded in [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) format.

## [0.9.1]

### Fixed

- **`up` could record a migration it never ran.** `ch-migrate new` writes Alembic's template, then replaces it. When both fell in the same second and were the same size, Python kept running the template it had cached, whose `upgrade()` does nothing, and `up` recorded the revision as applied. The size depends on the message, the object name and, with `--irreversible`, the reason, so it took a particular combination: a 41-character message with a 40-character `--dict` name was one. `new --exchange` and `rebase` rewrote files the same way. Every rewrite now drops the cached bytecode, and `up` and `down` drop it for every revision before they start.

Only the checkout where a revision was created or rebased could be affected: a fresh checkout, such as CI, compiles the final file. If you ran `up` from that checkout on 0.9.0 or earlier:

1. Before the first `up` or `down` on 0.9.1, which clear these caches, list the revisions whose cached code is still the template:

```bash
sh -c 'for f in migrations/versions/*.py; do grep -q get_db "$f" || grep -l get_db "migrations/versions/__pycache__/$(basename "$f" .py)".*.pyc; done' 2>/dev/null
```

A revision you haven't run yet can be listed too. An empty list doesn't prove none was affected: an edit or a Python upgrade also replaces the cache.
2. Compare the revisions you created there with the database. Where a change is missing, put the same statements in a new migration. Upgrading doesn't rerun it, because the database says it was applied.

## [0.9.0]

0.9 declares users, roles and grants in `access.yaml`. `ch-migrate access plan` shows how a server differs from it, and `access apply` makes the server match, logged in as the admin. A new project's migration role holds only what migrations need, with no right to manage users or roles. A normal `pip install -U` reaches 0.9 from 0.8, so read this before upgrading:
Expand Down
2 changes: 1 addition & 1 deletion ch_migrate/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from ch_migrate import read_sql, get_db, get_env_config, create_dictionary
"""

__version__ = "0.9.0"
__version__ = "0.9.1"


from typing import Any
Expand Down
3 changes: 2 additions & 1 deletion ch_migrate/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,10 +428,11 @@ def _check_new_options(options: NewOptions) -> None:

def _create_sql_first_migration(migration_path: Path, options: NewOptions) -> None:
from ch_migrate.authoring import read_revision_header, render_revision, write_sql_files
from ch_migrate.revision_files import write_revision

header = read_revision_header(migration_path)
files = write_sql_files(Path.cwd() / "migrations" / "sql", header, options)
migration_path.write_text(render_revision(header, files, options.irreversible_reason))
write_revision(migration_path, render_revision(header, files, options.irreversible_reason))
ui.success(f"Created migration {header.revision[:8]} {header.message}")
ui.detail(f"migrations/sql/{files.upgrade}")
if files.downgrade:
Expand Down
2 changes: 2 additions & 0 deletions ch_migrate/migration_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from alembic.config import Config

from ch_migrate import ui
from ch_migrate.revision_files import discard_revision_bytecode
from ch_migrate.runner import (
_RUNNING,
_SELF_DESCRIBING,
Expand Down Expand Up @@ -63,6 +64,7 @@ def run_upgrade(upgrade: Upgrade) -> int:
# Project helpers intentionally read these during migration execution only.
saved = {name: os.environ.get(name) for name in ("CH_DATABASE", "CH_CLUSTER")}
try:
discard_revision_bytecode(Path.cwd() / "migrations" / "versions")
with _restored_loggers("alembic", "ch_migrate"):
command.upgrade(config, upgrade.revision)
except KeyboardInterrupt:
Expand Down
4 changes: 3 additions & 1 deletion ch_migrate/rebase.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from pathlib import Path
from typing import Any

from ch_migrate.revision_files import write_revision

DownRevisions = tuple[str, ...]
_MISSING = object()

Expand Down Expand Up @@ -305,4 +307,4 @@ def apply_rebase(changes: list[RebaseChange]) -> None:
change.old_down_revision,
change.new_down_revision,
)
change.migration.path.write_text(new_content)
write_revision(change.migration.path, new_content)
35 changes: 35 additions & 0 deletions ch_migrate/revision_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Writing revision files without leaving stale bytecode behind.

Python reuses a revision's cached `.pyc` when the source file's size and modified time,
in whole seconds, still match. `new` and `rebase` rewrite a file Alembic may already have
loaded, often in the same second and sometimes at the same size, so the old bytecode would
keep running and a migration could be recorded as applied without sending its SQL.
"""

from __future__ import annotations

import contextlib
import glob
import importlib.util
from pathlib import Path


def write_revision(path: Path, content: str) -> None:
"""Write a revision file, and drop bytecode cached from what it held before."""
path.write_text(content)
_discard_bytecode(path)


def discard_revision_bytecode(versions_dir: Path) -> None:
"""Make the next load of every revision compile the file on disk."""
for path in versions_dir.glob("*.py"):
_discard_bytecode(path)


def _discard_bytecode(path: Path) -> None:
# Best effort: a cache that can't be removed, as in a read-only checkout, must not
# stop a command.
with contextlib.suppress(OSError, NotImplementedError):
cache_dir = Path(importlib.util.cache_from_source(str(path))).parent
for cached in cache_dir.glob(f"{glob.escape(path.stem)}.*.pyc"):
cached.unlink(missing_ok=True)
2 changes: 2 additions & 0 deletions ch_migrate/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

from ch_migrate import ui
from ch_migrate.config import get_env_config
from ch_migrate.revision_files import discard_revision_bytecode
from ch_migrate.sql import clean_database_error

_LOG_LINE = re.compile(r"^(?P<level>[A-Z]+)\s+\[(?P<logger>[^\]]+)\]\s?(?P<message>.*)$")
Expand All @@ -37,6 +38,7 @@ def run_migrations(environment: str, args: list[str], *, verbose: bool) -> int:
Returns Alembic's exit status.
"""
progress = _Progress()
discard_revision_bytecode(Path.cwd() / "migrations" / "versions")
command = [sys.executable, "-m", "alembic", *args]
with subprocess.Popen(
command,
Expand Down
4 changes: 3 additions & 1 deletion ch_migrate/scaffold.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from pathlib import Path
from typing import Any

from ch_migrate.revision_files import write_revision


def fetch_current_ddl(env_config: dict[str, Any], table_name: str) -> str | None:
"""Fetch current CREATE TABLE statement from the live database.
Expand Down Expand Up @@ -246,4 +248,4 @@ def rewrite_migration_file(
sql_path=sql_path,
dict_names=dict_names,
)
migration_path.write_text(new_content)
write_revision(migration_path, new_content)
142 changes: 142 additions & 0 deletions tests/test_revision_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
"""A rewritten revision file is always the one that runs."""

import importlib.util
import os
import py_compile

import pytest
from click.testing import CliRunner

from ch_migrate import migration_runner, runner
from ch_migrate.cli import main
from ch_migrate.rebase import RebaseChange, apply_rebase, parse_migration
from ch_migrate.revision_files import discard_revision_bytecode, write_revision

_FIRST = "def upgrade():\n return 'empty!'\n"
_SECOND = "def upgrade():\n return 'filled'\n"
_WHEN = 1_700_000_000


@pytest.fixture
def stale(tmp_path):
"""A revision rewritten within the second, at the same size, after Python cached it."""
path = tmp_path / "2026_01_01_0000_add_thing.py"
_write_at(path, _FIRST)
py_compile.compile(str(path))
assert len(_FIRST) == len(_SECOND)
return path


@pytest.fixture
def stale_project(tmp_path, monkeypatch, stale):
"""A project whose only revision has a stale cache, as an older version left it."""
versions = tmp_path / "migrations" / "versions"
versions.mkdir(parents=True)
path = versions / stale.name
_write_at(path, _FIRST)
py_compile.compile(str(path))
_write_at(path, _SECOND)
monkeypatch.chdir(tmp_path)
return path


def test_equal_size_rewrite_in_one_second_would_run_the_old_code(stale):
# The hazard itself: without dropping the cache, Python runs the first version.
_write_at(stale, _SECOND)
assert _load(stale).upgrade() == "empty!"


def test_write_revision_runs_what_is_on_disk(stale):
write_revision(stale, _SECOND)
os.utime(stale, (_WHEN, _WHEN))
assert _load(stale).upgrade() == "filled"


def test_discard_revision_bytecode_covers_every_revision(stale):
_write_at(stale, _SECOND)
discard_revision_bytecode(stale.parent)
assert _load(stale).upgrade() == "filled"


def test_discard_revision_bytecode_ignores_a_cache_it_cannot_remove(stale, monkeypatch):
def refuse(self, missing_ok=False):
raise PermissionError(str(self))

monkeypatch.setattr("pathlib.Path.unlink", refuse)
discard_revision_bytecode(stale.parent)


def test_discard_revision_bytecode_accepts_a_missing_directory(tmp_path):
discard_revision_bytecode(tmp_path / "versions")


def test_up_drops_a_stale_cache_before_alembic_loads_a_revision(stale_project, monkeypatch):
seen = []
monkeypatch.setattr(migration_runner, "_alembic_config", lambda *args: None)
monkeypatch.setattr(
migration_runner.command,
"upgrade",
lambda *args: seen.append(_load(stale_project).upgrade()),
)
migration_runner.run_upgrade(migration_runner.Upgrade("dev"))
assert seen == ["filled"]


def test_down_drops_a_stale_cache_before_alembic_loads_a_revision(stale_project, monkeypatch):
seen = []

class Process:
stdout = iter(())

def __init__(self, *args, **kwargs):
seen.append(_load(stale_project).upgrade())

def __enter__(self):
return self

def __exit__(self, *exc):
return None

def wait(self):
return 0

monkeypatch.setattr(runner, "alembic_env", lambda environment: {})
monkeypatch.setattr(runner.subprocess, "Popen", Process)
runner.run_migrations("dev", ["downgrade", "-1"], verbose=False)
assert seen == ["filled"]


def test_rebase_runs_the_new_parent(tmp_path):
path = tmp_path / "2026_01_01_0000_b.py"
old, new = "aaaaaaaaaaaa", "bbbbbbbbbbbb"
_write_at(path, f"revision = 'cccccccccccc'\ndown_revision = '{old}'\n")
py_compile.compile(str(path))
migration = parse_migration(path)
apply_rebase([RebaseChange(migration, old, new)])
os.utime(path, (_WHEN, _WHEN))
assert _load(path).down_revision == new


@pytest.mark.parametrize("options", [[], ["--irreversible", "It drops data"], ["--exchange"]])
def test_new_leaves_no_bytecode_from_the_template(tmp_path, monkeypatch, options):
assert CliRunner().invoke(main, ["init", str(tmp_path), "--name", "demo"]).exit_code == 0
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("CH_DEV_MIGRATION_PASSWORD", "test-only")
table = ["--table", "logs"]
result = CliRunner().invoke(main, ["new", "dev", "add_status", *table, *options])
assert result.exit_code == 0, result.output
[revision] = (tmp_path / "migrations" / "versions").glob("*.py")
cached = importlib.util.cache_from_source(str(revision))
assert not os.path.exists(cached)


def _write_at(path, content):
path.write_text(content)
os.utime(path, (_WHEN, _WHEN))


def _load(path):
spec = importlib.util.spec_from_file_location("revision_under_test", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
Loading