You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@paimon.apache.org by lz...@apache.org on 2023/05/25 05:58:28 UTC
[incubator-paimon] branch master updated: [flink] Support multi-table write operator (#1212)
This is an automated email from the ASF dual-hosted git repository.
lzljs3620320 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-paimon.git
The following commit(s) were added to refs/heads/master by this push:
new d536dcb5f [flink] Support multi-table write operator (#1212)
d536dcb5f is described below
commit d536dcb5f725f4943d72fce7377828c5b9a24776
Author: Dian Qi <qi...@163.com>
AuthorDate: Thu May 25 13:58:23 2023 +0800
[flink] Support multi-table write operator (#1212)
---
.../java/org/apache/paimon/catalog/Catalog.java | 7 +
.../org/apache/paimon/flink/sink/Committable.java | 3 +-
.../paimon/flink/sink/CommittableStateManager.java | 9 +-
.../org/apache/paimon/flink/sink/Committer.java | 19 +-
.../paimon/flink/sink/CommitterOperator.java | 38 +-
.../apache/paimon/flink/sink/CompactorSink.java | 7 +-
.../apache/paimon/flink/sink/FileStoreSink.java | 7 +-
.../org/apache/paimon/flink/sink/FlinkSink.java | 9 +-
...Committable.java => MultiTableCommittable.java} | 47 +-
.../sink/MultiTableCommittableSerializer.java | 155 +++++
.../flink/sink/MultiTableCommittableTypeInfo.java | 98 +++
.../flink/sink/NoopCommittableStateManager.java | 5 +-
.../paimon/flink/sink/PrepareCommitOperator.java | 6 +-
.../RestoreAndFailCommittableStateManager.java | 9 +-
.../flink/sink/RowDataStoreWriteOperator.java | 2 +-
.../apache/paimon/flink/sink/StoreCommitter.java | 15 +-
.../paimon/flink/sink/StoreCompactOperator.java | 2 +-
.../paimon/flink/sink/cdc/CdcMultiplexRecord.java | 88 +++
.../apache/paimon/flink/sink/cdc/CdcRecord.java | 8 +
....java => CdcRecordStoreMultiWriteOperator.java} | 131 ++--
.../sink/cdc/CdcRecordStoreWriteOperator.java | 2 +-
.../apache/paimon/flink/sink/cdc/FlinkCdcSink.java | 7 +-
.../paimon/flink/sink/CommitterOperatorTest.java | 11 +-
.../sink/MultiTableCommittableSerializerTest.java | 63 ++
.../cdc/CdcRecordStoreMultiWriteOperatorTest.java | 710 +++++++++++++++++++++
25 files changed, 1338 insertions(+), 120 deletions(-)
diff --git a/paimon-core/src/main/java/org/apache/paimon/catalog/Catalog.java b/paimon-core/src/main/java/org/apache/paimon/catalog/Catalog.java
index 2a0f80d08..b26d7fe37 100644
--- a/paimon-core/src/main/java/org/apache/paimon/catalog/Catalog.java
+++ b/paimon-core/src/main/java/org/apache/paimon/catalog/Catalog.java
@@ -23,6 +23,7 @@ import org.apache.paimon.schema.Schema;
import org.apache.paimon.schema.SchemaChange;
import org.apache.paimon.table.Table;
+import java.io.Serializable;
import java.util.List;
import java.util.Optional;
@@ -342,4 +343,10 @@ public interface Catalog extends AutoCloseable {
return column;
}
}
+
+ /** Loader of {@link Catalog}. */
+ @FunctionalInterface
+ interface Loader extends Serializable {
+ Catalog load();
+ }
}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/Committable.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/Committable.java
index 99cee468f..27a00717e 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/Committable.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/Committable.java
@@ -57,7 +57,8 @@ public class Committable {
+ '}';
}
- enum Kind {
+ /** Kind of the produced Committable. */
+ public enum Kind {
FILE((byte) 0),
LOG_OFFSET((byte) 1);
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CommittableStateManager.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CommittableStateManager.java
index 827882de4..34bd74374 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CommittableStateManager.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CommittableStateManager.java
@@ -17,8 +17,6 @@
package org.apache.paimon.flink.sink;
-import org.apache.paimon.manifest.ManifestCommittable;
-
import org.apache.flink.runtime.state.StateInitializationContext;
import org.apache.flink.runtime.state.StateSnapshotContext;
@@ -29,10 +27,11 @@ import java.util.List;
* Helper interface for {@link CommitterOperator}. This interface manages operator states about
* {@link org.apache.paimon.manifest.ManifestCommittable}.
*/
-public interface CommittableStateManager extends Serializable {
+public interface CommittableStateManager<GlobalCommitT> extends Serializable {
- void initializeState(StateInitializationContext context, Committer committer) throws Exception;
+ void initializeState(StateInitializationContext context, Committer<?, GlobalCommitT> committer)
+ throws Exception;
- void snapshotState(StateSnapshotContext context, List<ManifestCommittable> committables)
+ void snapshotState(StateSnapshotContext context, List<GlobalCommitT> committables)
throws Exception;
}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/Committer.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/Committer.java
index 5c47c959e..15b3d5098 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/Committer.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/Committer.java
@@ -19,10 +19,10 @@
package org.apache.paimon.flink.sink;
-import org.apache.paimon.manifest.ManifestCommittable;
-
import java.io.IOException;
+import java.util.Collection;
import java.util.List;
+import java.util.Map;
/**
* The {@code Committer} is responsible for creating and committing an aggregated committable, which
@@ -30,17 +30,18 @@ import java.util.List;
*
* <p>The {@code Committer} runs with parallelism equal to 1.
*/
-public interface Committer extends AutoCloseable {
+public interface Committer<CommitT, GlobalCommitT> extends AutoCloseable {
/** Find out which global committables need to be retried when recovering from the failure. */
- List<ManifestCommittable> filterRecoveredCommittables(
- List<ManifestCommittable> globalCommittables) throws IOException;
+ List<GlobalCommitT> filterRecoveredCommittables(List<GlobalCommitT> globalCommittables)
+ throws IOException;
/** Compute an aggregated committable from a list of committables. */
- ManifestCommittable combine(long checkpointId, long watermark, List<Committable> committables)
+ GlobalCommitT combine(long checkpointId, long watermark, List<CommitT> committables)
throws IOException;
- /** Commits the given {@link ManifestCommittable}. */
- void commit(List<ManifestCommittable> globalCommittables)
- throws IOException, InterruptedException;
+ /** Commits the given {@link GlobalCommitT}. */
+ void commit(List<GlobalCommitT> globalCommittables) throws IOException, InterruptedException;
+
+ Map<Long, List<CommitT>> groupByCheckpoint(Collection<CommitT> committables);
}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CommitterOperator.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CommitterOperator.java
index e30867b54..8efc3220a 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CommitterOperator.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CommitterOperator.java
@@ -17,7 +17,6 @@
package org.apache.paimon.flink.sink;
-import org.apache.paimon.manifest.ManifestCommittable;
import org.apache.paimon.utils.SerializableFunction;
import org.apache.flink.runtime.state.StateInitializationContext;
@@ -32,7 +31,6 @@ import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
@@ -41,13 +39,13 @@ import java.util.TreeMap;
import static org.apache.paimon.utils.Preconditions.checkNotNull;
/** Operator to commit {@link Committable}s for each snapshot. */
-public class CommitterOperator extends AbstractStreamOperator<Committable>
- implements OneInputStreamOperator<Committable, Committable>, BoundedOneInput {
+public class CommitterOperator<CommitT, GlobalCommitT> extends AbstractStreamOperator<CommitT>
+ implements OneInputStreamOperator<CommitT, CommitT>, BoundedOneInput {
private static final long serialVersionUID = 1L;
/** Record all the inputs until commit. */
- private final Deque<Committable> inputs = new ArrayDeque<>();
+ private final Deque<CommitT> inputs = new ArrayDeque<>();
/**
* If checkpoint is enabled we should do nothing in {@link CommitterOperator#endInput}.
@@ -65,17 +63,17 @@ public class CommitterOperator extends AbstractStreamOperator<Committable>
private final String initialCommitUser;
/** Group the committable by the checkpoint id. */
- protected final NavigableMap<Long, ManifestCommittable> committablesPerCheckpoint;
+ protected final NavigableMap<Long, GlobalCommitT> committablesPerCheckpoint;
- private final SerializableFunction<String, Committer> committerFactory;
+ private final SerializableFunction<String, Committer<CommitT, GlobalCommitT>> committerFactory;
- private final CommittableStateManager committableStateManager;
+ private final CommittableStateManager<GlobalCommitT> committableStateManager;
/**
* Aggregate committables to global committables and commit the global committables to the
* external system.
*/
- protected Committer committer;
+ protected Committer<CommitT, GlobalCommitT> committer;
private transient long currentWatermark;
@@ -84,8 +82,8 @@ public class CommitterOperator extends AbstractStreamOperator<Committable>
public CommitterOperator(
boolean streamingCheckpointEnabled,
String initialCommitUser,
- SerializableFunction<String, Committer> committerFactory,
- CommittableStateManager committableStateManager) {
+ SerializableFunction<String, Committer<CommitT, GlobalCommitT>> committerFactory,
+ CommittableStateManager<GlobalCommitT> committableStateManager) {
this.streamingCheckpointEnabled = streamingCheckpointEnabled;
this.initialCommitUser = initialCommitUser;
this.committablesPerCheckpoint = new TreeMap<>();
@@ -121,8 +119,7 @@ public class CommitterOperator extends AbstractStreamOperator<Committable>
}
}
- private ManifestCommittable toCommittables(long checkpoint, List<Committable> inputs)
- throws Exception {
+ private GlobalCommitT toCommittables(long checkpoint, List<CommitT> inputs) throws Exception {
return committer.combine(checkpoint, currentWatermark, inputs);
}
@@ -133,7 +130,7 @@ public class CommitterOperator extends AbstractStreamOperator<Committable>
committableStateManager.snapshotState(context, committables(committablesPerCheckpoint));
}
- private List<ManifestCommittable> committables(NavigableMap<Long, ManifestCommittable> map) {
+ private List<GlobalCommitT> committables(NavigableMap<Long, GlobalCommitT> map) {
return new ArrayList<>(map.values());
}
@@ -155,14 +152,14 @@ public class CommitterOperator extends AbstractStreamOperator<Committable>
}
private void commitUpToCheckpoint(long checkpointId) throws Exception {
- NavigableMap<Long, ManifestCommittable> headMap =
+ NavigableMap<Long, GlobalCommitT> headMap =
committablesPerCheckpoint.headMap(checkpointId, true);
committer.commit(committables(headMap));
headMap.clear();
}
@Override
- public void processElement(StreamRecord<Committable> element) {
+ public void processElement(StreamRecord<CommitT> element) {
output.collect(element);
this.inputs.add(element.getValue());
}
@@ -176,14 +173,11 @@ public class CommitterOperator extends AbstractStreamOperator<Committable>
}
private void pollInputs() throws Exception {
- Map<Long, List<Committable>> grouped = new HashMap<>();
- for (Committable c : inputs) {
- grouped.computeIfAbsent(c.checkpointId(), k -> new ArrayList<>()).add(c);
- }
+ Map<Long, List<CommitT>> grouped = committer.groupByCheckpoint(inputs);
- for (Map.Entry<Long, List<Committable>> entry : grouped.entrySet()) {
+ for (Map.Entry<Long, List<CommitT>> entry : grouped.entrySet()) {
Long cp = entry.getKey();
- List<Committable> committables = entry.getValue();
+ List<CommitT> committables = entry.getValue();
if (committablesPerCheckpoint.containsKey(cp)) {
throw new RuntimeException(
String.format(
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CompactorSink.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CompactorSink.java
index c41bc0b43..6d3eb753f 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CompactorSink.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/CompactorSink.java
@@ -18,6 +18,7 @@
package org.apache.paimon.flink.sink;
+import org.apache.paimon.manifest.ManifestCommittable;
import org.apache.paimon.operation.Lock;
import org.apache.paimon.table.FileStoreTable;
import org.apache.paimon.utils.SerializableFunction;
@@ -44,13 +45,13 @@ public class CompactorSink extends FlinkSink<RowData> {
}
@Override
- protected SerializableFunction<String, Committer> createCommitterFactory(
- boolean streamingCheckpointEnabled) {
+ protected SerializableFunction<String, Committer<Committable, ManifestCommittable>>
+ createCommitterFactory(boolean streamingCheckpointEnabled) {
return user -> new StoreCommitter(table.newCommit(user).withLock(lockFactory.create()));
}
@Override
- protected CommittableStateManager createCommittableStateManager() {
+ protected CommittableStateManager<ManifestCommittable> createCommittableStateManager() {
return new NoopCommittableStateManager();
}
}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FileStoreSink.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FileStoreSink.java
index 777c25dc4..c726c6640 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FileStoreSink.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FileStoreSink.java
@@ -19,6 +19,7 @@
package org.apache.paimon.flink.sink;
import org.apache.paimon.flink.VersionedSerializerWrapper;
+import org.apache.paimon.manifest.ManifestCommittable;
import org.apache.paimon.manifest.ManifestCommittableSerializer;
import org.apache.paimon.operation.Lock;
import org.apache.paimon.table.FileStoreTable;
@@ -58,8 +59,8 @@ public class FileStoreSink extends FlinkSink<RowData> {
}
@Override
- protected SerializableFunction<String, Committer> createCommitterFactory(
- boolean streamingCheckpointEnabled) {
+ protected SerializableFunction<String, Committer<Committable, ManifestCommittable>>
+ createCommitterFactory(boolean streamingCheckpointEnabled) {
// If checkpoint is enabled for streaming job, we have to
// commit new files list even if they're empty.
// Otherwise we can't tell if the commit is successful after
@@ -73,7 +74,7 @@ public class FileStoreSink extends FlinkSink<RowData> {
}
@Override
- protected CommittableStateManager createCommittableStateManager() {
+ protected CommittableStateManager<ManifestCommittable> createCommittableStateManager() {
return new RestoreAndFailCommittableStateManager(
() -> new VersionedSerializerWrapper<>(new ManifestCommittableSerializer()));
}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkSink.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkSink.java
index f1436cb47..5fbeedfb1 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkSink.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkSink.java
@@ -20,6 +20,7 @@ package org.apache.paimon.flink.sink;
import org.apache.paimon.CoreOptions.ChangelogProducer;
import org.apache.paimon.flink.utils.StreamExecutionEnvironmentUtils;
+import org.apache.paimon.manifest.ManifestCommittable;
import org.apache.paimon.options.Options;
import org.apache.paimon.table.FileStoreTable;
import org.apache.paimon.utils.Preconditions;
@@ -142,7 +143,7 @@ public abstract class FlinkSink<T> implements Serializable {
written.transform(
GLOBAL_COMMITTER_NAME + " -> " + table.name(),
typeInfo,
- new CommitterOperator(
+ new CommitterOperator<>(
streamingCheckpointEnabled,
commitUser,
createCommitterFactory(streamingCheckpointEnabled),
@@ -168,8 +169,8 @@ public abstract class FlinkSink<T> implements Serializable {
protected abstract OneInputStreamOperator<T, Committable> createWriteOperator(
StoreSinkWrite.Provider writeProvider, boolean isStreaming, String commitUser);
- protected abstract SerializableFunction<String, Committer> createCommitterFactory(
- boolean streamingCheckpointEnabled);
+ protected abstract SerializableFunction<String, Committer<Committable, ManifestCommittable>>
+ createCommitterFactory(boolean streamingCheckpointEnabled);
- protected abstract CommittableStateManager createCommittableStateManager();
+ protected abstract CommittableStateManager<ManifestCommittable> createCommittableStateManager();
}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/Committable.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/MultiTableCommittable.java
similarity index 61%
copy from paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/Committable.java
copy to paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/MultiTableCommittable.java
index 99cee468f..42d9af6b5 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/Committable.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/MultiTableCommittable.java
@@ -18,26 +18,58 @@
package org.apache.paimon.flink.sink;
-/** Committable produced by {@link PrepareCommitOperator}. */
-public class Committable {
+import org.apache.paimon.catalog.Identifier;
+/**
+ * MultiTableCommittable produced by {@link PrepareCommitOperator}. This type of Committable will
+ * only be produced by multiplexed operators that handles data from multiple tables. Thus, the
+ * database, table, and commit user of each table is included in the committable.
+ */
+public class MultiTableCommittable {
+
+ private final String database;
+ private final String table;
private final long checkpointId;
- private final Kind kind;
+ private final Committable.Kind kind;
private final Object wrappedCommittable;
- public Committable(long checkpointId, Kind kind, Object wrappedCommittable) {
+ public MultiTableCommittable(
+ String database,
+ String table,
+ long checkpointId,
+ Committable.Kind kind,
+ Object wrappedCommittable) {
this.checkpointId = checkpointId;
this.kind = kind;
this.wrappedCommittable = wrappedCommittable;
+ this.database = database;
+ this.table = table;
+ }
+
+ public static MultiTableCommittable fromCommittable(Identifier id, Committable committable) {
+ return new MultiTableCommittable(
+ id.getDatabaseName(),
+ id.getObjectName(),
+ committable.checkpointId(),
+ committable.kind(),
+ committable.wrappedCommittable());
+ }
+
+ public String getDatabase() {
+ return database;
+ }
+
+ public String getTable() {
+ return table;
}
public long checkpointId() {
return checkpointId;
}
- public Kind kind() {
+ public Committable.Kind kind() {
return kind;
}
@@ -47,7 +79,7 @@ public class Committable {
@Override
public String toString() {
- return "Committable{"
+ return "MultiTableCommittable{"
+ "checkpointId="
+ checkpointId
+ ", kind="
@@ -57,7 +89,8 @@ public class Committable {
+ '}';
}
- enum Kind {
+ /** Kind of the produced Committable. */
+ public enum Kind {
FILE((byte) 0),
LOG_OFFSET((byte) 1);
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/MultiTableCommittableSerializer.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/MultiTableCommittableSerializer.java
new file mode 100644
index 000000000..2cb9f4167
--- /dev/null
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/MultiTableCommittableSerializer.java
@@ -0,0 +1,155 @@
+/*
+ * 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.paimon.flink.sink;
+
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.table.sink.CommitMessageSerializer;
+
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+
+/**
+ * {@link SimpleVersionedSerializer} for {@link MultiTableCommittable}. If a type info class is
+ * using this this serde of MultiTableCommittable. It should make sure that the operator that
+ * produces it will include the database, table, and commit user information. This can be done by
+ * calling MultiTableCommittable::fromCommittable.
+ */
+public class MultiTableCommittableSerializer
+ implements SimpleVersionedSerializer<MultiTableCommittable> {
+
+ private final CommittableSerializer committableSerializer;
+ private final CommitMessageSerializer commitMessageSerializer;
+
+ public MultiTableCommittableSerializer(CommitMessageSerializer commitMessageSerializer) {
+ this.committableSerializer = new CommittableSerializer(commitMessageSerializer);
+ this.commitMessageSerializer = commitMessageSerializer;
+ }
+
+ @Override
+ public int getVersion() {
+ return 2;
+ }
+
+ @Override
+ public byte[] serialize(MultiTableCommittable committable) throws IOException {
+ // first serialize all metadata
+ String database = committable.getDatabase();
+ int databaseLen = database.length();
+ String table = committable.getTable();
+ int tableLen = table.length();
+
+ int multiTableMetaLen = databaseLen + tableLen + 2 * 4;
+
+ // use committable serializer (of the same version) to serialize committable
+ byte[] serializedCommittable = serializeCommittable(committable);
+
+ return ByteBuffer.allocate(multiTableMetaLen + serializedCommittable.length)
+ .putInt(databaseLen)
+ .put(database.getBytes())
+ .putInt(tableLen)
+ .put(table.getBytes())
+ .put(serializedCommittable)
+ .array();
+ }
+
+ @Override
+ public MultiTableCommittable deserialize(int committableVersion, byte[] bytes)
+ throws IOException {
+ if (committableVersion != getVersion()) {
+ throw new RuntimeException("Can not deserialize version: " + committableVersion);
+ }
+
+ // first deserialize all metadata
+ ByteBuffer buffer = ByteBuffer.wrap(bytes);
+ int databaseLen = buffer.getInt();
+ byte[] databaseBytes = new byte[databaseLen];
+ buffer.get(databaseBytes, 0, databaseLen);
+ String database = new String(databaseBytes);
+ int tableLen = buffer.getInt();
+ byte[] tableBytes = new byte[tableLen];
+ buffer.get(tableBytes, 0, tableLen);
+ String table = new String(tableBytes);
+ int multiTableMetaLen = databaseLen + tableLen + 2 * 4;
+
+ // use committable serializer (of the same version) to deserialize committable
+ byte[] serializedCommittable = new byte[bytes.length - multiTableMetaLen];
+
+ buffer.get(serializedCommittable, 0, bytes.length - multiTableMetaLen);
+ Committable committable = deserializeCommittable(committableVersion, serializedCommittable);
+
+ return MultiTableCommittable.fromCommittable(
+ Identifier.create(database, table), committable);
+ }
+
+ public byte[] serializeCommittable(MultiTableCommittable committable) throws IOException {
+ byte[] wrapped;
+ int version;
+ switch (committable.kind()) {
+ case FILE:
+ version = commitMessageSerializer.getVersion();
+ wrapped =
+ commitMessageSerializer.serialize(
+ (CommitMessage) committable.wrappedCommittable());
+ break;
+ case LOG_OFFSET:
+ version = 1;
+ wrapped = ((LogOffsetCommittable) committable.wrappedCommittable()).toBytes();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported kind: " + committable.kind());
+ }
+
+ return ByteBuffer.allocate(8 + 1 + wrapped.length + 4)
+ .putLong(committable.checkpointId())
+ .put(committable.kind().toByteValue())
+ .put(wrapped)
+ .putInt(version)
+ .array();
+ }
+
+ public Committable deserializeCommittable(int committableVersion, byte[] bytes)
+ throws IOException {
+ if (committableVersion != getVersion()) {
+ throw new RuntimeException("Can not deserialize version: " + committableVersion);
+ }
+
+ ByteBuffer buffer = ByteBuffer.wrap(bytes);
+ long checkpointId = buffer.getLong();
+ Committable.Kind kind = Committable.Kind.fromByteValue(buffer.get());
+ byte[] wrapped = new byte[bytes.length - 13];
+ buffer.get(wrapped);
+ int version = buffer.getInt();
+
+ Object wrappedCommittable;
+ switch (kind) {
+ case FILE:
+ wrappedCommittable = commitMessageSerializer.deserialize(version, wrapped);
+ break;
+ case LOG_OFFSET:
+ wrappedCommittable = LogOffsetCommittable.fromBytes(wrapped);
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported kind: " + kind);
+ }
+ return new Committable(checkpointId, kind, wrappedCommittable);
+ }
+}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/MultiTableCommittableTypeInfo.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/MultiTableCommittableTypeInfo.java
new file mode 100644
index 000000000..48efd349d
--- /dev/null
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/MultiTableCommittableTypeInfo.java
@@ -0,0 +1,98 @@
+/*
+ * 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.paimon.flink.sink;
+
+import org.apache.paimon.table.sink.CommitMessageSerializer;
+
+import org.apache.flink.api.common.ExecutionConfig;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.core.io.SimpleVersionedSerializerTypeSerializerProxy;
+
+/** Type information of {@link MultiTableCommittable}. */
+public class MultiTableCommittableTypeInfo extends TypeInformation<MultiTableCommittable> {
+
+ @Override
+ public boolean isBasicType() {
+ return false;
+ }
+
+ @Override
+ public boolean isTupleType() {
+ return false;
+ }
+
+ @Override
+ public int getArity() {
+ return 1;
+ }
+
+ @Override
+ public int getTotalFields() {
+ return 1;
+ }
+
+ @Override
+ public Class<MultiTableCommittable> getTypeClass() {
+ return MultiTableCommittable.class;
+ }
+
+ @Override
+ public boolean isKeyType() {
+ return false;
+ }
+
+ @Override
+ public TypeSerializer<MultiTableCommittable> createSerializer(ExecutionConfig config) {
+ // no copy, so that data from writer is directly going into committer while chaining
+ return new SimpleVersionedSerializerTypeSerializerProxy<MultiTableCommittable>(
+ () -> new MultiTableCommittableSerializer(new CommitMessageSerializer())) {
+ @Override
+ public MultiTableCommittable copy(MultiTableCommittable from) {
+ return from;
+ }
+
+ @Override
+ public MultiTableCommittable copy(
+ MultiTableCommittable from, MultiTableCommittable reuse) {
+ return from;
+ }
+ };
+ }
+
+ @Override
+ public int hashCode() {
+ return 0;
+ }
+
+ @Override
+ public boolean canEqual(Object obj) {
+ return obj instanceof MultiTableCommittableTypeInfo;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return obj instanceof MultiTableCommittableTypeInfo;
+ }
+
+ @Override
+ public String toString() {
+ return "MultiTableCommittableTypeInfo";
+ }
+}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/NoopCommittableStateManager.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/NoopCommittableStateManager.java
index d72fb45c6..dc03e0c96 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/NoopCommittableStateManager.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/NoopCommittableStateManager.java
@@ -31,10 +31,11 @@ import java.util.List;
* <p>Useful for committing optional snapshots. For example COMPACT snapshots produced by a separate
* compact job.
*/
-public class NoopCommittableStateManager implements CommittableStateManager {
+public class NoopCommittableStateManager implements CommittableStateManager<ManifestCommittable> {
@Override
- public void initializeState(StateInitializationContext context, Committer committer)
+ public void initializeState(
+ StateInitializationContext context, Committer<?, ManifestCommittable> committer)
throws Exception {
// nothing to do
}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/PrepareCommitOperator.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/PrepareCommitOperator.java
index 0b3683ff0..86838bab5 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/PrepareCommitOperator.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/PrepareCommitOperator.java
@@ -28,8 +28,8 @@ import java.io.IOException;
import java.util.List;
/** Prepare commit operator to emit {@link Committable}s. */
-public abstract class PrepareCommitOperator<T> extends AbstractStreamOperator<Committable>
- implements OneInputStreamOperator<T, Committable>, BoundedOneInput {
+public abstract class PrepareCommitOperator<IN, OUT> extends AbstractStreamOperator<OUT>
+ implements OneInputStreamOperator<IN, OUT>, BoundedOneInput {
private boolean endOfInput = false;
@@ -56,6 +56,6 @@ public abstract class PrepareCommitOperator<T> extends AbstractStreamOperator<Co
.forEach(committable -> output.collect(new StreamRecord<>(committable)));
}
- protected abstract List<Committable> prepareCommit(boolean doCompaction, long checkpointId)
+ protected abstract List<OUT> prepareCommit(boolean doCompaction, long checkpointId)
throws IOException;
}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RestoreAndFailCommittableStateManager.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RestoreAndFailCommittableStateManager.java
index 6b5d31a4b..1260be3ef 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RestoreAndFailCommittableStateManager.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RestoreAndFailCommittableStateManager.java
@@ -41,7 +41,8 @@ import java.util.List;
* <p>Useful for committing snapshots containing records. For example snapshots produced by table
* store writers.
*/
-public class RestoreAndFailCommittableStateManager implements CommittableStateManager {
+public class RestoreAndFailCommittableStateManager
+ implements CommittableStateManager<ManifestCommittable> {
private static final long serialVersionUID = 1L;
@@ -59,7 +60,8 @@ public class RestoreAndFailCommittableStateManager implements CommittableStateMa
}
@Override
- public void initializeState(StateInitializationContext context, Committer committer)
+ public void initializeState(
+ StateInitializationContext context, Committer<?, ManifestCommittable> committer)
throws Exception {
streamingCommitterState =
new SimpleVersionedListState<>(
@@ -75,7 +77,8 @@ public class RestoreAndFailCommittableStateManager implements CommittableStateMa
recover(restored, committer);
}
- private void recover(List<ManifestCommittable> committables, Committer committer)
+ private void recover(
+ List<ManifestCommittable> committables, Committer<?, ManifestCommittable> committer)
throws Exception {
committables = committer.filterRecoveredCommittables(committables);
if (!committables.isEmpty()) {
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RowDataStoreWriteOperator.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RowDataStoreWriteOperator.java
index 16f5f98f3..bfdae8760 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RowDataStoreWriteOperator.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RowDataStoreWriteOperator.java
@@ -45,7 +45,7 @@ import java.io.IOException;
import java.util.List;
/** A {@link PrepareCommitOperator} to write {@link RowData}. Record schema is fixed. */
-public class RowDataStoreWriteOperator extends PrepareCommitOperator<RowData> {
+public class RowDataStoreWriteOperator extends PrepareCommitOperator<RowData, Committable> {
private static final long serialVersionUID = 3L;
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StoreCommitter.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StoreCommitter.java
index f3f58d98a..ed564e6e8 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StoreCommitter.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StoreCommitter.java
@@ -24,12 +24,16 @@ import org.apache.paimon.table.sink.TableCommit;
import org.apache.paimon.table.sink.TableCommitImpl;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/** {@link Committer} for dynamic store. */
-public class StoreCommitter implements Committer {
+public class StoreCommitter implements Committer<Committable, ManifestCommittable> {
private final TableCommitImpl commit;
@@ -76,6 +80,15 @@ public class StoreCommitter implements Committer {
commit.commitMultiple(committables);
}
+ @Override
+ public Map<Long, List<Committable>> groupByCheckpoint(Collection<Committable> committables) {
+ Map<Long, List<Committable>> grouped = new HashMap<>();
+ for (Committable c : committables) {
+ grouped.computeIfAbsent(c.checkpointId(), k -> new ArrayList<>()).add(c);
+ }
+ return grouped;
+ }
+
@Override
public void close() throws Exception {
commit.close();
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StoreCompactOperator.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StoreCompactOperator.java
index f1b77cf35..c610c48be 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StoreCompactOperator.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StoreCompactOperator.java
@@ -42,7 +42,7 @@ import static org.apache.paimon.utils.SerializationUtils.deserializeBinaryRow;
* org.apache.paimon.flink.source.CompactorSourceBuilder}. The records will contain partition keys
* in the first few columns, and bucket number in the last column.
*/
-public class StoreCompactOperator extends PrepareCommitOperator<RowData> {
+public class StoreCompactOperator extends PrepareCommitOperator<RowData, Committable> {
private final FileStoreTable table;
private final StoreSinkWrite.Provider storeSinkWriteProvider;
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcMultiplexRecord.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcMultiplexRecord.java
new file mode 100644
index 000000000..7429369df
--- /dev/null
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcMultiplexRecord.java
@@ -0,0 +1,88 @@
+/*
+ * 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.paimon.flink.sink.cdc;
+
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.types.DataField;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.Serializable;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+
+/**
+ * A data change message from the CDC source. Compared to {@link CdcRecord}, MultiplexCdcRecord
+ * contains database and table information.
+ */
+public class CdcMultiplexRecord implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private static final Logger LOG = LoggerFactory.getLogger(CdcMultiplexRecord.class);
+
+ private final String databaseName;
+ private final String tableName;
+ private final CdcRecord record;
+
+ public CdcMultiplexRecord(String databaseName, String tableName, CdcRecord record) {
+ this.databaseName = databaseName;
+ this.tableName = tableName;
+ this.record = record;
+ }
+
+ public static CdcMultiplexRecord fromCdcRecord(
+ String databaseName, String tableName, CdcRecord record) {
+ return new CdcMultiplexRecord(databaseName, tableName, record);
+ }
+
+ public GenericRow projectAsInsert(List<DataField> dataFields) {
+ return record.projectAsInsert(dataFields);
+ }
+
+ public Optional<GenericRow> toGenericRow(List<DataField> dataFields) {
+ return record.toGenericRow(dataFields);
+ }
+
+ public String getDatabaseName() {
+ return databaseName;
+ }
+
+ public String getTableName() {
+ return tableName;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof CdcMultiplexRecord)) {
+ return false;
+ }
+
+ CdcMultiplexRecord that = (CdcMultiplexRecord) o;
+ return Objects.equals(databaseName, that.databaseName)
+ && Objects.equals(tableName, that.tableName)
+ && Objects.equals(record, that.record);
+ }
+
+ @Override
+ public String toString() {
+ return databaseName + "." + tableName + " " + record.toString();
+ }
+}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecord.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecord.java
index cfdf64817..5f7021b68 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecord.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecord.java
@@ -123,6 +123,10 @@ public class CdcRecord implements Serializable {
return Optional.of(genericRow);
}
+ public RowKind getKind() {
+ return kind;
+ }
+
@Override
public boolean equals(Object o) {
if (!(o instanceof CdcRecord)) {
@@ -137,4 +141,8 @@ public class CdcRecord implements Serializable {
public String toString() {
return kind.shortString() + " " + fields;
}
+
+ public Map<String, String> getFields() {
+ return fields;
+ }
}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreWriteOperator.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreMultiWriteOperator.java
similarity index 50%
copy from paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreWriteOperator.java
copy to paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreMultiWriteOperator.java
index 3e9cafeb0..738ee8122 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreWriteOperator.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreMultiWriteOperator.java
@@ -18,14 +18,14 @@
package org.apache.paimon.flink.sink.cdc;
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
import org.apache.paimon.data.GenericRow;
-import org.apache.paimon.flink.sink.Committable;
+import org.apache.paimon.flink.sink.MultiTableCommittable;
import org.apache.paimon.flink.sink.PrepareCommitOperator;
import org.apache.paimon.flink.sink.StateUtils;
import org.apache.paimon.flink.sink.StoreSinkWrite;
import org.apache.paimon.flink.sink.StoreSinkWriteState;
-import org.apache.paimon.options.ConfigOption;
-import org.apache.paimon.options.ConfigOptions;
import org.apache.paimon.table.FileStoreTable;
import org.apache.flink.runtime.state.StateInitializationContext;
@@ -33,74 +33,97 @@ import org.apache.flink.runtime.state.StateSnapshotContext;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import java.io.IOException;
-import java.time.Duration;
+import java.util.HashMap;
+import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
+import java.util.stream.Collectors;
+
+import static org.apache.paimon.flink.sink.cdc.CdcRecordStoreWriteOperator.RETRY_SLEEP_TIME;
/**
* A {@link PrepareCommitOperator} to write {@link CdcRecord}. Record schema may change. If current
* known schema does not fit record schema, this operator will wait for schema changes.
*/
-public class CdcRecordStoreWriteOperator extends PrepareCommitOperator<CdcRecord> {
+public class CdcRecordStoreMultiWriteOperator
+ extends PrepareCommitOperator<CdcMultiplexRecord, MultiTableCommittable> {
private static final long serialVersionUID = 1L;
-
- static final ConfigOption<Duration> RETRY_SLEEP_TIME =
- ConfigOptions.key("cdc.retry-sleep-time")
- .durationType()
- .defaultValue(Duration.ofMillis(500));
-
- private FileStoreTable table;
+ private final long retrySleepMillis;
private final StoreSinkWrite.Provider storeSinkWriteProvider;
private final String initialCommitUser;
- private final long retrySleepMillis;
-
- private transient StoreSinkWriteState state;
- private transient StoreSinkWrite write;
-
- public CdcRecordStoreWriteOperator(
- FileStoreTable table,
+ private final Catalog.Loader catalogLoader;
+ protected Catalog catalog;
+ protected FileStoreTable table;
+ protected Map<Identifier, FileStoreTable> tables;
+ protected StoreSinkWriteState state;
+ protected StoreSinkWrite write;
+ protected Map<Identifier, StoreSinkWrite> writes;
+ protected String commitUser;
+
+ public CdcRecordStoreMultiWriteOperator(
+ Catalog.Loader catalogLoader,
StoreSinkWrite.Provider storeSinkWriteProvider,
String initialCommitUser) {
- this.table = table;
+ this.catalogLoader = catalogLoader;
this.storeSinkWriteProvider = storeSinkWriteProvider;
this.initialCommitUser = initialCommitUser;
- this.retrySleepMillis =
- table.coreOptions().toConfiguration().get(RETRY_SLEEP_TIME).toMillis();
+ this.retrySleepMillis = RETRY_SLEEP_TIME.defaultValue().toMillis();
}
@Override
public void initializeState(StateInitializationContext context) throws Exception {
super.initializeState(context);
+ catalog = catalogLoader.load();
+
// Each job can only have one user name and this name must be consistent across restarts.
// We cannot use job id as commit user name here because user may change job id by creating
// a savepoint, stop the job and then resume from savepoint.
- String commitUser =
+ commitUser =
StateUtils.getSingleValueFromState(
context, "commit_user_state", String.class, initialCommitUser);
- CdcRecordChannelComputer channelComputer = new CdcRecordChannelComputer(table.schema());
- channelComputer.setup(getRuntimeContext().getNumberOfParallelSubtasks());
- state =
- new StoreSinkWriteState(
- context,
- (tableName, partition, bucket) ->
- channelComputer.channel(partition, bucket)
- == getRuntimeContext().getIndexOfThisSubtask());
-
- table = table.copyWithLatestSchema();
- write =
- storeSinkWriteProvider.provide(
- table,
- commitUser,
- state,
- getContainingTask().getEnvironment().getIOManager());
+ // TODO: should use CdcRecordMultiChannelComputer to filter
+ state = new StoreSinkWriteState(context, (tableName, partition, bucket) -> true);
+ tables = new HashMap<>();
+ writes = new HashMap<>();
}
@Override
- public void processElement(StreamRecord<CdcRecord> element) throws Exception {
- CdcRecord record = element.getValue();
+ public void processElement(StreamRecord<CdcMultiplexRecord> element) throws Exception {
+ CdcMultiplexRecord record = element.getValue();
+
+ String databaseName = record.getDatabaseName();
+ String tableName = record.getTableName();
+ Identifier tableId = Identifier.create(databaseName, tableName);
+
+ table = tables.get(tableId);
+ if (table == null) {
+ while (true) {
+ try {
+ table = (FileStoreTable) catalog.getTable(tableId);
+ tables.put(tableId, table);
+ break;
+ } catch (Catalog.TableNotExistException e) {
+ // table not found, waiting until table is created by
+ // upstream operators
+ }
+ Thread.sleep(retrySleepMillis);
+ }
+ }
+
+ write =
+ writes.computeIfAbsent(
+ tableId,
+ id ->
+ storeSinkWriteProvider.provide(
+ table,
+ commitUser,
+ state,
+ getContainingTask().getEnvironment().getIOManager()));
+
Optional<GenericRow> optionalConverted = record.toGenericRow(table.schema().fields());
if (!optionalConverted.isPresent()) {
while (true) {
@@ -109,7 +132,8 @@ public class CdcRecordStoreWriteOperator extends PrepareCommitOperator<CdcRecord
if (optionalConverted.isPresent()) {
break;
}
- Thread.sleep(retrySleepMillis);
+ Thread.sleep(
+ table.coreOptions().toConfiguration().get(RETRY_SLEEP_TIME).toMillis());
}
write.replace(table);
}
@@ -125,19 +149,34 @@ public class CdcRecordStoreWriteOperator extends PrepareCommitOperator<CdcRecord
public void snapshotState(StateSnapshotContext context) throws Exception {
super.snapshotState(context);
- write.snapshotState();
+ for (StoreSinkWrite write : writes.values()) {
+ write.snapshotState();
+ }
state.snapshotState();
}
@Override
public void close() throws Exception {
super.close();
- write.close();
+ for (StoreSinkWrite write : writes.values()) {
+ write.close();
+ }
}
@Override
- protected List<Committable> prepareCommit(boolean doCompaction, long checkpointId)
+ protected List<MultiTableCommittable> prepareCommit(boolean doCompaction, long checkpointId)
throws IOException {
- return write.prepareCommit(doCompaction, checkpointId);
+ List<MultiTableCommittable> committables = new LinkedList<>();
+ for (Map.Entry<Identifier, StoreSinkWrite> entry : writes.entrySet()) {
+ Identifier key = entry.getKey();
+ StoreSinkWrite write = entry.getValue();
+ committables.addAll(
+ write.prepareCommit(doCompaction, checkpointId).stream()
+ .map(
+ committable ->
+ MultiTableCommittable.fromCommittable(key, committable))
+ .collect(Collectors.toList()));
+ }
+ return committables;
}
}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreWriteOperator.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreWriteOperator.java
index 3e9cafeb0..4842a1400 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreWriteOperator.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreWriteOperator.java
@@ -41,7 +41,7 @@ import java.util.Optional;
* A {@link PrepareCommitOperator} to write {@link CdcRecord}. Record schema may change. If current
* known schema does not fit record schema, this operator will wait for schema changes.
*/
-public class CdcRecordStoreWriteOperator extends PrepareCommitOperator<CdcRecord> {
+public class CdcRecordStoreWriteOperator extends PrepareCommitOperator<CdcRecord, Committable> {
private static final long serialVersionUID = 1L;
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/FlinkCdcSink.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/FlinkCdcSink.java
index 43f7efee6..8ef4acc63 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/FlinkCdcSink.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/cdc/FlinkCdcSink.java
@@ -26,6 +26,7 @@ import org.apache.paimon.flink.sink.FlinkSink;
import org.apache.paimon.flink.sink.RestoreAndFailCommittableStateManager;
import org.apache.paimon.flink.sink.StoreCommitter;
import org.apache.paimon.flink.sink.StoreSinkWrite;
+import org.apache.paimon.manifest.ManifestCommittable;
import org.apache.paimon.manifest.ManifestCommittableSerializer;
import org.apache.paimon.operation.Lock;
import org.apache.paimon.table.FileStoreTable;
@@ -54,8 +55,8 @@ public class FlinkCdcSink extends FlinkSink<CdcRecord> {
}
@Override
- protected SerializableFunction<String, Committer> createCommitterFactory(
- boolean streamingCheckpointEnabled) {
+ protected SerializableFunction<String, Committer<Committable, ManifestCommittable>>
+ createCommitterFactory(boolean streamingCheckpointEnabled) {
// If checkpoint is enabled for streaming job, we have to
// commit new files list even if they're empty.
// Otherwise we can't tell if the commit is successful after
@@ -68,7 +69,7 @@ public class FlinkCdcSink extends FlinkSink<CdcRecord> {
}
@Override
- protected CommittableStateManager createCommittableStateManager() {
+ protected CommittableStateManager<ManifestCommittable> createCommittableStateManager() {
return new RestoreAndFailCommittableStateManager(
() -> new VersionedSerializerWrapper<>(new ManifestCommittableSerializer()));
}
diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/CommitterOperatorTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/CommitterOperatorTest.java
index 23da4d0da..b7dcd24f7 100644
--- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/CommitterOperatorTest.java
+++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/CommitterOperatorTest.java
@@ -21,6 +21,7 @@ package org.apache.paimon.flink.sink;
import org.apache.paimon.data.GenericRow;
import org.apache.paimon.flink.VersionedSerializerWrapper;
import org.apache.paimon.fs.local.LocalFileIO;
+import org.apache.paimon.manifest.ManifestCommittable;
import org.apache.paimon.manifest.ManifestCommittableSerializer;
import org.apache.paimon.table.FileStoreTable;
import org.apache.paimon.table.sink.CommitMessage;
@@ -233,8 +234,8 @@ public class CommitterOperatorTest extends CommitterOperatorTestBase {
private OneInputStreamOperatorTestHarness<Committable, Committable>
createRecoverableTestHarness(FileStoreTable table) throws Exception {
- CommitterOperator operator =
- new CommitterOperator(
+ CommitterOperator<Committable, ManifestCommittable> operator =
+ new CommitterOperator<Committable, ManifestCommittable>(
true,
initialCommitUser,
user ->
@@ -251,8 +252,8 @@ public class CommitterOperatorTest extends CommitterOperatorTestBase {
private OneInputStreamOperatorTestHarness<Committable, Committable> createLossyTestHarness(
FileStoreTable table) throws Exception {
- CommitterOperator operator =
- new CommitterOperator(
+ CommitterOperator<Committable, ManifestCommittable> operator =
+ new CommitterOperator<Committable, ManifestCommittable>(
true,
initialCommitUser,
user ->
@@ -265,7 +266,7 @@ public class CommitterOperatorTest extends CommitterOperatorTestBase {
}
private OneInputStreamOperatorTestHarness<Committable, Committable> createTestHarness(
- CommitterOperator operator) throws Exception {
+ CommitterOperator<Committable, ManifestCommittable> operator) throws Exception {
TypeSerializer<Committable> serializer =
new CommittableTypeInfo().createSerializer(new ExecutionConfig());
OneInputStreamOperatorTestHarness<Committable, Committable> harness =
diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/MultiTableCommittableSerializerTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/MultiTableCommittableSerializerTest.java
new file mode 100644
index 000000000..37fcd465a
--- /dev/null
+++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/MultiTableCommittableSerializerTest.java
@@ -0,0 +1,63 @@
+/*
+ * 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.paimon.flink.sink;
+
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.io.CompactIncrement;
+import org.apache.paimon.io.NewFilesIncrement;
+import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.table.sink.CommitMessageImpl;
+import org.apache.paimon.table.sink.CommitMessageSerializer;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+
+import static org.apache.paimon.manifest.ManifestCommittableSerializerTest.randomCompactIncrement;
+import static org.apache.paimon.manifest.ManifestCommittableSerializerTest.randomNewFilesIncrement;
+import static org.apache.paimon.mergetree.compact.MergeTreeCompactManagerTest.row;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class MultiTableCommittableSerializerTest {
+ private final CommitMessageSerializer fileSerializer = new CommitMessageSerializer();
+
+ private final MultiTableCommittableSerializer serializer =
+ new MultiTableCommittableSerializer(fileSerializer);
+
+ @Test
+ public void testFileMetadata() throws IOException {
+ NewFilesIncrement newFilesIncrement = randomNewFilesIncrement();
+ CompactIncrement compactIncrement = randomCompactIncrement();
+ CommitMessage commitMessage =
+ new CommitMessageImpl(row(0), 1, newFilesIncrement, compactIncrement);
+ Committable committable = new Committable(9, Committable.Kind.FILE, commitMessage);
+ String database = "database";
+ String table = "table";
+ MultiTableCommittable multiTableCommittable =
+ MultiTableCommittable.fromCommittable(
+ Identifier.create(database, table), committable);
+ MultiTableCommittable deserializeCommittable =
+ serializer.deserialize(2, serializer.serialize(multiTableCommittable));
+
+ assertThat(deserializeCommittable).isInstanceOf(MultiTableCommittable.class);
+
+ assertThat(deserializeCommittable.getDatabase()).isEqualTo(database);
+ assertThat(deserializeCommittable.getTable()).isEqualTo(table);
+ }
+}
diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreMultiWriteOperatorTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreMultiWriteOperatorTest.java
new file mode 100644
index 000000000..998883fc3
--- /dev/null
+++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/cdc/CdcRecordStoreMultiWriteOperatorTest.java
@@ -0,0 +1,710 @@
+/*
+ * 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.paimon.flink.sink.cdc;
+
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.CatalogContext;
+import org.apache.paimon.catalog.CatalogFactory;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.flink.sink.MultiTableCommittable;
+import org.apache.paimon.flink.sink.MultiTableCommittableTypeInfo;
+import org.apache.paimon.flink.sink.StoreSinkWriteImpl;
+import org.apache.paimon.fs.FileIO;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.options.CatalogOptions;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.schema.SchemaChange;
+import org.apache.paimon.schema.SchemaManager;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.types.DataType;
+import org.apache.paimon.types.DataTypes;
+import org.apache.paimon.types.RowKind;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.utils.TraceableFileIO;
+
+import org.apache.flink.api.common.ExecutionConfig;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.runtime.checkpoint.OperatorSubtaskState;
+import org.apache.flink.runtime.state.JavaSerializer;
+import org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Predicate;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Tests for {@link CdcRecordStoreMultiWriteOperator}. */
+public class CdcRecordStoreMultiWriteOperatorTest {
+
+ @TempDir java.nio.file.Path tempDir;
+
+ private String commitUser;
+ private Path warehouse;
+ private String databaseName;
+ private Identifier firstTable;
+ private Catalog catalog;
+ private Identifier secondTable;
+ private Catalog.Loader catalogLoader;
+ private Schema firstTableSchema;
+
+ @BeforeEach
+ public void before() throws Exception {
+ warehouse = new Path(TraceableFileIO.SCHEME + "://" + tempDir.toString());
+ commitUser = UUID.randomUUID().toString();
+
+ databaseName = "test_db";
+ firstTable = Identifier.create(databaseName, "test_table1");
+ secondTable = Identifier.create(databaseName, "test_table2");
+
+ catalogLoader = createCatalogLoader();
+ catalog = catalogLoader.load();
+ catalog.createDatabase(databaseName, true);
+ Options conf = new Options();
+ conf.set(CdcRecordStoreWriteOperator.RETRY_SLEEP_TIME, Duration.ofMillis(10));
+
+ RowType rowType1 =
+ RowType.of(
+ new DataType[] {DataTypes.INT(), DataTypes.INT(), DataTypes.STRING()},
+ new String[] {"pt", "k", "v"});
+ RowType rowType2 =
+ RowType.of(
+ new DataType[] {
+ DataTypes.INT(),
+ DataTypes.INT(),
+ DataTypes.FLOAT(),
+ DataTypes.VARCHAR(5),
+ DataTypes.VARBINARY(5)
+ },
+ new String[] {"k", "v1", "v2", "v3", "v4"});
+
+ firstTableSchema =
+ new Schema(
+ rowType1.getFields(),
+ Collections.singletonList("pt"),
+ Arrays.asList("pt", "k"),
+ conf.toMap(),
+ "");
+ createTestTables(
+ catalog,
+ Tuple2.of(firstTable, firstTableSchema),
+ Tuple2.of(
+ secondTable,
+ new Schema(
+ rowType2.getFields(),
+ Collections.emptyList(),
+ Collections.singletonList("k"),
+ conf.toMap(),
+ "")));
+ }
+
+ private void createTestTables(Catalog catalog, Tuple2<Identifier, Schema>... tableSpecs)
+ throws Exception {
+
+ for (Tuple2<Identifier, Schema> spec : tableSpecs) {
+ catalog.createTable(spec.f0, spec.f1, false);
+ }
+ }
+
+ @AfterEach
+ public void after() {
+ // assert all connections are closed
+ Predicate<Path> pathPredicate = path -> path.toString().contains(tempDir.toString());
+ assertThat(TraceableFileIO.openInputStreams(pathPredicate)).isEmpty();
+ assertThat(TraceableFileIO.openOutputStreams(pathPredicate)).isEmpty();
+ }
+
+ private static FileIO getFileIO(CatalogContext catalogContext, Path warehouse) {
+ FileIO fileIO;
+ try {
+ fileIO = FileIO.get(warehouse, catalogContext);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ return fileIO;
+ }
+
+ @Test
+ @Timeout(30)
+ public void testAsyncTableCreate() throws Exception {
+ // the async table will have same row type, partitions, and pks as firstTable
+ Identifier tableId = Identifier.create(databaseName, "async_new_table");
+
+ OneInputStreamOperatorTestHarness<CdcMultiplexRecord, MultiTableCommittable> harness =
+ createTestHarness(catalogLoader);
+
+ harness.open();
+
+ Runner runner = new Runner(harness);
+ Thread t = new Thread(runner);
+ t.start();
+
+ // check that records should be processed after table is created
+ Map<String, String> fields = new HashMap<>();
+ fields.put("pt", "0");
+ fields.put("k", "1");
+ fields.put("v", "10");
+
+ CdcMultiplexRecord expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ CdcMultiplexRecord actual = runner.poll(1);
+
+ assertThat(actual).isNull();
+
+ catalog.createTable(tableId, firstTableSchema, true);
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // after table is created, record should be processed immediately
+ fields = new HashMap<>();
+ fields.put("pt", "0");
+ fields.put("k", "3");
+ fields.put("v", "30");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ runner.stop();
+ t.join();
+ harness.close();
+ }
+
+ @Test
+ @Timeout(30)
+ public void testInitializeState() throws Exception {
+ // the async table will have same row type, partitions, and pks as firstTable
+ Identifier tableId = Identifier.create(databaseName, "async_new_table");
+ long timestamp = 1;
+
+ OneInputStreamOperatorTestHarness<CdcMultiplexRecord, MultiTableCommittable> harness =
+ createTestHarness(catalogLoader);
+
+ harness.open();
+
+ Runner runner = new Runner(harness);
+ Thread t = new Thread(runner);
+ t.start();
+
+ // check that records should be processed after table is created
+ Map<String, String> fields = new HashMap<>();
+ fields.put("pt", "0");
+ fields.put("k", "1");
+ fields.put("v", "10");
+
+ CdcMultiplexRecord expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ CdcMultiplexRecord actual = runner.poll(1);
+
+ assertThat(actual).isNull();
+
+ CdcRecordStoreMultiWriteOperator operator =
+ (CdcRecordStoreMultiWriteOperator) harness.getOperator();
+ assertThat(operator.tables.size()).isEqualTo(0);
+ assertThat(operator.writes.size()).isEqualTo(0);
+
+ catalog.createTable(tableId, firstTableSchema, true);
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+ assertThat(operator.tables.size()).isEqualTo(1);
+ assertThat(operator.writes.size()).isEqualTo(1);
+
+ // after table is created, record should be processed immediately
+ fields = new HashMap<>();
+ fields.put("pt", "0");
+ fields.put("k", "3");
+ fields.put("v", "30");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // trigger a snapshot and re-create test harness using a different commit user
+ OperatorSubtaskState snapshot = harness.snapshot(0, timestamp++);
+ String prevCommitUser = commitUser;
+ commitUser = UUID.randomUUID().toString();
+ harness.close();
+
+ harness = createTestHarness(catalogLoader);
+ harness.initializeState(snapshot);
+ operator = (CdcRecordStoreMultiWriteOperator) harness.getOperator();
+
+ assertThat(operator.commitUser).isEqualTo(prevCommitUser);
+
+ runner.stop();
+ t.join();
+ harness.close();
+ }
+
+ @Test
+ @Timeout(30)
+ public void testSingleTableAddColumn() throws Exception {
+
+ Identifier tableId = firstTable;
+ FileStoreTable table = (FileStoreTable) catalog.getTable(tableId);
+
+ OneInputStreamOperatorTestHarness<CdcMultiplexRecord, MultiTableCommittable> harness =
+ createTestHarness(catalogLoader);
+
+ harness.open();
+
+ Runner runner = new Runner(harness);
+ Thread t = new Thread(runner);
+ t.start();
+
+ // check that records with compatible schema can be processed immediately
+
+ Map<String, String> fields = new HashMap<>();
+ fields.put("pt", "0");
+ fields.put("k", "1");
+ fields.put("v", "10");
+
+ CdcMultiplexRecord expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ CdcMultiplexRecord actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ fields = new HashMap<>();
+ fields.put("pt", "0");
+ fields.put("k", "2");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // check that records with new fields should be processed after schema is updated
+
+ fields = new HashMap<>();
+ fields.put("pt", "0");
+ fields.put("k", "3");
+ fields.put("v", "30");
+ fields.put("v2", "300");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.poll(1);
+ assertThat(actual).isNull();
+
+ SchemaManager schemaManager = new SchemaManager(table.fileIO(), table.location());
+ schemaManager.commitChanges(SchemaChange.addColumn("v2", DataTypes.INT()));
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ runner.stop();
+ t.join();
+ harness.close();
+ }
+
+ private Catalog.Loader createCatalogLoader() {
+ Options catalogOptions = createCatalogOptions(warehouse);
+ return () -> CatalogFactory.createCatalog(CatalogContext.create(catalogOptions));
+ }
+
+ private Options createCatalogOptions(Path warehouse) {
+ Options conf = new Options();
+ conf.set(CatalogOptions.WAREHOUSE, warehouse.getPath());
+ conf.set(CatalogOptions.URI, "");
+
+ return conf;
+ }
+
+ @Test
+ @Timeout(30)
+ public void testSingleTableUpdateColumnType() throws Exception {
+ Identifier tableId = secondTable;
+ FileStoreTable table = (FileStoreTable) catalog.getTable(tableId);
+
+ OneInputStreamOperatorTestHarness<CdcMultiplexRecord, MultiTableCommittable> harness =
+ createTestHarness(catalogLoader);
+ harness.open();
+
+ Runner runner = new Runner(harness);
+ Thread t = new Thread(runner);
+ t.start();
+
+ // check that records with compatible schema can be processed immediately
+
+ Map<String, String> fields = new HashMap<>();
+ fields.put("k", "1");
+ fields.put("v1", "10");
+ fields.put("v2", "0.625");
+ fields.put("v3", "one");
+ fields.put("v4", "b_one");
+ CdcMultiplexRecord expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ CdcMultiplexRecord actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // check that records with new fields should be processed after schema is updated
+
+ // int -> bigint
+
+ fields = new HashMap<>();
+ fields.put("k", "2");
+ fields.put("v1", "12345678987654321");
+ fields.put("v2", "0.25");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.poll(1);
+ assertThat(actual).isNull();
+
+ SchemaManager schemaManager = new SchemaManager(table.fileIO(), table.location());
+ schemaManager.commitChanges(SchemaChange.updateColumnType("v1", DataTypes.BIGINT()));
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // float -> double
+
+ fields = new HashMap<>();
+ fields.put("k", "3");
+ fields.put("v1", "100");
+ fields.put("v2", "1.0000000000009095");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.poll(1);
+ assertThat(actual).isNull();
+
+ schemaManager.commitChanges(SchemaChange.updateColumnType("v2", DataTypes.DOUBLE()));
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // varchar(5) -> varchar(10)
+
+ fields = new HashMap<>();
+ fields.put("k", "4");
+ fields.put("v1", "40");
+ fields.put("v3", "long four");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.poll(1);
+ assertThat(actual).isNull();
+
+ schemaManager.commitChanges(SchemaChange.updateColumnType("v3", DataTypes.VARCHAR(10)));
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // varbinary(5) -> varbinary(10)
+
+ fields = new HashMap<>();
+ fields.put("k", "5");
+ fields.put("v1", "50");
+ fields.put("v4", "long five~");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ tableId.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.poll(1);
+ assertThat(actual).isNull();
+
+ schemaManager.commitChanges(SchemaChange.updateColumnType("v4", DataTypes.VARBINARY(10)));
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ runner.stop();
+ t.join();
+ harness.close();
+ }
+
+ @Test
+ @Timeout(30)
+ public void testMultiTableUpdateColumnType() throws Exception {
+ FileStoreTable table1 = (FileStoreTable) catalog.getTable(firstTable);
+ FileStoreTable table2 = (FileStoreTable) catalog.getTable(secondTable);
+
+ OneInputStreamOperatorTestHarness<CdcMultiplexRecord, MultiTableCommittable> harness =
+ createTestHarness(catalogLoader);
+ harness.open();
+
+ Runner runner = new Runner(harness);
+ Thread t = new Thread(runner);
+ t.start();
+
+ // check that records with compatible schema from different tables
+ // can be processed immediately
+
+ Map<String, String> fields;
+
+ // first table record
+ fields = new HashMap<>();
+ fields.put("pt", "0");
+ fields.put("k", "1");
+ fields.put("v", "10");
+
+ CdcMultiplexRecord expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ firstTable.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ CdcMultiplexRecord actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // second table record
+ fields = new HashMap<>();
+ fields.put("k", "1");
+ fields.put("v1", "10");
+ fields.put("v2", "0.625");
+ fields.put("v3", "one");
+ fields.put("v4", "b_one");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ secondTable.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // check that records with new fields should be processed after schema is updated
+
+ // int -> bigint
+ SchemaManager schemaManager;
+ // first table
+ fields = new HashMap<>();
+ fields.put("pt", "1");
+ fields.put("k", "123456789876543211");
+ fields.put("v", "varchar");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ firstTable.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.poll(1);
+ assertThat(actual).isNull();
+
+ schemaManager = new SchemaManager(table1.fileIO(), table1.location());
+ schemaManager.commitChanges(SchemaChange.updateColumnType("k", DataTypes.BIGINT()));
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // second table
+ fields = new HashMap<>();
+ fields.put("k", "2");
+ fields.put("v1", "12345678987654321");
+ fields.put("v2", "0.25");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ secondTable.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.poll(1);
+ assertThat(actual).isNull();
+
+ schemaManager = new SchemaManager(table2.fileIO(), table2.location());
+ schemaManager.commitChanges(SchemaChange.updateColumnType("v1", DataTypes.BIGINT()));
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // below are schema changes only from the second table
+ // float -> double
+
+ fields = new HashMap<>();
+ fields.put("k", "3");
+ fields.put("v1", "100");
+ fields.put("v2", "1.0000000000009095");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ secondTable.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.poll(1);
+ assertThat(actual).isNull();
+
+ schemaManager = new SchemaManager(table2.fileIO(), table2.location());
+ schemaManager.commitChanges(SchemaChange.updateColumnType("v2", DataTypes.DOUBLE()));
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // varchar(5) -> varchar(10)
+
+ fields = new HashMap<>();
+ fields.put("k", "4");
+ fields.put("v1", "40");
+ fields.put("v3", "long four");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ secondTable.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.poll(1);
+ assertThat(actual).isNull();
+
+ schemaManager = new SchemaManager(table2.fileIO(), table2.location());
+ schemaManager.commitChanges(SchemaChange.updateColumnType("v3", DataTypes.VARCHAR(10)));
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ // varbinary(5) -> varbinary(10)
+
+ fields = new HashMap<>();
+ fields.put("k", "5");
+ fields.put("v1", "50");
+ fields.put("v4", "long five~");
+ expected =
+ CdcMultiplexRecord.fromCdcRecord(
+ databaseName,
+ secondTable.getObjectName(),
+ new CdcRecord(RowKind.INSERT, fields));
+ runner.offer(expected);
+ actual = runner.poll(1);
+ assertThat(actual).isNull();
+
+ schemaManager.commitChanges(SchemaChange.updateColumnType("v4", DataTypes.VARBINARY(10)));
+ actual = runner.take();
+ assertThat(actual).isEqualTo(expected);
+
+ runner.stop();
+ t.join();
+ harness.close();
+ }
+
+ private OneInputStreamOperatorTestHarness<CdcMultiplexRecord, MultiTableCommittable>
+ createTestHarness(Catalog.Loader catalogLoader) throws Exception {
+ CdcRecordStoreMultiWriteOperator operator =
+ new CdcRecordStoreMultiWriteOperator(
+ catalogLoader,
+ (t, commitUser, state, ioManager) ->
+ new StoreSinkWriteImpl(
+ t, commitUser, state, ioManager, false, false),
+ commitUser);
+ TypeSerializer<CdcMultiplexRecord> inputSerializer = new JavaSerializer<>();
+ TypeSerializer<MultiTableCommittable> outputSerializer =
+ new MultiTableCommittableTypeInfo().createSerializer(new ExecutionConfig());
+ OneInputStreamOperatorTestHarness<CdcMultiplexRecord, MultiTableCommittable> harness =
+ new OneInputStreamOperatorTestHarness<>(operator, inputSerializer);
+ harness.setup(outputSerializer);
+ return harness;
+ }
+
+ private static class Runner implements Runnable {
+
+ private final OneInputStreamOperatorTestHarness<CdcMultiplexRecord, MultiTableCommittable>
+ harness;
+ private final BlockingQueue<CdcMultiplexRecord> toProcess = new LinkedBlockingQueue<>();
+ private final BlockingQueue<CdcMultiplexRecord> processed = new LinkedBlockingQueue<>();
+ private final AtomicBoolean running = new AtomicBoolean(true);
+
+ private Runner(
+ OneInputStreamOperatorTestHarness<CdcMultiplexRecord, MultiTableCommittable>
+ harness) {
+ this.harness = harness;
+ }
+
+ private void offer(CdcMultiplexRecord record) {
+ toProcess.offer(record);
+ }
+
+ private CdcMultiplexRecord take() throws Exception {
+ return processed.take();
+ }
+
+ private CdcMultiplexRecord poll(long seconds) throws Exception {
+ return processed.poll(seconds, TimeUnit.SECONDS);
+ }
+
+ private void stop() {
+ running.set(false);
+ }
+
+ @Override
+ public void run() {
+ long timestamp = 0;
+ try {
+ while (running.get()) {
+ if (toProcess.isEmpty()) {
+ Thread.sleep(10);
+ continue;
+ }
+
+ CdcMultiplexRecord record = toProcess.poll();
+ harness.processElement(record, ++timestamp);
+ processed.offer(record);
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+}