From 7380c726ce21a13173f596c5cb74b7802d51e600 Mon Sep 17 00:00:00 2001 From: James Robinson Date: Thu, 9 Jan 2025 15:47:01 +0000 Subject: [PATCH 1/2] :bug: Use all() to instantiate query results before returning. This avoids dangling queries which unnecessarily use up connections from the pool. --- guacamole_user_sync/postgresql/postgresql_backend.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/guacamole_user_sync/postgresql/postgresql_backend.py b/guacamole_user_sync/postgresql/postgresql_backend.py index f939166..7d29e6c 100644 --- a/guacamole_user_sync/postgresql/postgresql_backend.py +++ b/guacamole_user_sync/postgresql/postgresql_backend.py @@ -86,7 +86,7 @@ def query( ) -> list[T]: with self.session() as session, session.begin(): if filter_kwargs: - result = session.query(table).filter_by(**filter_kwargs) + result = session.query(table).filter_by(**filter_kwargs).all() else: - result = session.query(table) + result = session.query(table).all() return list(result) From b71f2535f4b4d9fe26ad3b48ba1f8f8a6352cac7 Mon Sep 17 00:00:00 2001 From: James Robinson Date: Thu, 9 Jan 2025 15:47:38 +0000 Subject: [PATCH 2/2] :bug: Mark queries as not expiring on commit to ensure that they can be used by calling functions --- guacamole_user_sync/postgresql/postgresql_backend.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/guacamole_user_sync/postgresql/postgresql_backend.py b/guacamole_user_sync/postgresql/postgresql_backend.py index 7d29e6c..cdc7621 100644 --- a/guacamole_user_sync/postgresql/postgresql_backend.py +++ b/guacamole_user_sync/postgresql/postgresql_backend.py @@ -50,10 +50,10 @@ def engine(self) -> Engine: self._engine = create_engine(url_object, echo=False) return self._engine - def session(self) -> Session: + def session(self, *, expire_on_commit: bool = True) -> Session: if self._session: return self._session - return Session(self.engine) + return Session(self.engine, expire_on_commit=expire_on_commit) def add_all(self, items: list[T]) -> None: with self.session() as session, session.begin(): @@ -84,7 +84,8 @@ def query( table: type[T], **filter_kwargs: Any, # noqa: ANN401 ) -> list[T]: - with self.session() as session, session.begin(): + # We need expire_on_commit to ensure that the results are not marked as stale + with self.session(expire_on_commit=False) as session, session.begin(): if filter_kwargs: result = session.query(table).filter_by(**filter_kwargs).all() else: