b9fcf17ae4
Co-Authored-By: Claude <noreply@anthropic.com>
49 lines
1.2 KiB
Python
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
|