fix: make with_session rollback only on SQLAlchemy errors (#5865)

* fix: remove unnecessary session commit in DatabaseService

* fix: improve error logging in DatabaseService session management

* fix: enhance error handling in DatabaseService session management by specifying SQLAlchemyError
This commit is contained in:
Gabriel Luiz Freitas Almeida 2025-01-22 15:53:24 -03:00 committed by GitHub
commit 79844fc54b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -14,7 +14,7 @@ import sqlalchemy as sa
from alembic import command, util
from alembic.config import Config
from loguru import logger
from sqlalchemy import event, inspect
from sqlalchemy import event, exc, inspect
from sqlalchemy.dialects import sqlite as dialect_sqlite
from sqlalchemy.engine import Engine
from sqlalchemy.exc import OperationalError
@ -148,12 +148,11 @@ class DatabaseService(Service):
@asynccontextmanager
async def with_session(self):
async with AsyncSession(self.engine, expire_on_commit=False) as session:
# Start of Selection
try:
yield session
if session.is_active:
await session.commit()
except Exception:
logger.error("An error occurred during the session scope")
except exc.SQLAlchemyError as db_exc:
logger.error(f"Database error during session scope: {db_exc}")
await session.rollback()
raise