keyvault-api / src /database.py
hashir-qt's picture
Upload folder using huggingface_hub
e656014 verified
Raw History Blame Contribute Delete
1.49 kB
from sqlmodel import SQLModel
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from src.config import settings
# NeonDB (and Supabase) require SSL — asyncpg accepts it via connect_args.
# prepared_statement_cache_size=0 prevents stale plan errors after migrations.
_connect_args: dict = {
"ssl": "require",
"statement_cache_size": 0, # asyncpg param — disables server-side prepared statement cache
}
engine = create_async_engine(
settings.database_url,
echo=settings.debug,
future=True,
connect_args=_connect_args,
pool_pre_ping=True, # test connection health before use; discards stale connections
pool_recycle=300, # recycle connections after 5 min (Supabase closes idle ~10 min)
pool_size=5,
max_overflow=10,
)
AsyncSessionLocal = sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
)
async def init_db() -> None:
"""Create all database tables. Called on app startup."""
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
async def get_db() -> AsyncSession:
"""Yield an async database session. Use as a FastAPI dependency."""
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise