Files
zcglxt/backend_new/app/db/session.py

71 lines
1.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
数据库会话管理
"""
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from app.core.config import settings
from app.db.base import Base
# 创建异步引擎
engine = create_async_engine(
settings.DATABASE_URL,
echo=settings.DATABASE_ECHO,
pool_pre_ping=True,
pool_size=50, # 从20增加到50提高并发性能
max_overflow=10, # 从0增加到10允许峰值时的额外连接
)
# 创建异步会话工厂
async_session_maker = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False,
)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
"""
获取数据库会话
Yields:
AsyncSession: 数据库会话
"""
async with async_session_maker() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
async def init_db() -> None:
"""
初始化数据库(创建所有表)
注意生产环境应使用Alembic迁移
"""
async with engine.begin() as conn:
# 导入所有模型以确保它们被注册
from app.models import user, asset, device_type, organization
# 创建所有表
await conn.run_sync(Base.metadata.create_all)
async def close_db() -> None:
"""关闭数据库连接"""
await engine.dispose()
__all__ = [
"engine",
"async_session_maker",
"get_db",
"init_db",
"close_db",
]