ploop/scripts/check_migrations.py
2026-08-31 20:19:05 +08:00

111 lines
4.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""只对显式指定的 PostgreSQL URL 执行 PLoop Alembic 迁移。"""
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:
"""将显式指定的目标升级到 head,仅打印不含敏感信息的 schema 验证结果。"""
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:
"""仅在显式指定的 schema 中没有已有关系对象时创建该 schema。"""
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 f"PLoop schema {schema}"
if __name__ == "__main__":
raise SystemExit(main())