Source code for s365b.db.session
"""Database engine and session factory."""
from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from sqlalchemy import text
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from s365b.core.config import Settings
[docs]
class Database:
"""Holds the async engine and hands out sessions.
Args:
settings: Settings providing ``database_url``.
"""
def __init__(self, settings: Settings) -> None:
[docs]
self.engine: AsyncEngine = create_async_engine(
settings.database_url.get_secret_value(), pool_pre_ping=True, pool_size=5
)
self._sessions = async_sessionmaker(self.engine, expire_on_commit=False)
@asynccontextmanager
[docs]
async def session(self) -> AsyncIterator[AsyncSession]:
"""Open a session that commits on success and rolls back on error.
Yields:
The session.
"""
async with self._sessions() as s:
try:
yield s
await s.commit()
except BaseException:
await s.rollback()
raise
[docs]
async def ping(self) -> bool:
"""Check the database is reachable.
Returns:
True if a trivial query succeeds.
"""
try:
async with self.engine.connect() as conn:
await conn.execute(text("SELECT 1"))
except Exception:
return False
return True
[docs]
async def dispose(self) -> None:
"""Close all pooled connections."""
await self.engine.dispose()