from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlmodel import SQLModel, create_engine, Session
from contextlib import contextmanager, asynccontextmanager

sqlite_file_name = "./db/safe-algo-pro.db"
sqlite_url = f"sqlite+aiosqlite:///{sqlite_file_name}"  # 使用异步SQLite驱动

engine = create_async_engine(sqlite_url, echo=False, future=True)


# 初始化数据库表
async def init_db():
    async with engine.begin() as conn:
        await conn.run_sync(SQLModel.metadata.create_all)


# 异步数据库会话管理
# @asynccontextmanager
async def get_db() -> AsyncSession:
    async_session = sessionmaker(
        engine, class_=AsyncSession, expire_on_commit=False
    )
    async with async_session() as session:
        yield session
