Files
yunke/yunke-server/app/db/base.py
T
浅念 b9fcf17ae4 feat: db base + config tests
Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-01 11:04:44 +08:00

49 lines
1.2 KiB
Python

"""Database core: declarative base, async engine, session factory.
Production targets MySQL via `asyncmy` (configured by `Settings.db_url`).
Unit tests build their own in-memory SQLite engines (see `tests/test_db_base.py`)
and only import `Base` / `async_session_maker` from here.
"""
from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import DeclarativeBase
from app.config import get_settings
class Base(DeclarativeBase):
"""Common declarative base for all ORM models in the project."""
settings = get_settings()
async_engine = create_async_engine(
settings.db_url,
pool_pre_ping=True,
future=True,
)
async_session_maker: async_sessionmaker[AsyncSession] = async_sessionmaker(
async_engine,
expire_on_commit=False,
)
async def get_session() -> AsyncIterator[AsyncSession]:
"""FastAPI dependency that yields an `AsyncSession`.
Usage::
@app.get("/")
async def index(session: AsyncSession = Depends(get_session)):
...
"""
async with async_session_maker() as session:
yield session