ploop/scripts/check_migrations.py
2026-08-31 16:47:25 +08:00

111 lines
4.2 KiB
Python

"""Run PLoop Alembic migrations only against an explicitly supplied PostgreSQL URL."""
from __future__ import annotations
import argparse
import os
import re
from pathlib import Path
from alembic.config import Config
from sqlalchemy import create_engine, text
from sqlalchemy.engine import make_url
from alembic import command
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
BACKEND_ROOT = REPOSITORY_ROOT / "backend"
DEFAULT_DATABASE_URL_ENV = "PLOOP_MIGRATION_DATABASE_URL"
DEFAULT_SCHEMA_ENV = "PLOOP_MIGRATION_SCHEMA"
PLOOP_SCHEMA_PATTERN = re.compile(r"ploop_[a-z0-9]+(?:_[a-z0-9]+)*\Z")
def main() -> int:
"""Upgrade an explicit target to head and print only non-sensitive schema evidence."""
arguments = _parser().parse_args()
if not arguments.allow_migration:
_parser().error("--allow-migration is required for a schema-changing command")
database_url = os.environ.get(arguments.database_url_env)
if not database_url:
_parser().error(f"{arguments.database_url_env} is not set")
try:
parsed_url = make_url(database_url)
except Exception as error:
_parser().error(f"{arguments.database_url_env} is not a valid SQLAlchemy URL: {error}")
if not parsed_url.drivername.startswith("postgresql"):
_parser().error(f"{arguments.database_url_env} must use a PostgreSQL URL")
schema = _require_ploop_schema(arguments.schema_env)
config = Config(str(BACKEND_ROOT / "alembic.ini"))
config.set_main_option("sqlalchemy.url", database_url)
config.set_main_option("ploop.target_schema", schema)
_prepare_empty_schema(database_url, schema)
command.upgrade(config, "head")
engine = create_engine(database_url)
try:
quoted_schema = engine.dialect.identifier_preparer.quote(schema)
with engine.connect() as connection:
revision = connection.execute(
text(f"SELECT version_num FROM {quoted_schema}.alembic_version")
).scalar_one()
table_count = connection.execute(
text("SELECT count(*) FROM information_schema.tables WHERE table_schema = :schema"),
{"schema": schema},
).scalar_one()
finally:
engine.dispose()
print(f"migration_revision={revision} table_count={table_count}")
return 0
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Run Alembic migration smoke only against an explicit PostgreSQL database URL."
)
parser.add_argument("--database-url-env", default=DEFAULT_DATABASE_URL_ENV)
parser.add_argument("--schema-env", default=DEFAULT_SCHEMA_ENV)
parser.add_argument("--allow-migration", action="store_true")
return parser
def _require_ploop_schema(schema_env: str) -> str:
schema = os.environ.get(schema_env)
if not schema:
_parser().error(f"{schema_env} is not set")
if not PLOOP_SCHEMA_PATTERN.fullmatch(schema):
_parser().error(f"{schema_env} must name a PLoop-specific schema such as ploop_m1_smoke")
return schema
def _prepare_empty_schema(database_url: str, schema: str) -> None:
"""Create the explicit schema only when it has no pre-existing relations."""
engine = create_engine(database_url)
try:
quoted_schema = engine.dialect.identifier_preparer.quote(schema)
with engine.begin() as connection:
relation_count = connection.execute(
text(
"SELECT count(*) FROM pg_catalog.pg_class AS relation "
"JOIN pg_catalog.pg_namespace AS namespace "
"ON namespace.oid = relation.relnamespace "
"WHERE namespace.nspname = :schema "
"AND relation.relkind IN ('r', 'p', 'v', 'm', 'S', 'f')"
),
{"schema": schema},
).scalar_one()
if relation_count:
_parser().error(f"{schema_env_name(schema)} must be empty before migration")
connection.execute(text(f"CREATE SCHEMA IF NOT EXISTS {quoted_schema}"))
finally:
engine.dispose()
def schema_env_name(schema: str) -> str:
"""Return a non-sensitive target description for safety errors."""
return f"PLoop schema {schema}"
if __name__ == "__main__":
raise SystemExit(main())