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

Disable reconnect toggle #453

Merged
merged 1 commit into from
Sep 6, 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
13 changes: 12 additions & 1 deletion clickhouse_driver/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ class Connection(object):
Defaults to ``False``.
:param client_revision: can be used for client version downgrading.
Defaults to ``None``.
:param disable_reconnect: disable automatic reconnect in case of
failed ``ping``, helpful when every reconnect
need to be caught in calling code.
Defaults to ``False``.
"""

def __init__(
Expand All @@ -161,7 +165,8 @@ def __init__(
alt_hosts=None,
settings_is_important=False,
tcp_keepalive=False,
client_revision=None
client_revision=None,
disable_reconnect=False,
):
if secure:
default_port = defines.DEFAULT_SECURE_PORT
Expand All @@ -187,6 +192,7 @@ def __init__(
self.client_revision = min(
client_revision or defines.CLIENT_REVISION, defines.CLIENT_REVISION
)
self.disable_reconnect = disable_reconnect

self.secure_socket = secure
self.verify_cert = verify
Expand Down Expand Up @@ -258,6 +264,11 @@ def force_connect(self):
self.connect()

elif not self.ping():
if self.disable_reconnect:
raise errors.NetworkError(
"Connection was closed, reconnect is disabled."
)

logger.warning('Connection was closed, reconnecting.')
self.connect()

Expand Down
22 changes: 22 additions & 0 deletions tests/test_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,28 @@ def test_transport_not_connection_on_disconnect(self):
# Close newly created socket.
connection.socket.close()

def test_transport_disable_reconnect(self):
with self.created_client(disable_reconnect=True) as client:
# Create connection.
client.execute('SELECT 1')

connection = client.connection

with patch.object(connection, 'ping') as mocked_ping:
mocked_ping.return_value = False

self.assertTrue(connection.connected)
error = errors.NetworkError
with self.assertRaises(error) as e:
client.execute('SELECT 1')

self.assertFalse(connection.connected)

self.assertEqual(
str(e.exception),
'Code: 210. Connection was closed, reconnect is disabled.'
)

def test_socket_error_on_ping(self):
self.client.execute('SELECT 1')

Expand Down