This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] 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 76889c9671e [Fix][Connector-V2][Databend] Apply the latest CDC event 
of a key in the merge (#13161)
76889c9671e is described below

commit 76889c9671ef983a4fc990655e447596d6dd1d94
Author: Sepuri Sai Krishna <[email protected]>
AuthorDate: Mon Nov 30 13:26:46 2026 +0000

    [Fix][Connector-V2][Databend] Apply the latest CDC event of a key in the 
merge (#13161)
---
 docs/en/connectors/sink/Databend.md                |   5 +
 .../introduction/concepts/incompatible-changes.md  |  17 +++
 docs/zh/connectors/sink/Databend.md                |   3 +
 .../introduction/concepts/incompatible-changes.md  |  11 ++
 .../sink/DatabendSinkAggregatedCommitter.java      |   2 +-
 .../databend/sink/DatabendSinkWriter.java          |  48 ++++++-
 .../databend/sink/DatabendSinkWriterTest.java      | 151 ++++++++++++++++++++-
 .../e2e/connector/databend/DatabendCDCSinkIT.java  |  86 +++++++++++-
 .../fake_to_databend_cdc_existing_key.conf         |  70 ++++++++++
 .../databend/fake_to_databend_cdc_one_merge.conf   |  95 +++++++++++++
 10 files changed, 480 insertions(+), 8 deletions(-)

diff --git a/docs/en/connectors/sink/Databend.md 
b/docs/en/connectors/sink/Databend.md
index fb89474aaad..18404bd6198 100644
--- a/docs/en/connectors/sink/Databend.md
+++ b/docs/en/connectors/sink/Databend.md
@@ -188,6 +188,11 @@ sink {
 
 Set `conflict_key` to the primary-key column used to merge update/delete 
events. Set
 `enable_delete = true` only when DELETE events should remove rows from 
Databend.
+An INSERT event for a key that already exists updates that row, the same as an 
update event.
+When events of one key from one writer reach the same merge, the latest wins. 
The order comes from
+the writer's clock in the local time zone of the JVM, so in the hour that 
repeats when daylight
+saving time ends an older event can still win; a time zone without daylight 
saving time, such as
+UTC, avoids this.
 If `conflict_key` is not configured, the sink writes normal insert-style 
batches.
 
 The following end-to-end example feeds CDC row kinds (`INSERT`, 
`UPDATE_BEFORE`,
diff --git a/docs/en/introduction/concepts/incompatible-changes.md 
b/docs/en/introduction/concepts/incompatible-changes.md
index 4189becf6c7..d4faa72b6d3 100644
--- a/docs/en/introduction/concepts/incompatible-changes.md
+++ b/docs/en/introduction/concepts/incompatible-changes.md
@@ -115,6 +115,23 @@ for connector requirements and the restrictions on shared 
physical destinations.
   - **Impact**: A job that reads a Databend `DECIMAL` column now emits decimal 
values. A sink table that SeaTunnel creates through `schema_save_mode` gets a 
decimal column instead of a string column, and a transform or sink that 
expected a string now receives a decimal.
   - **Migration Guide**: No configuration change is needed. If a downstream 
step needs text, convert the column explicitly, for example `CAST(price AS 
STRING)` in the SQL transform. A sink table that an earlier run already created 
with a string column keeps that type.
 
+### Databend Sink: the latest CDC event of a key is applied
+
+- **Affected jobs**: Databend sinks in CDC mode (`conflict_key` set).
+- **Behavior change**: an INSERT event for a key that already exists in the 
target table was ignored,
+  so the row kept its old values. It now overwrites the row, the same as an 
update event. This
+  includes a re-insert after a DELETE that `enable_delete = false` dropped, 
and a snapshot that runs
+  again over an existing table. When events of one key from one writer reach 
the same merge, the latest
+  now wins. Before, events within the same millisecond could leave an older 
value in the row, or
+  remove a row that had been inserted again. The merge orders the events by 
`add_time`, which the
+  writer takes from its clock in the local time zone of the JVM. When daylight 
saving time ends, the
+  local times of one hour repeat, so in that hour an event can still lose to 
an older event of the
+  same key in the same merge. This limit is not new; a JVM time zone without 
daylight saving time,
+  such as UTC, does not have it. Events of one key from different writers are 
ordered only by the
+  clocks of their workers.
+- **Migration**: no configuration change is required. Jobs that relied on an 
INSERT leaving an
+  existing row unchanged need to filter those events before the sink.
+
 ### JDBC source: a nullable key column is no longer chosen as the split key
 
 - **Behavior change: the automatic split key selection skips nullable columns**
diff --git a/docs/zh/connectors/sink/Databend.md 
b/docs/zh/connectors/sink/Databend.md
index a1d58e28b92..1b029c1e8fe 100644
--- a/docs/zh/connectors/sink/Databend.md
+++ b/docs/zh/connectors/sink/Databend.md
@@ -182,6 +182,9 @@ sink {
 
 `conflict_key` 用来指定合并更新/删除事件的主键列。只有当 DELETE 事件需要删除
 Databend 中的数据时,才需要设置 `enable_delete = true`。
+如果主键已存在,INSERT 事件会像更新事件一样更新该行。
+当同一 writer 中同一主键的多个事件进入同一次合并时,最新事件生效。该顺序来自 writer 按 JVM 本地时区读取的时钟,
+因此在夏令时结束、本地时间重复的那一小时内,较早的事件仍可能生效;使用没有夏令时的时区(例如 UTC)可以避免这一点。
 如果不配置 `conflict_key`,sink 会按普通批量插入方式写入。
 
 下面的端到端示例将 CDC 行类型(`INSERT`、`UPDATE_BEFORE`、`UPDATE_AFTER`、`DELETE`)
diff --git a/docs/zh/introduction/concepts/incompatible-changes.md 
b/docs/zh/introduction/concepts/incompatible-changes.md
index e0c3d79f771..7931429c956 100644
--- a/docs/zh/introduction/concepts/incompatible-changes.md
+++ b/docs/zh/introduction/concepts/incompatible-changes.md
@@ -91,6 +91,17 @@
   - **影响**:读取 Databend `DECIMAL` 列的作业现在输出 decimal 值。SeaTunnel 通过 
`schema_save_mode` 创建的 Sink 表会得到 decimal 列而不是字符串列,原本期望字符串的 Transform 或 Sink 
现在会收到 decimal。
   - **迁移指南**:无需修改配置。如果下游步骤需要文本,请显式转换该列,例如在 SQL Transform 中使用 `CAST(price AS 
STRING)`。早期运行中已创建为字符串列的 Sink 表会保留原有类型。
 
+### Databend Sink:应用主键最新的 CDC 事件
+
+- **影响范围**:CDC 模式(设置了 `conflict_key`)下的 Databend Sink。
+- **行为变化**:以前如果 INSERT 事件的主键已存在于目标表,该事件会被忽略,目标行保留旧值。现在它会像更新事件一样覆盖该行。
+  这也包括 `enable_delete = false` 丢弃 DELETE 后的重新插入,以及在已有表上重新运行快照。当同一 writer 
中同一主键的多个事件进入
+  同一次合并时,现在最新事件生效;以前同一毫秒内的事件可能使该行保留旧值,或删除已重新插入的行。合并按 `add_time` 对事件排序,
+  writer 从自己的时钟按 JVM 的本地时区取得该值。夏令时结束时,本地时间会重复一个小时,因此在这一小时内,同一主键的事件仍可能
+  在同一次合并中输给更早的事件。这个限制并非新引入;使用没有夏令时的 JVM 时区(例如 UTC)时不存在该问题。来自不同 writer 的
+  同一主键事件只按各自 worker 的时钟排序。
+- **迁移方式**:无需修改配置。依赖 INSERT 不改变已有行的作业,需要在 Sink 之前过滤这些事件。
+
 ### JDBC Source:可空的键列不再被选为分片键
 
 - **行为变化:自动选择分片键时跳过可空列**
diff --git 
a/seatunnel-connectors-v2/connector-databend/src/main/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkAggregatedCommitter.java
 
b/seatunnel-connectors-v2/connector-databend/src/main/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkAggregatedCommitter.java
index 206419da662..2725a00adfa 100644
--- 
a/seatunnel-connectors-v2/connector-databend/src/main/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkAggregatedCommitter.java
+++ 
b/seatunnel-connectors-v2/connector-databend/src/main/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkAggregatedCommitter.java
@@ -208,7 +208,7 @@ public class DatabendSinkAggregatedCommitter
                 .append(databendSinkConfig.getConflictKey())
                 .append(" ");
 
-        sql.append("WHEN MATCHED AND b.action = 'update' THEN UPDATE * ");
+        sql.append("WHEN MATCHED AND b.action IN ('insert', 'update') THEN 
UPDATE * ");
 
         if (databendSinkConfig.isEnableDelete()) {
             sql.append("WHEN MATCHED AND b.action = 'delete' THEN DELETE ");
diff --git 
a/seatunnel-connectors-v2/connector-databend/src/main/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkWriter.java
 
b/seatunnel-connectors-v2/connector-databend/src/main/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkWriter.java
index 2b8a29d48c5..8e865d2cae2 100644
--- 
a/seatunnel-connectors-v2/connector-databend/src/main/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkWriter.java
+++ 
b/seatunnel-connectors-v2/connector-databend/src/main/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkWriter.java
@@ -47,6 +47,7 @@ import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
+import java.sql.Timestamp;
 import java.time.LocalDateTime;
 import java.time.LocalTime;
 import java.time.format.DateTimeFormatter;
@@ -58,6 +59,7 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
+import java.util.function.LongSupplier;
 import java.util.stream.Collectors;
 
 @Slf4j
@@ -99,6 +101,20 @@ public class DatabendSinkWriter
     private String conflictKey;
     private boolean enableDelete;
 
+    /**
+     * The add_time of the last CDC row of this writer, in microseconds since 
the epoch. The merge
+     * keeps the row with the latest add_time for each key, so {@link 
#nextAddTime()} makes each row
+     * of this writer later than the one before, also within one millisecond 
and when the clock
+     * steps back. The value lives only in this writer instance: it is not 
checkpointed, a new or
+     * restored writer starts again from the clock, and rows of different 
writers are ordered only
+     * by their clocks. add_time is written in the local time of the JVM, so 
when daylight saving
+     * time ends the written times repeat an hour.
+     */
+    private long lastAddTimeMicros = 0L;
+
+    /** The clock that add_time is taken from, in milliseconds since the 
epoch. Tests replace it. */
+    LongSupplier clockMillis = System::currentTimeMillis;
+
     public DatabendSinkWriter(
             Context context,
             Connection connection,
@@ -273,7 +289,7 @@ public class DatabendSinkWriter
 
         sql.append("ON a.").append(conflictKey).append(" = 
b.").append(conflictKey).append(" ");
 
-        sql.append("WHEN MATCHED AND b.action = 'update' THEN UPDATE * ");
+        sql.append("WHEN MATCHED AND b.action IN ('insert', 'update') THEN 
UPDATE * ");
 
         if (enableDelete) {
             sql.append("WHEN MATCHED AND b.action = 'delete' THEN DELETE ");
@@ -422,12 +438,40 @@ public class DatabendSinkWriter
         cdcPreparedStatement.setString(1, conflictKeyValue);
         cdcPreparedStatement.setString(2, targetTableName);
         cdcPreparedStatement.setString(3, jsonData);
-        cdcPreparedStatement.setTimestamp(4, 
java.sql.Timestamp.valueOf(LocalDateTime.now()));
+        cdcPreparedStatement.setString(4, nextAddTime());
         cdcPreparedStatement.setString(5, action);
 
         cdcPreparedStatement.addBatch();
     }
 
+    /**
+     * Returns the add_time of the next CDC row. The merge keeps the row with 
the latest add_time
+     * for each key, so rows of a burst must not share a value or an older 
event can win. It is a
+     * string because the driver's setTimestamp drops everything below 
milliseconds.
+     *
+     * @return a timestamp, in microseconds, later than the one returned by 
the previous call
+     */
+    String nextAddTime() {
+        lastAddTimeMicros = nextAddTimeMicros(clockMillis.getAsLong(), 
lastAddTimeMicros);
+        return formatAddTime(lastAddTimeMicros);
+    }
+
+    /**
+     * Returns the add_time, in microseconds, that follows {@code lastMicros} 
when the clock reads
+     * {@code nowMillis}: the clock time, or one microsecond after {@code 
lastMicros} if the clock
+     * is not past it.
+     */
+    static long nextAddTimeMicros(long nowMillis, long lastMicros) {
+        return Math.max(nowMillis * 1000, lastMicros + 1);
+    }
+
+    /** Returns {@code micros} as a timestamp in the local time of the JVM, 
with microseconds. */
+    static String formatAddTime(long micros) {
+        Timestamp addTime = new Timestamp(micros / 1000);
+        addTime.setNanos((int) (micros % 1_000_000) * 1000);
+        return addTime.toString();
+    }
+
     private void processTraditionalRow(SeaTunnelRow row) throws SQLException {
         // Ensure preparedStatement is initialized
         if (preparedStatement == null) {
diff --git 
a/seatunnel-connectors-v2/connector-databend/src/test/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkWriterTest.java
 
b/seatunnel-connectors-v2/connector-databend/src/test/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkWriterTest.java
index 3680ea3798b..e71bf72a210 100644
--- 
a/seatunnel-connectors-v2/connector-databend/src/test/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkWriterTest.java
+++ 
b/seatunnel-connectors-v2/connector-databend/src/test/java/org/apache/seatunnel/connectors/seatunnel/databend/sink/DatabendSinkWriterTest.java
@@ -30,6 +30,7 @@ import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
 import 
org.apache.seatunnel.connectors.seatunnel.databend.config.DatabendSinkConfig;
 
 import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
 
 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
@@ -38,20 +39,27 @@ import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.Statement;
+import java.sql.Timestamp;
 import java.time.LocalDate;
 import java.time.LocalDateTime;
 import java.time.LocalTime;
+import java.util.Arrays;
 import java.util.Collections;
+import java.util.TimeZone;
+import java.util.function.Supplier;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.startsWith;
 import static org.mockito.Mockito.doCallRealMethod;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
@@ -95,7 +103,7 @@ public class DatabendSinkWriterTest {
                         + "FROM test_db.cdc_stream "
                         + "QUALIFY ROW_NUMBER() OVER(PARTITION BY id ORDER BY 
add_time DESC) = 1) b "
                         + "ON a.id = b.id "
-                        + "WHEN MATCHED AND b.action = 'update' THEN UPDATE * "
+                        + "WHEN MATCHED AND b.action IN ('insert', 'update') 
THEN UPDATE * "
                         + "WHEN MATCHED AND b.action = 'delete' THEN DELETE "
                         + "WHEN NOT MATCHED AND b.action!='delete' THEN INSERT 
*";
 
@@ -140,7 +148,7 @@ public class DatabendSinkWriterTest {
                         + "FROM test_db.cdc_stream "
                         + "QUALIFY ROW_NUMBER() OVER(PARTITION BY id ORDER BY 
add_time DESC) = 1) b "
                         + "ON a.id = b.id "
-                        + "WHEN MATCHED AND b.action = 'update' THEN UPDATE * "
+                        + "WHEN MATCHED AND b.action IN ('insert', 'update') 
THEN UPDATE * "
                         + "WHEN NOT MATCHED AND b.action!='delete' THEN INSERT 
*";
 
         assertEquals(expectedSql, mergeSql);
@@ -293,6 +301,9 @@ public class DatabendSinkWriterTest {
         
org.junit.jupiter.api.Assertions.assertTrue(mergeSql.contains("raw_data:id as 
id"));
         
org.junit.jupiter.api.Assertions.assertTrue(mergeSql.contains("raw_data:name as 
name"));
         
org.junit.jupiter.api.Assertions.assertFalse(mergeSql.contains("raw_data:score 
as score"));
+        org.junit.jupiter.api.Assertions.assertTrue(
+                mergeSql.contains(
+                        "WHEN MATCHED AND b.action IN ('insert', 'update') 
THEN UPDATE * "));
     }
 
     @Test
@@ -346,6 +357,132 @@ public class DatabendSinkWriterTest {
         verify(preparedStatement).addBatch();
     }
 
+    /** 2023-11-14 22:13:20 UTC. */
+    private static final long CLOCK_MILLIS = 1_700_000_000_000L;
+
+    @Test
+    public void testEventsOfABurstGetDistinctIncreasingAddTimes() {
+        long last = 0L;
+        for (int i = 0; i < 10000; i++) {
+            long next = DatabendSinkWriter.nextAddTimeMicros(CLOCK_MILLIS, 
last);
+            org.junit.jupiter.api.Assertions.assertTrue(next > last);
+            last = next;
+        }
+        // Microsecond steps keep a burst close to the clock: millisecond 
steps would be 10 s ahead.
+        assertEquals(CLOCK_MILLIS * 1000 + 9999, last);
+    }
+
+    @Test
+    public void testAddTimeKeepsIncreasingWhenTheClockStepsBack() {
+        long last = DatabendSinkWriter.nextAddTimeMicros(CLOCK_MILLIS, 0L);
+
+        assertEquals(last + 1, 
DatabendSinkWriter.nextAddTimeMicros(CLOCK_MILLIS - 1000, last));
+        assertEquals(
+                (CLOCK_MILLIS + 5) * 1000,
+                DatabendSinkWriter.nextAddTimeMicros(CLOCK_MILLIS + 5, last + 
1));
+    }
+
+    @Test
+    public void testAddTimeIsWrittenInTheLocalTimeOfTheJvmWithMicroseconds() {
+        long micros = CLOCK_MILLIS * 1000 + 123_456;
+
+        assertEquals(
+                "2023-11-14 22:13:20.123456",
+                inTimeZone("UTC", () -> 
DatabendSinkWriter.formatAddTime(micros)));
+        assertEquals(
+                "2023-11-15 06:13:20.123456",
+                inTimeZone("Asia/Shanghai", () -> 
DatabendSinkWriter.formatAddTime(micros)));
+    }
+
+    /**
+     * add_time is local time, so when daylight saving time ends the written 
times repeat an hour:
+     * one second later is written as almost an hour earlier. The field 
comment of lastAddTimeMicros
+     * states this limit.
+     */
+    @Test
+    public void testAddTimeRepeatsAnHourWhenDaylightSavingTimeEnds() {
+        // 2026-11-01 05:59:59 UTC is 01:59:59 EDT, one second later is 
01:00:00 EST.
+        long beforeMicros = 1_793_512_799_000_000L;
+        long afterMicros = beforeMicros + 1_000_000;
+
+        assertEquals(
+                "2026-11-01 01:59:59.0",
+                inTimeZone(
+                        "America/New_York", () -> 
DatabendSinkWriter.formatAddTime(beforeMicros)));
+        assertEquals(
+                "2026-11-01 01:00:00.0",
+                inTimeZone(
+                        "America/New_York", () -> 
DatabendSinkWriter.formatAddTime(afterMicros)));
+    }
+
+    /**
+     * Goes through write() and processCdcRow() to the add_time parameter of 
the raw table insert:
+     * it is bound with setString, keeps its microseconds, and increases 
within one millisecond. The
+     * driver's setTimestamp would drop everything below milliseconds.
+     */
+    @Test
+    public void 
testWriteBindsTheAddTimeOfEachCdcRowAsAStringWithMicroseconds() throws 
Exception {
+        Connection connection = mock(Connection.class);
+        PreparedStatement cdcStatement = mock(PreparedStatement.class);
+        when(connection.prepareStatement(startsWith("INSERT INTO 
test_db.raw_table")))
+                .thenReturn(cdcStatement);
+        DatabendSinkWriter sinkWriter = cdcWriter(connection);
+        // Every row arrives in the same millisecond.
+        sinkWriter.clockMillis = () -> CLOCK_MILLIS + 123;
+
+        inTimeZone(
+                "UTC",
+                () -> {
+                    for (int id = 1; id <= 3; id++) {
+                        sinkWriter.write(new SeaTunnelRow(new Object[] {id, 
"name" + id}));
+                    }
+                    return null;
+                });
+
+        ArgumentCaptor<String> addTimes = 
ArgumentCaptor.forClass(String.class);
+        verify(cdcStatement, times(3)).setString(eq(4), addTimes.capture());
+        verify(cdcStatement, never()).setTimestamp(eq(4), any());
+        verify(cdcStatement, never()).setTimestamp(eq(4), any(), any());
+        assertEquals(
+                Arrays.asList(
+                        "2023-11-14 22:13:20.123",
+                        "2023-11-14 22:13:20.123001",
+                        "2023-11-14 22:13:20.123002"),
+                addTimes.getAllValues());
+        for (int i = 1; i < addTimes.getAllValues().size(); i++) {
+            Timestamp previous = 
Timestamp.valueOf(addTimes.getAllValues().get(i - 1));
+            Timestamp current = 
Timestamp.valueOf(addTimes.getAllValues().get(i));
+            assertTrue(current.after(previous), 
addTimes.getAllValues().toString());
+        }
+    }
+
+    /** A real writer in CDC mode, with the raw table insert prepared on 
{@code connection}. */
+    private static DatabendSinkWriter cdcWriter(Connection connection) {
+        DatabendSinkConfig config = mock(DatabendSinkConfig.class);
+        when(config.isCdcMode()).thenReturn(true);
+        when(config.getConflictKey()).thenReturn("id");
+        CatalogTable catalogTable = mock(CatalogTable.class);
+        when(catalogTable.getSeaTunnelRowType())
+                .thenReturn(
+                        new SeaTunnelRowType(
+                                new String[] {"id", "name"},
+                                new 
org.apache.seatunnel.api.table.type.SeaTunnelDataType[] {
+                                    BasicType.INT_TYPE, BasicType.STRING_TYPE
+                                }));
+        return new DatabendSinkWriter(
+                mock(SinkWriter.Context.class),
+                connection,
+                catalogTable,
+                config,
+                null,
+                "test_db",
+                "target_table",
+                "raw_table",
+                "cdc_stream",
+                10,
+                30);
+    }
+
     /**
      * Goes through write() of a real writer in traditional mode to the insert 
statement it
      * prepared. databend-jdbc's setObject throws "Unsupported object type" 
for a LocalDateTime, and
@@ -419,6 +556,16 @@ public class DatabendSinkWriterTest {
                 30);
     }
 
+    private static String inTimeZone(String zone, Supplier<String> action) {
+        TimeZone previous = TimeZone.getDefault();
+        TimeZone.setDefault(TimeZone.getTimeZone(zone));
+        try {
+            return action.get();
+        } finally {
+            TimeZone.setDefault(previous);
+        }
+    }
+
     private DatabendSinkWriter mockCdcWriter(Statement statement) throws 
Exception {
         Connection connection = mock(Connection.class);
         when(connection.createStatement()).thenReturn(statement);
diff --git 
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-databend-e2e/src/test/java/org/apache/seatunnel/e2e/connector/databend/DatabendCDCSinkIT.java
 
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-databend-e2e/src/test/java/org/apache/seatunnel/e2e/connector/databend/DatabendCDCSinkIT.java
index 72c66871ae6..aa344dddce5 100644
--- 
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-databend-e2e/src/test/java/org/apache/seatunnel/e2e/connector/databend/DatabendCDCSinkIT.java
+++ 
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-databend-e2e/src/test/java/org/apache/seatunnel/e2e/connector/databend/DatabendCDCSinkIT.java
@@ -64,6 +64,10 @@ public class DatabendCDCSinkIT extends TestSuiteBase 
implements TestResource {
     private static final int PORT = 8000;
     private static final String DATABASE = "default";
     private static final String DATABEND_CDC_JOB_CONFIG = 
"/databend/fake_to_databend_cdc.conf";
+    private static final String DATABEND_CDC_EXISTING_KEY_JOB_CONFIG =
+            "/databend/fake_to_databend_cdc_existing_key.conf";
+    private static final String DATABEND_CDC_ONE_MERGE_JOB_CONFIG =
+            "/databend/fake_to_databend_cdc_one_merge.conf";
     private static final int MAX_JOB_SUBMIT_ATTEMPTS = 2;
     private static final int JOB_SUBMIT_RETRY_INTERVAL_SECONDS = 10;
     private DatabendContainer container;
@@ -78,7 +82,7 @@ public class DatabendCDCSinkIT extends TestSuiteBase 
implements TestResource {
                             + " while sink_table remains empty")
     public void testDatabendSinkCDC(TestContainer container) throws Exception {
         // Run the CDC test job
-        Container.ExecResult execResult = executeDatabendCdcJob(container);
+        Container.ExecResult execResult = executeDatabendCdcJob(container, 
DATABEND_CDC_JOB_CONFIG);
         Assertions.assertEquals(0, execResult.getExitCode(), 
execResult.getStderr());
 
         Awaitility.await()
@@ -171,10 +175,86 @@ public class DatabendCDCSinkIT extends TestSuiteBase 
implements TestResource {
         clearSinkTable();
     }
 
-    private Container.ExecResult executeDatabendCdcJob(TestContainer 
container) throws Exception {
+    @TestTemplate
+    @DisabledOnContainer(
+            value = {TestContainerId.FLINK_1_15},
+            disabledReason =
+                    "Flaky on GitHub-hosted Flink 1.15.3: the CDC job can exit 
successfully"
+                            + " while sink_table remains empty")
+    public void testInsertOverwritesAnExistingKey(TestContainer container) 
throws Exception {
+        try (Statement statement = connection.createStatement()) {
+            statement.execute(
+                    "INSERT INTO sink_table VALUES"
+                            + " (5, 'old', 'old', 1, 1.0), (6, 'old', 'old', 
1, 1.0)");
+        }
+        try {
+            Container.ExecResult execResult =
+                    executeDatabendCdcJob(container, 
DATABEND_CDC_EXISTING_KEY_JOB_CONFIG);
+            Assertions.assertEquals(0, execResult.getExitCode(), 
execResult.getStderr());
+
+            Awaitility.await()
+                    .atMost(180, TimeUnit.SECONDS)
+                    .pollInterval(1, TimeUnit.SECONDS)
+                    .ignoreExceptions()
+                    .untilAsserted(
+                            () ->
+                                    Assertions.assertEquals(
+                                            Arrays.asList("5:new", "6:new", 
"7:new"),
+                                            readIdsAndNames()));
+        } finally {
+            clearSinkTable();
+        }
+    }
+
+    @TestTemplate
+    @DisabledOnContainer(
+            value = {TestContainerId.FLINK_1_15},
+            disabledReason =
+                    "Flaky on GitHub-hosted Flink 1.15.3: the CDC job can exit 
successfully"
+                            + " while sink_table remains empty")
+    public void testLatestEventOfAKeyWinsInOneMerge(TestContainer container) 
throws Exception {
+        StringBuilder values = new StringBuilder();
+        List<String> expected = new ArrayList<>();
+        for (int id = 10; id < 30; id++) {
+            values.append(id == 10 ? "" : ", ")
+                    .append(String.format("(%d, 'old', 'old', 1, 1.0)", id));
+            expected.add(id + ":new");
+        }
+        try (Statement statement = connection.createStatement()) {
+            statement.execute("INSERT INTO sink_table VALUES " + values);
+        }
+        try {
+            Container.ExecResult execResult =
+                    executeDatabendCdcJob(container, 
DATABEND_CDC_ONE_MERGE_JOB_CONFIG);
+            Assertions.assertEquals(0, execResult.getExitCode(), 
execResult.getStderr());
+
+            Awaitility.await()
+                    .atMost(180, TimeUnit.SECONDS)
+                    .pollInterval(1, TimeUnit.SECONDS)
+                    .ignoreExceptions()
+                    .untilAsserted(() -> Assertions.assertEquals(expected, 
readIdsAndNames()));
+        } finally {
+            clearSinkTable();
+        }
+    }
+
+    private List<String> readIdsAndNames() throws SQLException {
+        List<String> rows = new ArrayList<>();
+        try (Statement statement = connection.createStatement();
+                ResultSet resultSet =
+                        statement.executeQuery("SELECT id, name FROM 
sink_table ORDER BY id")) {
+            while (resultSet.next()) {
+                rows.add(resultSet.getInt("id") + ":" + 
resultSet.getString("name"));
+            }
+        }
+        return rows;
+    }
+
+    private Container.ExecResult executeDatabendCdcJob(TestContainer 
container, String jobConfig)
+            throws Exception {
         Container.ExecResult execResult = null;
         for (int attempt = 1; attempt <= MAX_JOB_SUBMIT_ATTEMPTS; attempt++) {
-            execResult = container.executeJob(DATABEND_CDC_JOB_CONFIG);
+            execResult = container.executeJob(jobConfig);
             if (execResult.getExitCode() == 0 || 
!isFlinkResourceNotReady(execResult)) {
                 return execResult;
             }
diff --git 
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-databend-e2e/src/test/resources/databend/fake_to_databend_cdc_existing_key.conf
 
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-databend-e2e/src/test/resources/databend/fake_to_databend_cdc_existing_key.conf
new file mode 100644
index 00000000000..3904daffa02
--- /dev/null
+++ 
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-databend-e2e/src/test/resources/databend/fake_to_databend_cdc_existing_key.conf
@@ -0,0 +1,70 @@
+#
+# 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 {
+  execution.parallelism = 1
+  job.mode = "BATCH"
+  checkpoint.interval = 1000
+}
+
+source {
+  FakeSource {
+    schema = {
+      fields {
+        id = "int"
+        name = "string"
+        position = "string"
+        age = "int"
+        score = "double"
+      }
+    }
+
+    # sink_table already holds ids 5 and 6. With enable_delete left at its 
default, the DELETE is
+    # dropped, so the row it should have removed is still there for the INSERT 
that follows.
+    rows = [
+      {
+        kind = INSERT
+        fields = [5, "new", "new", 2, 2.0]
+      },
+      {
+        kind = DELETE
+        fields = [6, "old", "old", 1, 1.0]
+      },
+      {
+        kind = INSERT
+        fields = [6, "new", "new", 2, 2.0]
+      },
+      {
+        kind = INSERT
+        fields = [7, "new", "new", 2, 2.0]
+      }
+    ]
+  }
+}
+
+sink {
+  Databend {
+    url = "jdbc:databend://databend:8000/default?ssl=false"
+    username = "root"
+    password = ""
+    database = "default"
+    table = "sink_table"
+
+    batch_size = 1
+    conflict_key = "id"
+  }
+}
diff --git 
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-databend-e2e/src/test/resources/databend/fake_to_databend_cdc_one_merge.conf
 
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-databend-e2e/src/test/resources/databend/fake_to_databend_cdc_one_merge.conf
new file mode 100644
index 00000000000..662c5d7b4d5
--- /dev/null
+++ 
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-databend-e2e/src/test/resources/databend/fake_to_databend_cdc_one_merge.conf
@@ -0,0 +1,95 @@
+#
+# 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 {
+  execution.parallelism = 1
+  job.mode = "BATCH"
+  checkpoint.interval = 1000
+}
+
+source {
+  FakeSource {
+    schema = {
+      fields {
+        id = "int"
+        name = "string"
+        position = "string"
+        age = "int"
+        score = "double"
+      }
+    }
+
+    # sink_table already holds these ids. batch_size below keeps every event 
in one merge, where the
+    # event that came last for each key has to win.
+    rows = [
+      { kind = DELETE, fields = [10, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [10, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [11, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [11, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [12, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [12, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [13, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [13, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [14, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [14, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [15, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [15, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [16, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [16, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [17, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [17, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [18, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [18, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [19, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [19, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [20, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [20, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [21, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [21, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [22, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [22, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [23, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [23, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [24, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [24, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [25, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [25, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [26, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [26, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [27, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [27, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [28, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [28, "new", "new", 2, 2.0] },
+      { kind = DELETE, fields = [29, "old", "old", 1, 1.0] },
+      { kind = INSERT, fields = [29, "new", "new", 2, 2.0] },
+    ]
+  }
+}
+
+sink {
+  Databend {
+    url = "jdbc:databend://databend:8000/default?ssl=false"
+    username = "root"
+    password = ""
+    database = "default"
+    table = "sink_table"
+
+    batch_size = 1000
+    conflict_key = "id"
+    enable_delete = true
+  }
+}

Reply via email to