Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DM-43288: Ensure per-request database sessions are closed #242

Merged
merged 1 commit into from
Mar 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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