87 lines
3.1 KiB
Python
87 lines
3.1 KiB
Python
"""Alembic 환경 설정 (async / asyncpg)
|
|
|
|
- settings.DATABASE_URL 에서 연결 문자열을 읽어 동기 드라이버(psycopg2) URL 로 변환
|
|
- 모델 메타데이터를 임포트해 autogenerate 지원
|
|
"""
|
|
import asyncio
|
|
from logging.config import fileConfig
|
|
|
|
from sqlalchemy import pool
|
|
from sqlalchemy.engine import Connection
|
|
from sqlalchemy.ext.asyncio import async_engine_from_config
|
|
|
|
from alembic import context
|
|
|
|
# ── 프로젝트 루트를 sys.path 에 추가 (alembic.ini prepend_sys_path = .) ───────
|
|
import sys
|
|
import os
|
|
|
|
# backend/ 가 작업 디렉토리이므로 app 패키지를 바로 임포트 가능
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
|
|
|
from app.core.config import settings
|
|
from app.core.database import Base
|
|
|
|
# 모든 모델 임포트 — autogenerate 가 테이블을 인식하도록
|
|
import app.models.models # noqa: F401
|
|
|
|
# ── alembic.ini 로거 설정 ─────────────────────────────────────────────────────
|
|
config = context.config
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
# ── DB URL: asyncpg → psycopg2 (Alembic 동기 드라이버용) ────────────────────
|
|
_db_url = settings.DATABASE_URL
|
|
if "+asyncpg" in _db_url:
|
|
_db_url = _db_url.replace("+asyncpg", "")
|
|
elif _db_url.startswith("postgresql://"):
|
|
pass # already sync-compatible
|
|
config.set_main_option("sqlalchemy.url", _db_url)
|
|
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
# ── 오프라인 마이그레이션 ─────────────────────────────────────────────────────
|
|
def run_migrations_offline() -> None:
|
|
url = config.get_main_option("sqlalchemy.url")
|
|
context.configure(
|
|
url=url,
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
# ── 온라인 마이그레이션 (async) ───────────────────────────────────────────────
|
|
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:
|
|
_async_url = settings.DATABASE_URL
|
|
if not "+asyncpg" in _async_url:
|
|
_async_url = _async_url.replace("postgresql://", "postgresql+asyncpg://")
|
|
|
|
connectable = async_engine_from_config(
|
|
{"sqlalchemy.url": _async_url},
|
|
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:
|
|
asyncio.run(run_async_migrations())
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
run_migrations_online()
|