"""Alembic environment for the Work Package Suite. We reuse the application's own database configuration (server/db.py) so a migration always targets the same database the app would connect to — Postgres in production (from POSTGRES_* / DATABASE_URL) or the SQLite dev file otherwise. No connection string is stored in alembic.ini. """ import os import sys from logging.config import fileConfig from alembic import context # Make the `server` package importable no matter where alembic is invoked from # (repo root, /app in the container, etc.). env.py lives at server/alembic/env.py, # so the repo root is two directories up. _HERE = os.path.dirname(os.path.abspath(__file__)) _REPO = os.path.dirname(os.path.dirname(_HERE)) if _REPO not in sys.path: sys.path.insert(0, _REPO) from server.db import Base, DATABASE_URL, engine # noqa: E402 from server import models # noqa: E402,F401 (imported for its side effect: registers all tables on Base.metadata) config = context.config if config.config_file_name is not None: fileConfig(config.config_file_name) # The app resolves its URL from the environment; feed the same value to Alembic. config.set_main_option("sqlalchemy.url", str(DATABASE_URL)) target_metadata = Base.metadata def run_migrations_offline() -> None: """Emit SQL to stdout (`alembic upgrade --sql`) without a live connection.""" context.configure( url=str(DATABASE_URL), target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, compare_type=True, ) with context.begin_transaction(): context.run_migrations() def run_migrations_online() -> None: """Run migrations against a live connection, reusing the app's engine.""" with engine.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, compare_type=True, # Each migration commits on its own. One transaction for the WHOLE # run meant a crash at step N rolled back steps 1..N-1 while their # "Running upgrade" lines stayed on screen claiming they ran - the # 2026-08-21 outage's stamp-to-head repair trusted those lines and # left production missing two tables (found 2026-08-23 when the # locations import 500'd on a table that "had been created"). transaction_per_migration=True, ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()