48 lines
1.0 KiB
Python
48 lines
1.0 KiB
Python
"""비동기 DB 엔진 + 세션 팩토리"""
|
|
|
|
from sqlalchemy.ext.asyncio import (
|
|
AsyncSession,
|
|
async_sessionmaker,
|
|
create_async_engine,
|
|
)
|
|
from sqlalchemy.orm import DeclarativeBase
|
|
from app.config import get_settings
|
|
|
|
settings = get_settings()
|
|
|
|
engine = create_async_engine(
|
|
settings.database_url,
|
|
echo=settings.DEBUG,
|
|
pool_size=10,
|
|
max_overflow=20,
|
|
)
|
|
|
|
AsyncSessionLocal = async_sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
)
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
|
|
async def get_db():
|
|
"""FastAPI Depends용 DB 세션 제너레이터"""
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close()
|
|
|
|
|
|
async def init_db():
|
|
"""테이블 생성 (개발용 — 프로덕션에서는 Alembic 사용)"""
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|