From f790ec383e370d4cd6b3a7774796c4f7903e2c7c Mon Sep 17 00:00:00 2001 From: Jorrit Schaap <schaap@astron.nl> Date: Thu, 19 Sep 2019 12:11:54 +0200 Subject: [PATCH] SW-816: fixed disconnect --- LCS/PyCommon/postgres.py | 22 ++++++++++++++-------- LCS/PyCommon/test/t_postgres.py | 2 +- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/LCS/PyCommon/postgres.py b/LCS/PyCommon/postgres.py index c43d56541bf..13d6cee1db2 100644 --- a/LCS/PyCommon/postgres.py +++ b/LCS/PyCommon/postgres.py @@ -116,6 +116,7 @@ class PostgresDatabaseConnection: query_timeout: float=3600): self._dbcreds = dbcreds self._connection = None + self._cursor = None self.__auto_commit_selects = auto_commit_selects self.__num_connect_retries = num_connect_retries self.__connect_retry_interval = connect_retry_interval @@ -132,7 +133,7 @@ class PostgresDatabaseConnection: for retry_cntr in range(self.__num_connect_retries+1): try: - logger.debug("trying to connect to database: %s", self) + logger.debug("connecting to database: %s", self) self._connection = psycopg2.connect(host=self._dbcreds.host, user=self._dbcreds.user, @@ -172,13 +173,18 @@ class PostgresDatabaseConnection: raise PostgresDBError(error_string) def disconnect(self): - if self.is_connected: - logger.debug("%s disconnecting from db: %s", self.__class__.__name__, self.database) - self._cursor.close() - self._cursor = None - self._connection.close() - self._connection = None - logger.debug("%s disconnected from db: %s", self.__class__.__name__, self.database) + if self._connection is not None or self._cursor is not None: + logger.debug("disconnecting from database: %s", self) + + if self._cursor is not None: + self._cursor.close() + self._cursor = None + + if self._connection is not None: + self._connection.close() + self._connection = None + + logger.info("disconnected from database: %s", self) def _is_recoverable_connection_error(self, error: psycopg2.DatabaseError) -> bool: '''test if psycopg2.DatabaseError is a recoverable connection error''' diff --git a/LCS/PyCommon/test/t_postgres.py b/LCS/PyCommon/test/t_postgres.py index 7a0fdf1bfe5..29368d849be 100755 --- a/LCS/PyCommon/test/t_postgres.py +++ b/LCS/PyCommon/test/t_postgres.py @@ -65,7 +65,7 @@ class TestPostgres(unittest.TestCase): # check logging self.assertEqual(NUM_CONNECT_RETRIES, len([ca for ca in mocked_logger.info.call_args_list if 'retrying to connect' in ca[0][0]])) - self.assertEqual(NUM_CONNECT_RETRIES+1, len([ca for ca in mocked_logger.debug.call_args_list if 'trying to connect to database' in ca[0][0]])) + self.assertEqual(NUM_CONNECT_RETRIES+1, len([ca for ca in mocked_logger.debug.call_args_list if 'connecting to database' in ca[0][0]])) self.assertEqual(NUM_CONNECT_RETRIES+1, len([ca for ca in mocked_logger.error.call_args_list if 'could not connect' in ca[0][0]])) def test_reconnect_on_connection_loss(self): -- GitLab