From ce82f7a74a26c0048d50b29cc9b64dd25409bf99 Mon Sep 17 00:00:00 2001 From: Wilson C Date: Fri, 12 Sep 2025 18:04:01 -0700 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20resolve=20SQLAlchemy=20session=20man?= =?UTF-8?q?agement=20errors=20and=20improve=20databas=E2=80=A6=20(#229)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/dependencies.py | 7 ++++++- app/core/database.py | 13 ++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/app/api/dependencies.py b/app/api/dependencies.py index 6cc5981..bb6b308 100644 --- a/app/api/dependencies.py +++ b/app/api/dependencies.py @@ -255,7 +255,12 @@ async def get_user_by_api_key( # Update last used timestamp for the API key api_key_record.last_used_at = datetime.utcnow() - await db.commit() + try: + await db.commit() + except Exception: + # If commit fails, rollback and continue + await db.rollback() + # Don't fail the request just because timestamp update failed # Cache the user data for future requests await cache_user_async(api_key, user) diff --git a/app/core/database.py b/app/core/database.py index 31a466f..2bc6345 100644 --- a/app/core/database.py +++ b/app/core/database.py @@ -76,8 +76,11 @@ async def get_async_db(): async with AsyncSessionLocal() as session: try: yield session - finally: - await session.close() + except Exception: + # Rollback on any exception + if not session.is_closed: + await session.rollback() + raise @asynccontextmanager @@ -87,10 +90,10 @@ async def get_db_session(): try: yield session except Exception: - await session.rollback() + # Rollback on any exception + if not session.is_closed: + await session.rollback() raise - finally: - await session.close() def get_connection_info(): From 3672760a198caead0a63982b15673699352128ad Mon Sep 17 00:00:00 2001 From: Wilson C Date: Fri, 12 Sep 2025 20:50:58 -0700 Subject: [PATCH 2/2] hot fix that asyncsession does not have attribute is_closed (#231) --- app/core/database.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/app/core/database.py b/app/core/database.py index 2bc6345..3eb5d1e 100644 --- a/app/core/database.py +++ b/app/core/database.py @@ -77,9 +77,13 @@ async def get_async_db(): try: yield session except Exception: - # Rollback on any exception - if not session.is_closed: + # Rollback on any exception, but handle potential session state issues + try: await session.rollback() + except Exception: + # If rollback fails (e.g., session already closed), ignore it + # The context manager will handle session cleanup + pass raise @@ -90,9 +94,13 @@ async def get_db_session(): try: yield session except Exception: - # Rollback on any exception - if not session.is_closed: + # Rollback on any exception, but handle potential session state issues + try: await session.rollback() + except Exception: + # If rollback fails (e.g., session already closed), ignore it + # The context manager will handle session cleanup + pass raise