Skip to content

Commit 95fc33f

Browse files
authored
Resolve SQLAlchemy session management errors (#94)
1 parent 30fd857 commit 95fc33f

2 files changed

Lines changed: 22 additions & 6 deletions

File tree

app/api/dependencies.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,12 @@ async def get_user_by_api_key(
255255

256256
# Update last used timestamp for the API key
257257
api_key_record.last_used_at = datetime.utcnow()
258-
await db.commit()
258+
try:
259+
await db.commit()
260+
except Exception:
261+
# If commit fails, rollback and continue
262+
await db.rollback()
263+
# Don't fail the request just because timestamp update failed
259264

260265
# Cache the user data for future requests
261266
await cache_user_async(api_key, user)

app/core/database.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,15 @@ async def get_async_db():
7676
async with AsyncSessionLocal() as session:
7777
try:
7878
yield session
79-
finally:
80-
await session.close()
79+
except Exception:
80+
# Rollback on any exception, but handle potential session state issues
81+
try:
82+
await session.rollback()
83+
except Exception:
84+
# If rollback fails (e.g., session already closed), ignore it
85+
# The context manager will handle session cleanup
86+
pass
87+
raise
8188

8289

8390
@asynccontextmanager
@@ -87,10 +94,14 @@ async def get_db_session():
8794
try:
8895
yield session
8996
except Exception:
90-
await session.rollback()
97+
# Rollback on any exception, but handle potential session state issues
98+
try:
99+
await session.rollback()
100+
except Exception:
101+
# If rollback fails (e.g., session already closed), ignore it
102+
# The context manager will handle session cleanup
103+
pass
91104
raise
92-
finally:
93-
await session.close()
94105

95106

96107
def get_connection_info():

0 commit comments

Comments
 (0)