This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-13134-8d56c65d83c28edfc7640c2e0148fcb94ab93732 in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit 9a53cc670373118861f4a35324053e4cee9a9c9e Author: nikitap-sg <[email protected]> AuthorDate: Sun Nov 29 10:29:25 2026 +0000 [Fix][Connector-V2][JDBC] Retry a flush when binding hits a closed statement (#13134) Signed-off-by: Nikita Punjabi <[email protected]> Co-authored-by: Cursor <[email protected]> --- .../seatunnel/jdbc/internal/JdbcOutputFormat.java | 28 +++- .../executor/BufferedBatchStatementExecutor.java | 4 +- .../internal/JdbcOutputFormatReconnectTest.java | 163 +++++++++++++++++++++ .../BufferedBatchStatementExecutorTest.java | 35 +++++ .../jdbc/sink/JdbcMultiTableReconnectTest.java | 54 ++++++- 5 files changed, 280 insertions(+), 4 deletions(-) diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java index 95ea980cfe..741b8b2869 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java @@ -372,7 +372,31 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem } protected void attemptFlush() throws SQLException { - jdbcStatementExecutor.executeBatch(); + try { + jdbcStatementExecutor.executeBatch(); + } catch (JdbcConnectorException exception) { + // Row binding wraps a closed statement as a connector exception. Flush retry + // only catches SQLException, so surface the original connection failure. + SQLException connectionFailure = closedConnectionFailure(exception); + if (connectionFailure == null) { + throw exception; + } + throw connectionFailure; + } + } + + /** + * Returns the outermost SQLException when the chain contains a lost connection or a closed + * statement. The whole chain is scanned so a connection failure buried under a conversion + * wrapper still retries, but the returned exception keeps its next-exception chain. A chain + * that only contains a data error returns null and flush stays fail-fast. + */ + private SQLException closedConnectionFailure(Throwable failure) { + List<SQLException> sqlExceptions = findSqlExceptions(failure); + if (sqlExceptions.isEmpty() || !isConnectionLost(sqlExceptions)) { + return null; + } + return sqlExceptions.get(0); } /** @@ -793,8 +817,10 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem String normalizedMessage = message.toLowerCase(Locale.ROOT); // SQL Server may report a closed statement handle without using "closed". + // PostgreSQL reports "This statement has been closed." return normalizedMessage.contains("statement closed") || normalizedMessage.contains("statement is closed") + || normalizedMessage.contains("has been closed") || normalizedMessage.contains("statement handle is not executing") || normalizedMessage.contains("statement handle is closed"); } diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java index 75181d4c08..d4eee4917f 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java @@ -61,7 +61,9 @@ public class BufferedBatchStatementExecutor implements JdbcBatchStatementExecuto statementExecutor.executeBatch(); buffer.clear(); flushFailed = false; - } catch (SQLException e) { + } catch (SQLException | RuntimeException e) { + // Keep the buffered rows. closeStatements runs during reconnect and must not + // bind them again onto the statement this attempt just failed against. flushFailed = true; throw e; } diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectTest.java index 461fb6232f..9ebb48dc03 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectTest.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectTest.java @@ -19,9 +19,11 @@ package org.apache.seatunnel.connectors.seatunnel.jdbc.internal; import org.apache.seatunnel.api.table.type.SeaTunnelRow; import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcConnectionConfig; +import org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorErrorCode; import org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorException; import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.connection.JdbcConnectionProvider; import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.connection.JdbcTransactionStateManager; +import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.executor.BufferedBatchStatementExecutor; import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.executor.JdbcBatchStatementExecutor; import org.junit.jupiter.api.Assertions; @@ -33,7 +35,12 @@ import org.mockito.Mockito; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import java.util.Optional; +import java.util.function.Function; /** Tests JDBC output retry decisions for nested SQLExceptions thrown by batch execution. */ public class JdbcOutputFormatReconnectTest { @@ -98,6 +105,162 @@ public class JdbcOutputFormatReconnectTest { Mockito.verify(provider, Mockito.never()).isConnectionValid(); } + @Test + public void testFlushRetryShouldReconnectWhenBindingFailsBecauseStatementHasBeenClosed() + throws Exception { + JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class); + Connection connection = Mockito.mock(Connection.class); + Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection); + Mockito.when(provider.getConnection()).thenReturn(connection); + Mockito.when(provider.reestablishConnection()).thenReturn(connection); + + int[] prepareStatementsCalls = new int[1]; + int[] executeBatchCalls = new int[1]; + int[] closeStatementsCalls = new int[1]; + JdbcBatchStatementExecutor<SeaTunnelRow> executor = + new JdbcBatchStatementExecutor<SeaTunnelRow>() { + @Override + public void prepareStatements(Connection ignored) { + prepareStatementsCalls[0]++; + } + + @Override + public void addToBatch(SeaTunnelRow record) {} + + @Override + public void executeBatch() { + executeBatchCalls[0]++; + if (executeBatchCalls[0] == 1) { + throw new JdbcConnectorException( + JdbcConnectorErrorCode.DATA_TYPE_CAST_FAILED, + "error field:id", + new SQLException("This statement has been closed.")); + } + } + + @Override + public void closeStatements() { + closeStatementsCalls[0]++; + } + }; + + JdbcOutputFormat<SeaTunnelRow, JdbcBatchStatementExecutor<SeaTunnelRow>> outputFormat = + new JdbcOutputFormat<>(provider, buildConnectionConfig(), () -> executor); + outputFormat.open(); + outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"})); + + outputFormat.flush(); + + Assertions.assertEquals(2, prepareStatementsCalls[0]); + Assertions.assertEquals(2, executeBatchCalls[0]); + Assertions.assertEquals(1, closeStatementsCalls[0]); + Mockito.verify(provider).reestablishConnection(); + } + + @Test + public void testBufferedRowsAreReplayedOnceWhenSecondRowBindHitsClosedStatement() + throws Exception { + JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class); + Connection connection = Mockito.mock(Connection.class); + Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection); + Mockito.when(provider.getConnection()).thenReturn(connection); + Mockito.when(provider.reestablishConnection()).thenReturn(connection); + + List<String> events = new ArrayList<>(); + List<List<Integer>> executedBatches = new ArrayList<>(); + List<Integer> currentBatch = new ArrayList<>(); + boolean[] failedOnce = new boolean[1]; + JdbcBatchStatementExecutor<SeaTunnelRow> delegate = + new JdbcBatchStatementExecutor<SeaTunnelRow>() { + @Override + public void prepareStatements(Connection ignored) { + currentBatch.clear(); + } + + @Override + public void addToBatch(SeaTunnelRow record) { + int id = (Integer) record.getField(0); + events.add("bind:" + id); + if (!failedOnce[0] && id == 2) { + failedOnce[0] = true; + throw new JdbcConnectorException( + JdbcConnectorErrorCode.DATA_TYPE_CAST_FAILED, + "error field:id", + new SQLException("This statement has been closed.")); + } + currentBatch.add(id); + } + + @Override + public void executeBatch() { + executedBatches.add(new ArrayList<>(currentBatch)); + currentBatch.clear(); + } + + @Override + public void closeStatements() { + events.add("close"); + } + }; + BufferedBatchStatementExecutor buffered = + new BufferedBatchStatementExecutor(delegate, Function.identity()); + + JdbcOutputFormat<SeaTunnelRow, BufferedBatchStatementExecutor> outputFormat = + new JdbcOutputFormat<>(provider, buildConnectionConfig(), () -> buffered); + outputFormat.open(); + outputFormat.writeRecord(new SeaTunnelRow(new Object[] {1})); + outputFormat.writeRecord(new SeaTunnelRow(new Object[] {2})); + + outputFormat.flush(); + + Assertions.assertEquals(Collections.singletonList(Arrays.asList(1, 2)), executedBatches); + Assertions.assertEquals( + Arrays.asList("bind:1", "bind:2", "close", "bind:1", "bind:2"), events); + Mockito.verify(provider).reestablishConnection(); + } + + @Test + public void testFlushShouldNotReconnectWhenBindingFailsWithADataError() throws Exception { + JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class); + Connection connection = Mockito.mock(Connection.class); + Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection); + Mockito.when(provider.getConnection()).thenReturn(connection); + + int[] executeBatchCalls = new int[1]; + JdbcBatchStatementExecutor<SeaTunnelRow> executor = + new JdbcBatchStatementExecutor<SeaTunnelRow>() { + @Override + public void prepareStatements(Connection ignored) {} + + @Override + public void addToBatch(SeaTunnelRow record) {} + + @Override + public void executeBatch() { + executeBatchCalls[0]++; + throw new JdbcConnectorException( + JdbcConnectorErrorCode.DATA_TYPE_CAST_FAILED, + "error field:id", + new SQLException("invalid integer", "22003")); + } + + @Override + public void closeStatements() {} + }; + + JdbcOutputFormat<SeaTunnelRow, JdbcBatchStatementExecutor<SeaTunnelRow>> outputFormat = + new JdbcOutputFormat<>(provider, buildConnectionConfig(), () -> executor); + outputFormat.open(); + outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"})); + + JdbcConnectorException failure = + Assertions.assertThrows(JdbcConnectorException.class, outputFormat::flush); + + Assertions.assertEquals("22003", ((SQLException) failure.getCause()).getSQLState()); + Assertions.assertEquals(1, executeBatchCalls[0]); + Mockito.verify(provider, Mockito.never()).reestablishConnection(); + } + @Test public void testFlushRetryShouldReconnectWhenSqlServerStatementHandleIsNotExecuting() throws Exception { diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutorTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutorTest.java index 1160013357..24eedfd7fc 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutorTest.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutorTest.java @@ -18,6 +18,8 @@ package org.apache.seatunnel.connectors.seatunnel.jdbc.internal.executor; import org.apache.seatunnel.api.table.type.SeaTunnelRow; +import org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorErrorCode; +import org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorException; import org.junit.jupiter.api.Test; @@ -104,4 +106,37 @@ public class BufferedBatchStatementExecutorTest extends BufferExecutorTest { assertEquals(1, executedBatches.size()); assertEquals(Collections.singletonList(validRow), executedBatches.get(0)); } + + @Test + void closeAfterClosedStatementBindDoesNotBindTheBufferAgain() throws SQLException { + List<SeaTunnelRow> boundRows = new ArrayList<>(); + JdbcBatchStatementExecutor<SeaTunnelRow> delegate = + new JdbcBatchStatementExecutor<SeaTunnelRow>() { + @Override + public void prepareStatements(Connection connection) {} + + @Override + public void addToBatch(SeaTunnelRow record) { + boundRows.add(record); + throw new JdbcConnectorException( + JdbcConnectorErrorCode.DATA_TYPE_CAST_FAILED, + "error field:id", + new SQLException("This statement has been closed.")); + } + + @Override + public void executeBatch() {} + + @Override + public void closeStatements() {} + }; + BufferedBatchStatementExecutor executor = + new BufferedBatchStatementExecutor(delegate, Function.identity()); + executor.addToBatch(new SeaTunnelRow(new Object[] {1})); + + assertThrows(JdbcConnectorException.class, executor::executeBatch); + executor.closeStatements(); + + assertEquals(1, boundRows.size()); + } } diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcMultiTableReconnectTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcMultiTableReconnectTest.java index d8cf760ab6..bd801227e2 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcMultiTableReconnectTest.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcMultiTableReconnectTest.java @@ -123,6 +123,33 @@ class JdbcMultiTableReconnectTest { assertTrue(activeDialect.generatedUpsertSqlCalls > 0); } + /** + * The second buffered row's bind reports a closed statement. Reconnect must insert both rows + * once; a second bind during statement cleanup would insert them again. + */ + @Test + void retainedRowsAreInsertedOnceWhenStatementClosesDuringBind() throws Exception { + String jdbcUrl = "jdbc:sqlite:" + tempDir.resolve("closed-statement-bind.db"); + createTables(jdbcUrl); + + Map<String, Object> insertOnly = new HashMap<>(); + insertOnly.put("primary_keys", Collections.emptyList()); + insertOnly.put("batch_size", 10); + TrackingSqliteDialect dialect = new TrackingSqliteDialect(); + TestJdbcSinkWriter writer = createWriter(jdbcUrl, "active_table", dialect, insertOnly); + try { + writer.write(insertRow(ACTIVE_TABLE_ID, 1, "first")); + writer.write(insertRow(ACTIVE_TABLE_ID, 2, "second")); + dialect.getConnectionProvider().failNextBindAfter(2); + writer.prepareCommit(1L); + } finally { + writer.close(); + } + + assertEquals(Arrays.asList("1:first", "2:second"), queryRows(jdbcUrl, "active_table")); + assertEquals(1, dialect.getConnectionProvider().reestablishConnectionCalls); + } + /** * With checkpointing, a manual-commit writer keeps every batch-size flush in one open * transaction until prepareCommit. If a later batch loses the connection, that transaction and @@ -1128,8 +1155,12 @@ class JdbcMultiTableReconnectTest { options.put("driver", "org.sqlite.JDBC"); options.put("database", "main"); options.put("table", table); - options.put("generate_sink_sql", true); - options.put("primary_keys", Arrays.asList("id")); + if (!options.containsKey("generate_sink_sql")) { + options.put("generate_sink_sql", true); + } + if (!options.containsKey("primary_keys")) { + options.put("primary_keys", Arrays.asList("id")); + } options.put("max_retries", 1); ReadonlyConfig config = ReadonlyConfig.fromMap(options); JdbcSinkConfig sinkConfig = JdbcSinkConfig.of(config); @@ -1226,6 +1257,8 @@ class JdbcMultiTableReconnectTest { private Connection connection; private Connection delegate; private boolean failNextBatch; + private int bindsBeforeClosedStatement = -1; + private int completedBinds; private SQLException nextBatchFailure; // Keyed by the first statement parameter (the id) of the failing rows. private final Map<String, SQLException> rowFailures = new HashMap<>(); @@ -1242,6 +1275,12 @@ class JdbcMultiTableReconnectTest { failNextBatch = true; } + /** Fails the next parameter bind after {@code successfulBinds} have completed. */ + private void failNextBindAfter(int successfulBinds) { + bindsBeforeClosedStatement = successfulBinds; + completedBinds = 0; + } + /** Fails the next batch with {@code failure} and keeps the connection open. */ private void failNextBatchWith(SQLException failure) { nextBatchFailure = failure; @@ -1393,6 +1432,17 @@ class JdbcMultiTableReconnectTest { owner.close(); throw new SQLException("connection dropped", "08S01"); } + if (bindsBeforeClosedStatement >= 0 + && method.getName().startsWith("set") + && args != null + && args.length >= 2 + && args[0] instanceof Integer) { + if (completedBinds >= bindsBeforeClosedStatement) { + bindsBeforeClosedStatement = -1; + throw new SQLException("This statement has been closed."); + } + completedBinds++; + } if ("executeBatch".equals(method.getName()) && nextBatchFailure != null) { SQLException failure = nextBatchFailure;
