| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- """
- alembic/env.py
- ──────────────
- Alembic runtime environment for PMDI.
- · Reads DATABASE_URL from the environment (same source as the FastAPI app)
- · Imports all ORM models so Alembic can perform autogenerate comparisons
- · Supports both offline (--sql) and online migration execution
- """
- from __future__ import annotations
- import os
- from logging.config import fileConfig
- from alembic import context
- from sqlalchemy import engine_from_config, pool
- # Import the shared declarative Base AND all models so Alembic sees every table
- from app.database import Base # noqa: F401
- from app.models import ( # noqa: F401
- AdminUser, Client, EmailTemplate, Invoice, NotificationLog,
- )
- # ── Alembic config object ──────────────────────────────────────────────────
- config = context.config
- # Set up logging from alembic.ini
- if config.config_file_name is not None:
- fileConfig(config.config_file_name)
- # Override sqlalchemy.url from the environment so credentials are never
- # stored in alembic.ini or any config file.
- database_url = os.environ.get("DATABASE_URL")
- if database_url:
- config.set_main_option("sqlalchemy.url", database_url)
- target_metadata = Base.metadata
- # ── Offline mode ───────────────────────────────────────────────────────────
- def run_migrations_offline() -> None:
- """Generate SQL script without a live database connection."""
- url = config.get_main_option("sqlalchemy.url")
- context.configure(
- url=url,
- target_metadata=target_metadata,
- literal_binds=True,
- dialect_opts={"paramstyle": "named"},
- compare_type=True,
- compare_server_default=True,
- )
- with context.begin_transaction():
- context.run_migrations()
- # ── Online mode ────────────────────────────────────────────────────────────
- def run_migrations_online() -> None:
- """Run migrations against a live database connection."""
- connectable = engine_from_config(
- config.get_section(config.config_ini_section, {}),
- prefix="sqlalchemy.",
- poolclass=pool.NullPool,
- )
- with connectable.connect() as connection:
- context.configure(
- connection=connection,
- target_metadata=target_metadata,
- compare_type=True,
- compare_server_default=True,
- )
- with context.begin_transaction():
- context.run_migrations()
- if context.is_offline_mode():
- run_migrations_offline()
- else:
- run_migrations_online()
|