Skip to content

Commit

Permalink
Merge pull request #242 from lsst-sqre/tickets/DM-43288
Browse files Browse the repository at this point in the history
DM-43288: Ensure per-request database sessions are closed
  • Loading branch information
rra authored Mar 14, 2024
2 parents e7eca52 + 8fab62d commit db7f415
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 db7f415

Please sign in to comment.