from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession  

from sqlalchemy.orm import sessionmaker, declarative_base 
from app.config.config import database_settings 

engine = create_async_engine(
    f"mysql+aiomysql://{database_settings.DB_USER}:{database_settings.DB_PASSWORD}@{database_settings.DB_HOST}:{database_settings.DB_PORT}/{database_settings.DB_NAME}",
    pool_size=database_settings.DB_POOL_SIZE,        # 连接池常驻连接数
    max_overflow=database_settings.DB_MAX_OVERFLOW,  # 池最大溢出连接数
    pool_timeout=database_settings.DB_POOL_TIMEOUT,  # 获取连接超时时间（秒）
    pool_recycle=database_settings.DB_POOL_RECYCLE,  # 连接回收间隔（秒）
    echo=False                             # 关闭SQL日志输出
)

# expire_on_commit=False 禁用提交后过期对象 --> 提交后原对象仍然可以使用.
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

# ORM模型基类
Base = declarative_base()


# 获取数据库会话
async def get_db():
    async with async_session() as session:
        try:
            yield session 
            # await session.commit() 
        except Exception:
            await session.rollback()
            raise 
        finally:
            await session.close()