56 lines
1.5 KiB
Python
56 lines
1.5 KiB
Python
"""
|
|
데이터베이스 연결 모듈
|
|
|
|
- SQLAlchemy async 엔진 및 세션 팩토리 (PostgreSQL + asyncpg)
|
|
- Base 모델 선언, get_db 의존성 제공
|
|
"""
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from app.core.config import settings
|
|
|
|
# PostgreSQL 연결 URL 변환 (asyncpg 사용)
|
|
DATABASE_URL = settings.DATABASE_URL
|
|
if DATABASE_URL.startswith("postgresql://"):
|
|
DATABASE_URL = DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://")
|
|
|
|
engine = create_async_engine(
|
|
DATABASE_URL,
|
|
echo=False, # SQL 로그 비활성화 (성능 개선)
|
|
future=True,
|
|
pool_pre_ping=True,
|
|
pool_size=20, # 증가
|
|
max_overflow=30, # 증가
|
|
pool_recycle=3600, # 1시간마다 연결 재생성
|
|
pool_timeout=30, # 타임아웃 설정
|
|
connect_args={
|
|
"timeout": 60,
|
|
"command_timeout": 60,
|
|
"server_settings": {
|
|
"jit": "off" # JIT 비활성화로 성능 개선
|
|
}
|
|
}
|
|
)
|
|
|
|
AsyncSessionLocal = sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
autocommit=False,
|
|
autoflush=False,
|
|
)
|
|
|
|
Base = declarative_base()
|
|
|
|
|
|
async def get_db():
|
|
"""DB 세션 생성 및 관리 (안전한 종료 보장)"""
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close()
|