Files
clubber/src/database.py
T

40 lines
964 B
Python
Raw Normal View History

from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from src.config import settings
# Create async engine
async_engine = create_async_engine(
settings.database_url,
echo=settings.debug,
future=True,
)
# Create async session factory
async_session_maker = async_sessionmaker(
async_engine,
class_=AsyncSession,
expire_on_commit=False,
)
# Declarative base for models
class Base(DeclarativeBase):
pass
# Dependency for FastAPI
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
"""Provide database session for FastAPI dependency injection."""
async with async_session_maker() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()