From dbd91bf41a95d138679112b18ebb3582be2606c8 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Sun, 15 Jan 2023 12:34:18 +0100 Subject: [PATCH] Fix closing connection on invalid connection --- src/de/steamwar/sql/internal/Statement.java | 32 ++++++++++++--------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/src/de/steamwar/sql/internal/Statement.java b/src/de/steamwar/sql/internal/Statement.java index 6c44332..ded799c 100644 --- a/src/de/steamwar/sql/internal/Statement.java +++ b/src/de/steamwar/sql/internal/Statement.java @@ -157,32 +157,36 @@ public class Statement implements AutoCloseable { private T withConnection(SQLRunnable runnable, Object... objects) { Connection connection = aquireConnection(); + T result; try { - try { - return tryWithConnection(connection, runnable, objects); - } finally { - if(connectionInvalid(connection)) { - closeConnection(connection); - } else { - synchronized (connections) { - connections.push(connection); - connections.notify(); - } - } - } - } catch (SQLException e) { + result = tryWithConnection(connection, runnable, objects); + } catch (Throwable e) { if(connectionInvalid(connection)) { + closeConnection(connection); + return withConnection(runnable, objects); } else { + synchronized (connections) { + connections.push(connection); + connections.notify(); + } + throw new SecurityException("Failing sql statement", e); } } + + synchronized (connections) { + connections.push(connection); + connections.notify(); + } + + return result; } private boolean connectionInvalid(Connection connection) { try { - return connection.isClosed(); + return connection.isClosed() || !connection.isValid(1); } catch (SQLException e) { logger.log(Level.INFO, "Could not check SQL connection status", e); // No database logging possible at this state return true;