Files
mtusi2026lab7-safronov/migrations/env.py
T
ricoromaandClaude Opus 5.5 089d78609d chore: port lab 6 solution into the lab 7 skeleton
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065.
Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public
tests, README, REPORT and evidence of lab 6 are not carried over; infra
and scripts of the lab 7 skeleton stay as they are.
Makefile is the lab 6 one with the lab 7 skeleton part restored
(HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore
are taken from lab 6 because both skeletons have the same files;
.env.example is the lab 6 one without changes.
The compose project, image and CI prefix are renamed to lab7, and
references to the previous lab now name lab6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 03:59:04 +03:00

69 lines
2.3 KiB
Python

"""Окружение alembic: асинхронный шаблон, URL и журнал — из приложения.
URL берётся из `settings.database.url` и не проходит через ConfigParser
alembic, поэтому `%` в пароле ничего не ломает. Журнал — JSON через
`src/infra/logger.py`, как у сервиса. Асинхронное здесь только
подключение: ревизии остаются синхронным кодом `op.*`.
"""
import asyncio
from alembic import context
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import create_async_engine
from src.config import settings
from src.infra.db.models import Base
from src.infra.logger import AbstractLogger, get_logger
logger: AbstractLogger = get_logger().bind(module="migrations")
target_metadata = Base.metadata
def run_migrations_offline() -> None:
"""SQL без подключения: `alembic upgrade head --sql`."""
context.configure(
url=settings.database.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:
database = settings.database
# адрес и имя базы — чтобы по журналу было видно, какую базу мигрировали
logger.info(
"Running alembic",
host=database.host,
port=database.port,
database=database.name,
)
engine = create_async_engine(
database.url,
poolclass=pool.NullPool,
connect_args={"timeout": database.connect_timeout_seconds},
)
try:
async with engine.connect() as connection:
await connection.run_sync(do_run_migrations)
finally:
await engine.dispose()
logger.info("Finished alembic", database=database.name)
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_async_migrations())