2026-01-25 22:34:33 +08:00
|
|
|
|
"""数据库引擎与 Session 工厂。
|
|
|
|
|
|
|
|
|
|
|
|
集中封装 SQLAlchemy async engine 与 async_sessionmaker 的创建逻辑,便于在主程序中统一注入。
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
2026-01-19 14:27:41 +08:00
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine
|
|
|
|
|
|
|
|
|
|
|
|
from backend.config.settings import DatabaseSettings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def create_engine(settings: DatabaseSettings) -> AsyncEngine:
|
2026-01-25 22:34:33 +08:00
|
|
|
|
"""根据配置创建 AsyncEngine。"""
|
2026-01-19 14:27:41 +08:00
|
|
|
|
return create_async_engine(
|
|
|
|
|
|
settings.url,
|
|
|
|
|
|
pool_pre_ping=True,
|
|
|
|
|
|
future=True,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def create_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
|
2026-01-25 22:34:33 +08:00
|
|
|
|
"""创建异步 Session 工厂(expire_on_commit=False 便于返回已提交对象)。"""
|
2026-01-19 14:27:41 +08:00
|
|
|
|
return async_sessionmaker(engine, expire_on_commit=False)
|