You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by li...@apache.org on 2026/04/10 09:04:23 UTC
(seatunnel) branch dev updated: [Feature][JDBC] Add batch_interval_ms option for JDBC Sink time-based flushing (#10609)
This is an automated email from the ASF dual-hosted git repository.
lidongdai pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
The following commit(s) were added to refs/heads/dev by this push:
new 4a8298df8b [Feature][JDBC] Add batch_interval_ms option for JDBC Sink time-based flushing (#10609)
4a8298df8b is described below
commit 4a8298df8b2fa9ada9ba723ae1efcb47eac01d25
Author: zhiwei.niu <ni...@126.com>
AuthorDate: Fri Apr 10 17:04:17 2026 +0800
[Feature][JDBC] Add batch_interval_ms option for JDBC Sink time-based flushing (#10609)
Co-authored-by: zhiwei.niu <zh...@advancegroup.com>
Co-authored-by: Doyeon Kim <13...@users.noreply.github.com>
---
docs/en/connectors/sink/Jdbc.md | 5 +
docs/zh/connectors/sink/Jdbc.md | 5 +
.../jdbc/config/JdbcConnectionConfig.java | 20 ++
.../seatunnel/jdbc/config/JdbcSinkOptions.java | 9 +
.../seatunnel/jdbc/internal/JdbcOutputFormat.java | 69 +++--
.../jdbc/sink/AbstractJdbcSinkWriter.java | 1 +
.../seatunnel/jdbc/sink/JdbcSinkFactory.java | 1 +
.../jdbc/config/JdbcConnectionConfigTest.java | 78 ++++++
.../seatunnel/jdbc/JdbcSinkBatchIntervalIT.java | 291 +++++++++++++++++++++
.../jdbc_postgres_sink_batch_interval.conf | 51 ++++
...gres_sink_batch_interval_with_batch_size_1.conf | 51 ++++
.../resources/jdbc_postgres_sink_batch_size.conf | 51 ++++
12 files changed, 603 insertions(+), 29 deletions(-)
diff --git a/docs/en/connectors/sink/Jdbc.md b/docs/en/connectors/sink/Jdbc.md
index b3dd2c900f..5cc522ffa7 100644
--- a/docs/en/connectors/sink/Jdbc.md
+++ b/docs/en/connectors/sink/Jdbc.md
@@ -46,6 +46,7 @@ support `Xa transactions`. You can set `is_exactly_once=true` to enable it.
| connection_check_timeout_sec | Int | No | 30 |
| max_retries | Int | No | 0 |
| batch_size | Int | No | 1000 |
+| batch_interval_ms | Long | No | 0 |
| is_exactly_once | Boolean | No | false |
| generate_sink_sql | Boolean | No | false |
| xa_data_source_class_name | String | No | - |
@@ -157,6 +158,10 @@ The number of retries to submit failed (executeBatch)
For batch writing, when the number of buffered records reaches the number of `batch_size` or the time reaches `checkpoint.interval`
, the data will be flushed into the database
+### batch_interval_ms [long]
+
+The flush interval in milliseconds. When set to a value greater than 0, if the elapsed time since the last flush exceeds this interval, the next `writeRecord` call will trigger a synchronous flush, even if `batch_size` has not been reached. Default value is `0` (disabled). This is a **write-triggered** time check, not a background timer — if no new records arrive (idle partition), no time-based flush occurs; buffered data is flushed at the next `prepareCommit` (checkpoint) or `close`. No [...]
+
### is_exactly_once [boolean]
Whether to enable exactly-once semantics, which will use Xa transactions. If on, you need to
diff --git a/docs/zh/connectors/sink/Jdbc.md b/docs/zh/connectors/sink/Jdbc.md
index 754780e138..ba56eb4565 100644
--- a/docs/zh/connectors/sink/Jdbc.md
+++ b/docs/zh/connectors/sink/Jdbc.md
@@ -44,6 +44,7 @@ import ChangeLog from '../changelog/connector-jdbc.md';
| connection_check_timeout_sec | Int | 否 | 30 |
| max_retries | Int | 否 | 0 |
| batch_size | Int | 否 | 1000 |
+| batch_interval_ms | Long | 否 | 0 |
| is_exactly_once | Boolean | 否 | false |
| generate_sink_sql | Boolean | 否 | false |
| xa_data_source_class_name | String | 否 | - |
@@ -155,6 +156,10 @@ Tip: 如果目标数据库有 SCHEMA 的概念,则表参数必须写成 `xxx.x
对于批量写入,当缓冲的记录数达到 `batch_size` 数量或者时间达到 `checkpoint.interval` 时,数据将被刷新到数据库中
+### batch_interval_ms [long]
+
+刷新间隔(毫秒)。当设置值大于 0 时,若距上次 flush 的时间超过该间隔,下一次 `writeRecord` 调用将同步触发 flush,即使尚未达到 `batch_size`。默认值为 `0`(禁用)。此为**写入触发**的时间检查,而非后台定时器——若无新记录到达(空闲分区),不会触发基于时间的 flush;缓冲数据将在下一次 `prepareCommit`(checkpoint)或 `close` 时刷出。注意:当 `auto_commit = false` 时,已 flush 的数据在下次 commit(如 checkpoint)之前对其他事务不可见。
+
### is_exactly_once [boolean]
是否启用通过XA事务实现的精确一次语义。开启,你还需要设置 `xa_data_source_class_name`
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcConnectionConfig.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcConnectionConfig.java
index 1c2ed5830f..a539e6a7c4 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcConnectionConfig.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcConnectionConfig.java
@@ -44,6 +44,10 @@ public class JdbcConnectionConfig implements Serializable {
private int batchSize = JdbcSinkOptions.BATCH_SIZE.defaultValue();
+ private long batchIntervalMs = JdbcSinkOptions.BATCH_INTERVAL_MS.defaultValue();
+
+ private boolean isExactlyOnce = JdbcSinkOptions.IS_EXACTLY_ONCE.defaultValue();
+
private String xaDataSourceClassName;
private boolean decimalTypeNarrowing = JdbcCommonOptions.DECIMAL_TYPE_NARROWING.defaultValue();
@@ -86,7 +90,9 @@ public class JdbcConnectionConfig implements Serializable {
builder.socketTimeoutMs(config.get(JdbcCommonOptions.SOCKET_TIMEOUT_MS));
builder.connectTimeoutMs(config.get(JdbcCommonOptions.CONNECT_TIMEOUT_MS));
builder.batchSize(config.get(JdbcSinkOptions.BATCH_SIZE));
+ builder.batchIntervalMs(config.get(JdbcSinkOptions.BATCH_INTERVAL_MS));
builder.handleBlobAsString(config.get(JdbcCommonOptions.HANDLE_BLOB_AS_STRING));
+ builder.isExactlyOnce(config.get(JdbcSinkOptions.IS_EXACTLY_ONCE));
if (config.get(JdbcSinkOptions.IS_EXACTLY_ONCE)) {
builder.xaDataSourceClassName(config.get(JdbcSinkOptions.XA_DATA_SOURCE_CLASS_NAME));
builder.maxCommitAttempts(config.get(JdbcSinkOptions.MAX_COMMIT_ATTEMPTS));
@@ -142,6 +148,8 @@ public class JdbcConnectionConfig implements Serializable {
private String query;
private boolean autoCommit = JdbcSinkOptions.AUTO_COMMIT.defaultValue();
private int batchSize = JdbcSinkOptions.BATCH_SIZE.defaultValue();
+ private long batchIntervalMs = JdbcSinkOptions.BATCH_INTERVAL_MS.defaultValue();
+ private boolean isExactlyOnce = JdbcSinkOptions.IS_EXACTLY_ONCE.defaultValue();
private String xaDataSourceClassName;
private boolean decimalTypeNarrowing =
JdbcCommonOptions.DECIMAL_TYPE_NARROWING.defaultValue();
@@ -223,11 +231,21 @@ public class JdbcConnectionConfig implements Serializable {
return this;
}
+ public Builder batchIntervalMs(long batchIntervalMs) {
+ this.batchIntervalMs = batchIntervalMs;
+ return this;
+ }
+
public Builder xaDataSourceClassName(String xaDataSourceClassName) {
this.xaDataSourceClassName = xaDataSourceClassName;
return this;
}
+ public Builder isExactlyOnce(boolean isExactlyOnce) {
+ this.isExactlyOnce = isExactlyOnce;
+ return this;
+ }
+
public Builder maxCommitAttempts(int maxCommitAttempts) {
this.maxCommitAttempts = maxCommitAttempts;
return this;
@@ -301,6 +319,7 @@ public class JdbcConnectionConfig implements Serializable {
public JdbcConnectionConfig build() {
JdbcConnectionConfig jdbcConnectionConfig = new JdbcConnectionConfig();
jdbcConnectionConfig.batchSize = this.batchSize;
+ jdbcConnectionConfig.batchIntervalMs = this.batchIntervalMs;
jdbcConnectionConfig.driverName = this.driverName;
jdbcConnectionConfig.compatibleMode = this.compatibleMode;
jdbcConnectionConfig.maxRetries = this.maxRetries;
@@ -313,6 +332,7 @@ public class JdbcConnectionConfig implements Serializable {
jdbcConnectionConfig.socketTimeoutMs = this.socketTimeoutMs;
jdbcConnectionConfig.connectTimeoutMs = this.connectTimeoutMs;
jdbcConnectionConfig.maxCommitAttempts = this.maxCommitAttempts;
+ jdbcConnectionConfig.isExactlyOnce = this.isExactlyOnce;
jdbcConnectionConfig.xaDataSourceClassName = this.xaDataSourceClassName;
jdbcConnectionConfig.decimalTypeNarrowing = this.decimalTypeNarrowing;
jdbcConnectionConfig.intTypeNarrowing = this.intTypeNarrowing;
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkOptions.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkOptions.java
index eacd23c599..78a0f7d543 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkOptions.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSinkOptions.java
@@ -84,6 +84,15 @@ public class JdbcSinkOptions extends JdbcCommonOptions {
public static final Option<Integer> BATCH_SIZE =
Options.key("batch_size").intType().defaultValue(1000).withDescription("batch size");
+ public static final Option<Long> BATCH_INTERVAL_MS =
+ Options.key("batch_interval_ms")
+ .longType()
+ .defaultValue(0L)
+ .withDescription(
+ "Write-triggered flush interval (ms). "
+ + "0 = disabled (default). "
+ + "When > 0, each writeRecord checks elapsed time and flushes synchronously if exceeded.");
+
public static final Option<Integer> TRANSACTION_TIMEOUT_SEC =
Options.key("transaction_timeout_sec")
.intType()
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 7c184c9f8d..d13462f07b 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
@@ -18,7 +18,6 @@
package org.apache.seatunnel.connectors.seatunnel.jdbc.internal;
import org.apache.seatunnel.common.exception.CommonErrorCodeDeprecated;
-import org.apache.seatunnel.common.utils.ExceptionUtils;
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;
@@ -51,6 +50,7 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
private transient int batchCount = 0;
private transient volatile boolean closed = false;
private transient volatile Exception flushException;
+ private transient long lastFlushTimeMs;
public JdbcOutputFormat(
JdbcConnectionProvider connectionProvider,
@@ -72,6 +72,7 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
e);
}
jdbcStatementExecutor = createAndOpenStatementExecutor(statementExecutorFactory);
+ lastFlushTimeMs = System.currentTimeMillis();
}
private E createAndOpenStatementExecutor(StatementExecutorFactory<E> statementExecutorFactory) {
@@ -101,8 +102,7 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
try {
addToBatch(record);
batchCount++;
- if (jdbcConnectionConfig.getBatchSize() > 0
- && batchCount >= jdbcConnectionConfig.getBatchSize()) {
+ if (batchCount > 0 && (isOverMaxBatchSizeLimit() || isOverMaxBatchIntervalLimit())) {
flush();
}
} catch (Exception e) {
@@ -118,13 +118,6 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
}
public synchronized void flush() throws IOException {
- if (flushException != null) {
- LOG.warn(
- String.format(
- "An exception occurred during the previous flush process %s, skipping this flush",
- ExceptionUtils.getMessage(flushException)));
- return;
- }
if (batchCount == 0) {
LOG.debug("No data to flush.");
return;
@@ -135,6 +128,7 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
try {
attemptFlush();
batchCount = 0;
+ lastFlushTimeMs = System.currentTimeMillis();
break;
} catch (SQLException e) {
LOG.error("JDBC executeBatch error, retry times = {}", i, e);
@@ -176,30 +170,47 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
public synchronized void close() {
if (!closed) {
closed = true;
+ flushBufferedRecords();
+ closeStatements();
+ }
+ connectionProvider.closeConnection();
+ checkFlushException();
+ }
- if (batchCount > 0) {
- try {
- flush();
- } catch (Exception e) {
- LOG.warn("Writing records to JDBC failed.", e);
- flushException =
- new JdbcConnectorException(
- CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
- "Writing records to JDBC failed.",
- e);
- }
+ private void flushBufferedRecords() {
+ if (batchCount > 0) {
+ try {
+ flush();
+ } catch (Exception e) {
+ LOG.warn("Writing records to JDBC failed.", e);
+ flushException =
+ new JdbcConnectorException(
+ CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
+ "Writing records to JDBC failed.",
+ e);
}
+ }
+ }
- try {
- if (jdbcStatementExecutor != null) {
- jdbcStatementExecutor.closeStatements();
- }
- } catch (SQLException | JdbcConnectorException e) {
- LOG.warn("Close JDBC writer failed.", e);
+ public void closeStatements() {
+ try {
+ if (jdbcStatementExecutor != null) {
+ jdbcStatementExecutor.closeStatements();
}
+ } catch (SQLException | JdbcConnectorException e) {
+ LOG.warn("Close JDBC writer failed.", e);
}
- connectionProvider.closeConnection();
- checkFlushException();
+ }
+
+ private boolean isOverMaxBatchSizeLimit() {
+ return jdbcConnectionConfig.getBatchSize() > 0
+ && batchCount >= jdbcConnectionConfig.getBatchSize();
+ }
+
+ private boolean isOverMaxBatchIntervalLimit() {
+ long batchIntervalMs = jdbcConnectionConfig.getBatchIntervalMs();
+ return batchIntervalMs > 0
+ && (System.currentTimeMillis() - lastFlushTimeMs) >= batchIntervalMs;
}
public void updateExecutor(boolean reconnect) throws SQLException, ClassNotFoundException {
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java
index 521b65ed94..406262c304 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java
@@ -75,6 +75,7 @@ public abstract class AbstractJdbcSinkWriter<ResourceT>
throw new JdbcConnectorException(
JdbcConnectorErrorCode.REFRESH_PHYSICAL_TABLESCHEMA_BY_SCHEMA_CHANGE_EVENT, e);
}
+
this.outputFormat =
new JdbcOutputFormatBuilder(
dialect,
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java
index 78a57cb6a9..b8fa4938c3 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java
@@ -219,6 +219,7 @@ public class JdbcSinkFactory implements TableSinkFactory {
JdbcSinkOptions.PASSWORD,
JdbcSinkOptions.CONNECTION_CHECK_TIMEOUT_SEC,
JdbcSinkOptions.BATCH_SIZE,
+ JdbcSinkOptions.BATCH_INTERVAL_MS,
JdbcSinkOptions.IS_EXACTLY_ONCE,
JdbcSinkOptions.GENERATE_SINK_SQL,
JdbcSinkOptions.AUTO_COMMIT,
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcConnectionConfigTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcConnectionConfigTest.java
new file mode 100644
index 0000000000..b9e5161b65
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcConnectionConfigTest.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.jdbc.config;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class JdbcConnectionConfigTest {
+
+ @Test
+ public void testBatchIntervalMsDefaultValue() {
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put("url", "jdbc:mysql://localhost:3306/test");
+ configMap.put("driver", "com.mysql.cj.jdbc.Driver");
+
+ JdbcConnectionConfig config = JdbcConnectionConfig.of(ReadonlyConfig.fromMap(configMap));
+
+ Assertions.assertEquals(0L, config.getBatchIntervalMs());
+ }
+
+ @Test
+ public void testBatchIntervalMsExplicitValue() {
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put("url", "jdbc:mysql://localhost:3306/test");
+ configMap.put("driver", "com.mysql.cj.jdbc.Driver");
+ configMap.put("batch_interval_ms", 1000L);
+
+ JdbcConnectionConfig config = JdbcConnectionConfig.of(ReadonlyConfig.fromMap(configMap));
+
+ Assertions.assertEquals(1000L, config.getBatchIntervalMs());
+ }
+
+ @Test
+ public void testBatchIntervalMsWithBatchSizeOne() {
+ Map<String, Object> configMap = new HashMap<>();
+ configMap.put("url", "jdbc:mysql://localhost:3306/test");
+ configMap.put("driver", "com.mysql.cj.jdbc.Driver");
+ configMap.put("batch_size", 1);
+ configMap.put("batch_interval_ms", 1000L);
+
+ JdbcConnectionConfig config = JdbcConnectionConfig.of(ReadonlyConfig.fromMap(configMap));
+
+ Assertions.assertEquals(1000L, config.getBatchIntervalMs());
+ Assertions.assertEquals(1, config.getBatchSize());
+ }
+
+ @Test
+ public void testBatchIntervalMsBuilder() {
+ JdbcConnectionConfig config =
+ JdbcConnectionConfig.builder()
+ .url("jdbc:mysql://localhost:3306/test")
+ .driverName("com.mysql.cj.jdbc.Driver")
+ .batchIntervalMs(2000L)
+ .build();
+
+ Assertions.assertEquals(2000L, config.getBatchIntervalMs());
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcSinkBatchIntervalIT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcSinkBatchIntervalIT.java
new file mode 100644
index 0000000000..8f081e62cf
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcSinkBatchIntervalIT.java
@@ -0,0 +1,291 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.jdbc;
+
+import org.apache.seatunnel.e2e.common.TestResource;
+import org.apache.seatunnel.e2e.common.TestSuiteBase;
+import org.apache.seatunnel.e2e.common.container.ContainerExtendedFactory;
+import org.apache.seatunnel.e2e.common.container.TestContainer;
+import org.apache.seatunnel.e2e.common.junit.TestContainerExtension;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.TestTemplate;
+import org.testcontainers.containers.Container;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.lifecycle.Startables;
+import org.testcontainers.utility.DockerImageName;
+import org.testcontainers.utility.DockerLoggerFactory;
+
+import lombok.extern.slf4j.Slf4j;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Stream;
+
+import static org.awaitility.Awaitility.given;
+
+@Slf4j
+public class JdbcSinkBatchIntervalIT extends TestSuiteBase implements TestResource {
+
+ private static final String PG_IMAGE = "postgres:14-alpine";
+ private static final String PG_DRIVER_JAR =
+ "https://repo1.maven.org/maven2/org/postgresql/postgresql/42.3.3/postgresql-42.3.3.jar";
+ private PostgreSQLContainer<?> postgreSQLContainer;
+
+ @TestContainerExtension
+ private final ContainerExtendedFactory extendedFactory =
+ container -> {
+ Container.ExecResult extraCommands =
+ container.execInContainer(
+ "bash",
+ "-c",
+ "mkdir -p /tmp/seatunnel/plugins/Jdbc/lib && cd /tmp/seatunnel/plugins/Jdbc/lib && curl -O "
+ + PG_DRIVER_JAR);
+ Assertions.assertEquals(0, extraCommands.getExitCode());
+ };
+
+ @BeforeAll
+ @Override
+ public void startUp() throws Exception {
+ postgreSQLContainer =
+ new PostgreSQLContainer<>(DockerImageName.parse(PG_IMAGE))
+ .withNetwork(TestSuiteBase.NETWORK)
+ .withNetworkAliases("postgresql")
+ .withLogConsumer(
+ new Slf4jLogConsumer(DockerLoggerFactory.getLogger(PG_IMAGE)));
+ Startables.deepStart(Stream.of(postgreSQLContainer)).join();
+ log.info("PostgreSQL container started");
+ Class.forName(postgreSQLContainer.getDriverClassName());
+ given().ignoreExceptions()
+ .await()
+ .atLeast(100, TimeUnit.MILLISECONDS)
+ .pollInterval(500, TimeUnit.MILLISECONDS)
+ .atMost(2, TimeUnit.MINUTES)
+ .untilAsserted(this::initializeJdbcTable);
+ }
+
+ @TestTemplate
+ public void testBatchIntervalFlush(TestContainer container) throws SQLException {
+ AtomicBoolean jobFinished = new AtomicBoolean(false);
+
+ CompletableFuture<Container.ExecResult> jobFuture =
+ CompletableFuture.supplyAsync(
+ () -> {
+ try {
+ return container.executeJob(
+ "/jdbc_postgres_sink_batch_interval.conf");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ } finally {
+ jobFinished.set(true);
+ }
+ });
+
+ given().ignoreExceptions()
+ .await()
+ .atMost(30, TimeUnit.SECONDS)
+ .pollInterval(2, TimeUnit.SECONDS)
+ .untilAsserted(
+ () -> {
+ Assertions.assertFalse(
+ jobFinished.get(),
+ "Job should still be running when timer flush is detected - "
+ + "if the job already finished, the flush may have come from close()");
+ int rowCount = getSinkRowCount("sink_batch_interval_timer");
+ log.info(
+ "Polling sink_batch_interval_timer during job execution: {} rows, jobFinished={}",
+ rowCount,
+ jobFinished.get());
+ Assertions.assertTrue(
+ rowCount > 0,
+ "Timer flush should have written rows to the database "
+ + "BEFORE job completion (batch_size=100000 is never reached)");
+ });
+
+ Container.ExecResult result = jobFuture.join();
+ Assertions.assertEquals(0, result.getExitCode(), result.getStderr());
+ truncateTable("sink_batch_interval_timer");
+ }
+
+ @TestTemplate
+ public void testBatchSizeFlush(TestContainer container) throws SQLException {
+ AtomicBoolean jobFinished = new AtomicBoolean(false);
+
+ CompletableFuture<Container.ExecResult> jobFuture =
+ CompletableFuture.supplyAsync(
+ () -> {
+ try {
+ return container.executeJob("/jdbc_postgres_sink_batch_size.conf");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ } finally {
+ jobFinished.set(true);
+ }
+ });
+
+ given().ignoreExceptions()
+ .await()
+ .atMost(30, TimeUnit.SECONDS)
+ .pollInterval(2, TimeUnit.SECONDS)
+ .untilAsserted(
+ () -> {
+ Assertions.assertFalse(
+ jobFinished.get(),
+ "Job should still be running when batch_size flush is detected");
+ int rowCount = getSinkRowCount("sink_batch_size_only");
+ log.info(
+ "Polling sink_batch_size_only during job execution: {} rows, jobFinished={}",
+ rowCount,
+ jobFinished.get());
+ Assertions.assertTrue(
+ rowCount > 0,
+ "batch_size flush should have written rows to the database "
+ + "BEFORE job completion");
+ Assertions.assertEquals(
+ 0,
+ rowCount % 5,
+ "Row count should be a multiple of batch_size(5), "
+ + "actual: "
+ + rowCount);
+ });
+
+ Container.ExecResult result = jobFuture.join();
+ Assertions.assertEquals(0, result.getExitCode(), result.getStderr());
+ truncateTable("sink_batch_size_only");
+ }
+
+ @TestTemplate
+ public void testBatchIntervalWithBatchSize1(TestContainer container)
+ throws SQLException, InterruptedException {
+ AtomicBoolean jobFinished = new AtomicBoolean(false);
+
+ CompletableFuture<Container.ExecResult> jobFuture =
+ CompletableFuture.supplyAsync(
+ () -> {
+ try {
+ return container.executeJob(
+ "/jdbc_postgres_sink_batch_interval_with_batch_size_1.conf");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ } finally {
+ jobFinished.set(true);
+ }
+ });
+
+ given().ignoreExceptions()
+ .await()
+ .atMost(30, TimeUnit.SECONDS)
+ .pollInterval(2, TimeUnit.SECONDS)
+ .untilAsserted(
+ () -> {
+ Assertions.assertFalse(
+ jobFinished.get(),
+ "Job should still be running when batch_size=1 flush is detected");
+ int rowCount = getSinkRowCount("sink_batch_interval_bs1");
+ log.info(
+ "Polling sink_batch_interval_bs1 during job execution: {} rows, jobFinished={}",
+ rowCount,
+ jobFinished.get());
+ Assertions.assertTrue(
+ rowCount > 0,
+ "batch_size=1 should flush each row immediately "
+ + "BEFORE job completion");
+ });
+
+ int firstCount = getSinkRowCount("sink_batch_interval_bs1");
+ Thread.sleep(5000);
+ Assertions.assertFalse(jobFinished.get(), "Job should still be running for second poll");
+ int secondCount = getSinkRowCount("sink_batch_interval_bs1");
+ log.info(
+ "batch_size=1 incremental check: firstCount={}, secondCount={}",
+ firstCount,
+ secondCount);
+ Assertions.assertTrue(
+ secondCount > firstCount,
+ "Row count should keep growing with batch_size=1 (per-row flush), "
+ + "firstCount="
+ + firstCount
+ + ", secondCount="
+ + secondCount);
+
+ Container.ExecResult result = jobFuture.join();
+ Assertions.assertEquals(0, result.getExitCode(), result.getStderr());
+ truncateTable("sink_batch_interval_bs1");
+ }
+
+ private int getSinkRowCount(String tableName) throws SQLException {
+ try (Connection connection = getJdbcConnection()) {
+ try (Statement statement = connection.createStatement();
+ ResultSet resultSet =
+ statement.executeQuery("SELECT count(*) FROM " + tableName)) {
+ Assertions.assertTrue(resultSet.next());
+ return resultSet.getInt(1);
+ }
+ }
+ }
+
+ private void truncateTable(String tableName) throws SQLException {
+ try (Connection connection = getJdbcConnection()) {
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("TRUNCATE TABLE " + tableName);
+ }
+ }
+ }
+
+ private Connection getJdbcConnection() throws SQLException {
+ return DriverManager.getConnection(
+ postgreSQLContainer.getJdbcUrl(),
+ postgreSQLContainer.getUsername(),
+ postgreSQLContainer.getPassword());
+ }
+
+ private static final String CREATE_TABLE_SQL =
+ "CREATE TABLE IF NOT EXISTS %s(\n"
+ + "pk_id BIGINT NOT NULL PRIMARY KEY,\n"
+ + "name VARCHAR(255),\n"
+ + "score INT\n"
+ + ")";
+
+ private void initializeJdbcTable() {
+ try (Connection connection = getJdbcConnection();
+ Statement statement = connection.createStatement()) {
+ statement.execute(String.format(CREATE_TABLE_SQL, "sink_batch_interval_timer"));
+ statement.execute(String.format(CREATE_TABLE_SQL, "sink_batch_size_only"));
+ statement.execute(String.format(CREATE_TABLE_SQL, "sink_batch_interval_bs1"));
+ } catch (SQLException e) {
+ throw new RuntimeException("Initializing PostgreSQL table failed!", e);
+ }
+ }
+
+ @AfterAll
+ @Override
+ public void tearDown() {
+ if (postgreSQLContainer != null) {
+ postgreSQLContainer.stop();
+ }
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/resources/jdbc_postgres_sink_batch_interval.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/resources/jdbc_postgres_sink_batch_interval.conf
new file mode 100644
index 0000000000..081ea2568f
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/resources/jdbc_postgres_sink_batch_interval.conf
@@ -0,0 +1,51 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+env {
+ parallelism = 1
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ row.num = 100
+ split.num = 10
+ split.read-interval = 3000
+ schema = {
+ fields {
+ pk_id = bigint
+ name = string
+ score = int
+ }
+ }
+ }
+}
+
+sink {
+ Jdbc {
+ driver = org.postgresql.Driver
+ url = "jdbc:postgresql://postgresql:5432/test?loggerLevel=OFF"
+ username = test
+ password = test
+ generate_sink_sql = true
+ database = test
+ table = public.sink_batch_interval_timer
+ primary_keys = ["pk_id"]
+ batch_size = 100000
+ batch_interval_ms = 2000
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/resources/jdbc_postgres_sink_batch_interval_with_batch_size_1.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/resources/jdbc_postgres_sink_batch_interval_with_batch_size_1.conf
new file mode 100644
index 0000000000..baa1a30709
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/resources/jdbc_postgres_sink_batch_interval_with_batch_size_1.conf
@@ -0,0 +1,51 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+env {
+ parallelism = 1
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ row.num = 50
+ split.num = 10
+ split.read-interval = 3000
+ schema = {
+ fields {
+ pk_id = bigint
+ name = string
+ score = int
+ }
+ }
+ }
+}
+
+sink {
+ Jdbc {
+ driver = org.postgresql.Driver
+ url = "jdbc:postgresql://postgresql:5432/test?loggerLevel=OFF"
+ username = test
+ password = test
+ generate_sink_sql = true
+ database = test
+ table = public.sink_batch_interval_bs1
+ primary_keys = ["pk_id"]
+ batch_size = 1
+ batch_interval_ms = 20000
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/resources/jdbc_postgres_sink_batch_size.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/resources/jdbc_postgres_sink_batch_size.conf
new file mode 100644
index 0000000000..d94a1d88d6
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/resources/jdbc_postgres_sink_batch_size.conf
@@ -0,0 +1,51 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+env {
+ parallelism = 1
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ row.num = 100
+ split.num = 10
+ split.read-interval = 3000
+ schema = {
+ fields {
+ pk_id = bigint
+ name = string
+ score = int
+ }
+ }
+ }
+}
+
+sink {
+ Jdbc {
+ driver = org.postgresql.Driver
+ url = "jdbc:postgresql://postgresql:5432/test?loggerLevel=OFF"
+ username = test
+ password = test
+ generate_sink_sql = true
+ database = test
+ table = public.sink_batch_size_only
+ primary_keys = ["pk_id"]
+ batch_size = 5
+ batch_interval_ms = 1000000
+ }
+}