Skip to content

Commit

Permalink
Ensure per-request database sessions are closed
Browse files Browse the repository at this point in the history
In the db_session_dependency FastAPI dependency, do database session
cleanup in a finally block. This will hopefully ensure that the
sessions are cleaned up even on uncaught exceptions, which in turn
fixes warnings in test cases in other packages.
  • Loading branch information
rra committed Mar 13, 2024
1 parent e7eca52 commit 8fab62d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
3 changes: 3 additions & 0 deletions changelog.d/20240312_174906_rra_DM_43288.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Bug fixes

- Ensure that per-request database sessions provided by `db_session_dependency` are cleaned up even if the request aborts with an uncaught exception.
15 changes: 8 additions & 7 deletions src/safir/dependencies/db_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,14 @@ async def __call__(self) -> AsyncIterator[async_scoped_session]:
"""
if not self._session:
raise RuntimeError("db_session_dependency not initialized")
yield self._session

# Following the recommendations in the SQLAlchemy documentation, each
# session is scoped to a single web request. However, this all uses
# the same async_scoped_session object, so should share an underlying
# engine and connection pool.
await self._session.remove()
try:
yield self._session
finally:
# Following the recommendations in the SQLAlchemy documentation,
# each session is scoped to a single web request. However, this
# all uses the same async_scoped_session object, so should share
# an underlying engine and connection pool.
await self._session.remove()

async def aclose(self) -> None:
"""Shut down the database engine."""
Expand Down

0 comments on commit 8fab62d

Please sign in to comment.