Buckets:

download
raw
4.07 kB
# src/OSSS/db/session.py
from __future__ import annotations
import os
from contextlib import asynccontextmanager
from typing import AsyncIterator, AsyncGenerator
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.pool import NullPool
from OSSS.core.config import settings
# ---------------------------------------------------------------------------
# Engine configuration
# ---------------------------------------------------------------------------
# Prefer ASYNC_DATABASE_URL (correct for containers), then DATABASE_URL, then settings
DATABASE_URL = (
os.getenv("ASYNC_DATABASE_URL")
or os.getenv("DATABASE_URL")
or settings.DATABASE_URL
)
# Use NullPool in tests (or when explicitly requested) to avoid sharing the same
# asyncpg connection across threads/tasks (common with TestClient).
USE_NULLPOOL = (
os.getenv("SQLALCHEMY_NULLPOOL", "0") == "1"
or bool(getattr(settings, "TESTING", False))
)
# Optional tuning via settings/env (falls back to sensible defaults)
POOL_SIZE = int(os.getenv("DB_POOL_SIZE", getattr(settings, "DB_POOL_SIZE", 5)))
MAX_OVERFLOW = int(os.getenv("DB_MAX_OVERFLOW", getattr(settings, "DB_MAX_OVERFLOW", 10)))
POOL_RECYCLE = int(
os.getenv("DB_POOL_RECYCLE", getattr(settings, "DB_POOL_RECYCLE", 1800))
) # seconds
_engine_kwargs: dict = {
"echo": bool(getattr(settings, "DB_ECHO", False)),
"pool_pre_ping": True, # 💡 protects against stale connections
}
if USE_NULLPOOL:
# Testing / one-off processes: don't keep a pool at all
_engine_kwargs["poolclass"] = NullPool
else:
# Normal runtime: keep a small, resilient pool
_engine_kwargs.update(
{
"pool_size": POOL_SIZE,
"max_overflow": MAX_OVERFLOW,
"pool_recycle": POOL_RECYCLE,
}
)
# Build the async engine once
engine = create_async_engine(DATABASE_URL, **_engine_kwargs)
# ---------------------------------------------------------------------------
# Sessionmaker (one factory for the whole app)
# - Define AsyncSessionLocal for backwards compatibility
# - Keep get_sessionmaker() for callers needing the factory
# ---------------------------------------------------------------------------
AsyncSessionLocal: async_sessionmaker[AsyncSession] = async_sessionmaker(
bind=engine,
expire_on_commit=False,
class_=AsyncSession,
)
# Backwards-compatible alias if other code expects "_sessionmaker"
_sessionmaker: async_sessionmaker[AsyncSession] = AsyncSessionLocal
def get_engine():
"""Expose the engine (e.g., for health checks / pings)."""
return engine
def get_sessionmaker() -> async_sessionmaker[AsyncSession]:
"""Return the app-wide async sessionmaker."""
return _sessionmaker
# ---------------------------------------------------------------------------
# FastAPI dependencies / session helpers
# - get_session: async context manager (use with `async with`)
# - get_db: async generator (use with `Depends(get_db)`)
# - get_async_session: backwards-compatible name expected by older modules
# ---------------------------------------------------------------------------
@asynccontextmanager
async def get_session() -> AsyncIterator[AsyncSession]:
async with AsyncSessionLocal() as session:
try:
yield session
except Exception:
await session.rollback()
raise
finally:
await session.close()
@asynccontextmanager
async def get_async_session() -> AsyncIterator[AsyncSession]:
"""
Backwards-compatible alias used by older/other modules.
Usage:
async with get_async_session() as session:
...
"""
async with get_session() as session:
yield session
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
try:
yield session
except Exception:
await session.rollback()
raise
finally:
await session.close()

Xet Storage Details

Size:
4.07 kB
·
Xet hash:
99dceaec397408f0dba282ca44fff83e2b06dcb2626660009c9a915176f3cccb

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.