@@ -402,32 +402,29 @@ def _close_connection_if_idle(self, internal_conn: Optional[Connection]):
402402 current_conn = self ._plugin_service .current_connection
403403 driver_dialect = self ._plugin_service .driver_dialect
404404
405+ if internal_conn == current_conn :
406+ # Connection is in use, do not close
407+ return
408+
405409 try :
406- if internal_conn != current_conn and self ._is_connection_usable (
407- internal_conn , driver_dialect
408- ):
410+ if self ._is_connection_usable (internal_conn , driver_dialect ):
409411 driver_dialect .execute (DbApiMethod .CONNECTION_CLOSE .method_name , lambda : internal_conn .close ())
410- if internal_conn == self ._writer_connection :
411- self ._writer_connection = None
412- self ._writer_host_info = None
413- if internal_conn == self ._reader_connection :
414- self ._reader_connection = None
415- self ._reader_host_info = None
416412 except Exception :
417413 # Ignore exceptions during cleanup - connection might already be dead
418414 pass
415+ finally :
416+ if internal_conn == self ._writer_connection :
417+ self ._writer_connection = None
418+ self ._writer_host_info = None
419+ if internal_conn == self ._reader_connection :
420+ self ._reader_connection = None
421+ self ._reader_host_info = None
419422
420423 def _close_idle_connections (self ):
421424 logger .debug ("ReadWriteSplittingPlugin.ClosingInternalConnections" )
422425 self ._close_connection_if_idle (self ._reader_connection )
423426 self ._close_connection_if_idle (self ._writer_connection )
424427
425- # Always clear cached references even if connections couldn't be closed
426- self ._reader_connection = None
427- self ._reader_host_info = None
428- self ._writer_connection = None
429- self ._writer_host_info = None
430-
431428 @staticmethod
432429 def log_and_raise_exception (log_msg : str ):
433430 logger .error (log_msg )
0 commit comments