Skip to content

Commit 9fd7758

Browse files
committed
Fix unclosed asyncpg connections causing SQLAlchemy pool warnings (#65)
- Apply recommended fix to get_async_db(): use explicit session management instead of async context manager - Remove redundant session.close() in get_db_session() after async with block - Fix synchronous commit() calls on async sessions in test files - Ensures proper cleanup of database connections and prevents pool exhaustion
1 parent abb567e commit 9fd7758

3 files changed

Lines changed: 9 additions & 11 deletions

File tree

app/core/database.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,11 +73,11 @@ def get_db():
7373

7474
# Async dependency
7575
async def get_async_db():
76-
async with AsyncSessionLocal() as session:
77-
try:
78-
yield session
79-
finally:
80-
await session.close()
76+
session = AsyncSessionLocal()
77+
try:
78+
yield session
79+
finally:
80+
await session.close()
8181

8282

8383
@asynccontextmanager
@@ -89,8 +89,6 @@ async def get_db_session():
8989
except Exception:
9090
await session.rollback()
9191
raise
92-
finally:
93-
await session.close()
9492

9593

9694
def get_connection_info():

tests/cache/test_async_cache.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -534,7 +534,7 @@ async def test_async_cache_warming():
534534
hashed_password="dummy_hash",
535535
)
536536
db.add(user)
537-
db.commit()
537+
await db.commit()
538538

539539
# Create a test API key
540540
test_api_key = "test_key_123"
@@ -546,7 +546,7 @@ async def test_async_cache_warming():
546546
encrypted_api_key=encrypted_key,
547547
)
548548
db.add(provider_key)
549-
db.commit()
549+
await db.commit()
550550

551551
# Warm the cache
552552
await warm_cache_async(db)

tests/mock_testing/add_mock_provider.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ async def setup_mock_provider(username: str, force: bool = False):
5555
# If force is set and provider exists, delete the existing one
5656
if existing_provider and force:
5757
db.delete(existing_provider)
58-
db.commit()
58+
await db.commit()
5959
print(f"🗑️ Deleted existing mock provider for user '{username}'.")
6060

6161
# Create a mock API key - it doesn't need to be secure as it's not used
@@ -83,7 +83,7 @@ async def setup_mock_provider(username: str, force: bool = False):
8383
)
8484

8585
db.add(provider_key)
86-
db.commit()
86+
await db.commit()
8787

8888
# Invalidate provider key cache for this user to force refresh
8989
provider_service_cache.delete(f"provider_keys:{user.id}")

0 commit comments

Comments
 (0)