Files
blog.pyaqa.ru/alembic/env.py
Sergey Vanyushkin 9cc2f6284d feat: add alembic migrations, integration tests, and CI support
- Add alembic dependency and initialize migration framework
- Configure async alembic env.py for SQLAlchemy 2.0
- Create initial migration for PostORM table
- Gate init_db() with SKIP_INIT_DB env var for CI/production
- Add PostgreSQL service to Woodpecker CI pipeline
- Create integration tests for migrations (TC-INT-001..002)
- Create integration tests for SQLAlchemyPostRepository (TC-INT-003..009)
- Add unit test for init_db skip behavior (TC-UNIT-901)
- All 176 tests pass, coverage 72.59%
2026-05-10 12:47:30 +03:00

65 lines
1.5 KiB
Python

import asyncio
import os
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import create_async_engine
from alembic import context
from app.infrastructure.database.models import Base
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def _get_database_url() -> str:
url = os.environ.get("DB_URL") or config.get_main_option("sqlalchemy.url")
if not url:
raise RuntimeError("Database URL not configured")
return url
def run_migrations_offline() -> None:
url = _get_database_url()
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
db_url = _get_database_url()
connectable = create_async_engine(db_url, poolclass=pool.NullPool)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()