PMFlow/backend/app/database.py

42 lines
856 B
Python

"""数据库会话与引擎管理。"""
from __future__ import annotations
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from .core.config import settings
DATABASE_URL = settings.database_url
def _is_sqlite() -> bool:
return DATABASE_URL.lower().startswith("sqlite")
engine: AsyncEngine = create_async_engine(
DATABASE_URL,
echo=settings.debug,
future=True,
pool_pre_ping=not _is_sqlite(),
)
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
"""FastAPI 依赖:提供数据库会话。"""
async with AsyncSessionLocal() as session:
yield session