218 lines
7.1 KiB
Python
218 lines
7.1 KiB
Python
"""Versioned schema migration tracker and runner for PostgreSQL/SQLite."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from datetime import UTC, datetime
|
|
import hashlib
|
|
import importlib.util
|
|
from pathlib import Path
|
|
import re
|
|
from typing import Any, Awaitable, Callable
|
|
|
|
from sqlalchemy import text
|
|
|
|
from app.core.logging import get_logger
|
|
|
|
logger = get_logger(__name__, service="migrations")
|
|
|
|
DEFAULT_STEPS_DIR = Path(__file__).resolve().parent / "migration_steps"
|
|
MIGRATION_FILE_RE = re.compile(r"^(?P<version>\d{4})_(?P<slug>[a-z0-9_]+)\.py$")
|
|
MIGRATION_LOCK_KEY = (17001613, 4)
|
|
|
|
CREATE_MIGRATIONS_TABLE_SQL = """
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version VARCHAR(64) PRIMARY KEY,
|
|
name VARCHAR(255) NOT NULL,
|
|
checksum VARCHAR(64) NOT NULL,
|
|
applied_at TIMESTAMP WITH TIME ZONE NOT NULL
|
|
)
|
|
"""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class MigrationStep:
|
|
version: str
|
|
name: str
|
|
checksum: str
|
|
path: Path
|
|
upgrade: Callable[[Any], Awaitable[None]]
|
|
|
|
|
|
def discover_migrations(steps_dir: Path | None = None) -> list[MigrationStep]:
|
|
"""Load ordered migration modules matching NNNN_name.py."""
|
|
directory = steps_dir or DEFAULT_STEPS_DIR
|
|
if not directory.exists():
|
|
return []
|
|
|
|
steps: list[MigrationStep] = []
|
|
for path in sorted(directory.glob("*.py")):
|
|
match = MIGRATION_FILE_RE.match(path.name)
|
|
if not match:
|
|
continue
|
|
raw_bytes = path.read_bytes()
|
|
checksum = hashlib.sha256(raw_bytes).hexdigest()
|
|
module_name = f"planet_migration_{match.group('version')}_{match.group('slug')}"
|
|
spec = importlib.util.spec_from_file_location(module_name, path)
|
|
if spec is None or spec.loader is None:
|
|
raise RuntimeError(f"Could not load migration module: {path}")
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
|
|
version = str(getattr(module, "VERSION", match.group("version")))
|
|
name = str(getattr(module, "NAME", match.group("slug")))
|
|
upgrade_fn = getattr(module, "upgrade", None)
|
|
if not callable(upgrade_fn):
|
|
raise RuntimeError(f"Migration {path.name} does not define callable upgrade(conn)")
|
|
steps.append(
|
|
MigrationStep(
|
|
version=version,
|
|
name=name,
|
|
checksum=checksum,
|
|
path=path,
|
|
upgrade=upgrade_fn,
|
|
)
|
|
)
|
|
|
|
steps.sort(key=lambda item: item.version)
|
|
return steps
|
|
|
|
|
|
async def ensure_migrations_table(conn: Any) -> None:
|
|
await conn.execute(text(CREATE_MIGRATIONS_TABLE_SQL))
|
|
|
|
|
|
async def _fetch_applied_map(conn: Any) -> dict[str, tuple[str, str]]:
|
|
result = await conn.execute(
|
|
text("SELECT version, name, checksum FROM schema_migrations ORDER BY version")
|
|
)
|
|
return {str(row[0]): (str(row[1]), str(row[2])) for row in result.fetchall()}
|
|
|
|
|
|
async def _record_migration(conn: Any, step: MigrationStep) -> None:
|
|
await conn.execute(
|
|
text(
|
|
"INSERT INTO schema_migrations (version, name, checksum, applied_at) "
|
|
"VALUES (:version, :name, :checksum, :applied_at)"
|
|
),
|
|
{
|
|
"version": step.version,
|
|
"name": step.name,
|
|
"checksum": step.checksum,
|
|
"applied_at": datetime.now(UTC),
|
|
},
|
|
)
|
|
|
|
|
|
async def ensure_baseline_stamped(conn: Any, steps_dir: Path | None = None) -> bool:
|
|
"""Ensure schema_migrations exists and stamp baseline 0001 if no version is recorded."""
|
|
await ensure_migrations_table(conn)
|
|
applied = await _fetch_applied_map(conn)
|
|
if applied:
|
|
return False
|
|
steps = discover_migrations(steps_dir)
|
|
if not steps:
|
|
return False
|
|
baseline = steps[0]
|
|
await _record_migration(conn, baseline)
|
|
return True
|
|
|
|
|
|
async def get_migration_status(engine: Any, steps_dir: Path | None = None) -> dict[str, Any]:
|
|
"""Return applied versions, pending versions, and checksum mismatches."""
|
|
steps = discover_migrations(steps_dir)
|
|
async with engine.begin() as conn:
|
|
await ensure_migrations_table(conn)
|
|
applied_map = await _fetch_applied_map(conn)
|
|
|
|
mismatches: list[dict[str, str]] = []
|
|
pending: list[str] = []
|
|
for step in steps:
|
|
recorded = applied_map.get(step.version)
|
|
if recorded is None:
|
|
pending.append(step.version)
|
|
elif recorded[1] != step.checksum:
|
|
mismatches.append(
|
|
{
|
|
"version": step.version,
|
|
"expected": recorded[1],
|
|
"actual": step.checksum,
|
|
}
|
|
)
|
|
|
|
return {
|
|
"applied": sorted(applied_map.keys()),
|
|
"pending": pending,
|
|
"mismatches": mismatches,
|
|
}
|
|
|
|
|
|
async def run_migrations(
|
|
engine: Any,
|
|
steps_dir: Path | None = None,
|
|
*,
|
|
verify_checksums: bool = True,
|
|
) -> list[str]:
|
|
"""Run all pending migrations transactionally under a PostgreSQL advisory lock."""
|
|
steps = discover_migrations(steps_dir)
|
|
newly_applied: list[str] = []
|
|
|
|
async with engine.begin() as conn:
|
|
if getattr(conn.dialect, "name", "") == "postgresql":
|
|
await conn.execute(
|
|
text("SELECT pg_advisory_xact_lock(:k1, :k2)"),
|
|
{"k1": MIGRATION_LOCK_KEY[0], "k2": MIGRATION_LOCK_KEY[1]},
|
|
)
|
|
await ensure_migrations_table(conn)
|
|
applied_map = await _fetch_applied_map(conn)
|
|
|
|
for step in steps:
|
|
recorded = applied_map.get(step.version)
|
|
if recorded is not None:
|
|
if verify_checksums and recorded[1] != step.checksum:
|
|
raise RuntimeError(
|
|
f"Checksum mismatch for already-applied migration {step.version} ({step.name})"
|
|
)
|
|
continue
|
|
|
|
logger.info_event(
|
|
"Applying database migration",
|
|
event="db.migration.applying",
|
|
context={"version": step.version, "name": step.name},
|
|
)
|
|
await step.upgrade(conn)
|
|
await _record_migration(conn, step)
|
|
newly_applied.append(step.version)
|
|
logger.info_event(
|
|
"Applied database migration",
|
|
event="db.migration.applied",
|
|
context={"version": step.version, "name": step.name},
|
|
)
|
|
|
|
return newly_applied
|
|
|
|
|
|
async def stamp_migrations(
|
|
engine: Any,
|
|
target_version: str,
|
|
steps_dir: Path | None = None,
|
|
) -> list[str]:
|
|
"""Record migrations up to target_version as applied without executing SQL."""
|
|
steps = discover_migrations(steps_dir)
|
|
known_versions = {step.version for step in steps}
|
|
if target_version not in known_versions:
|
|
raise ValueError(f"Unknown migration version: {target_version}")
|
|
|
|
stamped: list[str] = []
|
|
async with engine.begin() as conn:
|
|
await ensure_migrations_table(conn)
|
|
applied_map = await _fetch_applied_map(conn)
|
|
for step in steps:
|
|
if step.version > target_version:
|
|
break
|
|
if step.version in applied_map:
|
|
continue
|
|
await _record_migration(conn, step)
|
|
stamped.append(step.version)
|
|
return stamped
|