Fix database session context manager errors

- Add explicit commit/rollback in session dependencies
- Prevents RuntimeError: generator didn't stop after athrow()
- Ensures proper transaction cleanup on exceptions
This commit is contained in:
2026-01-23 18:35:15 +01:00
parent e09bb0451c
commit 2b904fd01e

View File

@@ -130,14 +130,15 @@ async def get_database_session() -> AsyncGenerator:
detail="Database functionality not installed" detail="Database functionality not installed"
) )
try:
async with get_db_session() as session: async with get_db_session() as session:
try:
yield session yield session
except RuntimeError as e: # Auto-commit on successful completion
raise HTTPException( await session.commit()
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, except Exception:
detail=f"Database not available: {str(e)}" # Auto-rollback on error
) await session.rollback()
raise
async def get_optional_database_session() -> AsyncGenerator: async def get_optional_database_session() -> AsyncGenerator:
@@ -169,12 +170,16 @@ async def get_optional_database_session() -> AsyncGenerator:
yield None yield None
return return
try: # Use get_db_session context manager properly
async with get_db_session() as session: async with get_db_session() as session:
try:
yield session yield session
except (ImportError, RuntimeError): # Auto-commit on successful completion
# Database became unavailable - this shouldn't happen but handle it await session.commit()
yield None except Exception:
# Auto-rollback on error
await session.rollback()
raise
def get_current_user( def get_current_user(