"""Alembic env.py — настройка среды для миграций (async режим).""" import asyncio import os from logging.config import fileConfig from alembic import context from sqlalchemy import pool from sqlalchemy.engine import Connection from sqlalchemy.ext.asyncio import async_engine_from_config # Импорт всех моделей для автоопределения изменений from app.database import Base import app.models # noqa: F401 — регистрирует все модели # Alembic Config config = context.config # Настройка логирования if config.config_file_name is not None: fileConfig(config.config_file_name) # Целевые метаданные для автогенерации target_metadata = Base.metadata # Читаем DATABASE URL из переменной окружения (синхронный psycopg2 для Alembic) def get_url() -> str: host = os.getenv("POSTGRES_HOST", "postgres") port = os.getenv("POSTGRES_PORT", "5432") db = os.getenv("POSTGRES_DB", "antiplagiator") user = os.getenv("POSTGRES_USER", "antiplagiator") password = os.getenv("POSTGRES_PASSWORD", "changeme") return f"postgresql+psycopg2://{user}:{password}@{host}:{port}/{db}" def run_migrations_offline() -> None: """Запустить миграции в 'offline' режиме (без реального соединения с БД).""" url = get_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() def do_run_migrations(connection: Connection) -> None: """Выполнить миграции с реальным соединением.""" context.configure( connection=connection, target_metadata=target_metadata, compare_type=True, compare_server_default=True, ) with context.begin_transaction(): context.run_migrations() async def run_async_migrations() -> None: """Запустить миграции в async режиме.""" configuration = config.get_section(config.config_ini_section) or {} configuration["sqlalchemy.url"] = get_url() connectable = async_engine_from_config( configuration, prefix="sqlalchemy.", poolclass=pool.NullPool, ) async with connectable.connect() as connection: await connection.run_sync(do_run_migrations) await connectable.dispose() def run_migrations_online() -> None: """Запустить миграции в 'online' режиме.""" asyncio.run(run_async_migrations()) if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()