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

🐛(api) fix not thread-safe database session singleton #131

Merged
merged 1 commit into from
Jul 19, 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
1 change: 1 addition & 0 deletions src/api/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ and this project adheres to
### Fixed

- Add relevant data examples for Swagger
- Improve database session management

## [0.10.0] - 2024-07-01

Expand Down
21 changes: 2 additions & 19 deletions src/api/qualicharge/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,20 +41,6 @@ def get_engine(self, url: PostgresDsn, echo: bool = False) -> SAEngine:
return self._engine


class Session(metaclass=Singleton):
"""Database session singleton."""

_session: Optional[SMSession] = None

def get_session(self, engine: SAEngine) -> SMSession:
"""Get active session or create a new one."""
if self._session is None:
logger.debug("Create new session")
self._session = SMSession(bind=engine)
logger.debug("Getting database session %s", self._session)
return self._session


class SAQueryCounter:
"""Context manager to count SQLALchemy queries.

Expand Down Expand Up @@ -88,12 +74,9 @@ def get_engine() -> SAEngine:

def get_session() -> Generator[SMSession, None, None]:
"""Get database session."""
session = Session().get_session(get_engine())
logger.debug("Getting session %s", session)
try:
with SMSession(bind=get_engine()) as session:
logger.debug("Getting session %s", session)
yield session
finally:
session.close()


def is_alive() -> bool:
Expand Down