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 2b0ef7c00f [flink] Support physical generated columns in SQL inserts
(#10946)
2b0ef7c00f is described below
commit 2b0ef7c00f346a73cbe086c14e34a90404b3f519
Author: Jingsong Lee <[email protected]>
AuthorDate: Mon Nov 2 21:19:51 2026 +0800
[flink] Support physical generated columns in SQL inserts (#10946)
---
docs/docs/concepts/spec/schema.md | 6 +-
docs/docs/flink/sql-write.mdx | 32 ++
docs/docs/spark/sql-ddl.md | 4 +-
.../paimon/flink/sink/FlinkTableSinkBase.java | 64 +++-
.../flink/sink/GeneratedColumnMapFunction.java | 95 ++++++
.../SupportsRowLevelOperationFlinkTableSink.java | 2 +
.../apache/paimon/flink/GeneratedColumnITCase.java | 373 +++++++++++++++++++++
.../flink/sink/GeneratedColumnMapFunctionTest.java | 115 +++++++
8 files changed, 686 insertions(+), 5 deletions(-)
diff --git a/docs/docs/concepts/spec/schema.md
b/docs/docs/concepts/spec/schema.md
index 44d7ae65f7..e081e454c7 100644
--- a/docs/docs/concepts/spec/schema.md
+++ b/docs/docs/concepts/spec/schema.md
@@ -136,8 +136,10 @@ A top-level field, including a partition field, may define
`generationExpression
Writers compile expressions for omitted columns into Paimon `Transform`
operations once at
initialization. These operations define the automatically generated value,
including CAST
formatting and invalid-input behavior; the write engine's ANSI mode or
implicit CAST rules do
-not change that definition. Spark fills omitted columns through the same
evaluator, including
-source-column defaults, before writing.
+not change that definition. Spark and Flink 1.18+ SQL inserts with an explicit
target column
+list fill omitted generated columns through the same evaluator, including
source-column defaults,
+before writing. Flink automatically fills only nullable generated columns
outside the primary key. See
+[Flink SQL Write](../../flink/sql-write#physical-generated-columns) for
details.
Expressions may reference ordinary top-level fields and compose supported
scalar calls, such as
`YEAR(event_time)`, `UPPER(name)`, `CONCAT(UPPER(name), '-', name)`, and
`DATE_ADD(CAST(event_time AS DATE), days)`. The expression result type must
match the declared
diff --git a/docs/docs/flink/sql-write.mdx b/docs/docs/flink/sql-write.mdx
index 29c1ee00e1..ba173adef5 100644
--- a/docs/docs/flink/sql-write.mdx
+++ b/docs/docs/flink/sql-write.mdx
@@ -79,6 +79,38 @@ expiration, and partition expiration.
For multiple jobs to write the same table, you can refer to [dedicated
compaction job](../maintenance/dedicated-compaction#dedicated-compaction-job)
for more info.
+### Physical Generated Columns
+
+On Flink 1.18 and later, `INSERT INTO` and batch `INSERT OVERWRITE` fill
nullable physical generated
+columns omitted from an explicit target column list. Create their definitions
through
+[Spark DDL](../spark/sql-ddl#generated-columns) or the Java schema builder's
+`generatedColumn(name, type, expression)`; Flink SQL does not provide DDL
syntax for these definitions.
+
+For an existing table with ordinary columns `id`, `name`, `event_time` and
generated columns
+`label = UPPER(name)` and `dt = CAST(event_time AS DATE)`:
+
+```sql
+INSERT INTO events (id, name, event_time)
+VALUES (1, 'hello', TIMESTAMP '2026-10-30 12:00:00');
+
+-- label is stored as 'HELLO', and dt as DATE '2026-10-30'.
+```
+
+Paimon evaluates its stored expressions, applying source-column defaults
before generation.
+Generation happens before partition routing and bucket assignment and supports
ordinary append,
+primary-key, and Data Evolution tables. Explicitly supplied generated values,
including NULL,
+are preserved without evaluating or checking the expression. Static partition
values are also
+treated as supplied.
+
+Flink SQL does not support automatically filling NOT NULL generated columns,
generated primary-key
+columns, or generated partition columns in primary-key tables; supply their
values explicitly.
+Nullable generated partition columns can be filled for ordinary append and
Data Evolution tables.
+Generated-column filling retains the sink's existing changelog and
merge-engine behavior.
+
+`UPDATE` preserves generated values unless explicitly assigned. Flink's
virtual computed columns
+(`column AS expression`) retain their existing semantics. On Flink 1.16 and
1.17, supply all
+physical generated values explicitly because those versions do not expose the
target column list.
+
### Clustering
Clustering groups append-table rows by selected columns to improve data
skipping. This write
diff --git a/docs/docs/spark/sql-ddl.md b/docs/docs/spark/sql-ddl.md
index ba7cefc1d9..88ea8c0fa6 100644
--- a/docs/docs/spark/sql-ddl.md
+++ b/docs/docs/spark/sql-ddl.md
@@ -145,7 +145,9 @@ writer fills in the generated fields and writes the full
table schema. If ordina
also omitted, `withWriteType` uses the underlying writer's partial-column
behavior and generates
no omitted columns. For Data Evolution partial updates, this preserves
unselected column files.
Flink's existing virtual computed columns retain their original semantics;
this feature does not
-add Flink SQL syntax for physical generated columns.
+add Flink SQL syntax for physical generated columns. Flink 1.18 and later can
fill nullable physical
+generated columns omitted from an explicit INSERT target column list; see
+[Flink SQL Write](../flink/sql-write#physical-generated-columns).
Generated definitions and the names and types of their dependencies cannot be
changed after
creation. Use writers that understand this schema attribute; older writers may
ignore it.
diff --git
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkTableSinkBase.java
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkTableSinkBase.java
index da5b8b58eb..ea26f621b2 100644
---
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkTableSinkBase.java
+++
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkTableSinkBase.java
@@ -27,6 +27,7 @@ import org.apache.paimon.flink.utils.ChangelogModeUtils;
import org.apache.paimon.options.Options;
import org.apache.paimon.table.FormatTable;
import org.apache.paimon.table.Table;
+import org.apache.paimon.utils.GeneratedColumnRow;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.table.catalog.ObjectIdentifier;
@@ -34,13 +35,18 @@ import org.apache.flink.table.connector.ChangelogMode;
import org.apache.flink.table.connector.sink.DynamicTableSink;
import org.apache.flink.table.connector.sink.abilities.SupportsOverwrite;
import org.apache.flink.table.connector.sink.abilities.SupportsPartitioning;
+import org.apache.flink.table.data.RowData;
import org.apache.flink.table.factories.DynamicTableFactory;
import org.apache.flink.types.RowKind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.stream.IntStream;
import static org.apache.paimon.CoreOptions.CHANGELOG_PRODUCER;
import static org.apache.paimon.CoreOptions.CLUSTERING_COLUMNS;
@@ -65,6 +71,7 @@ public abstract class FlinkTableSinkBase
protected Map<String, String> staticPartitions = new HashMap<>();
protected boolean overwrite = false;
+ protected boolean rowLevelUpdate = false;
public FlinkTableSinkBase(
ObjectIdentifier tableIdentifier, Table table,
DynamicTableFactory.Context context) {
@@ -131,6 +138,7 @@ public abstract class FlinkTableSinkBase
"Paimon doesn't support streaming INSERT OVERWRITE.");
}
String name = tableIdentifier.asSummaryString();
+ int[] generatedColumns = omittedGeneratedColumns(context);
if (table instanceof FormatTable) {
FormatTable formatTable = (FormatTable) table;
@@ -147,11 +155,19 @@ public abstract class FlinkTableSinkBase
// Do not sink to log store when overwrite mode
return new PaimonDataStreamSinkProvider(
(dataStream) -> {
+ DataStream<RowData> input = dataStream;
+ if (generatedColumns.length > 0) {
+ input =
+ input.map(
+ new GeneratedColumnMapFunction(
+ table.rowType(),
generatedColumns),
+ input.getType())
+ .name("Paimon generated columns");
+ }
FlinkSinkBuilder builder = createSinkBuilder();
builder.forRowData(
new DataStream<>(
- dataStream.getExecutionEnvironment(),
- dataStream.getTransformation()));
+ input.getExecutionEnvironment(),
input.getTransformation()));
if (!conf.get(CLUSTERING_INCREMENTAL)
||
conf.get(CLUSTERING_INCREMENTAL_OPTIMIZE_WRITE)) {
builder.clusteringIfPossible(
@@ -170,6 +186,49 @@ public abstract class FlinkTableSinkBase
table);
}
+ private int[] omittedGeneratedColumns(Context context) {
+ if (rowLevelUpdate ||
!GeneratedColumnRow.hasGeneratedColumns(table.rowType())) {
+ return new int[0];
+ }
+ int[][] targets;
+ try {
+ // Flink 1.16 and 1.17 do not expose target columns. Keep their
full-row writes working.
+ targets = context.getTargetColumns().orElse(null);
+ } catch (NoSuchMethodError e) {
+ return new int[0];
+ }
+ if (targets == null || targets.length == 0) {
+ return new int[0];
+ }
+ List<String> columnNames =
+
this.context.getCatalogTable().getResolvedSchema().getColumnNames();
+ Set<String> supplied = new HashSet<>(staticPartitions.keySet());
+ for (int[] path : targets) {
+ // Target paths include virtual columns, while the runtime row
contains physical ones.
+ supplied.add(columnNames.get(path[0]));
+ }
+ int[] omitted =
+ IntStream.range(0, table.rowType().getFieldCount())
+ .filter(
+ i ->
+
table.rowType().getFields().get(i).generationExpression()
+ != null)
+ .filter(i ->
!supplied.contains(table.rowType().getFields().get(i).name()))
+ .toArray();
+ for (int index : omitted) {
+ String name = table.rowType().getFields().get(index).name();
+ if (table.primaryKeys().contains(name)
+ || (!table.primaryKeys().isEmpty() &&
table.partitionKeys().contains(name))) {
+ throw new UnsupportedOperationException(
+ "Flink SQL does not support omitting generated column
'"
+ + name
+ + "' used as a primary key or partition column
in a primary-key table. "
+ + "Supply its value explicitly.");
+ }
+ }
+ return omitted;
+ }
+
protected FlinkSinkBuilder createSinkBuilder() {
return new FlinkSinkBuilder(table);
}
@@ -179,6 +238,7 @@ public abstract class FlinkTableSinkBase
FlinkTableSink copied = new FlinkTableSink(tableIdentifier, table,
context);
copied.staticPartitions = new HashMap<>(staticPartitions);
copied.overwrite = overwrite;
+ copied.rowLevelUpdate = rowLevelUpdate;
return copied;
}
diff --git
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/GeneratedColumnMapFunction.java
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/GeneratedColumnMapFunction.java
new file mode 100644
index 0000000000..ee3e030fd7
--- /dev/null
+++
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/GeneratedColumnMapFunction.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.paimon.flink.sink;
+
+import org.apache.paimon.flink.FlinkRowDataWithBlob;
+import org.apache.paimon.flink.FlinkRowWrapper;
+import org.apache.paimon.flink.ProjectedRowData;
+import org.apache.paimon.types.BlobType;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.utils.GeneratedColumnRow;
+
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+
+import java.util.BitSet;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.IntStream;
+
+import static org.apache.paimon.flink.LogicalTypeConversion.toLogicalType;
+
+/** Fills omitted physical generated columns before partitioning and bucket
assignment. */
+class GeneratedColumnMapFunction implements MapFunction<RowData, RowData> {
+
+ private final RowType rowType;
+ private final int[] generatedColumns;
+
+ private transient GeneratedColumnRow generator;
+ private transient ProjectedRowData inputProjection;
+ private transient RowData.FieldGetter[] getters;
+ private transient FlinkRowDataWithBlob generatedRow;
+
+ GeneratedColumnMapFunction(RowType rowType, int[] generatedColumns) {
+ this.rowType = rowType;
+ this.generatedColumns = generatedColumns;
+ }
+
+ private void initialize() {
+ BitSet omitted = new BitSet(rowType.getFieldCount());
+ for (int index : generatedColumns) {
+ omitted.set(index);
+ }
+ int[] inputFields =
+ IntStream.range(0, rowType.getFieldCount()).filter(i ->
!omitted.get(i)).toArray();
+ inputProjection = ProjectedRowData.from(inputFields);
+ generator = new GeneratedColumnRow(rowType,
rowType.project(inputFields));
+ getters = new RowData.FieldGetter[rowType.getFieldCount()];
+ Set<Integer> blobFields = new HashSet<>();
+ for (int i = 0; i < getters.length; i++) {
+ getters[i] =
+
RowData.createFieldGetter(toLogicalType(rowType.getTypeAt(i)).copy(true), i);
+ if (BlobType.isBlobFileField(rowType.getTypeAt(i))) {
+ blobFields.add(i);
+ }
+ }
+ generatedRow = new FlinkRowDataWithBlob(null, blobFields, true);
+ }
+
+ @Override
+ public RowData map(RowData row) {
+ if (generator == null) {
+ initialize();
+ }
+ // Remove only omitted generated columns; supplied columns, including
NULLs, stay in input.
+ generatedRow.replace(
+ generator.replaceRow(new
FlinkRowWrapper(inputProjection.replaceRow(row))));
+ GenericRowData result = new GenericRowData(row.getRowKind(),
getters.length);
+ // Preserve Flink's representation of supplied columns, including BLOB
bytes and nested
+ // rows.
+ for (int i = 0; i < getters.length; i++) {
+ result.setField(i, getters[i].getFieldOrNull(row));
+ }
+ for (int index : generatedColumns) {
+ result.setField(index,
getters[index].getFieldOrNull(generatedRow));
+ }
+ return result;
+ }
+}
diff --git
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java
index 8e80038ecd..1db6769e91 100644
---
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java
+++
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/SupportsRowLevelOperationFlinkTableSink.java
@@ -86,6 +86,7 @@ public abstract class SupportsRowLevelOperationFlinkTableSink
extends FlinkTable
FlinkTableSink copied = new FlinkTableSink(tableIdentifier, table,
context);
copied.staticPartitions = new HashMap<>(staticPartitions);
copied.overwrite = overwrite;
+ copied.rowLevelUpdate = rowLevelUpdate;
copied.deletePredicate = deletePredicate;
copied.dataEvolutionDeleteSnapshotId = dataEvolutionDeleteSnapshotId;
return copied;
@@ -94,6 +95,7 @@ public abstract class SupportsRowLevelOperationFlinkTableSink
extends FlinkTable
@Override
public RowLevelUpdateInfo applyRowLevelUpdate(
List<Column> updatedColumns, @Nullable
RowLevelModificationScanContext context) {
+ rowLevelUpdate = true;
// Since only UPDATE_AFTER type messages can be received at present,
// AppendOnlyFileStoreTable cannot correctly handle old data, so they
are marked as
// unsupported. Similarly, it is not allowed to update the primary key
column when updating
diff --git
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/GeneratedColumnITCase.java
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/GeneratedColumnITCase.java
new file mode 100644
index 0000000000..4f984910af
--- /dev/null
+++
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/GeneratedColumnITCase.java
@@ -0,0 +1,373 @@
+/*
+ * 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;
+
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.types.DataTypes;
+
+import org.apache.flink.table.planner.factories.TestValuesTableFactory;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledIf;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.time.LocalDate;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Tests physical generated columns written through Flink SQL. */
+@EnabledIf("supportsTargetColumns")
+class GeneratedColumnITCase extends CatalogITCaseBase {
+
+ static boolean supportsTargetColumns() {
+ return isFlinkVersionGreaterThanOrEqualTo("1.18");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"append", "primary-key", "data-evolution"})
+ void testOmittedGeneratedColumns(String mode) throws Exception {
+ Schema.Builder builder =
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .column("name", DataTypes.STRING(), null, "default")
+ .column("ts", DataTypes.TIMESTAMP(3))
+ .generatedColumn("label", DataTypes.STRING(),
"UPPER(name)")
+ .generatedColumn("dt", DataTypes.DATE(), "CAST(ts AS
DATE)");
+ if (mode.equals("primary-key")) {
+ builder.primaryKey("id", "ts").partitionKeys("ts");
+ } else {
+ builder.partitionKeys("dt");
+ }
+ if (mode.equals("data-evolution")) {
+ builder.option("row-tracking.enabled", "true")
+ .option("data-evolution.enabled", "true")
+ .option("bucket", "-1");
+ }
+ createTable("events", builder.build());
+
+ tEnv.executeSql(
+ "INSERT INTO events (ts, name, id) VALUES "
+ + "(TIMESTAMP '2026-10-30 12:00:00', 'hello',
1)")
+ .await();
+ tEnv.executeSql("INSERT INTO events (id, ts) SELECT 2, TIMESTAMP
'2026-10-31 23:59:59.999'")
+ .await();
+
+ assertThat(sql("SELECT id, name, label, dt FROM events"))
+ .containsExactlyInAnyOrder(
+ Row.of(1, "hello", "HELLO", LocalDate.of(2026, 10,
30)),
+ Row.of(2, "default", "DEFAULT", LocalDate.of(2026, 10,
31)));
+ assertThat(sql("SELECT id FROM events WHERE dt = DATE '2026-10-30'"))
+ .containsExactly(Row.of(1));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"append, DATE", "append, STRING", "data-evolution, DATE",
"data-evolution, STRING"})
+ void testStringEventDayPartition(String mode, String partitionType) throws
Exception {
+ boolean datePartition = partitionType.equals("DATE");
+ Schema.Builder builder =
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .column("event_day", DataTypes.STRING())
+ .column("payload", DataTypes.STRING())
+ .generatedColumn(
+ "dt",
+ datePartition ? DataTypes.DATE() :
DataTypes.STRING(),
+ datePartition
+ ? "CAST(event_day AS DATE)"
+ : "CAST(CAST(event_day AS DATE) AS
STRING)")
+ .partitionKeys("dt");
+ if (mode.equals("data-evolution")) {
+ builder.option("row-tracking.enabled", "true")
+ .option("data-evolution.enabled", "true")
+ .option("bucket", "-1");
+ }
+ createTable("events", builder.build());
+
+ // The same id on different business dates must stay in separate
partitions.
+ tEnv.executeSql(
+ "INSERT INTO events (event_day, payload, id) VALUES "
+ + "('2025-12-31', 'initial', 1), ('2026-1-1',
'next-day', 1)")
+ .await();
+ // A late record must return to its business-date partition.
+ tEnv.executeSql(
+ "INSERT INTO events (id, event_day, payload) "
+ + "SELECT 1, '2025-12-31', 'late'")
+ .await();
+
+ Object previousDay = datePartition ? LocalDate.of(2025, 12, 31) :
"2025-12-31";
+ Object nextDay = datePartition ? LocalDate.of(2026, 1, 1) :
"2026-01-01";
+ List<Row> previousPartition = new ArrayList<>();
+ previousPartition.add(Row.of(1, "2025-12-31", "late", previousDay));
+ previousPartition.add(Row.of(1, "2025-12-31", "initial", previousDay));
+ Row nextPartition = Row.of(1, "2026-1-1", "next-day", nextDay);
+ List<Row> expected = new ArrayList<>(previousPartition);
+ expected.add(nextPartition);
+ assertThat(sql("SELECT * FROM
events")).containsExactlyInAnyOrderElementsOf(expected);
+ assertThat(
+ sql(
+ "SELECT * FROM events WHERE dt =
%s'2025-12-31'",
+ datePartition ? "DATE " : ""))
+ .containsExactlyInAnyOrderElementsOf(previousPartition);
+ assertThat(
+ sql(
+ "SELECT * FROM events WHERE dt =
%s'2026-01-01'",
+ datePartition ? "DATE " : ""))
+ .containsExactly(nextPartition);
+ assertThat(sql("SELECT `partition` FROM events$partitions"))
+ .containsExactlyInAnyOrder(Row.of("dt=2025-12-31"),
Row.of("dt=2026-01-01"));
+ }
+
+ @Test
+ void testSuppliedGeneratedValuesAndNulls() throws Exception {
+ createTable(
+ "numbers",
+ Schema.newBuilder()
+ .column("text", DataTypes.STRING())
+ .generatedColumn("number", DataTypes.INT(), "CAST(text
AS INT)")
+ .generatedColumn("label", DataTypes.STRING(),
"UPPER(text)")
+ .build());
+
+ tEnv.executeSql(
+ "INSERT INTO numbers VALUES ('invalid', 42,
'supplied'), "
+ + "('invalid', CAST(NULL AS INT), CAST(NULL AS
STRING))")
+ .await();
+ tEnv.executeSql("INSERT INTO numbers (text, number) VALUES ('still
invalid', 7)").await();
+ tEnv.executeSql("INSERT INTO numbers (text) VALUES ('123'), (CAST(NULL
AS STRING))")
+ .await();
+
+ assertThat(sql("SELECT * FROM numbers"))
+ .containsExactlyInAnyOrder(
+ Row.of("invalid", 42, "supplied"),
+ Row.of("invalid", null, null),
+ Row.of("still invalid", 7, "STILL INVALID"),
+ Row.of("123", 123, "123"),
+ Row.of(null, null, null));
+ }
+
+ @Test
+ void testStreamingInsertAndUpdatePreserveSuppliedColumns() throws
Exception {
+ createTable(
+ "events",
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .column("name", DataTypes.STRING())
+ .generatedColumn("label", DataTypes.STRING(),
"UPPER(name)")
+ .primaryKey("id")
+ .build());
+
+ sEnv.executeSql("INSERT INTO events (id, name) VALUES (1,
'hello')").await();
+ assertThat(sql("SELECT * FROM events")).containsExactly(Row.of(1,
"hello", "HELLO"));
+ tEnv.executeSql("UPDATE events SET name = 'changed' WHERE id =
1").await();
+
+ assertThat(sql("SELECT * FROM events"))
+ .containsExactly(Row.ofKind(RowKind.UPDATE_AFTER, 1,
"changed", "HELLO"));
+ }
+
+ @Test
+ void testStaticGeneratedPartitionAndOverwrite() throws Exception {
+ createTable(
+ "events",
+ Schema.newBuilder()
+ .column("name", DataTypes.STRING())
+ .generatedColumn("label", DataTypes.STRING(),
"UPPER(name)")
+ .generatedColumn("part", DataTypes.STRING(),
"LOWER(name)")
+ .partitionKeys("part")
+ .build());
+
+ tEnv.executeSql("INSERT INTO events PARTITION (part = 'fixed') (name)
VALUES ('Hello')")
+ .await();
+ assertThat(sql("SELECT * FROM
events")).containsExactly(Row.of("Hello", "HELLO", "fixed"));
+ tEnv.executeSql("INSERT OVERWRITE events PARTITION (part = 'fixed')
(name) SELECT 'World'")
+ .await();
+ assertThat(sql("SELECT * FROM
events")).containsExactly(Row.of("World", "WORLD", "fixed"));
+ }
+
+ @Test
+ void testNotNullGeneratedColumnMustBeSupplied() throws Exception {
+ createTable(
+ "events",
+ Schema.newBuilder()
+ .column("name", DataTypes.STRING())
+ .generatedColumn("label",
DataTypes.STRING().notNull(), "UPPER(name)")
+ .build());
+
+ assertThat(
+ tEnv.from("events")
+ .getResolvedSchema()
+ .getColumn("label")
+ .get()
+ .getDataType()
+ .getLogicalType()
+ .isNullable())
+ .isFalse();
+ assertThatThrownBy(
+ () -> tEnv.executeSql("INSERT INTO events (name)
VALUES ('hello')").await())
+ .hasStackTraceContaining("Column 'label'");
+ assertThat(sql("SELECT * FROM events")).isEmpty();
+
+ tEnv.executeSql("INSERT INTO events VALUES ('hello',
'supplied')").await();
+ assertThat(sql("SELECT * FROM
events")).containsExactly(Row.of("hello", "supplied"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"unpartitioned", "partitioned", "cross-partition"})
+ void testGeneratedPrimaryKeyOrPartitionCannotBeOmitted(String mode) throws
Exception {
+ Schema.Builder builder =
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .column("event_day", DataTypes.STRING())
+ .generatedColumn("dt", DataTypes.DATE(),
"CAST(event_day AS DATE)")
+ .option("primary-key.nullable", "true");
+ if (mode.equals("cross-partition")) {
+ builder.primaryKey("id").option("bucket", "-1");
+ } else {
+ builder.primaryKey("id", "dt");
+ }
+ if (!mode.equals("unpartitioned")) {
+ builder.partitionKeys("dt");
+ }
+ createTable("events", builder.build());
+
+ // Even nullable primary keys must not silently receive Flink's NULL
placeholder.
+ assertThatThrownBy(
+ () ->
+ tEnv.executeSql(
+ "INSERT INTO events (id, event_day)
VALUES (1, '2026-11-02')"))
+ .hasStackTraceContaining("does not support omitting generated
column 'dt'");
+ assertThat(sql("SELECT * FROM events")).isEmpty();
+ // Explicit values remain ordinary physical writes, without evaluating
the expression.
+ tEnv.executeSql("INSERT INTO events VALUES (1, 'invalid', DATE
'2026-11-02')").await();
+ assertThat(sql("SELECT * FROM events"))
+ .containsExactly(Row.of(1, "invalid", LocalDate.of(2026, 11,
2)));
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "first-row, false",
+ "first-row, true",
+ "partial-update, false",
+ "partial-update, true"
+ })
+ void testUpdatingInsertPreservesMergeEngineSemantics(
+ String mergeEngine, boolean omitGeneratedColumn) throws Exception {
+ createTable(
+ "events",
+ Schema.newBuilder()
+ .column("name", DataTypes.STRING())
+ .column("cnt", DataTypes.BIGINT())
+ .generatedColumn("label", DataTypes.STRING(),
"UPPER(name)")
+ .primaryKey("name")
+ .option("merge-engine", mergeEngine)
+ .build());
+ String dataId =
+ TestValuesTableFactory.registerData(
+ Arrays.asList(Row.of("hello"), Row.of("hello")));
+ sEnv.executeSql(
+ "CREATE TEMPORARY TABLE input_events (name STRING) WITH ("
+ + "'connector' = 'values', 'bounded' = 'true',
'data-id' = '"
+ + dataId
+ + "')");
+ sEnv.executeSql(
+ omitGeneratedColumn
+ ? "INSERT INTO events (name, cnt) SELECT name,
COUNT(*) FROM input_events GROUP BY name"
+ : "INSERT INTO events SELECT name, COUNT(*),
UPPER(name) FROM input_events GROUP BY name")
+ .await();
+
+ assertThat(sql("SELECT COUNT(*), MAX(cnt), MAX(label) FROM events"))
+ .containsExactly(Row.of(1L, mergeEngine.equals("first-row") ?
1L : 2L, "HELLO"));
+ }
+
+ @Test
+ void testGeneratedColumnWithPrimaryKeyAndBlob() throws Exception {
+ createTable(
+ "events",
+ Schema.newBuilder()
+ .column("name", DataTypes.STRING())
+ .column("payload", DataTypes.BLOB())
+ .generatedColumn("label", DataTypes.STRING(),
"UPPER(name)")
+ .primaryKey("name")
+ .option("blob-field", "payload")
+ .build());
+
+ assertThatCode(() -> tEnv.explainSql("SELECT name FROM
events")).doesNotThrowAnyException();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"DATE", "STRING"})
+ void testExplicitNullGeneratedPartition(String partitionType) throws
Exception {
+ boolean datePartition = partitionType.equals("DATE");
+ Schema.Builder builder =
+ Schema.newBuilder()
+ .column("id", DataTypes.INT())
+ .column("event_day", DataTypes.STRING())
+ .generatedColumn(
+ "dt",
+ datePartition ? DataTypes.DATE() :
DataTypes.STRING(),
+ datePartition
+ ? "CAST(event_day AS DATE)"
+ : "CAST(CAST(event_day AS DATE) AS
STRING)")
+ .partitionKeys("dt");
+ createTable("events", builder.build());
+ tEnv.executeSql("INSERT INTO events (id, event_day) VALUES (1,
'2026-11-02')").await();
+ tEnv.executeSql(
+ "INSERT INTO events (id, event_day, dt) VALUES (2,
'invalid', CAST(NULL AS "
+ + partitionType
+ + "))")
+ .await();
+ assertThat(sql("SELECT id, dt FROM events"))
+ .containsExactlyInAnyOrder(
+ Row.of(1, datePartition ? LocalDate.of(2026, 11, 2) :
"2026-11-02"),
+ Row.of(2, null));
+ assertThat(sql("SELECT id FROM events WHERE dt IS
NULL")).containsExactly(Row.of(2));
+ assertThat(sql("SELECT `partition` FROM events$partitions"))
+ .containsExactlyInAnyOrder(
+ Row.of("dt=2026-11-02"),
Row.of("dt=__DEFAULT_PARTITION__"));
+ }
+
+ @Test
+ void testVirtualColumnBeforePhysicalColumns() throws Exception {
+ createTable(
+ "events",
+ Schema.newBuilder()
+ .column("name", DataTypes.STRING())
+ .generatedColumn("label", DataTypes.STRING(),
"UPPER(name)")
+ .build());
+ sql("ALTER TABLE events ADD virtual_name AS LOWER(name) FIRST");
+
+ tEnv.executeSql("INSERT INTO events (name) VALUES ('Hello')").await();
+
+ assertThat(sql("SELECT name, label, virtual_name FROM events"))
+ .containsExactly(Row.of("Hello", "HELLO", "hello"));
+ }
+
+ private void createTable(String name, Schema schema) throws Exception {
+ flinkCatalog()
+ .catalog()
+ .createTable(Identifier.create(tEnv.getCurrentDatabase(),
name), schema, false);
+ }
+}
diff --git
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/GeneratedColumnMapFunctionTest.java
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/GeneratedColumnMapFunctionTest.java
new file mode 100644
index 0000000000..8c4bfbf095
--- /dev/null
+++
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/GeneratedColumnMapFunctionTest.java
@@ -0,0 +1,115 @@
+/*
+ * 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.data.BlobDescriptor;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.DataTypes;
+import org.apache.paimon.types.RowType;
+
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.types.RowKind;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import java.time.LocalDate;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Tests the Flink projection and conversion around shared generated-column
evaluation. */
+class GeneratedColumnMapFunctionTest {
+
+ @ParameterizedTest
+ @EnumSource(RowKind.class)
+ void testOmittedColumnsDefaultsAndSuppliedNull(RowKind kind) throws
Exception {
+ RowType rowType =
+ RowType.of(
+ new DataField(0, "name",
DataTypes.STRING()).newDefaultValue("fallback"),
+ new DataField(1, "number", DataTypes.INT())
+ .newGenerationExpression("CAST(text AS INT)"),
+ new DataField(2, "text", DataTypes.STRING()),
+ new DataField(3, "label", DataTypes.STRING())
+ .newGenerationExpression("UPPER(name)"),
+ new DataField(4, "dt", DataTypes.DATE())
+ .newGenerationExpression("CAST(event_day AS
DATE)"),
+ new DataField(5, "event_day", DataTypes.STRING()));
+ GeneratedColumnMapFunction mapper =
+ new GeneratedColumnMapFunction(rowType, new int[] {4, 3});
+ GenericRowData input =
+ GenericRowData.of(
+ null,
+ null,
+ StringData.fromString("invalid integer"),
+ null,
+ null,
+ StringData.fromString("2026-11-02"));
+ input.setRowKind(kind);
+
+ RowData first = mapper.map(input);
+ assertThat(first.getRowKind()).isEqualTo(kind);
+ assertThat(first.isNullAt(1)).isTrue();
+ assertThat(first.getString(3).toString()).isEqualTo("FALLBACK");
+ assertThat(first.getInt(4)).isEqualTo((int) LocalDate.of(2026, 11,
2).toEpochDay());
+ assertThat(input.isNullAt(3)).isTrue();
+ assertThat(input.isNullAt(4)).isTrue();
+
+ input.setField(0, StringData.fromString("other"));
+ input.setField(1, 42);
+ input.setField(5, StringData.fromString("2026-11-03"));
+ RowData second = mapper.map(input);
+ assertThat(second.getRowKind()).isEqualTo(kind);
+ assertThat(second.getInt(1)).isEqualTo(42);
+ assertThat(second.getString(3).toString()).isEqualTo("OTHER");
+ assertThat(second.getInt(4)).isEqualTo((int) LocalDate.of(2026, 11,
3).toEpochDay());
+ assertThat(first.getString(3).toString()).isEqualTo("FALLBACK");
+ assertThat(first.getInt(4)).isEqualTo((int) LocalDate.of(2026, 11,
2).toEpochDay());
+ }
+
+ @Test
+ void testSuppliedBlobAndNestedRowKeepFlinkRepresentation() throws
Exception {
+ RowType rowType =
+ RowType.of(
+ new DataField(0, "name", DataTypes.STRING()),
+ new DataField(1, "content", DataTypes.BLOB()),
+ new DataField(
+ 2,
+ "nested",
+ DataTypes.ROW(new DataField(10, "content",
DataTypes.BLOB()))),
+ new DataField(3, "label", DataTypes.STRING())
+ .newGenerationExpression("UPPER(name)"));
+ GeneratedColumnMapFunction mapper = new
GeneratedColumnMapFunction(rowType, new int[] {3});
+ byte[] inline = new byte[] {1, 2, 3};
+ byte[] descriptor = new BlobDescriptor("file:///not-opened", 1,
2).serialize();
+ GenericRowData input =
+ GenericRowData.of(
+ StringData.fromString("hello"),
+ inline,
+ GenericRowData.of((Object) descriptor),
+ null);
+
+ RowData result = mapper.map(input);
+
+ assertThat(result.getString(3).toString()).isEqualTo("HELLO");
+ assertThat(result.getBinary(1)).isEqualTo(inline);
+ assertThat(result.getRow(2, 1).getBinary(0)).isEqualTo(descriptor);
+ }
+}