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 1f7a41d7d7 [spark] Resolve NullType against target fields during
schema evolution (#11161)
1f7a41d7d7 is described below
commit 1f7a41d7d735f1a871c20b3a2ee6a44f5e49e963
Author: Zouxxyy <[email protected]>
AuthorDate: Mon Nov 16 00:04:39 2026 +0800
[spark] Resolve NullType against target fields during schema evolution
(#11161)
---
.../spark/commands/SchemaEvolutionHelper.scala | 68 ++++++++-
.../paimon/spark/sql/WriteMergeSchemaTest.scala | 157 +++++++++++++++++++++
2 files changed, 220 insertions(+), 5 deletions(-)
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/SchemaEvolutionHelper.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/SchemaEvolutionHelper.scala
index 7bfb7ee905..d1c16a8693 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/SchemaEvolutionHelper.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/SchemaEvolutionHelper.scala
@@ -31,7 +31,7 @@ import org.apache.spark.sql.{DataFrame, PaimonUtils,
SparkSession}
import org.apache.spark.sql.catalyst.expressions.Attribute
import org.apache.spark.sql.connector.catalog.TableCatalog
import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
-import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.types.{ArrayType, DataType, MapType, NullType,
StructType}
import scala.collection.JavaConverters._
@@ -99,8 +99,7 @@ private[spark] object SchemaEvolutionHelper {
table: FileStoreTable,
dataSchema: StructType,
flags: SchemaEvolutionFlags): Option[TableSchema] = {
- val filtered = SparkSystemColumns.filterSparkSystemColumns(dataSchema)
- val dataRowType =
SparkTypeUtils.toPaimonType(filtered).asInstanceOf[RowType]
+ val dataRowType = toDataRowType(table, dataSchema, flags.caseSensitive)
val current = table.schema()
val merged =
SchemaMergingUtils.mergeSchemas(
@@ -122,14 +121,73 @@ private[spark] object SchemaEvolutionHelper {
dataSchema: StructType,
sparkSession: SparkSession,
options: Options = new Options()): Boolean = {
- val filtered = SparkSystemColumns.filterSparkSystemColumns(dataSchema)
val flags = readFlags(sparkSession, options)
- val dataRowType =
SparkTypeUtils.toPaimonType(filtered).asInstanceOf[RowType]
+ val dataRowType = toDataRowType(table, dataSchema, flags.caseSensitive)
table
.store()
.mergeSchema(dataRowType, flags.typeWidening, flags.allowExplicitCast,
flags.caseSensitive)
}
+ private def toDataRowType(
+ table: FileStoreTable,
+ dataSchema: StructType,
+ caseSensitive: Boolean): RowType = {
+ val filtered = SparkSystemColumns.filterSparkSystemColumns(dataSchema)
+ val target =
SparkTypeUtils.fromPaimonRowType(table.schema().logicalRowType())
+ val resolved = resolveNullTypes(filtered, Some(target), Nil, caseSensitive)
+ SparkTypeUtils.toPaimonType(resolved).asInstanceOf[RowType]
+ }
+
+ /**
+ * NULL and empty collections have no concrete leaf type. Resolve only those
leaves against the
+ * target before converting to Paimon types, preserving typed siblings for
schema evolution.
+ */
+ private def resolveNullTypes(
+ source: DataType,
+ target: Option[DataType],
+ path: Seq[String],
+ caseSensitive: Boolean): DataType = source match {
+ case NullType =>
+ target.getOrElse {
+ val fieldPath = path.map(name => s"`${name.replace("`",
"``")}`").mkString(".")
+ throw new UnsupportedOperationException(
+ s"Cannot infer the type of field $fieldPath from NULL during schema
evolution. " +
+ "Use CAST to specify a concrete type for NULL or the empty
collection.")
+ }
+ case struct: StructType =>
+ val targetFields = target.collect { case s: StructType => s.fields.toSeq
}.getOrElse(Nil)
+ StructType(struct.fields.map {
+ field =>
+ val targetField = targetFields.find(
+ f => if (caseSensitive) f.name == field.name else
f.name.equalsIgnoreCase(field.name))
+ field.copy(dataType = resolveNullTypes(
+ field.dataType,
+ targetField.map(_.dataType),
+ path :+ field.name,
+ caseSensitive))
+ })
+ case array: ArrayType =>
+ array.copy(elementType = resolveNullTypes(
+ array.elementType,
+ target.collect { case a: ArrayType => a.elementType },
+ path :+ "element",
+ caseSensitive))
+ case map: MapType =>
+ map.copy(
+ keyType = resolveNullTypes(
+ map.keyType,
+ target.collect { case m: MapType => m.keyType },
+ path :+ "key",
+ caseSensitive),
+ valueType = resolveNullTypes(
+ map.valueType,
+ target.collect { case m: MapType => m.valueType },
+ path :+ "value",
+ caseSensitive)
+ )
+ case other => other
+ }
+
/**
* Persist the schema that MERGE INTO evolved in memory (see
[[evolvedTableInMemory]]) and refresh
* the catalog cache. Called from the merge command's `run`, so the commit
happens at execution,
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/WriteMergeSchemaTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/WriteMergeSchemaTest.scala
index 094bd60e48..f2ea8ca635 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/WriteMergeSchemaTest.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/WriteMergeSchemaTest.scala
@@ -22,6 +22,7 @@ import org.apache.paimon.spark.PaimonSparkTestBase
import org.apache.spark.SparkConf
import org.apache.spark.sql.Row
+import org.apache.spark.sql.types.{ArrayType, LongType, StringType, StructType}
class WriteMergeSchemaTest extends PaimonSparkTestBase {
@@ -1001,4 +1002,160 @@ class WriteMergeSchemaTest extends PaimonSparkTestBase {
}
}
}
+
+ private def writeWithSchemaEvolution(mode: String, projection: String): Unit
=
+ withSparkSQLConf("spark.paimon.write.merge-schema" -> "true") {
+ if (mode == "MERGE") {
+ sql(s"""MERGE INTO t USING (SELECT $projection) s ON false
+ |WHEN NOT MATCHED THEN INSERT *""".stripMargin)
+ } else {
+ sql(s"INSERT INTO t BY NAME SELECT $projection")
+ }
+ }
+
+ Seq("MERGE", "INSERT").foreach {
+ mode =>
+ test(s"$mode: NULL and empty collections preserve existing types") {
+ withTable("t") {
+ sql("""CREATE TABLE t (
+ | id INT, label STRING, items ARRAY<STRING>, attrs MAP<STRING,
INT>,
+ | payload STRUCT<name: STRING>) USING paimon""".stripMargin)
+ val before = spark.table("t").schema
+ withSparkSQLConf("spark.paimon.write.merge-schema.type-widening" ->
"true") {
+ writeWithSchemaEvolution(
+ mode,
+ "1 AS id, NULL AS label, array() AS items, map() AS attrs, NULL
AS payload")
+ }
+ assert(spark.table("t").schema == before)
+ checkAnswer(sql("SELECT * FROM t"), Row(1, null, Seq.empty,
Map.empty, null))
+ }
+ }
+
+ test(s"$mode: nested NULL preserves typed additions in structs, arrays
and maps") {
+ withTable("t") {
+ sql("""CREATE TABLE t (
+ | id INT, payload STRUCT<name: STRING>,
+ | items ARRAY<STRUCT<name: STRING>>,
+ | attrs MAP<STRING, STRUCT<name: STRING>>) USING
paimon""".stripMargin)
+ sql("""INSERT INTO t VALUES (
+ | 0, named_struct('name', 'old'), array(named_struct('name',
'old')),
+ | map('key', named_struct('name', 'old')))""".stripMargin)
+
+ writeWithSchemaEvolution(
+ mode,
+ """1 AS id, named_struct('name', NULL, 'added', 10) AS payload,
+ |array(named_struct('name', NULL, 'added', 20)) AS items,
+ |map('key', named_struct('name', NULL, 'added', 30)) AS
attrs""".stripMargin
+ )
+
+ checkAnswer(
+ sql("SELECT * FROM t ORDER BY id"),
+ Seq(
+ Row(0, Row("old", null), Seq(Row("old", null)), Map("key" ->
Row("old", null))),
+ Row(1, Row(null, 10), Seq(Row(null, 20)), Map("key" -> Row(null,
30))))
+ )
+ assert(
+
spark.table("t").schema("payload").dataType.asInstanceOf[StructType].fieldNames.toSeq
==
+ Seq("name", "added"))
+ }
+ }
+
+ test(s"$mode: nested NULL does not suppress sibling type widening") {
+ withTable("t") {
+ sql("CREATE TABLE t (id INT, payload STRUCT<value: INT, label:
STRING>) USING paimon")
+ sql("INSERT INTO t VALUES (0, named_struct('value', 10, 'label',
'old'))")
+ withSparkSQLConf("spark.paimon.write.merge-schema.type-widening" ->
"true") {
+ writeWithSchemaEvolution(
+ mode,
+ "1 AS id, named_struct('value', 2147483648L, 'label', NULL) AS
payload")
+ }
+ val payload =
spark.table("t").schema("payload").dataType.asInstanceOf[StructType]
+ assert(payload("value").dataType == LongType)
+ assert(payload("label").dataType == StringType)
+ checkAnswer(
+ sql("SELECT * FROM t ORDER BY id"),
+ Seq(Row(0, Row(10L, "old")), Row(1, Row(2147483648L, null))))
+ }
+ }
+
+ test(s"$mode: explicit casts allow new NULL and empty-array columns") {
+ withTable("t") {
+ sql("CREATE TABLE t (id INT) USING paimon")
+ writeWithSchemaEvolution(
+ mode,
+ "1 AS id, CAST(NULL AS STRING) AS label, CAST(array() AS
ARRAY<STRING>) AS items")
+ assert(spark.table("t").schema("label").dataType == StringType)
+ assert(spark.table("t").schema("items").dataType ==
ArrayType(StringType))
+ checkAnswer(sql("SELECT * FROM t"), Row(1, null, Seq.empty))
+ }
+ }
+
+ Seq(
+ ("NULL AS extra", "`extra`"),
+ ("array() AS extra", "`extra`.`element`"),
+ ("map() AS extra", "`extra`.`key`"),
+ ("named_struct('name', NULL, 'extra', NULL) AS payload",
"`payload`.`extra`"),
+ ("array(named_struct('name', NULL, 'extra', NULL)) AS items",
"`items`.`element`.`extra`"),
+ (
+ "map('key', named_struct('name', NULL, 'extra', NULL)) AS attrs",
+ "`attrs`.`value`.`extra`")
+ ).foreach {
+ case (projection, path) =>
+ test(s"$mode: reject an untyped new field at $path without changing
the table") {
+ withTable("t") {
+ sql("""CREATE TABLE t (
+ | id INT, payload STRUCT<name: STRING>,
+ | items ARRAY<STRUCT<name: STRING>>,
+ | attrs MAP<STRING, STRUCT<name: STRING>>) USING
paimon""".stripMargin)
+ val before = spark.table("t").schema
+ val error = intercept[Exception] {
+ writeWithSchemaEvolution(mode, s"1 AS id, $projection")
+ }
+ assert(error.getMessage.contains(s"Cannot infer the type of
field $path"))
+ assert(error.getMessage.contains("CAST"))
+ assert(spark.table("t").schema == before)
+ checkAnswer(sql("SELECT COUNT(*) FROM t"), Row(0L))
+ }
+ }
+ }
+ }
+
+ Seq(false, true).foreach {
+ caseSensitive =>
+ test(s"NULL resolution respects nested field case sensitivity:
$caseSensitive") {
+ withTable("t") {
+ sql("CREATE TABLE t (id INT, payload STRUCT<Name: STRING>) USING
paimon")
+ withSparkSQLConf("spark.sql.caseSensitive" ->
caseSensitive.toString) {
+ if (caseSensitive) {
+ val error = intercept[Exception] {
+ writeWithSchemaEvolution("MERGE", "1 AS id,
named_struct('name', NULL) AS payload")
+ }
+ assert(error.getMessage.contains("`payload`.`name`"))
+ writeWithSchemaEvolution("MERGE", "1 AS id, named_struct('Name',
NULL) AS payload")
+ } else {
+ writeWithSchemaEvolution("MERGE", "1 AS ID, named_struct('name',
NULL) AS PAYLOAD")
+ }
+ }
+ checkAnswer(sql("SELECT * FROM t"), Row(1, Row(null)))
+ assert(
+
spark.table("t").schema("payload").dataType.asInstanceOf[StructType].fieldNames.toSeq
==
+ Seq("Name"))
+ }
+ }
+ }
+
+ test("MERGE UPDATE resolves nested NULL while adding a typed field") {
+ withTable("t") {
+ sql("""CREATE TABLE t (id INT, payload STRUCT<name: STRING>) USING paimon
+ |TBLPROPERTIES ('primary-key' = 'id', 'bucket' =
'1')""".stripMargin)
+ sql("INSERT INTO t VALUES (1, named_struct('name', 'old'))")
+ withSparkSQLConf("spark.paimon.write.merge-schema" -> "true") {
+ sql("""MERGE INTO t
+ |USING (SELECT 1 AS id, named_struct('name', NULL, 'added', 10)
AS payload) s
+ |ON t.id = s.id
+ |WHEN MATCHED THEN UPDATE SET *""".stripMargin)
+ }
+ checkAnswer(sql("SELECT * FROM t"), Row(1, Row(null, 10)))
+ }
+ }
}