from typing import AsyncGenerator from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlmodel import SQLModel from .config import settings engine = create_async_engine( settings.database_url, echo=settings.debug, pool_pre_ping=True, ) async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async def get_session() -> AsyncGenerator[AsyncSession, None]: async with async_session() as session: yield session async def create_db_and_tables(): """Create database tables if they don't exist.""" async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) async def db_health_check() -> bool: """Check if database connection is healthy.""" try: async with async_session() as session: await session.execute(text("SELECT 1")) return True except Exception: return False