Skip to content
Snippets Groups Projects
Commit f790ec38 authored by Jorrit Schaap's avatar Jorrit Schaap
Browse files

SW-816: fixed disconnect

parent 84638baf
No related branches found
No related tags found
2 merge requests!59Merge LOFAR-Release-4_0 into master,!57Resolve SW-816
......@@ -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'''
......
......@@ -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):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment