people-reading/backend/app/core/database.py
2026-05-12 20:50:15 +08:00

32 lines
905 B
Python

from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from app.core.config import settings
class Base(DeclarativeBase):
pass
engine = create_async_engine(settings.database_url, echo=False, future=True)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
async def init_db() -> None:
from app.models import daily_usage, palm_report, reading, share_image_job, uploaded_image, user # noqa: F401
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)