This is an automated email from the ASF dual-hosted git repository.
tyrantlucifer pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/incubator-seatunnel.git
The following commit(s) were added to refs/heads/dev by this push:
new 67e602797 [Hotfix][Connector-v2][Clickhouse] Fix clickhouse write cdc
changelog update event (#3951)
67e602797 is described below
commit 67e6027970b282794d36813080817939c80b0259
Author: hailin0 <[email protected]>
AuthorDate: Wed Jan 18 10:31:25 2023 +0800
[Hotfix][Connector-v2][Clickhouse] Fix clickhouse write cdc changelog
update event (#3951)
---
release-note.md | 1 +
.../seatunnel/clickhouse/shard/ShardMetadata.java | 17 +-
.../clickhouse/sink/client/ClickhouseProxy.java | 4 +-
.../clickhouse/sink/client/ClickhouseSink.java | 2 +
.../sink/client/ClickhouseSinkWriter.java | 31 +
.../clickhouse/sink/client/ShardRouter.java | 4 +
.../executor/FieldNamedPreparedStatement.java | 668 +++++++++++++++++++++
.../JdbcBatchStatementExecutorBuilder.java | 46 +-
.../clickhouse/sink/client/executor/SqlUtils.java | 29 +-
.../clickhouse/sink/file/ClickhouseTable.java | 64 +-
.../connector-clickhouse-e2e/pom.xml | 6 +
.../clickhouse/ClickhouseSinkCDCChangelogIT.java | 193 ++++++
.../clickhouse_sink_cdc_changelog_case1.conf | 86 +++
.../clickhouse_sink_cdc_changelog_case2.conf | 87 +++
14 files changed, 1152 insertions(+), 86 deletions(-)
diff --git a/release-note.md b/release-note.md
index 07f4910a0..49dd47a0a 100644
--- a/release-note.md
+++ b/release-note.md
@@ -39,6 +39,7 @@
## Bug Fixes
### Connectors
- [ClickHouse File] Fix ClickhouseFile Committer Serializable Problems #3803
+- [ClickHouse] Fix clickhouse write cdc changelog update event #3951
### Zeta Engine
- [Checkpoint] Fix Checkpoint Continue Trigger After Job CANCELED #3808
diff --git
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/shard/ShardMetadata.java
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/shard/ShardMetadata.java
index 7a8e98624..25c88d7ab 100644
---
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/shard/ShardMetadata.java
+++
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/shard/ShardMetadata.java
@@ -32,6 +32,7 @@ public class ShardMetadata implements Serializable {
private String shardKey;
private String shardKeyType;
+ private String sortingKey;
private String database;
private String table;
private String tableEngine;
@@ -42,12 +43,26 @@ public class ShardMetadata implements Serializable {
public ShardMetadata(String shardKey,
String shardKeyType,
+ String sortingKey,
String database,
String table,
String tableEngine,
boolean splitMode,
Shard defaultShard) {
- this(shardKey, shardKeyType, database, table, tableEngine,
+ this(shardKey, shardKeyType, sortingKey, database, table, tableEngine,
splitMode, defaultShard, null, null);
}
+
+ public ShardMetadata(String shardKey,
+ String shardKeyType,
+ String database,
+ String table,
+ String tableEngine,
+ boolean splitMode,
+ Shard defaultShard,
+ String username,
+ String password) {
+ this(shardKey, shardKeyType, null, database, table, tableEngine,
+ splitMode, defaultShard, username, password);
+ }
}
diff --git
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseProxy.java
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseProxy.java
index def00f912..da4d401aa 100644
---
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseProxy.java
+++
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseProxy.java
@@ -167,7 +167,7 @@ public class ClickhouseProxy {
* @return clickhouse table info.
*/
public ClickhouseTable getClickhouseTable(String database, String table) {
- String sql = String.format("select
engine,create_table_query,engine_full,data_paths from system.tables where
database = '%s' and name = '%s'", database, table);
+ String sql = String.format("select
engine,create_table_query,engine_full,data_paths,sorting_key from system.tables
where database = '%s' and name = '%s'", database, table);
try (ClickHouseResponse response =
clickhouseRequest.query(sql).executeAndWait()) {
List<ClickHouseRecord> records =
response.stream().collect(Collectors.toList());
if (records.isEmpty()) {
@@ -178,6 +178,7 @@ public class ClickhouseProxy {
String createTableDDL = record.getValue(1).asString();
String engineFull = record.getValue(2).asString();
List<String> dataPaths =
record.getValue(3).asTuple().stream().map(Object::toString).collect(Collectors.toList());
+ String sortingKey = record.getValue(4).asString();
DistributedEngine distributedEngine = null;
if ("Distributed".equals(engine)) {
distributedEngine =
getClickhouseDistributedTable(clickhouseRequest, database, table);
@@ -191,6 +192,7 @@ public class ClickhouseProxy {
createTableDDL,
engineFull,
dataPaths,
+ sortingKey,
getClickhouseTableSchema(clickhouseRequest, table));
} catch (ClickHouseException e) {
throw new
ClickhouseConnectorException(SeaTunnelAPIErrorCode.TABLE_NOT_EXISTED, "Cannot
get clickhouse table", e);
diff --git
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseSink.java
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseSink.java
index c95b0112f..3ce5c1442 100644
---
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseSink.java
+++
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseSink.java
@@ -142,6 +142,7 @@ public class ClickhouseSink implements
SeaTunnelSink<SeaTunnelRow, ClickhouseSin
metadata = new ShardMetadata(
shardKey,
shardKeyType,
+ table.getSortingKey(),
config.getString(DATABASE.key()),
config.getString(TABLE.key()),
table.getEngine(),
@@ -151,6 +152,7 @@ public class ClickhouseSink implements
SeaTunnelSink<SeaTunnelRow, ClickhouseSin
metadata = new ShardMetadata(
shardKey,
shardKeyType,
+ table.getSortingKey(),
config.getString(DATABASE.key()),
config.getString(TABLE.key()),
table.getEngine(),
diff --git
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseSinkWriter.java
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseSinkWriter.java
index f1f7fa531..a7a21a362 100644
---
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseSinkWriter.java
+++
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ClickhouseSinkWriter.java
@@ -31,14 +31,18 @@ import
org.apache.seatunnel.connectors.seatunnel.clickhouse.state.ClickhouseSink
import org.apache.seatunnel.connectors.seatunnel.clickhouse.tool.IntHolder;
import com.clickhouse.jdbc.internal.ClickHouseConnectionImpl;
+import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
+import java.sql.ResultSet;
import java.sql.SQLException;
+import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
+import java.util.stream.Stream;
@Slf4j
public class ClickhouseSinkWriter implements SinkWriter<SeaTunnelRow,
CKCommitInfo, ClickhouseSinkState> {
@@ -129,13 +133,23 @@ public class ClickhouseSinkWriter implements
SinkWriter<SeaTunnelRow, CKCommitIn
ClickHouseConnectionImpl clickhouseConnection = new
ClickHouseConnectionImpl(s.getJdbcUrl(),
this.option.getProperties());
+ String[] orderByKeys = null;
+ if (!Strings.isNullOrEmpty(shardRouter.getSortingKey())) {
+ orderByKeys =
Stream.of(shardRouter.getSortingKey().split(","))
+ .map(key -> StringUtils.trim(key))
+ .toArray(value -> new String[value]);
+
+ }
JdbcBatchStatementExecutor jdbcBatchStatementExecutor = new
JdbcBatchStatementExecutorBuilder()
.setTable(shardRouter.getShardTable())
.setTableEngine(shardRouter.getShardTableEngine())
.setRowType(option.getSeaTunnelRowType())
.setPrimaryKeys(option.getPrimaryKeys())
+ .setOrderByKeys(orderByKeys)
.setClickhouseTableSchema(option.getTableSchema())
.setAllowExperimentalLightweightDelete(option.isAllowExperimentalLightweightDelete())
+ .setClickhouseServerEnableExperimentalLightweightDelete(
+
clickhouseServerEnableExperimentalLightweightDelete(clickhouseConnection))
.setSupportUpsert(option.isSupportUpsert())
.build();
jdbcBatchStatementExecutor.prepareStatements(clickhouseConnection);
@@ -149,4 +163,21 @@ public class ClickhouseSinkWriter implements
SinkWriter<SeaTunnelRow, CKCommitIn
});
return result;
}
+
+ private static boolean clickhouseServerEnableExperimentalLightweightDelete(
+ ClickHouseConnectionImpl clickhouseConnection) {
+ String configKey = "allow_experimental_lightweight_delete";
+ try (Statement stmt = clickhouseConnection.createStatement()) {
+ ResultSet resultSet = stmt.executeQuery("SHOW SETTINGS ILIKE '%" +
configKey + "%'");
+ while (resultSet.next()) {
+ String name = resultSet.getString("name");
+ if (name.equalsIgnoreCase(configKey)) {
+ return resultSet.getBoolean("value");
+ }
+ }
+ return false;
+ } catch (SQLException e) {
+ throw new
ClickhouseConnectorException(CommonErrorCode.SQL_OPERATION_FAILED, e);
+ }
+ }
}
diff --git
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ShardRouter.java
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ShardRouter.java
index b31fb15ae..3e167e37b 100644
---
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ShardRouter.java
+++
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/ShardRouter.java
@@ -24,6 +24,7 @@ import
org.apache.seatunnel.connectors.seatunnel.clickhouse.shard.ShardMetadata;
import
org.apache.seatunnel.connectors.seatunnel.clickhouse.sink.DistributedEngine;
import com.clickhouse.client.ClickHouseRequest;
+import lombok.Getter;
import net.jpountz.xxhash.XXHash64;
import net.jpountz.xxhash.XXHashFactory;
import org.apache.commons.lang3.StringUtils;
@@ -47,6 +48,8 @@ public class ShardRouter implements Serializable {
private final TreeMap<Integer, Shard> shards;
private final String shardKey;
private final String shardKeyType;
+ @Getter
+ private final String sortingKey;
private final boolean splitMode;
private static final XXHash64 HASH_INSTANCE =
XXHashFactory.fastestInstance().hash64();
@@ -56,6 +59,7 @@ public class ShardRouter implements Serializable {
this.shards = new TreeMap<>();
this.shardKey = shardMetadata.getShardKey();
this.shardKeyType = shardMetadata.getShardKeyType();
+ this.sortingKey = shardMetadata.getSortingKey();
this.splitMode = shardMetadata.isSplitMode();
this.table = shardMetadata.getTable();
this.tableEngine = shardMetadata.getTableEngine();
diff --git
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/executor/FieldNamedPreparedStatement.java
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/executor/FieldNamedPreparedStatement.java
new file mode 100644
index 000000000..be0359f4e
--- /dev/null
+++
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/executor/FieldNamedPreparedStatement.java
@@ -0,0 +1,668 @@
+/*
+ * 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.clickhouse.sink.client.executor;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import lombok.RequiredArgsConstructor;
+
+import java.io.InputStream;
+import java.io.Reader;
+import java.math.BigDecimal;
+import java.net.URL;
+import java.sql.Array;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.Connection;
+import java.sql.Date;
+import java.sql.NClob;
+import java.sql.ParameterMetaData;
+import java.sql.PreparedStatement;
+import java.sql.Ref;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.RowId;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.SQLXML;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@RequiredArgsConstructor
+public class FieldNamedPreparedStatement implements PreparedStatement {
+ private final PreparedStatement statement;
+ private final int[][] indexMapping;
+
+ @Override
+ public void setNull(int parameterIndex, int sqlType) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setNull(index, sqlType);
+ }
+ }
+
+ @Override
+ public void setBoolean(int parameterIndex, boolean x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setBoolean(index, x);
+ }
+ }
+
+ @Override
+ public void setByte(int parameterIndex, byte x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setByte(index, x);
+ }
+ }
+
+ @Override
+ public void setShort(int parameterIndex, short x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setShort(index, x);
+ }
+ }
+
+ @Override
+ public void setInt(int parameterIndex, int x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setInt(index, x);
+ }
+ }
+
+ @Override
+ public void setLong(int parameterIndex, long x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setLong(index, x);
+ }
+ }
+
+ @Override
+ public void setFloat(int parameterIndex, float x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setFloat(index, x);
+ }
+ }
+
+ @Override
+ public void setDouble(int parameterIndex, double x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setDouble(index, x);
+ }
+ }
+
+ @Override
+ public void setBigDecimal(int parameterIndex, BigDecimal x) throws
SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setBigDecimal(index, x);
+ }
+ }
+
+ @Override
+ public void setString(int parameterIndex, String x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setString(index, x);
+ }
+ }
+
+ @Override
+ public void setBytes(int parameterIndex, byte[] x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setBytes(index, x);
+ }
+ }
+
+ @Override
+ public void setDate(int parameterIndex, Date x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setDate(index, x);
+ }
+ }
+
+ @Override
+ public void setTime(int parameterIndex, Time x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setTime(index, x);
+ }
+ }
+
+ @Override
+ public void setTimestamp(int parameterIndex, Timestamp x) throws
SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setTimestamp(index, x);
+ }
+ }
+
+ @Override
+ public void setObject(int parameterIndex, Object x, int targetSqlType)
throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setObject(index, x, targetSqlType);
+ }
+ }
+
+ @Override
+ public void setObject(int parameterIndex, Object x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setObject(index, x);
+ }
+ }
+
+ @Override
+ public void setRef(int parameterIndex, Ref x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setRef(index, x);
+ }
+ }
+
+ @Override
+ public void setBlob(int parameterIndex, Blob x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setBlob(index, x);
+ }
+ }
+
+ @Override
+ public void setClob(int parameterIndex, Clob x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setClob(index, x);
+ }
+ }
+
+ @Override
+ public void setArray(int parameterIndex, Array x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setArray(index, x);
+ }
+ }
+
+ @Override
+ public void setDate(int parameterIndex, Date x, Calendar cal) throws
SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setDate(index, x, cal);
+ }
+ }
+
+ @Override
+ public void setTime(int parameterIndex, Time x, Calendar cal) throws
SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setTime(index, x, cal);
+ }
+ }
+
+ @Override
+ public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal)
throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setTimestamp(index, x, cal);
+ }
+ }
+
+ @Override
+ public void setNull(int parameterIndex, int sqlType, String typeName)
throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setNull(index, sqlType, typeName);
+ }
+ }
+
+ @Override
+ public void setURL(int parameterIndex, URL x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setURL(index, x);
+ }
+ }
+
+ @Override
+ public void setRowId(int parameterIndex, RowId x) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setRowId(index, x);
+ }
+ }
+
+ @Override
+ public void setNString(int parameterIndex, String value) throws
SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setNString(index, value);
+ }
+ }
+
+ @Override
+ public void setNClob(int parameterIndex, NClob value) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setNClob(index, value);
+ }
+ }
+
+ @Override
+ public void setNClob(int parameterIndex, Reader reader, long length)
throws SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws
SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setSQLXML(index, xmlObject);
+ }
+ }
+
+ @Override
+ public void setObject(int parameterIndex, Object x, int targetSqlType, int
scaleOrLength) throws SQLException {
+ for (int index : indexMapping[parameterIndex - 1]) {
+ statement.setObject(index, x, targetSqlType, scaleOrLength);
+ }
+ }
+
+ @Override
+ public void setAsciiStream(int parameterIndex, InputStream x, int length)
throws SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setUnicodeStream(int parameterIndex, InputStream x, int
length) throws SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setBinaryStream(int parameterIndex, InputStream x, int length)
throws SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setCharacterStream(int parameterIndex, Reader reader, int
length) throws SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setNCharacterStream(int parameterIndex, Reader value, long
length) throws SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setClob(int parameterIndex, Reader reader, long length) throws
SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setBlob(int parameterIndex, InputStream inputStream, long
length) throws SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setAsciiStream(int parameterIndex, InputStream x, long length)
throws SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setBinaryStream(int parameterIndex, InputStream x, long
length) throws SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setCharacterStream(int parameterIndex, Reader reader, long
length) throws SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setAsciiStream(int parameterIndex, InputStream x) throws
SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setBinaryStream(int parameterIndex, InputStream x) throws
SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setCharacterStream(int parameterIndex, Reader reader) throws
SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setNCharacterStream(int parameterIndex, Reader value) throws
SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setClob(int parameterIndex, Reader reader) throws SQLException
{
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setBlob(int parameterIndex, InputStream inputStream) throws
SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setNClob(int parameterIndex, Reader reader) throws
SQLException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean execute() throws SQLException {
+ return statement.execute();
+ }
+
+ @Override
+ public void addBatch() throws SQLException {
+ statement.addBatch();
+ }
+
+ @Override
+ public ResultSet executeQuery() throws SQLException {
+ return statement.executeQuery();
+ }
+
+ @Override
+ public int executeUpdate() throws SQLException {
+ return statement.executeUpdate();
+ }
+
+ @Override
+ public void clearParameters() throws SQLException {
+ statement.clearParameters();
+ }
+
+ @Override
+ public ResultSetMetaData getMetaData() throws SQLException {
+ return statement.getMetaData();
+ }
+
+ @Override
+ public ParameterMetaData getParameterMetaData() throws SQLException {
+ return statement.getParameterMetaData();
+ }
+
+ @Override
+ public ResultSet executeQuery(String sql) throws SQLException {
+ return statement.executeQuery(sql);
+ }
+
+ @Override
+ public int executeUpdate(String sql) throws SQLException {
+ return statement.executeUpdate(sql);
+ }
+
+ @Override
+ public void close() throws SQLException {
+ statement.close();
+ }
+
+ @Override
+ public int getMaxFieldSize() throws SQLException {
+ return statement.getMaxFieldSize();
+ }
+
+ @Override
+ public void setMaxFieldSize(int max) throws SQLException {
+ statement.setMaxFieldSize(max);
+ }
+
+ @Override
+ public int getMaxRows() throws SQLException {
+ return statement.getMaxRows();
+ }
+
+ @Override
+ public void setMaxRows(int max) throws SQLException {
+ statement.setMaxRows(max);
+ }
+
+ @Override
+ public void setEscapeProcessing(boolean enable) throws SQLException {
+ statement.setEscapeProcessing(enable);
+ }
+
+ @Override
+ public int getQueryTimeout() throws SQLException {
+ return statement.getQueryTimeout();
+ }
+
+ @Override
+ public void setQueryTimeout(int seconds) throws SQLException {
+ statement.setQueryTimeout(seconds);
+ }
+
+ @Override
+ public void cancel() throws SQLException {
+ statement.cancel();
+ }
+
+ @Override
+ public SQLWarning getWarnings() throws SQLException {
+ return statement.getWarnings();
+ }
+
+ @Override
+ public void clearWarnings() throws SQLException {
+ statement.clearWarnings();
+ }
+
+ @Override
+ public void setCursorName(String name) throws SQLException {
+ statement.setCursorName(name);
+ }
+
+ @Override
+ public boolean execute(String sql) throws SQLException {
+ return statement.execute(sql);
+ }
+
+ @Override
+ public ResultSet getResultSet() throws SQLException {
+ return statement.getResultSet();
+ }
+
+ @Override
+ public int getUpdateCount() throws SQLException {
+ return statement.getUpdateCount();
+ }
+
+ @Override
+ public boolean getMoreResults() throws SQLException {
+ return statement.getMoreResults();
+ }
+
+ @Override
+ public void setFetchDirection(int direction) throws SQLException {
+ statement.setFetchDirection(direction);
+ }
+
+ @Override
+ public int getFetchDirection() throws SQLException {
+ return statement.getFetchDirection();
+ }
+
+ @Override
+ public void setFetchSize(int rows) throws SQLException {
+ statement.setFetchSize(rows);
+ }
+
+ @Override
+ public int getFetchSize() throws SQLException {
+ return statement.getFetchSize();
+ }
+
+ @Override
+ public int getResultSetConcurrency() throws SQLException {
+ return statement.getResultSetConcurrency();
+ }
+
+ @Override
+ public int getResultSetType() throws SQLException {
+ return statement.getResultSetType();
+ }
+
+ @Override
+ public void addBatch(String sql) throws SQLException {
+ statement.addBatch(sql);
+ }
+
+ @Override
+ public void clearBatch() throws SQLException {
+ statement.clearBatch();
+ }
+
+ @Override
+ public int[] executeBatch() throws SQLException {
+ return statement.executeBatch();
+ }
+
+ @Override
+ public Connection getConnection() throws SQLException {
+ return statement.getConnection();
+ }
+
+ @Override
+ public boolean getMoreResults(int current) throws SQLException {
+ return statement.getMoreResults(current);
+ }
+
+ @Override
+ public ResultSet getGeneratedKeys() throws SQLException {
+ return statement.getGeneratedKeys();
+ }
+
+ @Override
+ public int executeUpdate(String sql, int autoGeneratedKeys) throws
SQLException {
+ return statement.executeUpdate(sql, autoGeneratedKeys);
+ }
+
+ @Override
+ public int executeUpdate(String sql, int[] columnIndexes) throws
SQLException {
+ return statement.executeUpdate(sql, columnIndexes);
+ }
+
+ @Override
+ public int executeUpdate(String sql, String[] columnNames) throws
SQLException {
+ return statement.executeUpdate(sql, columnNames);
+ }
+
+ @Override
+ public boolean execute(String sql, int autoGeneratedKeys) throws
SQLException {
+ return statement.execute(sql, autoGeneratedKeys);
+ }
+
+ @Override
+ public boolean execute(String sql, int[] columnIndexes) throws
SQLException {
+ return statement.execute(sql, columnIndexes);
+ }
+
+ @Override
+ public boolean execute(String sql, String[] columnNames) throws
SQLException {
+ return statement.execute(sql, columnNames);
+ }
+
+ @Override
+ public int getResultSetHoldability() throws SQLException {
+ return statement.getResultSetHoldability();
+ }
+
+ @Override
+ public boolean isClosed() throws SQLException {
+ return statement.isClosed();
+ }
+
+ @Override
+ public void setPoolable(boolean poolable) throws SQLException {
+ statement.setPoolable(poolable);
+ }
+
+ @Override
+ public boolean isPoolable() throws SQLException {
+ return statement.isPoolable();
+ }
+
+ @Override
+ public void closeOnCompletion() throws SQLException {
+ statement.closeOnCompletion();
+ }
+
+ @Override
+ public boolean isCloseOnCompletion() throws SQLException {
+ return statement.isCloseOnCompletion();
+ }
+
+ @Override
+ public <T> T unwrap(Class<T> iface) throws SQLException {
+ return statement.unwrap(iface);
+ }
+
+ @Override
+ public boolean isWrapperFor(Class<?> iface) throws SQLException {
+ return statement.isWrapperFor(iface);
+ }
+
+ public static FieldNamedPreparedStatement prepareStatement(
+ Connection connection, String sql, String[] fieldNames) throws
SQLException {
+ checkNotNull(connection, "connection must not be null.");
+ checkNotNull(sql, "sql must not be null.");
+ checkNotNull(fieldNames, "fieldNames must not be null.");
+
+ int[][] indexMapping = new int[fieldNames.length][];
+ String parsedSQL;
+ if (sql.contains("?")) {
+ parsedSQL = sql;
+ for (int i = 0; i < fieldNames.length; i++) {
+ // SQL statement parameter index starts from 1
+ indexMapping[i] = new int[] {i + 1};
+ }
+ } else {
+ HashMap<String, List<Integer>> parameterMap = new HashMap<>();
+ parsedSQL = parseNamedStatement(sql, parameterMap);
+ // currently, the statements must contain all the field parameters
+ checkArgument(parameterMap.size() >= fieldNames.length);
+ for (int i = 0; i < fieldNames.length; i++) {
+ String fieldName = fieldNames[i];
+ checkArgument(
+ parameterMap.containsKey(fieldName),
+ fieldName + " doesn't exist in the parameters of SQL
statement: " + sql);
+ indexMapping[i] =
parameterMap.get(fieldName).stream().mapToInt(v -> v).toArray();
+ }
+ }
+ return new FieldNamedPreparedStatement(
+ connection.prepareStatement(parsedSQL), indexMapping);
+ }
+
+ public static String parseNamedStatement(String sql, Map<String,
List<Integer>> paramMap) {
+ StringBuilder parsedSql = new StringBuilder();
+ int fieldIndex = 1; // SQL statement parameter index starts from 1
+ int length = sql.length();
+ for (int i = 0; i < length; i++) {
+ char c = sql.charAt(i);
+ if (':' == c) {
+ int j = i + 1;
+ while (j < length &&
(Character.isJavaIdentifierPart(sql.charAt(j)) ||
".".equals(String.valueOf(sql.charAt(j))))) {
+ j++;
+ }
+ String parameterName = sql.substring(i + 1, j);
+ checkArgument(
+ !parameterName.isEmpty(),
+ "Named parameters in SQL statement must not be empty.");
+ paramMap.computeIfAbsent(parameterName, n -> new
ArrayList<>()).add(fieldIndex);
+ fieldIndex++;
+ i = j - 1;
+ parsedSql.append('?');
+ } else {
+ parsedSql.append(c);
+ }
+ }
+ return parsedSql.toString();
+ }
+}
diff --git
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/executor/JdbcBatchStatementExecutorBuilder.java
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/executor/JdbcBatchStatementExecutorBuilder.java
index a13681d3a..89bc2c897 100644
---
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/executor/JdbcBatchStatementExecutorBuilder.java
+++
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/executor/JdbcBatchStatementExecutorBuilder.java
@@ -43,6 +43,7 @@ public class JdbcBatchStatementExecutorBuilder {
private Map<String, String> clickhouseTableSchema;
private boolean supportUpsert;
private boolean allowExperimentalLightweightDelete;
+ private boolean clickhouseServerEnableExperimentalLightweightDelete;
private String[] orderByKeys;
private boolean supportMergeTreeEngineExperimentalLightweightDelete() {
@@ -88,7 +89,7 @@ public class JdbcBatchStatementExecutorBuilder {
boolean convertUpdateBeforeEventToDeleteAction;
// DELETE: delete sql
JdbcBatchStatementExecutor deleteExecutor = createDeleteExecutor(
- table, primaryKeys, pkRowConverter);
+ table, primaryKeys, pkRowConverter,
!clickhouseServerEnableExperimentalLightweightDelete);
JdbcBatchStatementExecutor updateExecutor;
if (supportReplacingMergeTreeTableUpsert()) {
// ReplacingMergeTree Update Row: upsert row by
order-by-keys(update_after event)
@@ -138,8 +139,12 @@ public class JdbcBatchStatementExecutorBuilder {
String[] pkNames,
JdbcRowConverter rowConverter) {
return new InsertOrUpdateBatchStatementExecutor(
- connection ->
connection.prepareStatement(SqlUtils.getInsertIntoStatement(table,
rowType.getFieldNames())),
- connection ->
connection.prepareStatement(SqlUtils.getAlterTableUpdateStatement(table,
rowType.getFieldNames(), pkNames)),
+ connection ->
FieldNamedPreparedStatement.prepareStatement(connection,
+ SqlUtils.getInsertIntoStatement(table,
rowType.getFieldNames()),
+ rowType.getFieldNames()),
+ connection ->
FieldNamedPreparedStatement.prepareStatement(connection,
+ SqlUtils.getAlterTableUpdateStatement(table,
rowType.getFieldNames(), pkNames),
+ rowType.getFieldNames()),
rowConverter);
}
@@ -150,9 +155,15 @@ public class JdbcBatchStatementExecutorBuilder {
JdbcRowConverter keyConverter,
JdbcRowConverter valueConverter) {
return new InsertOrUpdateBatchStatementExecutor(
- connection ->
connection.prepareStatement(SqlUtils.getRowExistsStatement(table, pkNames)),
- connection ->
connection.prepareStatement(SqlUtils.getInsertIntoStatement(table,
rowType.getFieldNames())),
- connection ->
connection.prepareStatement(SqlUtils.getAlterTableUpdateStatement(table,
rowType.getFieldNames(), pkNames)),
+ connection ->
FieldNamedPreparedStatement.prepareStatement(connection,
+ SqlUtils.getRowExistsStatement(table, pkNames),
+ pkNames),
+ connection ->
FieldNamedPreparedStatement.prepareStatement(connection,
+ SqlUtils.getInsertIntoStatement(table,
rowType.getFieldNames()),
+ rowType.getFieldNames()),
+ connection ->
FieldNamedPreparedStatement.prepareStatement(connection,
+ SqlUtils.getAlterTableUpdateStatement(table,
rowType.getFieldNames(), pkNames),
+ rowType.getFieldNames()),
keyExtractor,
keyConverter,
valueConverter);
@@ -162,27 +173,30 @@ public class JdbcBatchStatementExecutorBuilder {
SeaTunnelRowType rowType,
JdbcRowConverter rowConverter) {
String insertSQL = SqlUtils.getInsertIntoStatement(table,
rowType.getFieldNames());
- return createSimpleExecutor(insertSQL, rowConverter);
+ return new SimpleBatchStatementExecutor(
+ connection -> FieldNamedPreparedStatement.prepareStatement(
+ connection, insertSQL, rowType.getFieldNames()),
+ rowConverter);
}
private static JdbcBatchStatementExecutor createDeleteExecutor(String
table,
String[]
primaryKeys,
-
JdbcRowConverter rowConverter) {
- String deleteSQL = SqlUtils.getDeleteStatement(table, primaryKeys);
- return createSimpleExecutor(deleteSQL, rowConverter);
+
JdbcRowConverter rowConverter,
+ boolean
enableExperimentalLightweightDelete) {
+ String deleteSQL = SqlUtils.getDeleteStatement(table, primaryKeys,
enableExperimentalLightweightDelete);
+ return new SimpleBatchStatementExecutor(
+ connection -> FieldNamedPreparedStatement.prepareStatement(
+ connection, deleteSQL, primaryKeys),
+ rowConverter);
}
private static JdbcBatchStatementExecutor
createAlterTableDeleteExecutor(String table,
String[] primaryKeys,
JdbcRowConverter rowConverter) {
String alterTableDeleteSQL =
SqlUtils.getAlterTableDeleteStatement(table, primaryKeys);
- return createSimpleExecutor(alterTableDeleteSQL, rowConverter);
- }
-
- private static JdbcBatchStatementExecutor createSimpleExecutor(String sql,
-
JdbcRowConverter rowConverter) {
return new SimpleBatchStatementExecutor(
- connection -> connection.prepareStatement(sql),
+ connection -> FieldNamedPreparedStatement.prepareStatement(
+ connection, alterTableDeleteSQL, primaryKeys),
rowConverter);
}
diff --git
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/executor/SqlUtils.java
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/executor/SqlUtils.java
index 0360bc72f..c0593d8a1 100644
---
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/executor/SqlUtils.java
+++
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/client/executor/SqlUtils.java
@@ -33,48 +33,53 @@ public class SqlUtils {
.map(SqlUtils::quoteIdentifier)
.collect(Collectors.joining(", "));
String placeholders = Arrays.stream(fieldNames)
- .map(fieldName -> "?")
+ .map(fieldName -> ":" + fieldName)
.collect(Collectors.joining(", "));
return String.format("INSERT INTO %s (%s) VALUES (%s)",
tableName, columns, placeholders);
}
public static String getDeleteStatement(String tableName,
- String[] conditionFields) {
+ String[] conditionFields,
+ boolean
enableExperimentalLightweightDelete) {
String conditionClause = Arrays.stream(conditionFields)
- .map(fieldName -> format("%s = ?", quoteIdentifier(fieldName)))
+ .map(fieldName -> format("%s = :%s", quoteIdentifier(fieldName),
fieldName))
.collect(Collectors.joining(" AND "));
- return String.format("" +
- "SET allow_experimental_lightweight_delete = true;" +
- "DELETE FROM %s WHERE %s", quoteIdentifier(tableName),
conditionClause);
+ String deleteStatement = format("DELETE FROM %s WHERE %s",
+ quoteIdentifier(tableName), conditionClause);
+ if (enableExperimentalLightweightDelete) {
+ deleteStatement += " settings
allow_experimental_lightweight_delete = true";
+ }
+ return deleteStatement;
}
public static String getAlterTableUpdateStatement(String tableName,
String[] fieldNames,
String[]
conditionFields) {
String setClause = Arrays.stream(fieldNames)
- .map(fieldName -> String.format("%s = ?",
quoteIdentifier(fieldName)))
+ .filter(fieldName ->
!Arrays.asList(conditionFields).contains(fieldName))
+ .map(fieldName -> String.format("%s = :%s",
quoteIdentifier(fieldName), fieldName))
.collect(Collectors.joining(", "));
String conditionClause = Arrays.stream(conditionFields)
- .map(fieldName -> String.format("%s = ?",
quoteIdentifier(fieldName)))
+ .map(fieldName -> String.format("%s = :%s",
quoteIdentifier(fieldName), fieldName))
.collect(Collectors.joining(" AND "));
- return String.format("ALTER TABLE %s UPDATE %s WHERE %s",
+ return String.format("ALTER TABLE %s UPDATE %s WHERE %s settings
mutations_sync = 1",
tableName, setClause, conditionClause);
}
public static String getAlterTableDeleteStatement(String tableName,
String[]
conditionFields) {
String conditionClause = Arrays.stream(conditionFields)
- .map(fieldName -> format("%s = ?", quoteIdentifier(fieldName)))
+ .map(fieldName -> format("%s = :%s", quoteIdentifier(fieldName),
fieldName))
.collect(Collectors.joining(" AND "));
- return String.format("ALTER TABLE %s DELETE WHERE %s",
+ return String.format("ALTER TABLE %s DELETE WHERE %s settings
mutations_sync = 1",
tableName, conditionClause);
}
public static String getRowExistsStatement(String tableName,
String[] conditionFields) {
String fieldExpressions = Arrays.stream(conditionFields)
- .map(field -> format("%s = ?", quoteIdentifier(field)))
+ .map(field -> format("%s = :%s", quoteIdentifier(field), field))
.collect(Collectors.joining(" AND "));
return String.format("SELECT 1 FROM %s WHERE %s",
quoteIdentifier(tableName), fieldExpressions);
diff --git
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/file/ClickhouseTable.java
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/file/ClickhouseTable.java
index b26a2264f..836e65e0f 100644
---
a/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/file/ClickhouseTable.java
+++
b/seatunnel-connectors-v2/connector-clickhouse/src/main/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/sink/file/ClickhouseTable.java
@@ -19,10 +19,15 @@ package
org.apache.seatunnel.connectors.seatunnel.clickhouse.sink.file;
import
org.apache.seatunnel.connectors.seatunnel.clickhouse.sink.DistributedEngine;
+import lombok.Getter;
+import lombok.Setter;
+
import java.io.Serializable;
import java.util.List;
import java.util.Map;
+@Getter
+@Setter
public class ClickhouseTable implements Serializable {
private String database;
@@ -31,6 +36,7 @@ public class ClickhouseTable implements Serializable {
private String engineFull;
private String createTableDDL;
private List<String> dataPaths;
+ private String sortingKey;
private final DistributedEngine distributedEngine;
private Map<String, String> tableSchema;
@@ -41,6 +47,7 @@ public class ClickhouseTable implements Serializable {
String createTableDDL,
String engineFull,
List<String> dataPaths,
+ String sortingKey,
Map<String, String> tableSchema) {
this.database = database;
this.tableName = tableName;
@@ -49,62 +56,7 @@ public class ClickhouseTable implements Serializable {
this.engineFull = engineFull;
this.createTableDDL = createTableDDL;
this.dataPaths = dataPaths;
- this.tableSchema = tableSchema;
- }
-
- public String getTableName() {
- return tableName;
- }
-
- public void setTableName(String tableName) {
- this.tableName = tableName;
- }
-
- public String getDatabase() {
- return database;
- }
-
- public void setDatabase(String database) {
- this.database = database;
- }
-
- public String getEngine() {
- return engine;
- }
-
- public void setEngine(String engine) {
- this.engine = engine;
- }
-
- public String getEngineFull() {
- return engineFull;
- }
-
- public void setEngineFull(String engineFull) {
- this.engineFull = engineFull;
- }
-
- public String getCreateTableDDL() {
- return createTableDDL;
- }
-
- public void setCreateTableDDL(String createTableDDL) {
- this.createTableDDL = createTableDDL;
- }
-
- public List<String> getDataPaths() {
- return dataPaths;
- }
-
- public void setDataPaths(List<String> dataPaths) {
- this.dataPaths = dataPaths;
- }
-
- public Map<String, String> getTableSchema() {
- return tableSchema;
- }
-
- public void setTableSchema(Map<String, String> tableSchema) {
+ this.sortingKey = sortingKey;
this.tableSchema = tableSchema;
}
diff --git
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/pom.xml
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/pom.xml
index 551f3c9cd..0a10bc252 100644
--- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/pom.xml
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/pom.xml
@@ -51,5 +51,11 @@
<version>${project.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.seatunnel</groupId>
+ <artifactId>connector-fake</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
\ No newline at end of file
diff --git
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/ClickhouseSinkCDCChangelogIT.java
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/ClickhouseSinkCDCChangelogIT.java
new file mode 100644
index 000000000..6f233524c
--- /dev/null
+++
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/clickhouse/ClickhouseSinkCDCChangelogIT.java
@@ -0,0 +1,193 @@
+/*
+ * 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.clickhouse;
+
+import org.apache.seatunnel.e2e.common.TestResource;
+import org.apache.seatunnel.e2e.common.TestSuiteBase;
+import org.apache.seatunnel.e2e.common.container.TestContainer;
+
+import lombok.extern.slf4j.Slf4j;
+import org.awaitility.Awaitility;
+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.ClickHouseContainer;
+import org.testcontainers.containers.Container;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.lifecycle.Startables;
+import org.testcontainers.utility.DockerLoggerFactory;
+
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+@Slf4j
+public class ClickhouseSinkCDCChangelogIT extends TestSuiteBase implements
TestResource {
+ private static final String CLICKHOUSE_DOCKER_IMAGE =
"clickhouse/clickhouse-server:latest";
+ private static final String HOST = "clickhouse";
+ private static final String DRIVER_CLASS =
"com.clickhouse.jdbc.ClickHouseDriver";
+ private static final String DATABASE = "default";
+ private static final String SINK_TABLE = "sink_table";
+ private ClickHouseContainer container;
+ private Connection connection;
+
+ @BeforeAll
+ @Override
+ public void startUp() throws Exception {
+ this.container = new ClickHouseContainer(CLICKHOUSE_DOCKER_IMAGE)
+ .withNetwork(NETWORK)
+ .withNetworkAliases(HOST)
+ .withExposedPorts(8123)
+ .withLogConsumer(new
Slf4jLogConsumer(DockerLoggerFactory.getLogger(CLICKHOUSE_DOCKER_IMAGE)));
+ Startables.deepStart(Stream.of(this.container)).join();
+ log.info("Clickhouse container started");
+ Awaitility.given()
+ .ignoreExceptions()
+ .await()
+ .atMost(360L, TimeUnit.SECONDS)
+ .untilAsserted(this::initConnection);
+ }
+
+ @AfterAll
+ @Override
+ public void tearDown() throws Exception {
+ if (this.connection != null) {
+ this.connection.close();
+ }
+ if (this.container != null) {
+ this.container.stop();
+ }
+ }
+
+ @TestTemplate
+ public void testClickhouseMergeTreeTable(TestContainer container) throws
Exception {
+ initializeClickhouseMergeTreeTable();
+
+ Container.ExecResult execResult =
container.executeJob("/clickhouse_sink_cdc_changelog_case1.conf");
+ Assertions.assertEquals(0, execResult.getExitCode());
+
+ checkSinkTableRows();
+ dropSinkTable();
+ }
+
+ @TestTemplate
+ public void testClickhouseMergeTreeTableWithEnableDelete(TestContainer
container) throws Exception {
+ initializeClickhouseMergeTreeTable();
+
+ Container.ExecResult execResult =
container.executeJob("/clickhouse_sink_cdc_changelog_case2.conf");
+ Assertions.assertEquals(0, execResult.getExitCode());
+
+ checkSinkTableRows();
+ dropSinkTable();
+ }
+
+ @TestTemplate
+ public void testClickhouseReplacingMergeTreeTable(TestContainer container)
throws Exception {
+ initializeClickhouseReplacingMergeTreeTable();
+
+ Container.ExecResult execResult =
container.executeJob("/clickhouse_sink_cdc_changelog_case1.conf");
+ Assertions.assertEquals(0, execResult.getExitCode());
+
+ checkSinkTableRows();
+ dropSinkTable();
+ }
+
+ @TestTemplate
+ public void
testClickhouseReplacingMergeTreeTableWithEnableDelete(TestContainer container)
throws Exception {
+ initializeClickhouseReplacingMergeTreeTable();
+
+ Container.ExecResult execResult =
container.executeJob("/clickhouse_sink_cdc_changelog_case2.conf");
+ Assertions.assertEquals(0, execResult.getExitCode());
+
+ checkSinkTableRows();
+ dropSinkTable();
+ }
+
+ private void initConnection() throws Exception {
+ final Properties info = new Properties();
+ info.put("user", this.container.getUsername());
+ info.put("password", this.container.getPassword());
+ this.connection = ((Driver)
Class.forName(DRIVER_CLASS).newInstance()).connect(this.container.getJdbcUrl(),
info);
+ }
+
+ private void initializeClickhouseMergeTreeTable() {
+ try {
+ Statement statement = this.connection.createStatement();
+ String sql = String.format("create table if not exists %s.%s(\n" +
+ " `pk_id` Int64,\n" +
+ " `name` String,\n" +
+ " `score` Int32\n" +
+ ")engine=MergeTree ORDER BY(pk_id) PRIMARY KEY(pk_id)",
DATABASE, SINK_TABLE);
+ statement.execute(sql);
+ } catch (SQLException e) {
+ throw new RuntimeException("Initializing Clickhouse table
failed!", e);
+ }
+ }
+
+ private void initializeClickhouseReplacingMergeTreeTable() {
+ try {
+ Statement statement = this.connection.createStatement();
+ String sql = String.format("create table if not exists %s.%s(\n" +
+ " `pk_id` Int64,\n" +
+ " `name` String,\n" +
+ " `score` Int32\n" +
+ ")engine=ReplacingMergeTree ORDER BY(pk_id) PRIMARY
KEY(pk_id)", DATABASE, SINK_TABLE);
+ statement.execute(sql);
+ } catch (SQLException e) {
+ throw new RuntimeException("Initializing Clickhouse table
failed!", e);
+ }
+ }
+
+ private void checkSinkTableRows() throws SQLException {
+ Set<List<Object>> actual = new HashSet<>();
+ try (Statement statement = connection.createStatement()) {
+ ResultSet resultSet = statement.executeQuery(String.format("select
* from %s.%s", DATABASE, SINK_TABLE));
+ while (resultSet.next()) {
+ List<Object> row = Arrays.asList(
+ resultSet.getLong("pk_id"),
+ resultSet.getString("name"),
+ resultSet.getInt("score"));
+ actual.add(row);
+ }
+ }
+ Set<List<Object>> expected = Stream.<List<Object>>of(
+ Arrays.asList(1L, "A_1", 100),
+ Arrays.asList(3L, "C", 100))
+ .collect(Collectors.toSet());
+ Assertions.assertIterableEquals(expected, actual);
+ }
+
+ private void dropSinkTable() {
+ try (Statement statement = connection.createStatement()) {
+ statement.execute(String.format("drop table %s.%s", DATABASE,
SINK_TABLE));
+ } catch (SQLException e) {
+ throw new RuntimeException("Test clickhouse server image error",
e);
+ }
+ }
+}
diff --git
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/src/test/resources/clickhouse_sink_cdc_changelog_case1.conf
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/src/test/resources/clickhouse_sink_cdc_changelog_case1.conf
new file mode 100644
index 000000000..c5060bba7
--- /dev/null
+++
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/src/test/resources/clickhouse_sink_cdc_changelog_case1.conf
@@ -0,0 +1,86 @@
+#
+# 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.
+#
+######
+###### This config file is a demonstration of streaming processing in
seatunnel config
+######
+
+env {
+ execution.parallelism = 1
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ schema = {
+ fields {
+ pk_id = bigint
+ name = string
+ score = int
+ }
+ }
+ rows = [
+ {
+ kind = INSERT
+ fields = [1, "A", 100]
+ },
+ {
+ kind = INSERT
+ fields = [2, "B", 100]
+ },
+ {
+ kind = INSERT
+ fields = [3, "C", 100]
+ },
+ {
+ kind = INSERT
+ fields = [3, "C", 100]
+ },
+ {
+ kind = INSERT
+ fields = [3, "C", 100]
+ },
+ {
+ kind = INSERT
+ fields = [3, "C", 100]
+ }
+ {
+ kind = UPDATE_BEFORE
+ fields = [1, "A", 100]
+ },
+ {
+ kind = UPDATE_AFTER
+ fields = [1, "A_1", 100]
+ },
+ {
+ kind = DELETE
+ fields = [2, "B", 100]
+ }
+ ]
+ }
+}
+
+sink {
+ Clickhouse {
+ host = "clickhouse:8123"
+ database = "default"
+ table = "sink_table"
+ username = "default"
+ password = ""
+
+ primary_key = "pk_id"
+ }
+}
\ No newline at end of file
diff --git
a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/src/test/resources/clickhouse_sink_cdc_changelog_case2.conf
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/src/test/resources/clickhouse_sink_cdc_changelog_case2.conf
new file mode 100644
index 000000000..f1a630a4c
--- /dev/null
+++
b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-clickhouse-e2e/src/test/resources/clickhouse_sink_cdc_changelog_case2.conf
@@ -0,0 +1,87 @@
+#
+# 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.
+#
+######
+###### This config file is a demonstration of streaming processing in
seatunnel config
+######
+
+env {
+ execution.parallelism = 1
+ job.mode = "BATCH"
+}
+
+source {
+ FakeSource {
+ schema = {
+ fields {
+ pk_id = bigint
+ name = string
+ score = int
+ }
+ }
+ rows = [
+ {
+ kind = INSERT
+ fields = [1, "A", 100]
+ },
+ {
+ kind = INSERT
+ fields = [2, "B", 100]
+ },
+ {
+ kind = INSERT
+ fields = [3, "C", 100]
+ },
+ {
+ kind = INSERT
+ fields = [3, "C", 100]
+ },
+ {
+ kind = INSERT
+ fields = [3, "C", 100]
+ },
+ {
+ kind = INSERT
+ fields = [3, "C", 100]
+ }
+ {
+ kind = UPDATE_BEFORE
+ fields = [1, "A", 100]
+ },
+ {
+ kind = UPDATE_AFTER
+ fields = [1, "A_1", 100]
+ },
+ {
+ kind = DELETE
+ fields = [2, "B", 100]
+ }
+ ]
+ }
+}
+
+sink {
+ Clickhouse {
+ host = "clickhouse:8123"
+ database = "default"
+ table = "sink_table"
+ username = "default"
+ password = ""
+
+ primary_key = "pk_id"
+ allow_experimental_lightweight_delete = true
+ }
+}
\ No newline at end of file