69 lines
1.6 KiB
Python
69 lines
1.6 KiB
Python
"""
|
|
数据库连接和会话管理
|
|
"""
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.pool import NullPool
|
|
from typing import AsyncGenerator
|
|
|
|
from .config import settings
|
|
|
|
# 创建异步数据库引擎
|
|
engine = create_async_engine(
|
|
settings.DATABASE_URL,
|
|
echo=settings.DATABASE_ECHO,
|
|
poolclass=NullPool, # 对于异步使用NullPool
|
|
future=True
|
|
)
|
|
|
|
# 创建异步会话工厂
|
|
AsyncSessionLocal = async_sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False
|
|
)
|
|
|
|
# 创建基础模型类
|
|
Base = declarative_base()
|
|
|
|
|
|
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
|
"""
|
|
数据库会话依赖注入
|
|
用于FastAPI路由中获取数据库会话
|
|
"""
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close()
|
|
|
|
|
|
async def init_db():
|
|
"""初始化数据库表"""
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
|
|
|
|
async def close_db():
|
|
"""关闭数据库连接"""
|
|
await engine.dispose()
|
|
|
|
|
|
async def check_db_connection() -> bool:
|
|
"""检查数据库连接是否正常"""
|
|
try:
|
|
async with AsyncSessionLocal() as session:
|
|
await session.execute("SELECT 1")
|
|
return True
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
async def get_db_session():
|
|
"""获取数据库会话的简化版本"""
|
|
return AsyncSessionLocal() |