from pathlib import Path from alembic import command from alembic.config import Config from sqlalchemy import create_engine, text from app.core.config import settings def ensure_postgis_available() -> None: engine = create_engine(settings.DATABASE_URL_SYNC, echo=False) try: with engine.connect() as connection: result = connection.execute( text("select 1 from pg_available_extensions where name = 'postgis'") ) if result.scalar() != 1: raise RuntimeError( "PostGIS is not available on the PostgreSQL server. " "Install/enable PostGIS before starting the backend." ) finally: engine.dispose() def run_startup_migrations() -> None: ensure_postgis_available() project_root = Path(__file__).resolve().parents[2] alembic_ini = project_root / "alembic.ini" alembic_dir = project_root / "alembic" config = Config(str(alembic_ini)) config.set_main_option("script_location", str(alembic_dir)) command.upgrade(config, "head")