"""The one way the cloud schema is created and upgraded: Alembic (APPS_PLATFORM D-22). v1 used create_all + an ALTER list in main.py (_run_migrations); both are gone on platform-v2. The production database predates Alembic: at cutover it is STAMPED to 0001_cloud_baseline (the exact v1 schema) and then upgraded (DEPLOYMENT_GUIDE.md, "Platform v2 cutover"). Until it is stamped, startup refuses it, so the v2 cloud can never half-migrate production by accident. """ from __future__ import annotations import logging from pathlib import Path from alembic import command from alembic.config import Config from sqlalchemy import inspect logger = logging.getLogger("cloud.schema") MIGRATIONS_DIR = Path(__file__).resolve().parent / "migrations" BASELINE = "0001_cloud_baseline" class UnstampedDatabaseError(RuntimeError): pass def alembic_config(connection=None) -> Config: cfg = Config() cfg.set_main_option("script_location", str(MIGRATIONS_DIR)) cfg.set_main_option("file_template", "%%(rev)s") if connection is not None: cfg.attributes["connection"] = connection return cfg def upgrade_to_head(engine=None) -> None: if engine is None: from database import engine as app_engine engine = app_engine with engine.begin() as conn: tables = set(inspect(conn).get_table_names()) if tables and "alembic_version" not in tables: raise UnstampedDatabaseError( "This cloud database predates Alembic (v1). Back it up, then run " f"`alembic stamp {BASELINE}` once (DEPLOYMENT_GUIDE.md, Platform v2 cutover).") command.upgrade(alembic_config(conn), "head") logger.info("schema upgraded to head") def stamp_baseline(engine) -> None: """Cutover helper: mark a v1 production DB as being at the baseline revision.""" with engine.begin() as conn: command.stamp(alembic_config(conn), BASELINE)