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 245680119a [spark] Add an isolated Spark 4.2 connector build (#11127)
245680119a is described below
commit 245680119a4efee32a50d4abb8953624e8272ce6
Author: Jingsong Lee <[email protected]>
AuthorDate: Fri Nov 13 08:47:34 2026 +0800
[spark] Add an isolated Spark 4.2 connector build (#11127)
---
docs/docs/spark/installation.mdx | 10 ++
.../pom.xml | 91 ++++++----
.../src/main/resources/META-INF/NOTICE | 5 +
.../analysis/Spark42RowLevelCommandRewrite.scala | 65 +++++++
.../spark/sql/Spark42CompatibilityTest.scala | 189 +++++++++++++++++++++
.../apache/paimon/spark/RollbackStagedTable.java | 7 +
.../org/apache/paimon/spark/SparkTypeUtils.java | 19 ++-
.../paimon/spark/catalyst/Compatibility.scala | 33 +++-
.../catalyst/analysis/PaimonViewResolver.scala | 17 +-
.../PaimonDynamicPartitionOverwriteCommand.scala | 8 +
.../paimon/spark/execution/PaimonStrategy.scala | 26 +--
.../extensions/PaimonSparkSessionExtensions.scala | 13 +-
.../catalog/PaimonV1FunctionRegistry.scala | 8 +-
.../parser/extensions/PaimonFunctionLookup.scala | 9 +-
.../extensions/RewritePaimonFunctionCommands.scala | 6 +-
.../sql/execution/PaimonDescribeTableExec.scala | 10 +-
paimon-spark/paimon-spark4-common/pom.xml | 44 +++++
.../catalog/functions/SQLFunctionConverter.scala | 7 +-
.../optimizer/MergePaimonScalarSubqueries.scala | 23 +--
.../CreatePaimonSQLFunctionCommand.scala | 8 +-
.../spark/sql/paimon/shims/SQLFunctionCompat.scala | 80 +++++++++
.../apache/spark/sql/paimon/shims/Spark4Shim.scala | 39 ++++-
.../paimon/spark/data/Spark42ArrayData.scala | 47 +++++
.../paimon/spark/data/Spark42InternalRow.scala | 48 ++++++
pom.xml | 19 +++
tools/ci/plan.py | 3 +-
tools/ci/run-java-tests.sh | 4 +
tools/ci/test_java_commands.py | 3 +
tools/ci/test_plan.py | 12 +-
29 files changed, 754 insertions(+), 99 deletions(-)
diff --git a/docs/docs/spark/installation.mdx b/docs/docs/spark/installation.mdx
index 4bfbc3734e..737e2e1515 100644
--- a/docs/docs/spark/installation.mdx
+++ b/docs/docs/spark/installation.mdx
@@ -34,6 +34,10 @@ may require a newer Java runtime. Check its runtime
requirements before starting
- Spark 3.x (including 3.5, 3.4, 3.3, 3.2) : Pre-built with Java 8 and Scala
2.12/2.13
+Spark 4.2 is available as an experimental source build with Java 17 and Scala
2.13.
+Its independent `spark42` profile recompiles the shared connector modules
against Spark 4.2;
+the `spark4` profile continues to build the Spark 4.0 and 4.1 connectors.
+
## Download the Connector
Choose the JAR matching your Spark and Scala versions:
@@ -82,8 +86,14 @@ mvn clean package -DskipTests -pl
paimon-spark/paimon-spark-4.0 -am -Pspark4
# build paimon spark 4.1
mvn clean package -DskipTests -pl paimon-spark/paimon-spark-4.1 -am -Pspark4
+
+# build paimon spark 4.2
+mvn clean package -DskipTests -pl paimon-spark/paimon-spark-4.2 -am -Pspark42
```
+Use `clean` when switching between Spark profiles: the shared modules produce
artifacts with
+the same names, but Spark 4.2 changes internal binary interfaces such as
`CatalogManager`.
+
For Spark 3.5, you can find the bundled jar in
`./paimon-spark/paimon-spark-3.5/target/paimon-spark-3.5_2.12-@@VERSION@@.jar`.
## Add the Connector to Spark
diff --git a/paimon-spark/paimon-spark4-common/pom.xml
b/paimon-spark/paimon-spark-4.2/pom.xml
similarity index 55%
copy from paimon-spark/paimon-spark4-common/pom.xml
copy to paimon-spark/paimon-spark-4.2/pom.xml
index 80c260b0e6..34298028c3 100644
--- a/paimon-spark/paimon-spark4-common/pom.xml
+++ b/paimon-spark/paimon-spark-4.2/pom.xml
@@ -8,7 +8,7 @@ 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
+ 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
@@ -28,26 +28,25 @@ under the License.
<version>2.2-SNAPSHOT</version>
</parent>
- <packaging>jar</packaging>
-
- <artifactId>paimon-spark4-common_2.13</artifactId>
- <name>Paimon : Spark4 : Common : 2.13</name>
+ <artifactId>paimon-spark-4.2_2.13</artifactId>
+ <name>Paimon : Spark : 4.2 : 2.13</name>
<properties>
- <spark.version>${paimon-spark-common.spark.version}</spark.version>
- <!-- Spark 4 only supports Scala 2.13. Pin it locally so this _2.13
module resolves its
- dependencies to _2.13 even when the spark4 profile is inactive
(see issue #6682);
- otherwise it inherits scala.binary.version=2.12 from
paimon-parent. -->
+ <spark.version>4.2.0</spark.version>
<scala.binary.version>2.13</scala.binary.version>
+ <scala.version>2.13.18</scala.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.paimon</groupId>
-
<artifactId>paimon-spark-common_${scala.binary.version}</artifactId>
+ <artifactId>paimon-format</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.paimon</groupId>
+
<artifactId>paimon-spark4-common_${scala.binary.version}</artifactId>
<version>${project.version}</version>
</dependency>
-
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql-api_${scala.binary.version}</artifactId>
@@ -57,21 +56,59 @@ under the License.
<groupId>org.apache.spark</groupId>
<artifactId>spark-connect-shims_${scala.binary.version}</artifactId>
</exclusion>
- <exclusion>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
-
+ <dependency>
+ <groupId>org.apache.spark</groupId>
+ <artifactId>spark-core_${scala.binary.version}</artifactId>
+ <version>${spark.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.spark</groupId>
+ <artifactId>spark-sql_${scala.binary.version}</artifactId>
+ <version>${spark.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.spark</groupId>
+ <artifactId>spark-catalyst_${scala.binary.version}</artifactId>
+ <version>${spark.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.spark</groupId>
+ <artifactId>spark-hive_${scala.binary.version}</artifactId>
+ <version>${spark.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.spark</groupId>
+ <artifactId>spark-sql_${scala.binary.version}</artifactId>
+ <version>${spark.version}</version>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>org.apache.spark</groupId>
+
<artifactId>spark-connect-shims_${scala.binary.version}</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.spark</groupId>
+ <artifactId>spark-catalyst_${scala.binary.version}</artifactId>
+ <version>${spark.version}</version>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.spark</groupId>
+ <artifactId>spark-core_${scala.binary.version}</artifactId>
+ <version>${spark.version}</version>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
@@ -89,25 +126,13 @@ under the License.
<configuration>
<artifactSet>
<includes combine.children="append">
-
<include>org.apache.paimon:paimon-bundle</include>
-
<include>org.apache.paimon:paimon-spark-common_${scala.binary.version}</include>
+
<include>org.apache.paimon:paimon-spark4-common_${scala.binary.version}</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
</plugins>
</build>
</project>
diff --git a/paimon-spark/paimon-spark-4.2/src/main/resources/META-INF/NOTICE
b/paimon-spark/paimon-spark-4.2/src/main/resources/META-INF/NOTICE
new file mode 100644
index 0000000000..6b79772894
--- /dev/null
+++ b/paimon-spark/paimon-spark-4.2/src/main/resources/META-INF/NOTICE
@@ -0,0 +1,5 @@
+paimon-spark-4.2
+Copyright 2023-2026 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
diff --git
a/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark42RowLevelCommandRewrite.scala
b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark42RowLevelCommandRewrite.scala
new file mode 100644
index 0000000000..1e7468e773
--- /dev/null
+++
b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/analysis/Spark42RowLevelCommandRewrite.scala
@@ -0,0 +1,65 @@
+/*
+ * 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.spark.sql.catalyst.analysis
+
+import org.apache.paimon.spark.SparkTable
+import org.apache.paimon.spark.catalyst.analysis.{MergeSchemaEvolutionHelper,
PaimonAssignmentUtils, PaimonRelation}
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.plans.logical.{AnalysisHelper,
LogicalPlan, MergeIntoTable, UpdateTable}
+import org.apache.spark.sql.catalyst.rules.Rule
+
+/** Re-enter Spark's native rewrite with fresh, aligned commands that are not
marked analyzed. */
+object Spark42RowLevelCommandRewrite
+ extends Rule[LogicalPlan]
+ with PureAppendOnlyScope
+ with MergeSchemaEvolutionHelper {
+
+ override def apply(plan: LogicalPlan): LogicalPlan = {
+ AnalysisHelper.allowInvokingTransformsInAnalyzer {
+ plan.transformDown {
+ case u: UpdateTable if u.resolved && u.rewritable && eligible(u.table)
=>
+ val assignments = PaimonAssignmentUtils.alignUpdateAssignments(
+ u.table.output,
+ u.assignments,
+ fromStar = false,
+ mergeSchemaEnabled = false)
+ RewriteUpdateTable(u.copy(assignments = assignments))
+
+ case m: MergeIntoTable
+ if m.resolved && m.rewritable && !m.withSchemaEvolution &&
eligible(m.targetTable) =>
+ val relation = PaimonRelation.getPaimonRelation(m.targetTable)
+ val table = relation.table.asInstanceOf[SparkTable]
+ val evolved = evolveTargetIfNeeded(
+ m,
+ relation,
+ table,
+ SparkSession.active,
+ _.notMatchedBySourceActions)
+ .map(_._1)
+ .getOrElse(m)
+ val aligned = alignAllMergeActions(evolved,
evolved.targetTable.output)
+ RewriteMergeIntoTable(aligned.copy())
+ }
+ }
+ }
+
+ private def eligible(table: LogicalPlan): Boolean =
+ targetsV2CopyOnWriteTable(table) || targetsV2DeltaTable(table)
+}
diff --git
a/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CompatibilityTest.scala
b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CompatibilityTest.scala
new file mode 100644
index 0000000000..2fe2f9baa1
--- /dev/null
+++
b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CompatibilityTest.scala
@@ -0,0 +1,189 @@
+/*
+ * 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.spark.sql
+
+import org.apache.paimon.rest.RESTCatalogServer
+import org.apache.paimon.rest.auth.BearTokenAuthProvider
+import org.apache.paimon.rest.responses.ConfigResponse
+import org.apache.paimon.spark.SparkCatalog
+import org.apache.paimon.spark.extensions.PaimonSparkSessionExtensions
+
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.{QueryTest, Row}
+import org.apache.spark.sql.test.SharedSparkSession
+
+import java.nio.file.Files
+import java.util.Collections
+
+/** Exercise the APIs whose signatures changed in Spark 4.2 using real Paimon
files. */
+class Spark42CompatibilityTest extends QueryTest with SharedSparkSession {
+ private val warehouse = Files.createTempDirectory("paimon-spark42-").toFile
+ private lazy val server = {
+ val s = new RESTCatalogServer(
+ warehouse.toURI.toString,
+ new BearTokenAuthProvider("test-token"),
+ new ConfigResponse(Collections.singletonMap("prefix", "paimon"),
Collections.emptyMap()),
+ "spark42-tests"
+ )
+ s.start()
+ s
+ }
+
+ override protected def sparkConf: SparkConf = super.sparkConf
+ .set("spark.sql.catalog.paimon", classOf[SparkCatalog].getName)
+ .set("spark.sql.catalog.paimon.metastore", "rest")
+ .set("spark.sql.catalog.paimon.uri", server.getUrl)
+ .set("spark.sql.catalog.paimon.warehouse", "spark42-tests")
+ .set("spark.sql.catalog.paimon.token.provider", "bear")
+ .set("spark.sql.catalog.paimon.token", "test-token")
+ .set("spark.sql.defaultCatalog", "paimon")
+ .set("spark.sql.extensions", classOf[PaimonSparkSessionExtensions].getName)
+
+ override protected def beforeAll(): Unit = {
+ super.beforeAll()
+ sql("CREATE DATABASE paimon.test")
+ sql("USE paimon.test")
+ }
+
+ override protected def afterAll(): Unit = {
+ try { super.afterAll() }
+ finally {
+ server.shutdown()
+ org.apache.commons.io.FileUtils.deleteDirectory(warehouse)
+ }
+ }
+
+ test("create, insert, CTAS and static and dynamic partition overwrite") {
+ withTable("t", "copied") {
+ sql(
+ "CREATE TABLE t (id INT, label VARCHAR(20), pt STRING) PARTITIONED BY
(pt) " +
+ "TBLPROPERTIES ('bucket'='-1', 'file.format'='avro')")
+ sql("INSERT INTO t VALUES (1, 'a', 'x'), (2, 'b', 'y')")
+ sql("INSERT OVERWRITE t PARTITION (pt='x') SELECT 3, 'c'")
+ checkAnswer(sql("SELECT * FROM t"), Seq(Row(3, "c", "x"), Row(2, "b",
"y")))
+ withSQLConf("spark.sql.sources.partitionOverwriteMode" -> "dynamic") {
+ sql("INSERT OVERWRITE t SELECT 4, 'd', 'y'")
+ }
+ checkAnswer(sql("SELECT * FROM t"), Seq(Row(3, "c", "x"), Row(4, "d",
"y")))
+ sql("CREATE TABLE copied TBLPROPERTIES ('file.format'='avro') AS SELECT
* FROM t")
+ checkAnswer(sql("SELECT * FROM copied"), sql("SELECT * FROM t"))
+ }
+ }
+
+ test("ordinary views, table description and partition description") {
+ withTable("t") {
+ sql(
+ "CREATE TABLE t (id INT, pt STRING) PARTITIONED BY (pt) " +
+ "TBLPROPERTIES ('bucket'='-1', 'file.format'='avro')")
+ sql("INSERT INTO t VALUES (1, 'x')")
+ try {
+ sql("CREATE VIEW v AS SELECT id FROM t")
+ checkAnswer(sql("SELECT * FROM v"), Seq(Row(1)))
+ assert(sql("DESCRIBE t").collect().exists(_.getString(0) == "id"))
+ assert(
+ sql("DESCRIBE EXTENDED t PARTITION (pt='x')")
+ .collect()
+ .exists(_.getString(0) == "# Detailed Partition Information"))
+ } finally { sql("DROP VIEW IF EXISTS v") }
+ }
+ }
+
+ test("SQL scalar functions, builtin lookup and unsupported table function
rejection") {
+ try {
+ sql("CREATE FUNCTION add_one(x INT) RETURNS INT RETURN x + 1")
+ checkAnswer(
+ sql("SELECT add_one(4), SUM(abs(v)) FROM VALUES (-2), (3) AS t(v)"),
+ Seq(Row(5, 5)))
+ val unsupported = intercept[UnsupportedOperationException] {
+ sql("CREATE FUNCTION rows_plus(x INT) RETURNS TABLE (v INT) RETURN
SELECT x + 1")
+ }
+ assert(unsupported.getMessage.contains("SQL table functions"))
+ } finally {
+ sql("DROP FUNCTION IF EXISTS add_one")
+ sql("DROP FUNCTION IF EXISTS rows_plus")
+ }
+ }
+
+ private val modes: Seq[(String, String)] = Seq(
+ "primary-key" -> "'bucket'='1', 'primary-key'='id'",
+ "append" -> "'bucket'='-1'",
+ "row-tracking" -> "'bucket'='-1', 'row-tracking.enabled'='true'",
+ "deletion-vectors" -> "'bucket'='-1', 'deletion-vectors.enabled'='true'",
+ "data-evolution" ->
+ ("'bucket'='-1', 'row-tracking.enabled'='true',
'data-evolution.enabled'='true', " +
+ "'deletion-vectors.enabled'='true'")
+ )
+
+ for ((mode, properties) <- modes; v2 <- Seq(false, true)) {
+ test(s"UPDATE, DELETE and MERGE on $mode tables with v2 writes $v2") {
+ withSQLConf("spark.paimon.write.use-v2-write" -> v2.toString) {
+ withTable("t") {
+ sql(s"CREATE TABLE t (id INT, v INT) TBLPROPERTIES ($properties,
'file.format'='avro')")
+ sql("INSERT INTO t VALUES (1, 10), (2, 20), (3, 30)")
+ sql("UPDATE t SET v=11 WHERE id=1")
+ checkAnswer(sql("SELECT * FROM t"), Seq(Row(1, 11), Row(2, 20),
Row(3, 30)))
+ sql("DELETE FROM t WHERE id=2")
+ sql(
+ "MERGE INTO t USING (SELECT 3 AS id, 33 AS v UNION ALL SELECT 4,
44) s " +
+ "ON t.id=s.id WHEN MATCHED THEN UPDATE SET * " +
+ "WHEN NOT MATCHED THEN INSERT *")
+ checkAnswer(sql("SELECT * FROM t"), Seq(Row(1, 11), Row(3, 33),
Row(4, 44)))
+ }
+ }
+ }
+ }
+
+ test("native V2 rewrite handles subquery updates and insert-only merges") {
+ withSQLConf("spark.paimon.write.use-v2-write" -> "true") {
+ withTable("t") {
+ sql(
+ "CREATE TABLE t (id INT, v INT) " +
+ "TBLPROPERTIES ('bucket'='-1', 'file.format'='avro')")
+ sql("INSERT INTO t VALUES (1, 10), (2, 20)")
+ sql("UPDATE t SET v=99 WHERE id IN (SELECT 1)")
+ sql(
+ "MERGE INTO t USING (SELECT 3 AS id, 30 AS v) s ON t.id=s.id " +
+ "WHEN NOT MATCHED THEN INSERT *")
+ checkAnswer(sql("SELECT * FROM t"), Seq(Row(1, 99), Row(2, 20), Row(3,
30)))
+ sql("DELETE FROM t")
+ checkAnswer(sql("SELECT COUNT(*) FROM t"), Seq(Row(0L)))
+ }
+ }
+ }
+
+ test("variant values and spatial scalar and array getters") {
+ val point = "0101000000000000000000F03F0000000000000040"
+ withTable("typed") {
+ sql(
+ "CREATE TABLE typed (v VARIANT, g GEOMETRY(3857), " +
+ "a ARRAY<GEOMETRY(3857)>, gg GEOGRAPHY(4326)) " +
+ "TBLPROPERTIES ('bucket'='-1', 'file.format'='parquet')")
+ sql(
+ s"INSERT INTO typed SELECT parse_json('{\"id\":1}'), " +
+ s"ST_GeomFromWKB(unhex('$point'), 3857), " +
+ s"array(ST_GeomFromWKB(unhex('$point'), 3857)),
ST_GeogFromWKB(unhex('$point'))")
+ checkAnswer(
+ sql(
+ "SELECT variant_get(v, '$.id', 'int'), hex(ST_AsBinary(g)), " +
+ "hex(ST_AsBinary(a[0])), hex(ST_AsBinary(gg)) FROM typed"),
+ Seq(Row(1, point, point, point))
+ )
+ }
+ }
+}
diff --git
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/RollbackStagedTable.java
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/RollbackStagedTable.java
index 2f90545b60..21ca7b6b8b 100644
---
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/RollbackStagedTable.java
+++
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/RollbackStagedTable.java
@@ -25,6 +25,7 @@ import org.apache.spark.sql.connector.catalog.SupportsWrite;
import org.apache.spark.sql.connector.catalog.Table;
import org.apache.spark.sql.connector.catalog.TableCapability;
import org.apache.spark.sql.connector.expressions.Transform;
+import org.apache.spark.sql.connector.metric.CustomTaskMetric;
import org.apache.spark.sql.connector.read.ScanBuilder;
import org.apache.spark.sql.connector.write.LogicalWriteInfo;
import org.apache.spark.sql.connector.write.WriteBuilder;
@@ -98,6 +99,12 @@ class RollbackStagedTable implements StagedTable,
SupportsRead, SupportsWrite, S
return table.capabilities();
}
+ // Resolve the StagedTable / TruncatableTable default-method conflict on
Spark 4.2.
+ // No @Override: older Spark versions do not expose this method.
+ public CustomTaskMetric[] reportDriverMetrics() {
+ return new CustomTaskMetric[0];
+ }
+
@Override
public void deleteWhere(Filter[] filters) {
call(SupportsDelete.class, t -> t.deleteWhere(filters));
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTypeUtils.java
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTypeUtils.java
index 2cdbca6d78..d09de9a560 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTypeUtils.java
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkTypeUtils.java
@@ -166,9 +166,23 @@ public class SparkTypeUtils {
private static final PaimonToSparkTypeVisitor INSTANCE = new
PaimonToSparkTypeVisitor();
+ private static DataType characterType(Class<? extends DataType> type,
int length) {
+ try {
+ try {
+ return type.getConstructor(int.class).newInstance(length);
+ } catch (NoSuchMethodException e) {
+ // Spark 4.2 adds an optional collation identifier to the
constructor.
+ return type.getConstructor(int.class, scala.Option.class)
+ .newInstance(length, scala.Option.empty());
+ }
+ } catch (ReflectiveOperationException e) {
+ throw new IllegalArgumentException("Cannot construct Spark
character type", e);
+ }
+ }
+
@Override
public DataType visit(CharType charType) {
- return new
org.apache.spark.sql.types.CharType(charType.getLength());
+ return characterType(org.apache.spark.sql.types.CharType.class,
charType.getLength());
}
@Override
@@ -176,7 +190,8 @@ public class SparkTypeUtils {
if (varCharType.getLength() == VarCharType.MAX_LENGTH) {
return DataTypes.StringType;
} else {
- return new
org.apache.spark.sql.types.VarcharType(varCharType.getLength());
+ return characterType(
+ org.apache.spark.sql.types.VarcharType.class,
varCharType.getLength());
}
}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
index 89de804eec..eaf1a6e0f3 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
@@ -35,13 +35,32 @@ object Compatibility {
query: LogicalPlan,
byName: Boolean,
conf: SQLConf): LogicalPlan = {
- TableOutputResolver.resolveOutputColumns(
- tableName,
- expected,
- query,
- byName,
- conf,
- supportColDefaultValue = false)
+ // Spark 4.2 replaced the boolean with DefaultValueFillMode. Preserve the
old false
+ // behavior (NONE) without linking 3.x/4.1 builds to the new enumeration.
+ val method = TableOutputResolver.getClass.getMethods
+ .find(m => m.getName == "resolveOutputColumns" &&
m.getParameterTypes.length == 6)
+ .get
+ val fillMode: AnyRef = if (method.getParameterTypes.last ==
java.lang.Boolean.TYPE) {
+ java.lang.Boolean.FALSE
+ } else {
+ val cls = Class.forName(
+
"org.apache.spark.sql.catalyst.analysis.TableOutputResolver$DefaultValueFillMode$")
+ cls.getMethod("NONE").invoke(cls.getField("MODULE$").get(null))
+ }
+ try {
+ method
+ .invoke(
+ TableOutputResolver,
+ tableName,
+ expected,
+ query,
+ java.lang.Boolean.valueOf(byName),
+ conf,
+ fillMode)
+ .asInstanceOf[LogicalPlan]
+ } catch {
+ case e: java.lang.reflect.InvocationTargetException => throw e.getCause
+ }
}
def withNewQuery(o: V2WriteCommand, query: LogicalPlan): V2WriteCommand = {
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonViewResolver.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonViewResolver.scala
index a85466caa9..58603df6a4 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonViewResolver.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonViewResolver.scala
@@ -56,13 +56,16 @@ case class PaimonViewResolver(spark: SparkSession)
u
}
- case u @ UnresolvedTableOrView(CatalogAndIdentifier(catalog:
SupportView, ident), _, _) =>
- try {
- catalog.loadView(ident)
- ResolvedPaimonView(catalog, ident)
- } catch {
- case _: ViewNotExistException =>
- u
+ case u: UnresolvedTableOrView =>
+ u.multipartIdentifier match {
+ case CatalogAndIdentifier(catalog: SupportView, ident) =>
+ try {
+ catalog.loadView(ident)
+ ResolvedPaimonView(catalog, ident)
+ } catch {
+ case _: ViewNotExistException => u
+ }
+ case _ => u
}
}
}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonDynamicPartitionOverwriteCommand.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonDynamicPartitionOverwriteCommand.scala
index 0f722d4c80..e582314d69 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonDynamicPartitionOverwriteCommand.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonDynamicPartitionOverwriteCommand.scala
@@ -49,6 +49,14 @@ case class PaimonDynamicPartitionOverwriteCommand(
override def child: LogicalPlan = query
+ // Spark 4.2's WriteWithSchemaEvolution contract. Paimon performs its own
schema handling.
+ def withSchemaEvolution: Boolean = false
+
+ def writePrivileges:
Set[org.apache.spark.sql.connector.catalog.TableWritePrivilege] =
+ Set(
+ org.apache.spark.sql.connector.catalog.TableWritePrivilege.INSERT,
+ org.apache.spark.sql.connector.catalog.TableWritePrivilege.DELETE)
+
override def withNewQuery(newQuery: LogicalPlan):
PaimonDynamicPartitionOverwriteCommand = {
copy(query = newQuery)
}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/PaimonStrategy.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/PaimonStrategy.scala
index 893d7a2734..0717322646 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/PaimonStrategy.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/PaimonStrategy.scala
@@ -198,19 +198,25 @@ case class PaimonStrategy(spark: SparkSession)
case ShowCreateTable(ResolvedPaimonView(viewCatalog, ident), _, output) =>
ShowCreatePaimonViewExec(output, viewCatalog, ident) :: Nil
- case DescribeRelation(ResolvedPaimonView(viewCatalog, ident), _,
isExtended, output) =>
- DescribePaimonViewExec(output, viewCatalog, ident, isExtended) :: Nil
-
- case DescribeRelation(r: ResolvedTable, partitionSpec, isExtended, output)
=>
- (r.table, r.catalog) match {
- case (sparkTable: SparkTable, sparkCatalog: SparkBaseCatalog) =>
+ case d: DescribeRelation =>
+ d.relation match {
+ case ResolvedPaimonView(viewCatalog, ident) =>
+ DescribePaimonViewExec(d.output, viewCatalog, ident, d.isExtended)
:: Nil
+ case r: ResolvedTable
+ if r.table.isInstanceOf[SparkTable] &&
+ r.catalog.isInstanceOf[SparkBaseCatalog] =>
+ // Spark 4.2 moved partition descriptions to a separate logical
command.
+ val partitionSpec = d.getClass.getMethods
+ .find(_.getName == "partitionSpec")
+ .map(_.invoke(d).asInstanceOf[Map[String, String]])
+ .getOrElse(Map.empty)
PaimonDescribeTableExec(
- output,
- sparkCatalog,
+ d.output,
+ r.catalog.asInstanceOf[SparkBaseCatalog],
r.identifier,
- sparkTable,
+ r.table.asInstanceOf[SparkTable],
partitionSpec,
- isExtended) :: Nil
+ d.isExtended) :: Nil
case _ => Nil
}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala
index e7eb99d31b..4390c4207d 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala
@@ -41,6 +41,12 @@ class PaimonSparkSessionExtensions extends
(SparkSessionExtensions => Unit) {
extensions.injectResolutionRule(spark => new PaimonAnalysis(spark))
extensions.injectResolutionRule(spark => PaimonProcedureResolver(spark))
extensions.injectResolutionRule(spark => PaimonViewResolver(spark))
+ if (org.apache.spark.SPARK_VERSION.startsWith("4.2.")) {
+ val module =
+
Class.forName("org.apache.spark.sql.catalyst.analysis.Spark42RowLevelCommandRewrite$")
+ val rule =
module.getField("MODULE$").get(null).asInstanceOf[Rule[LogicalPlan]]
+ extensions.injectResolutionRule(_ => rule)
+ }
extensions.injectResolutionRule(spark => PaimonFunctionResolver(spark))
extensions.injectResolutionRule(spark =>
SparkShimLoader.shim.createCustomResolution(spark))
extensions.injectResolutionRule(spark =>
PaimonIncompatibleResolutionRules(spark))
@@ -75,7 +81,8 @@ class PaimonSparkSessionExtensions extends
(SparkSessionExtensions => Unit) {
// `MergeRows.Keep(Copy, ...)`, ...), so they must not be statically
referenced from
// `paimon-spark-common` or they'd fail to link when
`paimon-spark-4.0` loads this
// extension.
- // The `SPARK_VERSION >= "4.1"` gate ensures we only look them up on 4.1+;
the
+ // The `SPARK_VERSION.startsWith("4.1.")` gate keeps these
binary-version-specific rules
+ // on 4.1; Spark 4.2 changed the RewriteRowLevelCommand trait. The
// `ClassNotFoundException` catch handles the spark3 case silently.
loadSpark41Rule("Spark41UpdateTableRewrite").foreach(
rule => extensions.injectResolutionRule(_ => rule))
@@ -125,11 +132,11 @@ class PaimonSparkSessionExtensions extends
(SparkSessionExtensions => Unit) {
/**
* Reflectively loads a Spark 4.1-only rewrite rule object from
`paimon-spark4-common` by its
- * simple class name. Returns `None` under Spark < 4.1 (gate avoids touching
4.1-only types in the
+ * simple class name. Returns `None` outside Spark 4.1 (gate avoids touching
4.1-only types in the
* rule class bodies) or when the class is not on the classpath (e.g. the
`spark3` build).
*/
private def loadSpark41Rule(simpleName: String): Option[Rule[LogicalPlan]] =
{
- if (org.apache.spark.SPARK_VERSION < "4.1") {
+ if (!org.apache.spark.SPARK_VERSION.startsWith("4.1.")) {
None
} else {
try {
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/catalog/PaimonV1FunctionRegistry.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/catalog/PaimonV1FunctionRegistry.scala
index ed69abd8bb..a62614568b 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/catalog/PaimonV1FunctionRegistry.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/catalog/PaimonV1FunctionRegistry.scala
@@ -164,7 +164,13 @@ case class PaimonV1FunctionRegistry(session: SparkSession)
extends SQLConfHelper
}
private def qualifyIdentifier(ident: FunctionIdentifier): FunctionIdentifier
= {
- FunctionIdentifier(funcName = format(ident.funcName), database =
ident.database)
+ val catalog = if (org.apache.spark.SPARK_VERSION.startsWith("4.2.")) {
+
ident.catalog.orElse(Some(session.sessionState.catalogManager.currentCatalog.name))
+ } else None
+ FunctionIdentifier(
+ funcName = format(ident.funcName),
+ database = ident.database,
+ catalog = catalog)
}
protected def format(name: String): String = {
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/PaimonFunctionLookup.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/PaimonFunctionLookup.scala
index 4a4b179ff6..3ac86268cb 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/PaimonFunctionLookup.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/PaimonFunctionLookup.scala
@@ -77,7 +77,14 @@ case class PaimonFunctionLookup(catalogManager:
CatalogManager) extends LookupCa
}
def isSparkBuiltInFunction(funcIdent: FunctionIdentifier): Boolean = {
- catalogManager.v1SessionCatalog.isBuiltinFunction(funcIdent)
+ val catalog = catalogManager.v1SessionCatalog
+ val method = catalog.getClass.getMethods.find(_.getName ==
"isBuiltinFunction").get
+ val argument = if (method.getParameterTypes.head == classOf[String]) {
+ funcIdent.funcName
+ } else {
+ funcIdent
+ }
+ method.invoke(catalog, argument).asInstanceOf[Boolean]
}
def isSparkTmpFunc(funcIdent: FunctionIdentifier): Boolean = {
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewritePaimonFunctionCommands.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewritePaimonFunctionCommands.scala
index 43f9a49d92..48138d1e16 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewritePaimonFunctionCommands.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewritePaimonFunctionCommands.scala
@@ -260,6 +260,10 @@ object UnResolvedPaimonV1Function {
funcIdent: FunctionIdentifier,
u: UnresolvedFunction,
fun: Option[PaimonFunction]): UnResolvedPaimonV1Function = {
- UnResolvedPaimonV1Function(funcIdent, u.arguments, u.isDistinct, u.filter,
u.ignoreNulls, fun)
+ val ignoreNulls = u.ignoreNulls.asInstanceOf[Any] match {
+ case value: Boolean => value
+ case value: Option[_] => value.contains(true)
+ }
+ UnResolvedPaimonV1Function(funcIdent, u.arguments, u.isDistinct, u.filter,
ignoreNulls, fun)
}
}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/PaimonDescribeTableExec.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/PaimonDescribeTableExec.scala
index 52f96d58f5..d0975ad581 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/PaimonDescribeTableExec.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/PaimonDescribeTableExec.scala
@@ -46,8 +46,14 @@ case class PaimonDescribeTableExec(
extends PaimonLeafV2CommandExec {
override protected def run(): Seq[InternalRow] = {
- val rows =
- ArrayBuffer.empty ++= DescribeTableExec(output, table,
isExtended).executeCollect()
+ val constructor = classOf[DescribeTableExec].getConstructors.head
+ val args: Seq[AnyRef] = if (constructor.getParameterTypes.length == 3) {
+ Seq(output, table, java.lang.Boolean.valueOf(isExtended))
+ } else {
+ Seq(output, catalog.name(), identifier, table,
java.lang.Boolean.valueOf(isExtended))
+ }
+ val description = constructor.newInstance(args:
_*).asInstanceOf[DescribeTableExec]
+ val rows = ArrayBuffer.empty ++= description.executeCollect()
if (partitionSpec.nonEmpty) {
describeDetailedPartitionInfo(rows)
diff --git a/paimon-spark/paimon-spark4-common/pom.xml
b/paimon-spark/paimon-spark4-common/pom.xml
index 80c260b0e6..032edb98e0 100644
--- a/paimon-spark/paimon-spark4-common/pom.xml
+++ b/paimon-spark/paimon-spark4-common/pom.xml
@@ -110,4 +110,48 @@ under the License.
</plugin>
</plugins>
</build>
+ <profiles>
+ <profile>
+ <id>spark42</id>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>com.diffplug.spotless</groupId>
+ <artifactId>spotless-maven-plugin</artifactId>
+ <configuration>
+ <scala>
+
<includes><include>src/**/*.scala</include></includes>
+ </scala>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>net.alchim31.maven</groupId>
+ <artifactId>scala-maven-plugin</artifactId>
+ <configuration>
+ <excludes>
+ <exclude>**/Spark4InternalRow.scala</exclude>
+ <exclude>**/Spark4ArrayData.scala</exclude>
+ <exclude>**/Spark41*.scala</exclude>
+ </excludes>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <version>3.2.0</version>
+ <executions>
+ <execution>
+ <id>spark42-getters</id>
+ <phase>generate-sources</phase>
+ <goals><goal>add-source</goal></goals>
+ <configuration>
+
<sources><source>src/main/spark42</source></sources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
</project>
diff --git
a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/paimon/spark/catalog/functions/SQLFunctionConverter.scala
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/paimon/spark/catalog/functions/SQLFunctionConverter.scala
index 178232faf4..791318f492 100644
---
a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/paimon/spark/catalog/functions/SQLFunctionConverter.scala
+++
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/paimon/spark/catalog/functions/SQLFunctionConverter.scala
@@ -62,7 +62,7 @@ object SQLFunctionConverter {
val inputParams: JList[DataField] = inputParamText.filter(_.trim.nonEmpty)
match {
case Some(text) =>
- val params = UserDefinedFunction.parseRoutineParam(text, parser)
+ val params =
org.apache.spark.sql.paimon.shims.SQLFunctionCompat.parseParams(text, parser)
params.fields.foreach(
p => SQLFunctionTypes.requireNoCollation(funcIdent, s"parameter
${p.name}", p.dataType))
SparkTypeUtils.toPaimonRowType(params).getFields
@@ -136,7 +136,7 @@ object SQLFunctionConverter {
.map(_.toBoolean)
.orElse(Some(function.isDeterministic))
- val sqlFunction = SQLFunction(
+ val sqlFunction =
org.apache.spark.sql.paimon.shims.SQLFunctionCompat.create(
name = funcIdent,
inputParam = inputParam,
returnType = Left(returnType),
@@ -160,7 +160,8 @@ object SQLFunctionConverter {
funcIdent: FunctionIdentifier,
returnTypeText: String,
parser: ParserInterface): SparkDataType =
- SQLFunction.parseReturnTypeText(returnTypeText, isTableFunc = false,
parser) match {
+ org.apache.spark.sql.paimon.shims.SQLFunctionCompat
+ .parseReturn(returnTypeText, isTableFunc = false, parser) match {
case Some(Left(dataType)) => dataType
case _ =>
throw new UnsupportedOperationException(
diff --git
a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/MergePaimonScalarSubqueries.scala
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/MergePaimonScalarSubqueries.scala
index e86195f1af..f93d39fd54 100644
---
a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/MergePaimonScalarSubqueries.scala
+++
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/paimon/spark/catalyst/optimizer/MergePaimonScalarSubqueries.scala
@@ -30,20 +30,15 @@ object MergePaimonScalarSubqueries extends
MergePaimonScalarSubqueriesBase {
newV2ScanRelation: DataSourceV2ScanRelation,
cachedV2ScanRelation: DataSourceV2ScanRelation)
: Option[(LogicalPlan, AttributeMap[Attribute])] = {
- (newV2ScanRelation, cachedV2ScanRelation) match {
- case (
- DataSourceV2ScanRelation(
- newRelation,
- newScan: PaimonScan,
- newOutput,
- newPartitioning,
- newOrdering),
- DataSourceV2ScanRelation(
- cachedRelation,
- cachedScan: PaimonScan,
- _,
- cachedPartitioning,
- cacheOrdering)) =>
+ (newV2ScanRelation.scan, cachedV2ScanRelation.scan) match {
+ case (newScan: PaimonScan, cachedScan: PaimonScan) =>
+ val newRelation = newV2ScanRelation.relation
+ val cachedRelation = cachedV2ScanRelation.relation
+ val newOutput = newV2ScanRelation.output
+ val newPartitioning = newV2ScanRelation.keyGroupedPartitioning
+ val cachedPartitioning = cachedV2ScanRelation.keyGroupedPartitioning
+ val newOrdering = newV2ScanRelation.ordering
+ val cacheOrdering = cachedV2ScanRelation.ordering
checkIdenticalPlans(newRelation, cachedRelation).flatMap {
outputMap =>
if (
diff --git
a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/CreatePaimonSQLFunctionCommand.scala
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/CreatePaimonSQLFunctionCommand.scala
index de4195ac3f..6c4a265af7 100644
---
a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/CreatePaimonSQLFunctionCommand.scala
+++
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/CreatePaimonSQLFunctionCommand.scala
@@ -68,10 +68,12 @@ case class CreatePaimonSQLFunctionCommand(
val sessionCatalog = sparkSession.sessionState.catalog
val conf = sparkSession.sessionState.conf
- val inputParam =
inputParamText.map(UserDefinedFunction.parseRoutineParam(_, parser))
- val returnType = parseReturnTypeText(returnTypeText, isTableFunc, parser)
+ val inputParam =
+
inputParamText.map(org.apache.spark.sql.paimon.shims.SQLFunctionCompat.parseParams(_,
parser))
+ val returnType = org.apache.spark.sql.paimon.shims.SQLFunctionCompat
+ .parseReturn(returnTypeText, isTableFunc, parser)
- val function = SQLFunction(
+ val function = org.apache.spark.sql.paimon.shims.SQLFunctionCompat.create(
name,
inputParam,
returnType.getOrElse(if (isTableFunc) Right(null) else Left(null)),
diff --git
a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/SQLFunctionCompat.scala
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/SQLFunctionCompat.scala
new file mode 100644
index 0000000000..93c2d53043
--- /dev/null
+++
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/SQLFunctionCompat.scala
@@ -0,0 +1,80 @@
+/*
+ * 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.spark.sql.paimon.shims
+
+import org.apache.spark.sql.catalyst.FunctionIdentifier
+import org.apache.spark.sql.catalyst.catalog.{SQLFunction, UserDefinedFunction}
+import org.apache.spark.sql.catalyst.parser.ParserInterface
+import org.apache.spark.sql.types.{DataType, StructType}
+
+/** Spark 4.2 adds optional collation to SQL function construction and
parsing. */
+object SQLFunctionCompat {
+ private def invoke(target: AnyRef, name: String, arguments: Seq[AnyRef]):
AnyRef = {
+ val method = target.getClass.getMethods.find(_.getName == name).get
+ val args =
+ if (method.getParameterTypes.length == arguments.size) arguments else
arguments :+ None
+ try { method.invoke(target, args: _*) }
+ catch { case e: java.lang.reflect.InvocationTargetException => throw
e.getCause }
+ }
+
+ def parseParams(text: String, parser: ParserInterface): StructType =
+ invoke(UserDefinedFunction, "parseRoutineParam", Seq(text,
parser)).asInstanceOf[StructType]
+
+ def parseReturn(
+ text: String,
+ isTableFunc: Boolean,
+ parser: ParserInterface): Option[Either[DataType, StructType]] =
+ invoke(
+ SQLFunction,
+ "parseReturnTypeText",
+ Seq(text, java.lang.Boolean.valueOf(isTableFunc), parser))
+ .asInstanceOf[Option[Either[DataType, StructType]]]
+
+ def create(
+ name: FunctionIdentifier,
+ inputParam: Option[StructType],
+ returnType: Either[DataType, StructType],
+ exprText: Option[String],
+ queryText: Option[String],
+ comment: Option[String],
+ deterministic: Option[Boolean],
+ containsSQL: Option[Boolean],
+ isTableFunc: Boolean,
+ properties: Map[String, String]): SQLFunction = {
+ val base: Seq[AnyRef] = Seq(
+ name,
+ inputParam,
+ returnType,
+ exprText,
+ queryText,
+ comment,
+ deterministic,
+ containsSQL,
+ java.lang.Boolean.valueOf(isTableFunc),
+ properties,
+ None,
+ java.lang.Long.valueOf(System.currentTimeMillis())
+ )
+ val constructor = classOf[SQLFunction].getConstructors.head
+ val args =
+ if (constructor.getParameterTypes.length == base.size) base
+ else base.take(6) ++ Seq(None) ++ base.drop(6)
+ constructor.newInstance(args: _*).asInstanceOf[SQLFunction]
+ }
+}
diff --git
a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala
index 65bf9e9797..f98f43b294 100644
---
a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala
+++
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala
@@ -373,19 +373,37 @@ class Spark4Shim extends SparkShim {
o.asInstanceOf[Geometry].getBytes
override def toPaimonGeometry(row: InternalRow, pos: Int): Array[Byte] =
- STUtils.stAsBinary(row.getGeometry(pos))
+ readSpatial(row, pos, geography = false)
override def toPaimonGeometry(array: ArrayData, pos: Int): Array[Byte] =
- STUtils.stAsBinary(array.getGeometry(pos))
+ readSpatial(array, pos, geography = false)
override def toPaimonGeography(o: Object): Array[Byte] =
o.asInstanceOf[Geography].getBytes
override def toPaimonGeography(row: InternalRow, pos: Int): Array[Byte] =
- STUtils.stAsBinary(row.getGeography(pos))
+ readSpatial(row, pos, geography = true)
override def toPaimonGeography(array: ArrayData, pos: Int): Array[Byte] =
- STUtils.stAsBinary(array.getGeography(pos))
+ readSpatial(array, pos, geography = true)
+
+ private def readSpatial(value: AnyRef, pos: Int, geography: Boolean):
Array[Byte] = {
+ val modern = org.apache.spark.SPARK_VERSION.startsWith("4.2.")
+ val getter = if (modern) "getBinaryView" else if (geography)
"getGeography" else "getGeometry"
+ val raw = value.getClass
+ .getMethod(getter, java.lang.Integer.TYPE)
+ .invoke(value, java.lang.Integer.valueOf(pos))
+ val name = if (!modern) "stAsBinary" else if (geography) "stGeogAsBinary"
else "stGeomAsBinary"
+ val method = Class
+ .forName("org.apache.spark.sql.catalyst.util.STUtils")
+ .getMethods
+ .find(
+ m =>
+ m.getName == name && m.getParameterTypes.length == 1 &&
+ m.getParameterTypes.head.isInstance(raw))
+ .get
+ method.invoke(null, raw).asInstanceOf[Array[Byte]]
+ }
override def toSparkGeometry(wkb: Array[Byte], crs: String): Object = {
val geometryType = sparkGeometryType(crs)
@@ -394,7 +412,18 @@ class Spark4Shim extends SparkShim {
override def toSparkGeography(wkb: Array[Byte], crs: String, algorithm:
String): Object = {
val geographyType = sparkGeographyType(crs, algorithm)
- STUtils.stSetSrid(STUtils.stGeogFromWKB(wkb), geographyType.srid)
+ val name =
+ if (org.apache.spark.SPARK_VERSION.startsWith("4.2.")) "stGeogSetSrid"
else "stSetSrid"
+ val raw = STUtils.stGeogFromWKB(wkb)
+ val method = Class
+ .forName("org.apache.spark.sql.catalyst.util.STUtils")
+ .getMethods
+ .find(
+ m =>
+ m.getName == name && m.getParameterTypes.length == 2 &&
+ m.getParameterTypes.head.isInstance(raw))
+ .get
+ method.invoke(null, raw, java.lang.Integer.valueOf(geographyType.srid))
}
override def isSparkGeometryType(dataType:
org.apache.spark.sql.types.DataType): Boolean =
diff --git
a/paimon-spark/paimon-spark4-common/src/main/spark42/org/apache/paimon/spark/data/Spark42ArrayData.scala
b/paimon-spark/paimon-spark4-common/src/main/spark42/org/apache/paimon/spark/data/Spark42ArrayData.scala
new file mode 100644
index 0000000000..04f9c73bbd
--- /dev/null
+++
b/paimon-spark/paimon-spark4-common/src/main/spark42/org/apache/paimon/spark/data/Spark42ArrayData.scala
@@ -0,0 +1,47 @@
+/*
+ * 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.spark.data
+
+import org.apache.paimon.types.{DataType, GeographyType, GeometryType}
+
+import org.apache.spark.sql.paimon.shims.SparkShimLoader
+import org.apache.spark.unsafe.types.{BinaryView, VariantVal}
+
+/** Spark 4.2 counterpart of Spark4ArrayData's specialized spatial getters. */
+class Spark4ArrayData(override val elementType: DataType) extends
AbstractSparkArrayData {
+ override def getVariant(ordinal: Int): VariantVal = {
+ val value = paimonArray.getVariant(ordinal)
+ new VariantVal(value.value(), value.metadata())
+ }
+
+ override def getBinaryView(ordinal: Int): BinaryView = {
+ val bytes = paimonArray.getBinary(ordinal)
+ val value = elementType match {
+ case geometry: GeometryType =>
+ SparkShimLoader.shim.toSparkGeometry(bytes, geometry.getCrs)
+ case geography: GeographyType =>
+ SparkShimLoader.shim.toSparkGeography(
+ bytes,
+ geography.getCrs,
+ geography.getAlgorithm.toString)
+ case other => throw new UnsupportedOperationException(s"No BinaryView
for $other")
+ }
+ value.asInstanceOf[BinaryView]
+ }
+}
diff --git
a/paimon-spark/paimon-spark4-common/src/main/spark42/org/apache/paimon/spark/data/Spark42InternalRow.scala
b/paimon-spark/paimon-spark4-common/src/main/spark42/org/apache/paimon/spark/data/Spark42InternalRow.scala
new file mode 100644
index 0000000000..870edc7b61
--- /dev/null
+++
b/paimon-spark/paimon-spark4-common/src/main/spark42/org/apache/paimon/spark/data/Spark42InternalRow.scala
@@ -0,0 +1,48 @@
+/*
+ * 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.spark.data
+
+import org.apache.paimon.spark.AbstractSparkInternalRow
+import org.apache.paimon.types.{GeographyType, GeometryType, RowType}
+
+import org.apache.spark.sql.paimon.shims.SparkShimLoader
+import org.apache.spark.unsafe.types.{BinaryView, VariantVal}
+
+/** Spark 4.2 stores spatial values in BinaryView rather than
GeometryVal/GeographyVal. */
+class Spark4InternalRow(rowType: RowType) extends
AbstractSparkInternalRow(rowType) {
+ override def getVariant(i: Int): VariantVal = {
+ val value = row.getVariant(i)
+ new VariantVal(value.value(), value.metadata())
+ }
+
+ override def getBinaryView(ordinal: Int): BinaryView = {
+ val bytes = row.getBinary(ordinal)
+ val value = rowType.getTypeAt(ordinal) match {
+ case geometry: GeometryType =>
+ SparkShimLoader.shim.toSparkGeometry(bytes, geometry.getCrs)
+ case geography: GeographyType =>
+ SparkShimLoader.shim.toSparkGeography(
+ bytes,
+ geography.getCrs,
+ geography.getAlgorithm.toString)
+ case other => throw new UnsupportedOperationException(s"No BinaryView
for $other")
+ }
+ value.asInstanceOf[BinaryView]
+ }
+}
diff --git a/pom.xml b/pom.xml
index 19134d53f8..4af8301208 100644
--- a/pom.xml
+++ b/pom.xml
@@ -456,6 +456,25 @@ under the License.
</activation>
</profile>
+ <profile>
+ <id>spark42</id>
+ <modules>
+ <module>paimon-spark/paimon-spark4-common</module>
+ <module>paimon-spark/paimon-spark-4.2</module>
+ </modules>
+ <properties>
+ <target.java.version>17</target.java.version>
+ <antlr4.version>4.13.1</antlr4.version>
+ <scala.binary.version>2.13</scala.binary.version>
+ <scala.version>2.13.18</scala.version>
+
<paimon-spark-common.spark.version>4.2.0</paimon-spark-common.spark.version>
+
<paimon-sparkx-common>paimon-spark4-common_2.13</paimon-sparkx-common>
+ <arrow.version>18.1.0</arrow.version>
+ <test.spark.main.version>4.2</test.spark.main.version>
+ <test.spark.version>4.2.0</test.spark.version>
+ </properties>
+ </profile>
+
<profile>
<id>flink1</id>
<properties>
diff --git a/tools/ci/plan.py b/tools/ci/plan.py
index 49954ca2bb..e0433ee52e 100644
--- a/tools/ci/plan.py
+++ b/tools/ci/plan.py
@@ -34,6 +34,7 @@ SUITES = [
("spark3", "Spark 3 / Scala 2.12", 8, "2.12", 90),
("spark3", "Spark 3 / Scala 2.13", 8, "2.13", 90),
("spark4", "Spark 4 / Scala 2.13", 17, "2.13", 90),
+ ("spark42", "Spark 4.2 / Scala 2.13", 17, "2.13", 90),
("e2e-flink1", "E2E / Flink 1 and Spark interoperability", 8, "2.12", 60),
("e2e-flink2", "E2E / Flink 2", 11, "2.12", 60),
("iceberg", "Iceberg GA / JDK 17", 17, "2.12", 60),
@@ -45,7 +46,7 @@ ALL_JAVA = {suite[0] for suite in SUITES}
REST_SPECS = {"docs/static/rest-catalog-open-api.yaml",
"docs/static/rest-management-open-api.yaml"}
OPENAPI_V4_ACTIONS =
"paimon-api/src/main/java/org/apache/paimon/rest/auth/DLFOpenApiActions.java"
FLINK = {"flink1-common", "flink1-connectors", "flink2"}
-SPARK = {"spark3", "spark4"}
+SPARK = {"spark3", "spark4", "spark42"}
E2E = {"e2e-flink1", "e2e-flink2"}
diff --git a/tools/ci/run-java-tests.sh b/tools/ci/run-java-tests.sh
index b5a7de266c..eb8061977f 100644
--- a/tools/ci/run-java-tests.sh
+++ b/tools/ci/run-java-tests.sh
@@ -65,6 +65,10 @@ case "$suite" in
modules+=("org.apache.paimon:paimon-spark-${version}_2.13")
done
;;
+ spark42)
+ profiles=flink1,spark42
+ modules=(org.apache.paimon:paimon-spark-4.2_2.13)
+ ;;
e2e-flink1)
profiles=flink1,spark3,flink-1.20
modules=(paimon-e2e-tests)
diff --git a/tools/ci/test_java_commands.py b/tools/ci/test_java_commands.py
index 5cfc7aa487..346ceccc4f 100644
--- a/tools/ci/test_java_commands.py
+++ b/tools/ci/test_java_commands.py
@@ -63,6 +63,9 @@ class MavenCommandsTest(unittest.TestCase):
self.assertEqual(self.modules(self.commands('spark4', '2.13', 17)[1]),
{'org.apache.paimon:paimon-spark-' + version + '_2.13'
for version in ('ut', '4.0', '4.1')})
+ spark42 = self.commands('spark42', '2.13', 17)[1]
+ self.assertEqual(self.modules(spark42),
{'org.apache.paimon:paimon-spark-4.2_2.13'})
+ self.assertIn('-Pflink1,spark42', spark42)
def
test_core_keeps_common_and_docs_tests_and_existing_jdk11_exclusion(self):
for java in (8, 11):
diff --git a/tools/ci/test_plan.py b/tools/ci/test_plan.py
index afcdb51e0c..89bcf71c6e 100644
--- a/tools/ci/test_plan.py
+++ b/tools/ci/test_plan.py
@@ -35,7 +35,7 @@ class SelectionTest(unittest.TestCase):
def test_spark_keeps_common_docs_and_interoperability_tests(self):
suites =
self.suites(['paimon-spark/paimon-spark-common/src/main/scala/Change.scala'])
- self.assertEqual(suites, {'core', 'spark3', 'spark4', 'e2e-flink1'})
+ self.assertEqual(suites, {'core', 'spark3', 'spark4', 'spark42',
'e2e-flink1'})
def test_flink_keeps_hive_iceberg_and_both_e2e_versions(self):
suites =
self.suites(['paimon-flink/paimon-flink-common/src/main/java/Change.java'])
@@ -64,7 +64,7 @@ class SelectionTest(unittest.TestCase):
def test_mixed_changes_take_union(self):
self.assertEqual(self.suites(['docs/intro.md', 'paimon-spark/pom.xml',
'paimon-flink/pom.xml']),
- {'core', 'spark3', 'spark4', 'flink1-common',
+ {'core', 'spark3', 'spark4', 'spark42',
'flink1-common',
'flink1-connectors', 'flink2', 'e2e-flink1',
'e2e-flink2', 'iceberg'})
result = plan.select(['paimon-python/setup.py',
'paimon-core/Change.java'])
@@ -104,7 +104,7 @@ class SelectionTest(unittest.TestCase):
plan.select(['.github/workflows/ci-java.yml']),
plan.select([], full=True)]:
self.assertTrue(all(result[key] for key in ('java', 'python',
'docs', 'licensing')))
- self.assertEqual(len(result['matrix']['include']), 13)
+ self.assertEqual(len(result['matrix']['include']),
len(plan.SUITES))
def test_empty_diff_does_not_run_expensive_jobs(self):
result = plan.select([])
@@ -209,7 +209,7 @@ class GitDiffTest(unittest.TestCase):
with patch('subprocess.check_output', side_effect=unavailable_diff):
outputs, log = self.run_pr_plan(base, head)
self.assertTrue(all(outputs[key] for key in ('java', 'python', 'docs',
'licensing')))
- self.assertEqual(len(outputs['matrix']['include']), 13)
+ self.assertEqual(len(outputs['matrix']['include']), len(plan.SUITES))
summary = Path('summary.md').read_text()
self.assertIn('Full run (manual or unavailable diff).', summary)
self.assertIn('Skipping changed-file size check', log)
@@ -220,7 +220,7 @@ class GitDiffTest(unittest.TestCase):
base = self.git('rev-parse', 'HEAD')
self.commit('paimon-spark/Change.scala', 'spark')
outputs, _ = self.run_pr_plan(base, self.git('rev-parse', 'HEAD'))
- self.assertEqual(len(outputs['matrix']['include']), 6)
+ self.assertEqual(len(outputs['matrix']['include']), 7)
for path in ('docs/static/old image.png', 'docs/static/new image.png'):
with self.subTest(path=path):
@@ -241,7 +241,7 @@ class GitDiffTest(unittest.TestCase):
outputs = dict(line.split('=', 1) for line in
Path('output.txt').read_text().splitlines())
self.assertTrue(json.loads(outputs['java']))
self.assertFalse(json.loads(outputs['python']))
- self.assertEqual(len(json.loads(outputs['matrix'])['include']), 6)
+ self.assertEqual(len(json.loads(outputs['matrix'])['include']), 7)
self.assertIn('Spark interoperability', Path('summary.md').read_text())