@@ -143,10 +143,29 @@ public ResultSet executeQuery(String sql) throws SQLException {
143143 return executeQuery (sql , new QuerySettings ().setDatabase (schema ));
144144 }
145145
146+ private void closePreviousResultSet () {
147+ if (currentResultSet != null ) {
148+ LOG .debug ("Previous result set is open [resultSet = " + currentResultSet + "]" );
149+ // Closing request blindly assuming that user do not care about it anymore (DDL request for example)
150+ try {
151+ currentResultSet .close ();
152+ } catch (Exception e ) {
153+ LOG .error ("Failed to close previous result set" , e );
154+ } finally {
155+ currentResultSet = null ;
156+ }
157+ }
158+ }
159+
146160 public ResultSetImpl executeQuery (String sql , QuerySettings settings ) throws SQLException {
147161 checkClosed ();
162+ // Closing before trying to do next request. Otherwise, deadlock because previous connection will not be
163+ // release before this one completes.
164+ closePreviousResultSet ();
165+
148166 QuerySettings mergedSettings = QuerySettings .merge (connection .getDefaultQuerySettings (), settings );
149167
168+
150169 if (mergedSettings .getQueryId () != null ) {
151170 lastQueryId = mergedSettings .getQueryId ();
152171 } else {
@@ -165,17 +184,6 @@ public ResultSetImpl executeQuery(String sql, QuerySettings settings) throws SQL
165184 }
166185 ClickHouseBinaryFormatReader reader = connection .client .newBinaryFormatReader (response );
167186
168- if (currentResultSet != null ) {
169- LOG .debug ("Previous result set is open [resultSet = " + currentResultSet + "]" );
170- // Closing request blindly assuming that user do not care about it anymore (DDL request for example)
171- try {
172- currentResultSet .close ();
173- } catch (Exception e ) {
174- LOG .error ("Failed to close previous result set" , e );
175- } finally {
176- currentResultSet = null ;
177- }
178- }
179187 currentResultSet = new ResultSetImpl (this , response , reader );
180188 metrics = response .getMetrics ();
181189 } catch (Exception e ) {
@@ -199,6 +207,10 @@ public int executeUpdate(String sql, QuerySettings settings) throws SQLException
199207 throw new SQLException ("executeUpdate() cannot be called with a SELECT/SHOW/DESCRIBE/EXPLAIN statement" , ExceptionUtils .SQL_STATE_SQL_ERROR );
200208 }
201209
210+ // Closing before trying to do next request. Otherwise, deadlock because previous connection will not be
211+ // release before this one completes.
212+ closePreviousResultSet ();
213+
202214 QuerySettings mergedSettings = QuerySettings .merge (connection .getDefaultQuerySettings (), settings );
203215
204216 if (mergedSettings .getQueryId () != null ) {
0 commit comments