더북(TheBook)

6. 기존 마이그레이션 수행 함수는 놔두고 비동기로 동작하는 수행 함수를 env.py 파일에 추가하겠습니다.

파이썬(/alembic/env.py)

import asyncio

from sqlalchemy.ext.asyncio import AsyncEngine
from sqlalchemy.engine import Connection

# 기존 내용 생략

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_migrations_online() -> None:  # ①
    configuration = config.get_section(config.config_ini_section, {})

    configuration["sqlalchemy.url"] = DSN  # DSN 설정

    connectable = AsyncEngine(  # ② 비동기 데이터베이스 엔진 생성
        engine_from_config(
            configuration,
            prefix="sqlalchemy.",
            poolclass=pool.NullPool,
        ),
    )

    async with connectable.connect() as connection:
        await connection.run_sync(do_run_migrations)  # ③ 비동기 맥락(context)에서 do_run_migrations() 실행
    await connectable.dispose()

# 다음은 기존 내용
if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.