SmartEDT/backend/database/engine.py

25 lines
816 B
Python
Raw 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.

"""数据库引擎与 Session 工厂。
集中封装 SQLAlchemy async engine 与 async_sessionmaker 的创建逻辑,便于在主程序中统一注入。
"""
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:
"""根据配置创建 AsyncEngine。"""
return create_async_engine(
settings.url,
pool_pre_ping=True,
future=True,
)
def create_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
"""创建异步 Session 工厂expire_on_commit=False 便于返回已提交对象)。"""
return async_sessionmaker(engine, expire_on_commit=False)