Files
skeleton-api/app/core/database.py
T

48 lines
1.2 KiB
Python

"""Async SQLAlchemy engine, session factory, and declarative base.
Works with SQLite (aiosqlite) or Postgres (asyncpg) depending on DATABASE_URL.
"""
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):
"""Declarative base shared by all models."""
engine = create_async_engine(settings.database_url, echo=settings.debug, future=True)
AsyncSessionLocal = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
"""FastAPI dependency yielding a request-scoped session."""
async with AsyncSessionLocal() as session:
yield session
async def init_db() -> None:
"""Create all tables. Convenient for dev/SQLite and tests.
In production prefer Alembic migrations (``alembic upgrade head``).
"""
# Import models so they register with Base.metadata before create_all.
import app.models # noqa: F401
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)