This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 8dec91b921 [flink] Support metadata references in CDC computed columns
for append only targets (#11101)
8dec91b921 is described below
commit 8dec91b9219ef3dfcb548fe7522e44feca672a07
Author: Muhammad Junaid Muzammil <[email protected]>
AuthorDate: Thu Nov 12 03:57:44 2026 +0000
[flink] Support metadata references in CDC computed columns for append only
targets (#11101)
---
docs/docs/cdc-ingestion/action-configuration.mdx | 7 +
docs/docs/cdc-ingestion/kafka-cdc.mdx | 27 ++
docs/generated/kafka_sync_table.html | 2 +-
.../paimon/flink/action/cdc/ComputedColumn.java | 54 +++-
.../flink/action/cdc/ComputedColumnUtils.java | 15 +
.../flink/action/cdc/SyncTableActionBase.java | 52 +++-
.../cdc/format/AbstractJsonRecordParser.java | 3 +-
.../action/cdc/format/AbstractRecordParser.java | 62 +++-
.../cdc/format/aliyun/AliyunRecordParser.java | 4 +-
.../action/cdc/format/canal/CanalRecordParser.java | 3 +-
.../format/debezium/DebeziumAvroRecordParser.java | 3 +-
.../format/debezium/DebeziumBsonRecordParser.java | 3 +-
.../format/debezium/DebeziumJsonRecordParser.java | 16 +-
.../cdc/format/debezium/DebeziumSchemaUtils.java | 16 +-
.../flink/action/cdc/mysql/MySqlRecordParser.java | 31 +-
.../action/cdc/postgres/PostgresRecordParser.java | 31 +-
.../flink/action/cdc/ComputedColumnUtilsTest.java | 67 +++++
.../cdc/KafkaMetadataComputedColumnTest.java | 249 ++++++++++++++++
.../flink/action/cdc/SyncTableActionBaseTest.java | 315 +++++++++++++++++++++
.../AbstractRecordParserCompatibilityTest.java | 206 ++++++++++++++
.../format/debezium/DebeziumBinaryRecordTest.java | 162 +++++++++++
.../DebeziumRecordParserBeforeImageTest.java | 165 +++++++++++
22 files changed, 1435 insertions(+), 58 deletions(-)
diff --git a/docs/docs/cdc-ingestion/action-configuration.mdx
b/docs/docs/cdc-ingestion/action-configuration.mdx
index 7632220937..c7e7c0cc23 100644
--- a/docs/docs/cdc-ingestion/action-configuration.mdx
+++ b/docs/docs/cdc-ingestion/action-configuration.mdx
@@ -97,6 +97,13 @@ See [Configurations](../maintenance/configurations) for
table and catalog option
Use one `--computed_column` argument per derived field. Expressions reference
source fields and
use Paimon's CDC functions; they are not arbitrary Flink SQL expressions.
+For single-table synchronization into an append-only table without primary
keys, expressions can
+also reference enabled metadata columns. Use the metadata column's name in the
Paimon table,
+including any configured prefix. Metadata references, including dependencies
through other
+computed columns, are rejected for primary-key targets. Metadata columns can
still be stored in
+primary-key tables when computed columns do not depend on them.
+See the [Kafka metadata
example](./kafka-cdc#compute-columns-from-kafka-metadata).
+
For a source with `id` and `create_time`, derive a daily partition as follows:
```bash
diff --git a/docs/docs/cdc-ingestion/kafka-cdc.mdx
b/docs/docs/cdc-ingestion/kafka-cdc.mdx
index 3097ff4254..658dd0aaf7 100644
--- a/docs/docs/cdc-ingestion/kafka-cdc.mdx
+++ b/docs/docs/cdc-ingestion/kafka-cdc.mdx
@@ -151,6 +151,33 @@ Command syntax (square brackets indicate optional
arguments):
<ConfigTable html={kafkaSyncTableHtml} />
+### Compute columns from Kafka metadata
+
+For table synchronization into an append-only table without primary keys,
computed columns can
+reference metadata columns enabled with `--metadata_column`. Include the
configured metadata
+prefix in the expression's field name. For example, for insert-only JSON
records, derive a daily
+partition from the Kafka record timestamp:
+
+```bash
+--kafka_conf value.format=json \
+--metadata_column timestamp \
+--metadata_column_prefix __kafka_ \
+--computed_column 'dt=date_format(__kafka_timestamp,yyyy-MM-dd)' \
+--partition_keys dt
+```
+
+The metadata timestamp is a `TIMESTAMP_LTZ(3)`, so this expression does not
use an epoch precision
+argument. A missing metadata value produces a null computed value.
+
+Source fields and earlier computed columns take precedence over equally named
metadata when
+resolving expression inputs. Use a metadata prefix such as `__kafka_` to avoid
ambiguous names.
+
+Computed columns based on metadata are rejected when the target has primary
keys, including keys
+inferred from the source. Values such as the Kafka record timestamp can change
between inserts,
+updates, and deletes, so they cannot reliably identify a row's original
partition.
+When starting against an existing table with an empty topic, ambiguous
references are checked
+against incoming records once they become available.
+
## Synchronizing Databases
By using
[KafkaSyncDatabaseAction](https://paimon.apache.org/docs/master/api/java/org/apache/paimon/flink/action/cdc/kafka/KafkaSyncDatabaseAction.html)
in a Flink DataStream job or directly through `flink run`, users can route
source tables from one or more topics into a Paimon database.
diff --git a/docs/generated/kafka_sync_table.html
b/docs/generated/kafka_sync_table.html
index f5fbf9d5d3..ac6621240a 100644
--- a/docs/generated/kafka_sync_table.html
+++ b/docs/generated/kafka_sync_table.html
@@ -49,7 +49,7 @@
</tr>
<tr>
<td><h5>--computed_column</h5></td>
- <td>The definitions of computed columns. The argument field is from
Kafka topic's table field name. See <a
href="./action-configuration#computed-functions">here</a> for a complete list
of configurations. </td>
+ <td>The definitions of computed columns. Arguments can reference Kafka
topic table fields. For append-only targets without primary keys, arguments can
also reference enabled metadata columns, including any configured metadata
prefix. See <a href="./action-configuration#computed-functions">here</a> for a
complete list of configurations. </td>
</tr>
<tr>
<td><h5>--metadata_column</h5></td>
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/ComputedColumn.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/ComputedColumn.java
index cb40728485..52599ad537 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/ComputedColumn.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/ComputedColumn.java
@@ -29,6 +29,8 @@ import java.util.Collections;
import java.util.Map;
import java.util.Set;
+import static org.apache.paimon.utils.Preconditions.checkArgument;
+
/**
* A Computed column's value is computed from input columns. Only expression
with at most two inputs
* (with referenced field at the first) is supported currently.
@@ -40,6 +42,7 @@ public class ComputedColumn implements Serializable {
private final String columnName;
private final Expression expression;
private final boolean caseSensitive;
+ private boolean metadataReferencesDisallowed;
public ComputedColumn(String columnName, Expression expression, boolean
caseSensitive) {
this.columnName = columnName;
@@ -82,23 +85,56 @@ public class ComputedColumn implements Serializable {
/** Evaluate binary source fields as text, preserving the existing
expression semantics. */
@Nullable
public String evalFromRecord(Map<String, String> rowData, Set<String>
base64EncodedFields) {
- return eval(referencedValue(rowData, base64EncodedFields));
+ return evalFromRecord(rowData, base64EncodedFields,
Collections.emptyMap());
+ }
+
+ /** Source and previously computed fields take precedence over metadata,
including nulls. */
+ @Nullable
+ public String evalFromRecord(
+ Map<String, String> rowData,
+ Set<String> base64EncodedFields,
+ Map<String, String> metadataValues) {
+ String field = referencedField(rowData);
+ if (field != null) {
+ return eval(
+ decodeBase64IfNeeded(rowData.get(field),
base64EncodedFields.contains(field)));
+ }
+
+ field = referencedField(metadataValues);
+ if (field != null) {
+ checkMetadataReferenceAllowed();
+ return eval(metadataValues.get(field));
+ }
+ return eval(null);
+ }
+
+ void disallowMetadataReferences() {
+ metadataReferencesDisallowed = true;
+ }
+
+ void checkMetadataReferenceAllowed() {
+ checkArgument(
+ !metadataReferencesDisallowed,
+ "Computed column '%s' references metadata column '%s'. "
+ + "Metadata references in computed columns are only
supported for append-only tables without primary keys.",
+ columnName,
+ fieldReference());
}
@Nullable
- private String referencedValue(Map<String, String> rowData, Set<String>
base64EncodedFields) {
+ private String referencedField(Map<String, String> values) {
String reference = fieldReference();
if (reference == null) {
return null;
}
- String value = rowData.get(reference);
- if (caseSensitive || rowData.containsKey(reference)) {
- return decodeBase64IfNeeded(value,
base64EncodedFields.contains(reference));
+ if (values.containsKey(reference)) {
+ return reference;
}
- for (Map.Entry<String, String> entry : rowData.entrySet()) {
- if (reference.equalsIgnoreCase(entry.getKey())) {
- return decodeBase64IfNeeded(
- entry.getValue(),
base64EncodedFields.contains(entry.getKey()));
+ if (!caseSensitive) {
+ for (String field : values.keySet()) {
+ if (reference.equalsIgnoreCase(field)) {
+ return field;
+ }
}
}
return null;
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/ComputedColumnUtils.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/ComputedColumnUtils.java
index c85f33b6aa..99cba9b43b 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/ComputedColumnUtils.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/ComputedColumnUtils.java
@@ -50,6 +50,16 @@ public class ComputedColumnUtils {
*/
public static List<ComputedColumn> buildComputedColumns(
List<String> computedColumnArgs, List<DataField> physicFields,
boolean caseSensitive) {
+ return buildComputedColumns(
+ computedColumnArgs, physicFields, new CdcMetadataConverter[0],
caseSensitive);
+ }
+
+ /** Builds computed columns from physical fields and configured metadata
columns. */
+ public static List<ComputedColumn> buildComputedColumns(
+ List<String> computedColumnArgs,
+ List<DataField> physicFields,
+ CdcMetadataConverter[] metadataConverters,
+ boolean caseSensitive) {
Map<String, DataType> typeMapping =
physicFields.stream()
.collect(
@@ -58,6 +68,11 @@ public class ComputedColumnUtils {
DataField::type,
(v1, v2) -> v2));
+ for (CdcMetadataConverter converter : metadataConverters) {
+ typeMapping.putIfAbsent(
+ toLowerCaseIfNeed(converter.columnName(), caseSensitive),
converter.dataType());
+ }
+
// sort computed column args by dependencies
LinkedHashMap<String, Tuple2<String, String[]>> sortedArgs =
sortComputedColumnArgs(computedColumnArgs, caseSensitive);
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/SyncTableActionBase.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/SyncTableActionBase.java
index c3d2e94bca..f8a23a714b 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/SyncTableActionBase.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/SyncTableActionBase.java
@@ -29,6 +29,7 @@ import
org.apache.paimon.flink.sink.cdc.RichCdcMultiplexRecord;
import org.apache.paimon.flink.sink.cdc.RichCdcMultiplexRecordEventParser;
import org.apache.paimon.schema.Schema;
import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.types.DataField;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
@@ -39,10 +40,13 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
import static
org.apache.paimon.flink.action.cdc.CdcActionCommonUtils.assertSchemaCompatible;
import static
org.apache.paimon.flink.action.cdc.ComputedColumnUtils.buildComputedColumns;
import static org.apache.paimon.utils.Preconditions.checkState;
+import static org.apache.paimon.utils.StringUtils.toLowerCaseIfNeed;
/** Base {@link Action} for synchronizing into one Paimon table. */
public abstract class SyncTableActionBase extends SynchronizationActionBase {
@@ -118,10 +122,16 @@ public abstract class SyncTableActionBase extends
SynchronizationActionBase {
try {
fileStoreTable = (FileStoreTable) catalog.getTable(identifier);
fileStoreTable = alterTableOptions(identifier, fileStoreTable);
+ List<DataField> sourceFields;
try {
Schema retrievedSchema = retrieveSchema();
+ sourceFields = retrievedSchema.fields();
computedColumns =
- buildComputedColumns(computedColumnArgs,
retrievedSchema.fields());
+ buildComputedColumns(
+ computedColumnArgs,
+ retrievedSchema.fields(),
+ metadataConverters,
+ caseSensitive);
Schema paimonSchema = buildPaimonSchema(retrievedSchema);
assertSchemaCompatible(fileStoreTable.schema(),
paimonSchema.fields());
} catch (SchemaRetrievalException e) {
@@ -131,23 +141,61 @@ public abstract class SyncTableActionBase extends
SynchronizationActionBase {
+ "here will use the existed Paimon table
schema to build them. Please make sure "
+ "the Paimon table has defined all the
argument columns used for computed columns.");
// schema evolution will add the computed columns
+ // These fields may include metadata outputs. Runtime
validation resolves ambiguous
+ // references against the actual source record when the topic
becomes available.
+ sourceFields = fileStoreTable.schema().fields();
computedColumns =
buildComputedColumns(
computedColumnArgs,
fileStoreTable.schema().fields(),
+ metadataConverters,
caseSensitive);
// check partition keys and primary keys in case that user
specified them
checkConstraints();
}
+ validateMetadataComputedColumns(fileStoreTable.primaryKeys(),
sourceFields);
} catch (Catalog.TableNotExistException e) {
Schema retrievedSchema = retrieveSchema();
- computedColumns = buildComputedColumns(computedColumnArgs,
retrievedSchema.fields());
+ computedColumns =
+ buildComputedColumns(
+ computedColumnArgs,
+ retrievedSchema.fields(),
+ metadataConverters,
+ caseSensitive);
Schema paimonSchema = buildPaimonSchema(retrievedSchema);
+ validateMetadataComputedColumns(paimonSchema.primaryKeys(),
retrievedSchema.fields());
catalog.createTable(identifier, paimonSchema, false);
fileStoreTable = (FileStoreTable) catalog.getTable(identifier);
}
}
+ private void validateMetadataComputedColumns(
+ List<String> targetPrimaryKeys, List<DataField> sourceFields) {
+ if (targetPrimaryKeys.isEmpty()) {
+ return;
+ }
+
+ Set<String> metadataNames =
+ Arrays.stream(metadataConverters)
+ .map(converter ->
toLowerCaseIfNeed(converter.columnName(), caseSensitive))
+ .collect(Collectors.toSet());
+ Set<String> availableFields =
+ sourceFields.stream()
+ .map(field -> toLowerCaseIfNeed(field.name(),
caseSensitive))
+ .collect(Collectors.toSet());
+ for (ComputedColumn column : computedColumns) {
+ column.disallowMetadataReferences();
+ String reference = column.fieldReference();
+ if (reference != null) {
+ String name = toLowerCaseIfNeed(reference, caseSensitive);
+ if (metadataNames.contains(name) &&
!availableFields.contains(name)) {
+ column.checkMetadataReferenceAllowed();
+ }
+ }
+ availableFields.add(toLowerCaseIfNeed(column.columnName(),
caseSensitive));
+ }
+ }
+
@Override
protected FlatMapFunction<CdcSourceRecord, RichCdcMultiplexRecord>
recordParse() {
return syncJobHandler.provideRecordParser(computedColumns,
typeMapping, metadataConverters);
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/AbstractJsonRecordParser.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/AbstractJsonRecordParser.java
index 5eb80a7151..ee612b672a 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/AbstractJsonRecordParser.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/AbstractJsonRecordParser.java
@@ -104,8 +104,7 @@ public abstract class AbstractJsonRecordParser extends
AbstractRecordParser {
}
return
Objects.toString(entry.getValue());
}));
- evalComputedColumns(rowData, schemaBuilder);
- evalMetadataColumns(rowData, schemaBuilder);
+ evalComputedAndMetadataColumns(rowData, schemaBuilder);
return rowData;
}
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/AbstractRecordParser.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/AbstractRecordParser.java
index 39c20f2ce5..830b63d0dd 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/AbstractRecordParser.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/AbstractRecordParser.java
@@ -36,6 +36,7 @@ import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.Collections;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -116,30 +117,72 @@ public abstract class AbstractRecordParser
protected abstract List<String> extractPrimaryKeys();
- /** generate values for computed columns. */
+ /**
+ * Evaluate against source fields and metadata, then append computed
columns before metadata.
+ */
+ protected void evalComputedAndMetadataColumns(
+ Map<String, String> rowData, CdcSchema.Builder schemaBuilder) {
+ Map<String, String> metadataValues = readMetadataColumns();
+ evalComputedColumns(rowData, schemaBuilder, metadataValues);
+ evalMetadataColumns(rowData, schemaBuilder, metadataValues);
+ }
+
+ /** Generate computed values from source fields for parsers using the
original helper API. */
protected void evalComputedColumns(
Map<String, String> rowData, CdcSchema.Builder schemaBuilder) {
+ evalComputedColumns(rowData, schemaBuilder, Collections.emptyMap());
+ }
+
+ private void evalComputedColumns(
+ Map<String, String> rowData,
+ CdcSchema.Builder schemaBuilder,
+ Map<String, String> metadataValues) {
Set<String> base64EncodedFields =
- computedColumns.isEmpty() ? Collections.emptySet() :
extractBase64EncodedFields();
+ computedColumns.isEmpty()
+ ? Collections.emptySet()
+ : new HashSet<>(extractBase64EncodedFields());
computedColumns.forEach(
computedColumn -> {
- String result = computedColumn.evalFromRecord(rowData,
base64EncodedFields);
+ String result =
+ computedColumn.evalFromRecord(
+ rowData, base64EncodedFields,
metadataValues);
rowData.put(computedColumn.columnName(), result);
+ base64EncodedFields.remove(computedColumn.columnName());
schemaBuilder.column(computedColumn.columnName(),
computedColumn.columnType());
});
}
- /** Extract metadata values using metadata converters. */
+ /** Append metadata outputs for parsers using the original helper API. */
protected void evalMetadataColumns(
Map<String, String> rowData, CdcSchema.Builder schemaBuilder) {
- for (CdcMetadataConverter metadataConverter : metadataConverters) {
- try {
- String value = metadataConverter.read(currentRecord);
+ evalMetadataColumns(rowData, schemaBuilder, readMetadataColumns());
+ }
+
+ private void evalMetadataColumns(
+ Map<String, String> rowData,
+ CdcSchema.Builder schemaBuilder,
+ Map<String, String> metadataValues) {
+ for (CdcMetadataConverter converter : metadataConverters) {
+ if (metadataValues.containsKey(converter.columnName())) {
+ String value = metadataValues.get(converter.columnName());
if (value != null) {
- rowData.put(metadataConverter.columnName(), value);
+ rowData.put(converter.columnName(), value);
}
- schemaBuilder.column(metadataConverter.columnName(),
metadataConverter.dataType());
+ schemaBuilder.column(converter.columnName(),
converter.dataType());
+ }
+ }
+ }
+
+ private Map<String, String> readMetadataColumns() {
+ if (metadataConverters.length == 0) {
+ return Collections.emptyMap();
+ }
+ Map<String, String> metadataValues = new HashMap<>();
+ for (CdcMetadataConverter metadataConverter : metadataConverters) {
+ try {
+ metadataValues.put(
+ metadataConverter.columnName(),
metadataConverter.read(currentRecord));
} catch (UnsupportedOperationException e) {
// This converter doesn't support CdcSourceRecord, skip it
LOG.debug(
@@ -147,6 +190,7 @@ public abstract class AbstractRecordParser
metadataConverter.getClass().getSimpleName());
}
}
+ return metadataValues;
}
/** Handle case sensitivity here. */
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/aliyun/AliyunRecordParser.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/aliyun/AliyunRecordParser.java
index 4f695d11a0..336b5dfa6e 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/aliyun/AliyunRecordParser.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/aliyun/AliyunRecordParser.java
@@ -185,14 +185,14 @@ public class AliyunRecordParser extends
AbstractJsonRecordParser {
DataType paimonDataType =
MySqlTypeUtils.toDataType(typeInfo.f0, typeInfo.f1,
typeInfo.f2, typeMapping);
schemaBuilder.column(originalName, paimonDataType);
+ rowData.put(originalName, null);
}
for (Map.Entry<String, Object> entry : recordMap.entrySet()) {
rowData.put(entry.getKey(), Objects.toString(entry.getValue(),
null));
}
- evalComputedColumns(rowData, schemaBuilder);
- evalMetadataColumns(rowData, schemaBuilder);
+ evalComputedAndMetadataColumns(rowData, schemaBuilder);
return rowData;
}
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/canal/CanalRecordParser.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/canal/CanalRecordParser.java
index 034e6734dd..e895f19817 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/canal/CanalRecordParser.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/canal/CanalRecordParser.java
@@ -180,8 +180,7 @@ public class CanalRecordParser extends
AbstractJsonRecordParser {
}
}
- evalComputedColumns(rowData, schemaBuilder);
- evalMetadataColumns(rowData, schemaBuilder);
+ evalComputedAndMetadataColumns(rowData, schemaBuilder);
return rowData;
}
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumAvroRecordParser.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumAvroRecordParser.java
index 2feacde32b..abfd6ea2fe 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumAvroRecordParser.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumAvroRecordParser.java
@@ -163,8 +163,7 @@ public class DebeziumAvroRecordParser extends
AbstractRecordParser {
schemaBuilder.column(fieldName, avroToPaimonDataType(schema),
field.doc());
}
- evalComputedColumns(resultMap, schemaBuilder);
- evalMetadataColumns(resultMap, schemaBuilder);
+ evalComputedAndMetadataColumns(resultMap, schemaBuilder);
return resultMap;
}
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumBsonRecordParser.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumBsonRecordParser.java
index 23855d249f..eb7f07da45 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumBsonRecordParser.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumBsonRecordParser.java
@@ -140,8 +140,7 @@ public class DebeziumBsonRecordParser extends
DebeziumJsonRecordParser {
schemaBuilder.column(fieldName, DataTypes.STRING());
}
- evalComputedColumns(resultMap, schemaBuilder);
- evalMetadataColumns(resultMap, schemaBuilder);
+ evalComputedAndMetadataColumns(resultMap, schemaBuilder);
return resultMap;
}
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumJsonRecordParser.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumJsonRecordParser.java
index 10333c418f..32bb346a1b 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumJsonRecordParser.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumJsonRecordParser.java
@@ -214,8 +214,20 @@ public class DebeziumJsonRecordParser extends
AbstractJsonRecordParser {
debeziumType, className,
parameters.get(fieldName)));
}
- evalComputedColumns(resultMap, schemaBuilder);
- evalMetadataColumns(resultMap, schemaBuilder);
+ // A nullable source field omitted from the payload must not fall back
to metadata.
+ for (String fieldName : debeziumTypes.keySet()) {
+ if (!recordMap.containsKey(fieldName)) {
+ resultMap.put(fieldName, null);
+ schemaBuilder.column(
+ fieldName,
+ DebeziumSchemaUtils.toDataType(
+ debeziumTypes.get(fieldName),
+ classNames.get(fieldName),
+ parameters.get(fieldName)));
+ }
+ }
+
+ evalComputedAndMetadataColumns(resultMap, schemaBuilder);
return resultMap;
}
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumSchemaUtils.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumSchemaUtils.java
index b5e483caee..b19ec2a32d 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumSchemaUtils.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumSchemaUtils.java
@@ -163,11 +163,8 @@ public class DebeziumSchemaUtils {
return "bytes".equals(debeziumType) && schemaName == null;
}
- /** Collect Base64-encoded source fields, excluding computed and metadata
output columns. */
- public static Set<String> extractBase64EncodedFields(
- DebeziumEvent.Field schema,
- List<ComputedColumn> computedColumns,
- CdcMetadataConverter[] metadataConverters) {
+ /** Collect Base64-encoded source fields before computed and metadata
outputs are added. */
+ public static Set<String> extractBase64EncodedFields(DebeziumEvent.Field
schema) {
Set<String> fields = new HashSet<>();
schema.beforeAndAfterFields()
.forEach(
@@ -176,6 +173,15 @@ public class DebeziumSchemaUtils {
fields.add(name);
}
});
+ return fields;
+ }
+
+ /** Collect Base64-encoded source fields, excluding computed and metadata
output columns. */
+ public static Set<String> extractBase64EncodedFields(
+ DebeziumEvent.Field schema,
+ List<ComputedColumn> computedColumns,
+ CdcMetadataConverter[] metadataConverters) {
+ Set<String> fields = extractBase64EncodedFields(schema);
computedColumns.forEach(column -> fields.remove(column.columnName()));
for (CdcMetadataConverter converter : metadataConverters) {
fields.remove(converter.columnName());
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/mysql/MySqlRecordParser.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/mysql/MySqlRecordParser.java
index 8e0407847f..25d9e24871 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/mysql/MySqlRecordParser.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/mysql/MySqlRecordParser.java
@@ -209,9 +209,13 @@ public class MySqlRecordParser implements
FlatMapFunction<CdcSourceRecord, RichC
}
List<RichCdcMultiplexRecord> records = new ArrayList<>();
- Map<String, String> before = extractRow(root.payload().before());
- if (!before.isEmpty()) {
- records.add(createRecord(RowKind.DELETE, before));
+ JsonNode beforeRow = root.payload().before();
+ // Check the raw image before expression lookup populates absent
source fields with nulls.
+ if (!isNull(beforeRow) && beforeRow.size() > 0) {
+ Map<String, String> before = extractRow(beforeRow);
+ if (!before.isEmpty()) {
+ records.add(createRecord(RowKind.DELETE, before));
+ }
}
Map<String, String> after = extractRow(root.payload().after());
@@ -262,6 +266,7 @@ public class MySqlRecordParser implements
FlatMapFunction<CdcSourceRecord, RichC
JsonNode objectValue = recordRow.get(fieldName);
if (isNull(objectValue)) {
+ resultMap.put(fieldName, null);
continue;
}
@@ -277,23 +282,29 @@ public class MySqlRecordParser implements
FlatMapFunction<CdcSourceRecord, RichC
resultMap.put(fieldName, newValue);
}
+ Map<String, String> metadataValues = new LinkedHashMap<>();
+ for (CdcMetadataConverter metadataConverter : metadataConverters) {
+ metadataValues.put(
+ metadataConverter.columnName(),
+ metadataConverter.read(root.payload().source()));
+ }
+
// generate values of computed columns
Set<String> base64EncodedFields =
- computedColumns.isEmpty() ? Collections.emptySet() :
extractBase64EncodedFields();
+ computedColumns.isEmpty()
+ ? Collections.emptySet()
+ :
DebeziumSchemaUtils.extractBase64EncodedFields(root.schema());
for (ComputedColumn computedColumn : computedColumns) {
resultMap.put(
computedColumn.columnName(),
- computedColumn.evalFromRecord(resultMap,
base64EncodedFields));
+ computedColumn.evalFromRecord(resultMap,
base64EncodedFields, metadataValues));
+ base64EncodedFields.remove(computedColumn.columnName());
// remember the computed column data type for later reference by
other computed columns
schemaBuilder.column(computedColumn.columnName(),
computedColumn.columnType());
}
- for (CdcMetadataConverter metadataConverter : metadataConverters) {
- resultMap.put(
- metadataConverter.columnName(),
- metadataConverter.read(root.payload().source()));
- }
+ resultMap.putAll(metadataValues);
return resultMap;
}
diff --git
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/postgres/PostgresRecordParser.java
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/postgres/PostgresRecordParser.java
index 7d543f9393..d94f92ddf8 100644
---
a/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/postgres/PostgresRecordParser.java
+++
b/paimon-flink/paimon-flink-cdc/src/main/java/org/apache/paimon/flink/action/cdc/postgres/PostgresRecordParser.java
@@ -217,9 +217,13 @@ public class PostgresRecordParser
CdcSchema.Builder schemaBuilder = CdcSchema.newBuilder();
CdcSchema schema = extractSchema(root.schema(), schemaBuilder);
- Map<String, String> before = extractRow(root.payload().before(),
schemaBuilder);
- if (!before.isEmpty()) {
- records.add(createRecord(RowKind.DELETE, before));
+ JsonNode beforeRow = root.payload().before();
+ // Check the raw image before expression lookup populates absent
source fields with nulls.
+ if (!isNull(beforeRow) && beforeRow.size() > 0) {
+ Map<String, String> before = extractRow(beforeRow, schemaBuilder);
+ if (!before.isEmpty()) {
+ records.add(createRecord(RowKind.DELETE, before));
+ }
}
Map<String, String> after = extractRow(root.payload().after(),
schemaBuilder);
@@ -256,6 +260,7 @@ public class PostgresRecordParser
String postgresSqlType = field.getValue().type();
JsonNode objectValue = recordRow.get(fieldName);
if (isNull(objectValue)) {
+ resultMap.put(fieldName, null);
continue;
}
@@ -355,20 +360,26 @@ public class PostgresRecordParser
resultMap.put(fieldName, newValue);
}
+ Map<String, String> metadataValues = new LinkedHashMap<>();
+ for (CdcMetadataConverter metadataConverter : metadataConverters) {
+ metadataValues.put(
+ metadataConverter.columnName(),
+ metadataConverter.read(root.payload().source()));
+ }
+
// generate values of computed columns
Set<String> base64EncodedFields =
- computedColumns.isEmpty() ? Collections.emptySet() :
extractBase64EncodedFields();
+ computedColumns.isEmpty()
+ ? Collections.emptySet()
+ :
DebeziumSchemaUtils.extractBase64EncodedFields(root.schema());
for (ComputedColumn computedColumn : computedColumns) {
resultMap.put(
computedColumn.columnName(),
- computedColumn.evalFromRecord(resultMap,
base64EncodedFields));
+ computedColumn.evalFromRecord(resultMap,
base64EncodedFields, metadataValues));
+ base64EncodedFields.remove(computedColumn.columnName());
}
- for (CdcMetadataConverter metadataConverter : metadataConverters) {
- resultMap.put(
- metadataConverter.columnName(),
- metadataConverter.read(root.payload().source()));
- }
+ resultMap.putAll(metadataValues);
return resultMap;
}
diff --git
a/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/ComputedColumnUtilsTest.java
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/ComputedColumnUtilsTest.java
index a740d41afe..36943d14e2 100644
---
a/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/ComputedColumnUtilsTest.java
+++
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/ComputedColumnUtilsTest.java
@@ -18,10 +18,13 @@
package org.apache.paimon.flink.action.cdc;
+import org.apache.paimon.flink.action.cdc.kafka.KafkaMetadataConverter;
import org.apache.paimon.types.DataField;
import org.apache.paimon.types.DataTypes;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import java.util.Arrays;
import java.util.Collections;
@@ -127,6 +130,70 @@ public class ComputedColumnUtilsTest {
assertEquals("20",
columns.get(1).eval(columns.get(0).eval("2023-03-23")));
}
+ @Test
+ public void testCaseInsensitiveMetadataReference() {
+ CdcMetadataConverter timestamp =
+ new PrefixedMetadataConverter(
+ new KafkaMetadataConverter.TimestampConverter(),
"__kafka_");
+ List<ComputedColumn> columns =
+ buildComputedColumns(
+
Collections.singletonList("dt=date_format(__KAFKA_TIMESTAMP,yyyy-MM-dd)"),
+ Collections.emptyList(),
+ new CdcMetadataConverter[] {timestamp},
+ false);
+
+ assertEquals(
+ "2024-12-30",
+ columns.get(0)
+ .evalFromRecord(
+ Collections.singletonMap(
+ "__kafka_timestamp", "2024-12-30
10:00:00.000")));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testPhysicalFieldTypeTakesPrecedenceOverMetadata(boolean
caseSensitive) {
+ String sourceName = caseSensitive ? "offset" : "OFFSET";
+ ComputedColumn column =
+ buildComputedColumns(
+
Collections.singletonList("s=truncate(offset,2)"),
+ Collections.singletonList(
+ new DataField(0, sourceName,
DataTypes.STRING())),
+ new CdcMetadataConverter[] {
+ new
KafkaMetadataConverter.OffsetConverter()
+ },
+ caseSensitive)
+ .get(0);
+
+ assertEquals(DataTypes.STRING(), column.columnType());
+ assertEquals("so", column.eval("source"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testPhysicalFieldValueTakesPrecedenceOverMetadata(boolean
caseSensitive) {
+ String sourceName = caseSensitive ? "topic" : "TOPIC";
+ ComputedColumn column =
+ buildComputedColumns(
+
Collections.singletonList("s=substring(topic,0)"),
+ Collections.singletonList(
+ new DataField(0, sourceName,
DataTypes.STRING())),
+ caseSensitive)
+ .get(0);
+ Map<String, String> source = new HashMap<>();
+ source.put(sourceName, "source-value");
+ Map<String, String> metadata = Collections.singletonMap("topic",
"wire-topic");
+
+ assertEquals(
+ "source-value", column.evalFromRecord(source,
Collections.emptySet(), metadata));
+ source.put(sourceName, null);
+ assertNull(column.evalFromRecord(source, Collections.emptySet(),
metadata));
+ source.clear();
+ assertEquals(
+ "wire-topic",
+ column.evalFromRecord(source, Collections.singleton("topic"),
metadata));
+ }
+
@Test
public void testCycleReference() {
List<String> calColArgs =
diff --git
a/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/KafkaMetadataComputedColumnTest.java
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/KafkaMetadataComputedColumnTest.java
new file mode 100644
index 0000000000..1d198d270a
--- /dev/null
+++
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/KafkaMetadataComputedColumnTest.java
@@ -0,0 +1,249 @@
+/*
+ * 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.action.cdc;
+
+import org.apache.paimon.flink.action.cdc.format.AbstractRecordParser;
+import org.apache.paimon.flink.action.cdc.format.aliyun.AliyunRecordParser;
+import org.apache.paimon.flink.action.cdc.format.canal.CanalRecordParser;
+import
org.apache.paimon.flink.action.cdc.format.debezium.DebeziumAvroRecordParser;
+import
org.apache.paimon.flink.action.cdc.format.debezium.DebeziumBsonRecordParser;
+import
org.apache.paimon.flink.action.cdc.format.debezium.DebeziumJsonRecordParser;
+import org.apache.paimon.flink.action.cdc.format.json.JsonRecordParser;
+import org.apache.paimon.flink.action.cdc.kafka.KafkaMetadataConverter;
+import org.apache.paimon.flink.sink.cdc.RichCdcMultiplexRecord;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.DataTypes;
+import org.apache.paimon.utils.JsonSerdeUtil;
+
+import
org.apache.paimon.shade.jackson2.com.fasterxml.jackson.databind.JsonNode;
+
+import org.apache.avro.Schema;
+import org.apache.avro.SchemaBuilder;
+import org.apache.avro.generic.GenericData;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.flink.api.common.functions.util.ListCollector;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Stream;
+
+import static
org.apache.paimon.flink.action.cdc.ComputedColumnUtils.buildComputedColumns;
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Kafka metadata must be available when a record's computed columns are
evaluated. */
+class KafkaMetadataComputedColumnTest {
+
+ @ParameterizedTest
+ @MethodSource("formatsAndPrefixes")
+ void testComputedColumnsReferenceMetadata(String format, String prefix)
throws Exception {
+ CdcMetadataConverter timestamp =
+ new PrefixedMetadataConverter(
+ new KafkaMetadataConverter.TimestampConverter(),
prefix);
+ CdcMetadataConverter topic =
+ new PrefixedMetadataConverter(new
KafkaMetadataConverter.TopicConverter(), prefix);
+ List<ComputedColumn> computedColumns =
+ buildComputedColumns(
+ Arrays.asList(
+ "yr=substring(dt,0,4)",
+ "dt=date_format(" + timestamp.columnName() +
",yyyy-MM-dd)",
+ "source=substring(" + topic.columnName() +
",0)"),
+ Arrays.asList(
+ new DataField(0, timestamp.columnName(),
timestamp.dataType()),
+ new DataField(1, topic.columnName(),
topic.dataType())));
+ AbstractRecordParser parser = createParser(format, computedColumns);
+ parser.withMetadataConverters(new CdcMetadataConverter[] {timestamp,
topic});
+ CdcSourceRecord input =
+ new CdcSourceRecord(
+ "test-topic",
+ null,
+ createValue(format),
+ Collections.singletonMap("timestamp", 1700000000000L));
+ String timestampValue = timestamp.read(input);
+ String date = timestampValue.substring(0, 10);
+
+ List<RichCdcMultiplexRecord> records = new ArrayList<>();
+ parser.flatMap(input, new ListCollector<>(records));
+
+ assertThat(records).hasSize(1);
+ assertThat(records.get(0).cdcSchema().fields())
+ .extracting(DataField::name)
+ .containsExactly(
+ format.equals("debezium-bson") ? "_id" : "id",
+ "dt",
+ "source",
+ "yr",
+ timestamp.columnName(),
+ topic.columnName());
+ assertThat(records.get(0).toRichCdcRecord().toCdcRecord().data())
+ .containsEntry(timestamp.columnName(), timestampValue)
+ .containsEntry("dt", date)
+ .containsEntry("yr", date.substring(0, 4))
+ .containsEntry("source", "test-topic");
+
+ // Reuse the parser with a missing timestamp to check null propagation
and stale values.
+ records.clear();
+ parser.flatMap(
+ new CdcSourceRecord("test-topic", null, createValue(format)),
+ new ListCollector<>(records));
+
+ assertThat(records).hasSize(1);
+ assertThat(records.get(0).toRichCdcRecord().toCdcRecord().data())
+ .containsEntry("dt", null)
+ .containsEntry("yr", null)
+ .containsEntry("source", "test-topic");
+ }
+
+ @ParameterizedTest
+ @CsvSource({"true,true", "true,false", "false,true", "false,false"})
+ void testAvroBinarySourceFieldWithMetadataName(boolean caseSensitive,
boolean nullValue) {
+ CdcMetadataConverter topic = new
KafkaMetadataConverter.TopicConverter();
+ String sourceName = caseSensitive ? "topic" : "TOPIC";
+ List<ComputedColumn> columns =
+ buildComputedColumns(
+ Collections.singletonList("s=substring(topic,0)"),
+ Collections.singletonList(new DataField(0, sourceName,
DataTypes.BYTES())),
+ new CdcMetadataConverter[] {topic},
+ caseSensitive);
+ Schema payloadSchema =
+ SchemaBuilder.record("row")
+ .fields()
+ .requiredInt("id")
+ .optionalBytes(sourceName)
+ .endRecord();
+ GenericRecord value = createAvroValue(payloadSchema);
+ ((GenericRecord) value.get("after"))
+ .put(
+ sourceName,
+ nullValue
+ ? null
+ :
ByteBuffer.wrap("source-value".getBytes(StandardCharsets.UTF_8)));
+ AbstractRecordParser parser =
+ new DebeziumAvroRecordParser(TypeMapping.defaultMapping(),
columns)
+ .withMetadataConverters(new CdcMetadataConverter[]
{topic});
+ List<RichCdcMultiplexRecord> records = new ArrayList<>();
+ parser.flatMap(
+ new CdcSourceRecord("wire-topic", null, value), new
ListCollector<>(records));
+
+ assertThat(records).hasSize(1);
+ assertThat(records.get(0).toRichCdcRecord().toCdcRecord().data())
+ .containsEntry("s", nullValue ? null : "source-value");
+ }
+
+ private static Stream<Arguments> formatsAndPrefixes() {
+ return Stream.of(
+ "avro",
+ "json",
+ "debezium-json",
+ "debezium-bson",
+ "canal-json",
+ "aliyun-json")
+ .flatMap(
+ format ->
+ Stream.of("", "__kafka_", "__custom_")
+ .map(prefix -> Arguments.of(format,
prefix)));
+ }
+
+ private static AbstractRecordParser createParser(String format,
List<ComputedColumn> columns) {
+ TypeMapping mapping = TypeMapping.defaultMapping();
+ switch (format) {
+ case "avro":
+ return new DebeziumAvroRecordParser(mapping, columns);
+ case "json":
+ return new JsonRecordParser(mapping, columns);
+ case "debezium-json":
+ return new DebeziumJsonRecordParser(mapping, columns);
+ case "debezium-bson":
+ return new DebeziumBsonRecordParser(mapping, columns);
+ case "canal-json":
+ return new CanalRecordParser(mapping, columns);
+ case "aliyun-json":
+ return new AliyunRecordParser(mapping, columns);
+ default:
+ throw new IllegalArgumentException(format);
+ }
+ }
+
+ private static Object createValue(String format) {
+ switch (format) {
+ case "avro":
+ return createAvroValue();
+ case "json":
+ return json("{\"id\":1}");
+ case "debezium-json":
+ return json("{\"op\":\"c\",\"after\":{\"id\":1}}");
+ case "debezium-bson":
+ return json("{\"op\":\"c\",\"after\":\"{\\\"_id\\\":1}\"}");
+ case "canal-json":
+ return json("{\"type\":\"INSERT\",\"data\":[{\"id\":1}]}");
+ case "aliyun-json":
+ return json(
+
"{\"schema\":{\"primaryKey\":[\"id\"],\"dataColumn\":[{\"name\":\"id\",\"type\":\"INT\"}]},"
+ +
"\"payload\":{\"op\":\"INSERT\",\"after\":{\"dataColumn\":{\"id\":1}}}}");
+ default:
+ throw new IllegalArgumentException(format);
+ }
+ }
+
+ private static JsonNode json(String value) {
+ return JsonSerdeUtil.fromJson(value, JsonNode.class);
+ }
+
+ private static GenericRecord createAvroValue() {
+ Schema payloadSchema =
SchemaBuilder.record("row").fields().requiredInt("id").endRecord();
+ return createAvroValue(payloadSchema);
+ }
+
+ private static GenericRecord createAvroValue(Schema payloadSchema) {
+ Schema sourceSchema =
+ SchemaBuilder.record("source")
+ .fields()
+ .requiredString("db")
+ .requiredString("table")
+ .endRecord();
+ Schema envelopeSchema =
+ SchemaBuilder.record("envelope")
+ .fields()
+ .requiredString("op")
+ .name("after")
+ .type(payloadSchema)
+ .noDefault()
+ .name("source")
+ .type(sourceSchema)
+ .noDefault()
+ .endRecord();
+ GenericRecord payload = new GenericData.Record(payloadSchema);
+ payload.put("id", 1);
+ GenericRecord source = new GenericData.Record(sourceSchema);
+ source.put("db", "test_db");
+ source.put("table", "test_table");
+ GenericRecord envelope = new GenericData.Record(envelopeSchema);
+ envelope.put("op", "c");
+ envelope.put("after", payload);
+ envelope.put("source", source);
+ return envelope;
+ }
+}
diff --git
a/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/SyncTableActionBaseTest.java
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/SyncTableActionBaseTest.java
new file mode 100644
index 0000000000..45f21edd36
--- /dev/null
+++
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/SyncTableActionBaseTest.java
@@ -0,0 +1,315 @@
+/*
+ * 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.action.cdc;
+
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.flink.action.cdc.kafka.KafkaSyncTableAction;
+import org.apache.paimon.flink.sink.cdc.CdcSchema;
+import org.apache.paimon.flink.sink.cdc.RichCdcMultiplexRecord;
+import org.apache.paimon.flink.sink.cdc.UpdatedDataFieldsProcessFunction;
+import org.apache.paimon.options.CatalogOptions;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.schema.FileSystemSchemaManager;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.DataTypes;
+import org.apache.paimon.utils.JsonSerdeUtil;
+
+import
org.apache.paimon.shade.jackson2.com.fasterxml.jackson.databind.JsonNode;
+
+import org.apache.flink.api.common.functions.util.ListCollector;
+import org.apache.flink.configuration.Configuration;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Tests for single-table CDC schema initialization. */
+class SyncTableActionBaseTest {
+
+ @TempDir private Path warehouse;
+
+ @ParameterizedTest
+ @ValueSource(strings = {"", "__kafka_", "__custom_"})
+ void testComputedColumnReferencesMetadata(String prefix) throws Exception {
+ try (TestingKafkaSyncTableAction action = new
TestingKafkaSyncTableAction(warehouse)) {
+ action.withComputedColumnArgs(
+ Collections.singletonList(
+ "dt=date_format(" + prefix +
"timestamp,yyyy-MM-dd)"));
+ action.withMetadataColumnPrefix(prefix);
+ action.withMetadataColumns(Collections.singletonList("timestamp"));
+ action.withPartitionKeys("dt");
+
+ // Create a new target, validate an existing target, then start
with an empty topic.
+ action.beforeBuildingSourceSink();
+ action.beforeBuildingSourceSink();
+ action.failSchemaRetrieval = true;
+ action.beforeBuildingSourceSink();
+
+ assertThat(action.fileStoreTable().schema().fields())
+ .extracting(DataField::name)
+ .containsExactly("id", "dt", prefix + "timestamp");
+
assertThat(action.fileStoreTable().schema().partitionKeys()).containsExactly("dt");
+ assertThat(action.fileStoreTable().primaryKeys()).isEmpty();
+ assertThat(action.computedColumns).hasSize(1);
+ assertThat(action.computedColumns.get(0).fieldReference())
+ .isEqualTo(prefix + "timestamp");
+ assertThat(action.computedColumns.get(0).eval("2026-11-11
12:00:00.000"))
+ .isEqualTo("2026-11-11");
+ assertThat(action.sourceSchema.fields())
+ .extracting(DataField::name)
+ .containsExactly("id");
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"true,true", "true,false", "false,true", "false,false"})
+ void testMetadataComputedColumnsRejectedForNewPrimaryKeyTable(
+ boolean inferPrimaryKey, boolean caseSensitive) throws Exception {
+ try (TestingKafkaSyncTableAction action =
+ new TestingKafkaSyncTableAction(warehouse, caseSensitive)) {
+ if (inferPrimaryKey) {
+ action.sourceSchema =
+ Schema.newBuilder().column("id",
DataTypes.INT()).primaryKey("id").build();
+ } else {
+ action.withPrimaryKeys("id");
+ }
+ String reference = caseSensitive ? "__kafka_timestamp" :
"__KAFKA_TIMESTAMP";
+ action.withMetadataColumnPrefix("__kafka_");
+ action.withMetadataColumns(Collections.singletonList("timestamp"));
+ action.withComputedColumnArgs(
+ Arrays.asList(
+ "yr=substring(dt,0,4)",
+ "dt=date_format(" + reference + ",yyyy-MM-dd)"));
+
+ assertThatThrownBy(action::beforeBuildingSourceSink)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Computed column 'dt'")
+ .hasMessageContaining("metadata column '" + reference +
"'")
+ .hasMessageContaining("only supported for append-only
tables");
+ assertThat(action.tableExists()).isFalse();
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testMetadataComputedColumnsRejectedForExistingPrimaryKeyTable(boolean
emptyTopic)
+ throws Exception {
+ try (TestingKafkaSyncTableAction action = new
TestingKafkaSyncTableAction(warehouse)) {
+ action.withPrimaryKeys("id");
+ action.withMetadataColumns(Collections.singletonList("timestamp"));
+
action.withComputedColumnArgs(Collections.singletonList("dt=substring(id,0)"));
+ action.beforeBuildingSourceSink();
+
assertThat(action.fileStoreTable().primaryKeys()).containsExactly("id");
+
+ // Use the actual target keys even when neither the action nor
source declares any.
+ action.withPrimaryKeys(Collections.emptyList());
+ action.withComputedColumnArgs(
+
Collections.singletonList("dt=date_format(timestamp,yyyy-MM-dd)"));
+ action.failSchemaRetrieval = emptyTopic;
+
+ if (emptyTopic) {
+ // The target schema cannot distinguish a physical timestamp
from metadata. Check
+ // the actual record before allowing the expression to consume
a metadata value.
+ action.beforeBuildingSourceSink();
+ assertThatThrownBy(() -> action.parse("{\"id\":1}"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Computed column 'dt'")
+ .hasMessageContaining("metadata column 'timestamp'")
+ .hasMessageContaining("only supported for append-only
tables");
+ } else {
+ assertThatThrownBy(action::beforeBuildingSourceSink)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Computed column 'dt'")
+ .hasMessageContaining("metadata column 'timestamp'")
+ .hasMessageContaining("only supported for append-only
tables");
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testPhysicalMetadataNameAllowedForExistingPrimaryKeyTable(boolean
caseSensitive)
+ throws Exception {
+ try (TestingKafkaSyncTableAction action =
+ new TestingKafkaSyncTableAction(warehouse, caseSensitive)) {
+ action.sourceSchema =
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .column("topic", DataTypes.STRING())
+ .build();
+ action.withPrimaryKeys("id");
+
action.withComputedColumnArgs(Collections.singletonList("s=substring(topic,0)"));
+ action.beforeBuildingSourceSink();
+
+ action.withPrimaryKeys(Collections.emptyList());
+ action.withMetadataColumns(Collections.singletonList("topic"));
+ action.failSchemaRetrieval = true;
+ action.beforeBuildingSourceSink();
+
+ String sourceName = caseSensitive ? "topic" : "TOPIC";
+ assertThat(
+ action.parse("{\"id\":1,\"" + sourceName +
"\":\"source-value\"}")
+ .toRichCdcRecord()
+ .toCdcRecord()
+ .data())
+ .containsEntry("s", "source-value");
+ }
+ }
+
+ @Test
+ void testSchemaEvolutionKeepsComputedColumnsBeforeMetadata() throws
Exception {
+ try (TestingKafkaSyncTableAction action = new
TestingKafkaSyncTableAction(warehouse)) {
+ action.sourceSchema = Schema.newBuilder().column("id",
DataTypes.STRING()).build();
+ action.beforeBuildingSourceSink();
+
action.withComputedColumnArgs(Collections.singletonList("s=substring(id,0)"));
+ action.withMetadataColumnPrefix("__kafka_");
+ action.withMetadataColumns(Collections.singletonList("timestamp"));
+ action.failSchemaRetrieval = true;
+ action.beforeBuildingSourceSink();
+
+ RichCdcMultiplexRecord record = action.parse("{\"id\":\"1\"}");
+ action.evolveSchema(record.cdcSchema());
+
+ assertThat(action.fileStoreTable().schema().fields())
+ .extracting(DataField::name)
+ .containsExactly("id", "s", "__kafka_timestamp");
+ }
+ }
+
+ @Test
+ void testMetadataComputedColumnsAllowedWhenSourcePrimaryKeysAreDisabled()
throws Exception {
+ try (TestingKafkaSyncTableAction action = new
TestingKafkaSyncTableAction(warehouse)) {
+ action.sourceSchema =
+ Schema.newBuilder().column("id",
DataTypes.INT()).primaryKey("id").build();
+ action.syncPKeysFromSourceSchema(false);
+ action.withMetadataColumns(Collections.singletonList("timestamp"));
+ action.withComputedColumnArgs(
+
Collections.singletonList("dt=date_format(timestamp,yyyy-MM-dd)"));
+
+ action.beforeBuildingSourceSink();
+
+ assertThat(action.fileStoreTable().primaryKeys()).isEmpty();
+ assertThat(action.computedColumns).hasSize(1);
+ }
+ }
+
+ @Test
+ void testUnconfiguredMetadataIsNotAvailableToComputedColumns() throws
Exception {
+ try (TestingKafkaSyncTableAction action = new
TestingKafkaSyncTableAction(warehouse)) {
+ action.withComputedColumnArgs(
+
Collections.singletonList("dt=date_format(__kafka_timestamp,yyyy-MM-dd)"));
+
+ assertThatThrownBy(action::beforeBuildingSourceSink)
+ .isInstanceOf(NullPointerException.class)
+ .hasMessageContaining("Referenced field
'__kafka_timestamp'");
+ }
+ }
+
+ private static class TestingKafkaSyncTableAction extends
KafkaSyncTableAction
+ implements AutoCloseable {
+
+ private Schema sourceSchema = Schema.newBuilder().column("id",
DataTypes.INT()).build();
+ private boolean failSchemaRetrieval;
+
+ private TestingKafkaSyncTableAction(Path warehouse) throws Exception {
+ this(warehouse, true);
+ }
+
+ private TestingKafkaSyncTableAction(Path warehouse, boolean
caseSensitive)
+ throws Exception {
+ super(
+ "test_db",
+ "test_table",
+ new Options()
+ .set(CatalogOptions.WAREHOUSE,
warehouse.toString())
+ .set(CatalogOptions.CASE_SENSITIVE, caseSensitive)
+ .toMap(),
+ Collections.singletonMap("value.format", "json"));
+ catalog.createDatabase(database, true);
+ withTableConfig(Collections.singletonMap("bucket", "-1"));
+ }
+
+ @Override
+ protected Schema retrieveSchema() throws SchemaRetrievalException {
+ if (failSchemaRetrieval) {
+ throw new SchemaRetrievalException("No records available");
+ }
+ return sourceSchema;
+ }
+
+ private boolean tableExists() {
+ try {
+ catalog.getTable(new Identifier(database, table));
+ return true;
+ } catch (Catalog.TableNotExistException e) {
+ return false;
+ }
+ }
+
+ private RichCdcMultiplexRecord parse(String value) throws Exception {
+ List<RichCdcMultiplexRecord> records = new ArrayList<>();
+ recordParse()
+ .flatMap(
+ new CdcSourceRecord(
+ "wire-topic",
+ null,
+ JsonSerdeUtil.fromJson(value,
JsonNode.class),
+ Collections.singletonMap("timestamp",
1700000000000L)),
+ new ListCollector<>(records));
+ assertThat(records).hasSize(1);
+ return records.get(0);
+ }
+
+ private void evolveSchema(CdcSchema schema) throws Exception {
+ Identifier identifier = new Identifier(database, table);
+ UpdatedDataFieldsProcessFunction function =
+ new UpdatedDataFieldsProcessFunction(
+ new FileSystemSchemaManager(
+ fileStoreTable.fileIO(),
fileStoreTable.location()),
+ identifier,
+ catalogLoader(),
+ typeMapping);
+ function.open(new Configuration());
+ try {
+ function.processElement(schema, null, new ListCollector<>(new
ArrayList<>()));
+ } finally {
+ function.close();
+ }
+ fileStoreTable = (FileStoreTable) catalog.getTable(identifier);
+ }
+
+ @Override
+ public void close() throws Exception {
+ catalog.close();
+ }
+ }
+}
diff --git
a/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/format/AbstractRecordParserCompatibilityTest.java
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/format/AbstractRecordParserCompatibilityTest.java
new file mode 100644
index 0000000000..5789dd92de
--- /dev/null
+++
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/format/AbstractRecordParserCompatibilityTest.java
@@ -0,0 +1,206 @@
+/*
+ * 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.action.cdc.format;
+
+import org.apache.paimon.flink.action.cdc.CdcMetadataConverter;
+import org.apache.paimon.flink.action.cdc.CdcSourceRecord;
+import org.apache.paimon.flink.action.cdc.ComputedColumn;
+import org.apache.paimon.flink.action.cdc.kafka.KafkaMetadataConverter;
+import org.apache.paimon.flink.sink.cdc.RichCdcMultiplexRecord;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.DataTypes;
+
+import org.apache.flink.api.common.functions.util.ListCollector;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import javax.tools.DiagnosticCollector;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.ToolProvider;
+
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static
org.apache.paimon.flink.action.cdc.ComputedColumnUtils.buildComputedColumns;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+
+/** Binary compatibility of the protected helpers used by custom CDC format
parsers. */
+class AbstractRecordParserCompatibilityTest {
+
+ @TempDir private Path temporaryDirectory;
+
+ @ParameterizedTest
+ @ValueSource(strings = {"evalComputedColumns", "evalMetadataColumns"})
+ void testLegacyParserHelper(String helperName) throws Exception {
+ Path classesDirectory = compileLegacyParser(helperName);
+ URL[] urls = {classesDirectory.toUri().toURL()};
+ // Resolve the superclass from the running connector, not the
compilation stub.
+ try (URLClassLoader classLoader =
+ new URLClassLoader(urls,
AbstractRecordParser.class.getClassLoader())) {
+ Class<?> legacyClass =
+ classLoader.loadClass(
+
"org.apache.paimon.flink.action.cdc.format.legacy.LegacyRecordParser");
+
assertThat(legacyClass.getSuperclass()).isSameAs(AbstractRecordParser.class);
+ List<ComputedColumn> columns =
+ buildComputedColumns(
+
Collections.singletonList("derived=substring(id,0)"),
+ Collections.singletonList(new DataField(0, "id",
DataTypes.STRING())));
+ AbstractRecordParser parser =
+ (AbstractRecordParser)
+
legacyClass.getConstructor(List.class).newInstance(columns);
+ parser.withMetadataConverters(
+ new CdcMetadataConverter[] {new
KafkaMetadataConverter.TopicConverter()});
+ List<RichCdcMultiplexRecord> records = new ArrayList<>();
+
+ assertThatCode(
+ () ->
+ parser.flatMap(
+ new
CdcSourceRecord("legacy-topic", null, "unused"),
+ new ListCollector<>(records)))
+ .as("Legacy parsers must still be able to call %s",
helperName)
+ .doesNotThrowAnyException();
+
+ boolean computed = helperName.equals("evalComputedColumns");
+ String outputColumn = computed ? "derived" : "topic";
+ assertThat(records).hasSize(1);
+ assertThat(records.get(0).toRichCdcRecord().toCdcRecord().data())
+ .hasSize(2)
+ .containsEntry("id", "source-value")
+ .containsEntry(outputColumn, computed ? "source-value" :
"legacy-topic");
+ assertThat(records.get(0).cdcSchema().fields())
+ .extracting(DataField::name)
+ .containsExactly("id", outputColumn);
+ }
+ }
+
+ private Path compileLegacyParser(String helperName) throws Exception {
+ Path sourceDirectory = temporaryDirectory.resolve("source");
+ Path classesDirectory = temporaryDirectory.resolve("classes");
+ Path legacyBase =
+ sourceDirectory.resolve(
+
"org/apache/paimon/flink/action/cdc/format/AbstractRecordParser.java");
+ Path legacyImplementation =
+ sourceDirectory.resolve(
+
"org/apache/paimon/flink/action/cdc/format/legacy/LegacyRecordParser.java");
+ Files.createDirectories(legacyBase.getParent());
+ Files.createDirectories(legacyImplementation.getParent());
+ Files.createDirectories(classesDirectory);
+
+ // Only the old superclass API is needed to compile a downstream
parser binary.
+ Files.write(
+ legacyBase,
+ Arrays.asList(
+ "package org.apache.paimon.flink.action.cdc.format;",
+ "import java.util.List;",
+ "import java.util.Map;",
+ "import
org.apache.paimon.flink.action.cdc.ComputedColumn;",
+ "import
org.apache.paimon.flink.action.cdc.TypeMapping;",
+ "import org.apache.paimon.flink.sink.cdc.CdcSchema;",
+ "import
org.apache.paimon.flink.sink.cdc.RichCdcMultiplexRecord;",
+ "import org.apache.paimon.types.RowKind;",
+ "public abstract class AbstractRecordParser {",
+ " public AbstractRecordParser(TypeMapping mapping,
List<ComputedColumn> columns) {}",
+ " protected void evalComputedColumns(Map<String,
String> row, CdcSchema.Builder schema) {}",
+ " protected void evalMetadataColumns(Map<String,
String> row, CdcSchema.Builder schema) {}",
+ " protected abstract List<RichCdcMultiplexRecord>
extractRecords();",
+ " protected abstract List<String>
extractPrimaryKeys();",
+ " protected abstract String getTableName();",
+ " protected abstract String getDatabaseName();",
+ " protected abstract String format();",
+ " protected RichCdcMultiplexRecord createRecord(",
+ " RowKind kind, Map<String, String> row,
CdcSchema.Builder schema) { return null; }",
+ "}"),
+ StandardCharsets.UTF_8);
+ Files.write(
+ legacyImplementation,
+ Arrays.asList(
+ "package
org.apache.paimon.flink.action.cdc.format.legacy;",
+ "import java.util.Collections;",
+ "import java.util.LinkedHashMap;",
+ "import java.util.List;",
+ "import java.util.Map;",
+ "import
org.apache.paimon.flink.action.cdc.ComputedColumn;",
+ "import
org.apache.paimon.flink.action.cdc.TypeMapping;",
+ "import
org.apache.paimon.flink.action.cdc.format.AbstractRecordParser;",
+ "import org.apache.paimon.flink.sink.cdc.CdcSchema;",
+ "import
org.apache.paimon.flink.sink.cdc.RichCdcMultiplexRecord;",
+ "import org.apache.paimon.types.DataTypes;",
+ "import org.apache.paimon.types.RowKind;",
+ "public class LegacyRecordParser extends
AbstractRecordParser {",
+ " public LegacyRecordParser(List<ComputedColumn>
columns) {",
+ " super(TypeMapping.defaultMapping(), columns);",
+ " }",
+ " @Override protected List<RichCdcMultiplexRecord>
extractRecords() {",
+ " Map<String, String> row = new LinkedHashMap<>();",
+ " row.put(\"id\", \"source-value\");",
+ " CdcSchema.Builder schema =
CdcSchema.newBuilder();",
+ " schema.column(\"id\", DataTypes.STRING());",
+ " " + helperName + "(row, schema);",
+ " return
Collections.singletonList(createRecord(RowKind.INSERT, row, schema));",
+ " }",
+ " @Override protected List<String>
extractPrimaryKeys() { return Collections.emptyList(); }",
+ " @Override protected String getTableName() { return
\"records\"; }",
+ " @Override protected String getDatabaseName() {
return \"legacy\"; }",
+ " @Override protected String format() { return
\"legacy\"; }",
+ "}"),
+ StandardCharsets.UTF_8);
+
+ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+ assertThat(compiler).as("A JDK compiler is required").isNotNull();
+ DiagnosticCollector<JavaFileObject> diagnostics = new
DiagnosticCollector<>();
+ try (StandardJavaFileManager fileManager =
+ compiler.getStandardFileManager(diagnostics, null,
StandardCharsets.UTF_8)) {
+ boolean compiled =
+ compiler.getTask(
+ null,
+ fileManager,
+ diagnostics,
+ Arrays.asList(
+ "-classpath",
+
System.getProperty("java.class.path"),
+ "-d",
+ classesDirectory.toString(),
+ "-source",
+ "8",
+ "-target",
+ "8",
+ "-proc:none",
+ "-Xlint:-options"),
+ null,
+ fileManager.getJavaFileObjects(
+ legacyBase.toFile(),
legacyImplementation.toFile()))
+ .call();
+ assertThat(compiled)
+ .as("Legacy fixture compilation: %s",
diagnostics.getDiagnostics())
+ .isTrue();
+ }
+ return classesDirectory;
+ }
+}
diff --git
a/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumBinaryRecordTest.java
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumBinaryRecordTest.java
index 195c2ccdb1..025a236397 100644
---
a/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumBinaryRecordTest.java
+++
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumBinaryRecordTest.java
@@ -24,8 +24,11 @@ import
org.apache.paimon.flink.action.cdc.CdcMetadataConverter;
import org.apache.paimon.flink.action.cdc.CdcSourceRecord;
import org.apache.paimon.flink.action.cdc.ComputedColumn;
import org.apache.paimon.flink.action.cdc.Expression;
+import org.apache.paimon.flink.action.cdc.PrefixedMetadataConverter;
import org.apache.paimon.flink.action.cdc.TypeMapping;
+import org.apache.paimon.flink.action.cdc.kafka.KafkaMetadataConverter;
import org.apache.paimon.flink.action.cdc.mysql.MySqlRecordParser;
+import org.apache.paimon.flink.action.cdc.postgres.PostgresRecordParser;
import org.apache.paimon.flink.sink.cdc.CdcRecord;
import org.apache.paimon.flink.sink.cdc.CdcRecordUtils;
import org.apache.paimon.flink.sink.cdc.RichCdcMultiplexRecord;
@@ -50,11 +53,13 @@ import
org.apache.paimon.shade.jackson2.com.fasterxml.jackson.databind.node.Arra
import
org.apache.paimon.shade.jackson2.com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.flink.api.common.functions.FlatMapFunction;
+import org.apache.flink.api.common.functions.util.ListCollector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.Collector;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.ByteBuffer;
@@ -66,6 +71,7 @@ import java.util.Base64;
import java.util.Collections;
import java.util.List;
+import static
org.apache.paimon.flink.action.cdc.ComputedColumnUtils.buildComputedColumns;
import static org.assertj.core.api.Assertions.assertThat;
/** Binary values must survive Debezium parsing, key projection and table
writes. */
@@ -93,6 +99,162 @@ class DebeziumBinaryRecordTest {
assertComputedColumns((bytes, computed) -> parse(format, bytes,
computed));
}
+ @ParameterizedTest
+ @ValueSource(strings = {"mysql", "postgres"})
+ void testComputedColumnsReferenceSourceMetadata(String format) throws
Exception {
+ CdcMetadataConverter[] metadata = {
+ new PrefixedMetadataConverter(
+ new CdcMetadataConverter.DatabaseNameConverter(),
"__source_"),
+ new PrefixedMetadataConverter(
+ new CdcMetadataConverter.TableNameConverter(), "__source_")
+ };
+ List<ComputedColumn> columns =
+ buildComputedColumns(
+ Arrays.asList(
+
"source_db=substring(__source_database_name,0)",
+
"source_table=substring(__source_table_name,0)"),
+ Collections.emptyList(),
+ metadata,
+ true);
+ FlatMapFunction<CdcSourceRecord, RichCdcMultiplexRecord> parser =
+ format.equals("mysql")
+ ? new MySqlRecordParser(
+ new Configuration(),
+ columns,
+ TypeMapping.defaultMapping(),
+ metadata)
+ : new PostgresRecordParser(
+ new Configuration(),
+ columns,
+ TypeMapping.defaultMapping(),
+ metadata);
+ CdcRecord record =
+ collectRecord(
+ parser,
+ jsonValue(ByteBuffer.wrap(new byte[] {0,
(byte) 0xff})).toString())
+ .toRichCdcRecord()
+ .toCdcRecord();
+
+ assertThat(record.data())
+ .containsEntry("source_db", "test")
+ .containsEntry("source_table", "binary_table");
+ assertThat(record.base64EncodedFields()).containsExactly("payload");
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "json,true,value", "json,false,value", "json,true,null",
"json,false,null",
+ "json,true,missing", "json,false,missing", "mysql,true,value",
"mysql,false,value",
+ "mysql,true,null", "mysql,false,null", "mysql,true,missing",
"mysql,false,missing",
+ "postgres,true,value", "postgres,false,value", "postgres,true,null",
"postgres,false,null",
+ "postgres,true,missing", "postgres,false,missing"
+ })
+ void testBinarySourceFieldWithMetadataName(
+ String format, boolean caseSensitive, String sourceValue) throws
Exception {
+ CdcMetadataConverter metadata =
+ format.equals("json")
+ ? new KafkaMetadataConverter.TopicConverter()
+ : new CdcMetadataConverter.TableNameConverter();
+ String sourceName =
+ caseSensitive
+ ? metadata.columnName()
+ :
metadata.columnName().toUpperCase(java.util.Locale.ROOT);
+ List<ComputedColumn> columns =
+ buildComputedColumns(
+ Collections.singletonList("s=substring(" +
metadata.columnName() + ",0)"),
+ Collections.singletonList(new DataField(0, sourceName,
DataTypes.BYTES())),
+ new CdcMetadataConverter[] {metadata},
+ caseSensitive);
+ ObjectNode value =
+ (ObjectNode)
+ jsonValue(
+ sourceValue.equals("value")
+ ? ByteBuffer.wrap(
+
"source-value".getBytes(StandardCharsets.UTF_8))
+ : null);
+ ((ObjectNode)
value.get("schema").get("fields").get(0).get("fields").get(0))
+ .put("field", sourceName);
+ ObjectNode after = (ObjectNode) value.get("payload").get("after");
+ JsonNode binaryValue = after.remove("payload");
+ if (!sourceValue.equals("missing")) {
+ after.set(sourceName, binaryValue);
+ }
+ CdcMetadataConverter[] converters = {metadata};
+ FlatMapFunction<CdcSourceRecord, RichCdcMultiplexRecord> parser;
+ switch (format) {
+ case "mysql":
+ parser =
+ new MySqlRecordParser(
+ new Configuration(),
+ columns,
+ TypeMapping.defaultMapping(),
+ converters);
+ break;
+ case "postgres":
+ parser =
+ new PostgresRecordParser(
+ new Configuration(),
+ columns,
+ TypeMapping.defaultMapping(),
+ converters);
+ break;
+ default:
+ parser =
+ new
DebeziumJsonRecordParser(TypeMapping.defaultMapping(), columns)
+ .withMetadataConverters(converters);
+ }
+ List<RichCdcMultiplexRecord> records = new ArrayList<>();
+ parser.flatMap(
+ new CdcSourceRecord(
+ "wire-topic", null, format.equals("json") ? value :
value.toString()),
+ new ListCollector<>(records));
+
+ assertThat(records).hasSize(1);
+ assertThat(records.get(0).toRichCdcRecord().toCdcRecord().data())
+ .containsEntry("s", sourceValue.equals("value") ?
"source-value" : null);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"json", "mysql", "postgres"})
+ void testComputedColumnReplacingBinarySourceField(String format) throws
Exception {
+ List<ComputedColumn> columns =
+ buildComputedColumns(
+ Arrays.asList("payload=substring(id,0)",
"s=substring(payload,0)"),
+ Arrays.asList(
+ new DataField(0, "payload", DataTypes.BYTES()),
+ new DataField(1, "id", DataTypes.INT())));
+ FlatMapFunction<CdcSourceRecord, RichCdcMultiplexRecord> parser;
+ switch (format) {
+ case "mysql":
+ parser =
+ new MySqlRecordParser(
+ new Configuration(),
+ columns,
+ TypeMapping.defaultMapping(),
+ new CdcMetadataConverter[0]);
+ break;
+ case "postgres":
+ parser =
+ new PostgresRecordParser(
+ new Configuration(),
+ columns,
+ TypeMapping.defaultMapping(),
+ new CdcMetadataConverter[0]);
+ break;
+ default:
+ parser = new
DebeziumJsonRecordParser(TypeMapping.defaultMapping(), columns);
+ }
+ JsonNode value =
+
jsonValue(ByteBuffer.wrap("source-value".getBytes(StandardCharsets.UTF_8)));
+ CdcRecord record =
+ collectRecord(parser, format.equals("json") ? value :
value.toString())
+ .toRichCdcRecord()
+ .toCdcRecord();
+
+ assertThat(record.data()).containsEntry("payload",
"1").containsEntry("s", "1");
+ assertThat(record.base64EncodedFields()).isEmpty();
+ }
+
@Test
void testBinaryAlongsideLogicalTypes() throws Exception {
byte[] bytes = {0, (byte) 0xff, (byte) 0x80, 65};
diff --git
a/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumRecordParserBeforeImageTest.java
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumRecordParserBeforeImageTest.java
new file mode 100644
index 0000000000..442bb2da14
--- /dev/null
+++
b/paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/action/cdc/format/debezium/DebeziumRecordParserBeforeImageTest.java
@@ -0,0 +1,165 @@
+/*
+ * 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.action.cdc.format.debezium;
+
+import org.apache.paimon.data.InternalRow;
+import org.apache.paimon.flink.action.cdc.CdcMetadataConverter;
+import org.apache.paimon.flink.action.cdc.CdcSourceRecord;
+import org.apache.paimon.flink.action.cdc.TypeMapping;
+import org.apache.paimon.flink.action.cdc.mysql.MySqlRecordParser;
+import org.apache.paimon.flink.action.cdc.postgres.PostgresRecordParser;
+import org.apache.paimon.flink.sink.cdc.CdcRecord;
+import org.apache.paimon.flink.sink.cdc.CdcRecordUtils;
+import org.apache.paimon.flink.sink.cdc.RichCdcMultiplexRecord;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.fs.local.LocalFileIO;
+import org.apache.paimon.schema.FileSystemSchemaManager;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.FileStoreTableFactory;
+import org.apache.paimon.table.sink.BatchTableCommit;
+import org.apache.paimon.table.sink.BatchTableWrite;
+import org.apache.paimon.table.sink.BatchWriteBuilder;
+import org.apache.paimon.table.source.ReadBuilder;
+import org.apache.paimon.types.DataTypes;
+import org.apache.paimon.types.RowKind;
+import org.apache.paimon.utils.CloseableIterator;
+
+import org.apache.flink.api.common.functions.FlatMapFunction;
+import org.apache.flink.api.common.functions.util.ListCollector;
+import org.apache.flink.configuration.Configuration;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+
+/** Before-image handling in the native MySQL and PostgreSQL Debezium parsers.
*/
+class DebeziumRecordParserBeforeImageTest {
+
+ @TempDir private java.nio.file.Path temporaryDirectory;
+
+ @ParameterizedTest
+ @CsvSource({"mysql, null", "mysql, {}", "postgres, null", "postgres, {}"})
+ void testUpdateWithoutBeforeImage(String format, String beforeImage)
throws Exception {
+ // The empty-object case is synthetic input supported by the parsers
before null fields
+ // were populated for expression lookup. It must not fabricate a
delete with a null key.
+ List<CdcRecord> records = parseUpdate(format, beforeImage);
+ FileStoreTable table = createPrimaryKeyTable();
+
+ assertThatCode(() -> writeRecords(table, records))
+ .as("An update without a before image must remain writable to
a primary-key table")
+ .doesNotThrowAnyException();
+
assertThat(records).extracting(CdcRecord::kind).containsExactly(RowKind.INSERT);
+ assertThat(records.get(0).data()).containsEntry("id",
"1").containsEntry("value", "new");
+
+ ReadBuilder read = table.newReadBuilder();
+ try (CloseableIterator<InternalRow> rows =
+
read.newRead().createReader(read.newScan().plan()).toCloseableIterator()) {
+ assertThat(rows.hasNext()).isTrue();
+ InternalRow row = rows.next();
+ assertThat(row.getInt(0)).isEqualTo(1);
+ assertThat(row.getString(1).toString()).isEqualTo("new");
+ assertThat(rows.hasNext()).isFalse();
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"mysql, false", "mysql, true", "postgres, false", "postgres,
true"})
+ void testNonEmptyBeforeImageRetainsDelete(String format, boolean
fullBeforeImage)
+ throws Exception {
+ String beforeImage = fullBeforeImage ? "{\"id\":1,\"value\":\"old\"}"
: "{\"id\":1}";
+ List<CdcRecord> records = parseUpdate(format, beforeImage);
+
+ assertThat(records)
+ .extracting(CdcRecord::kind)
+ .containsExactly(RowKind.DELETE, RowKind.INSERT);
+ assertThat(records.get(0).data()).containsEntry("id", "1");
+ if (fullBeforeImage) {
+ assertThat(records.get(0).data()).containsEntry("value", "old");
+ }
+ assertThat(records.get(1).data()).containsEntry("id",
"1").containsEntry("value", "new");
+ }
+
+ private FileStoreTable createPrimaryKeyTable() throws Exception {
+ Path path = new Path(temporaryDirectory.resolve("table").toUri());
+ LocalFileIO fileIO = LocalFileIO.create();
+ Schema schema =
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .column("value", DataTypes.STRING())
+ .primaryKey("id")
+ .option("bucket", "1")
+ .build();
+ new FileSystemSchemaManager(fileIO, path).createTable(schema);
+ return FileStoreTableFactory.create(fileIO, path);
+ }
+
+ private static void writeRecords(FileStoreTable table, List<CdcRecord>
records)
+ throws Exception {
+ BatchWriteBuilder builder = table.newBatchWriteBuilder();
+ try (BatchTableWrite write = builder.newWrite();
+ BatchTableCommit commit = builder.newCommit()) {
+ for (CdcRecord record : records) {
+ write.write(
+ CdcRecordUtils.toGenericRow(record,
table.schema().fields(), true).get());
+ }
+ commit.commit(write.prepareCommit());
+ }
+ }
+
+ private static List<CdcRecord> parseUpdate(String format, String
beforeImage) throws Exception {
+ FlatMapFunction<CdcSourceRecord, RichCdcMultiplexRecord> parser =
+ format.equals("mysql")
+ ? new MySqlRecordParser(
+ new Configuration(),
+ Collections.emptyList(),
+ TypeMapping.defaultMapping(),
+ new CdcMetadataConverter[0])
+ : new PostgresRecordParser(
+ new Configuration(),
+ Collections.emptyList(),
+ TypeMapping.defaultMapping(),
+ new CdcMetadataConverter[0]);
+ String rowFields =
+
"\"fields\":[{\"field\":\"id\",\"type\":\"int32\",\"optional\":false},"
+ +
"{\"field\":\"value\",\"type\":\"string\",\"optional\":true}]";
+ String event =
+ "{\"schema\":{\"type\":\"struct\",\"fields\":["
+ +
"{\"field\":\"before\",\"type\":\"struct\",\"optional\":true,"
+ + rowFields
+ +
"},{\"field\":\"after\",\"type\":\"struct\",\"optional\":true,"
+ + rowFields
+ + "}]},\"payload\":{\"op\":\"u\","
+ +
"\"source\":{\"db\":\"test\",\"table\":\"records\"},\"before\":"
+ + beforeImage
+ + ",\"after\":{\"id\":1,\"value\":\"new\"}}}";
+ List<RichCdcMultiplexRecord> records = new ArrayList<>();
+ parser.flatMap(new CdcSourceRecord(event), new
ListCollector<>(records));
+ return records.stream()
+ .map(record -> record.toRichCdcRecord().toCdcRecord())
+ .collect(Collectors.toList());
+ }
+}