legacybot / database /session.py
zoldyckff999oy's picture
update project files
251964d
Raw History Blame Contribute Delete
1.08 kB
"""
Session helpers — replace the old `async with db.acquire()` pattern.
"""
from __future__ import annotations
from contextlib import asynccontextmanager
from typing import AsyncIterator
from sqlalchemy.ext.asyncio import AsyncSession
@asynccontextmanager
async def session_scope() -> AsyncIterator[AsyncSession]:
"""
Preferred context manager for business logic.
"""
# استيراد المصنع ديناميكياً داخل الدالة لتفادي تعارض الأسماء والحصول على القيمة المحدثة
from database.engine import async_session_factory
if async_session_factory is None:
raise RuntimeError("Database not initialized. Call init_database() first.")
session: AsyncSession = async_session_factory()
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
async def get_session() -> AsyncIterator[AsyncSession]:
async with session_scope() as session:
yield session