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 57c0e3fd48 [spark] Enable V2 batch writes by default (#11190)
57c0e3fd48 is described below
commit 57c0e3fd486f5b7824369de80e16e89a24d677d4
Author: Zouxxyy <[email protected]>
AuthorDate: Tue Nov 17 13:54:01 2026 +0800
[spark] Enable V2 batch writes by default (#11190)
---
docs/generated/spark_connector_configuration.html | 4 +-
.../paimon/spark/catalyst/Compatibility.scala | 6 +-
.../v2/PaimonTableAsSelectWriteExec.scala | 214 +++++++++
.../shim/PaimonCreateTableAsSelectStrategy.scala | 38 +-
.../shim/PaimonReplaceTableAsSelectStrategy.scala | 26 +-
.../paimon/spark/sql/V2WriteDistributionTest.scala | 21 +
.../paimon/spark/sql/V2WriteOptionTest.scala | 37 ++
.../paimon/spark/catalyst/Compatibility.scala | 6 +-
.../v2/PaimonTableAsSelectWriteExec.scala | 214 +++++++++
.../shim/PaimonCreateTableAsSelectStrategy.scala | 41 +-
.../shim/PaimonReplaceTableAsSelectStrategy.scala | 27 +-
.../paimon/spark/sql/V2WriteDistributionTest.scala | 21 +
.../paimon/spark/sql/V2WriteOptionTest.scala | 21 +
.../paimon/spark/catalyst/Compatibility.scala | 6 +-
.../v2/PaimonTableAsSelectWriteExec.scala | 214 +++++++++
.../shim/PaimonCreateTableAsSelectStrategy.scala | 42 +-
.../shim/PaimonReplaceTableAsSelectStrategy.scala | 52 +--
.../paimon/spark/sql/V2WriteDistributionTest.scala | 21 +
.../paimon/spark/sql/V2WriteOptionTest.scala | 21 +
.../apache/spark/sql/paimon/shims/Spark4Shim.scala | 19 +-
.../paimon/spark/sql/V2WriteDistributionTest.scala | 21 +
.../paimon/spark/sql/V2WriteOptionTest.scala | 21 +
.../apache/paimon/spark/RollbackStagedTable.java | 10 +-
.../apache/paimon/spark/SparkConnectorOptions.java | 7 +-
.../apache/paimon/spark/PaimonSparkTableBase.scala | 42 +-
.../paimon/spark/PaimonTableAsSelectWrite.scala | 80 ++++
.../org/apache/paimon/spark/SparkSource.scala | 25 +-
.../paimon/spark/catalyst/Compatibility.scala | 6 +-
.../spark/catalyst/analysis/PaimonAnalysis.scala | 87 +++-
.../catalyst/analysis/PaimonUpdateTable.scala | 16 +-
.../org/apache/paimon/spark/util/OptionUtils.scala | 39 +-
.../apache/paimon/spark/write/PaimonV2Write.scala | 8 +-
.../spark/write/PaimonWriteRequirement.scala | 40 +-
.../scala/org/apache/spark/sql/PaimonUtils.scala | 5 +
.../sql/execution/PaimonTableAsSelectHelper.scala | 5 +-
.../shim/PaimonReplaceTableAsSelectStrategy.scala | 4 +-
.../apache/spark/sql/paimon/shims/SparkShim.scala | 8 +
.../spark/sql/CustomBucketFunctionTest.scala | 2 +-
.../org/apache/paimon/spark/sql/DDLTestBase.scala | 7 +-
.../paimon/spark/sql/DataFrameWriteTestBase.scala | 11 +-
.../apache/paimon/spark/sql/PaimonOptionTest.scala | 230 +++++++++-
.../paimon/spark/sql/RowTrackingTestBase.scala | 25 ++
.../spark/sql/V2WriteRequireDistributionTest.scala | 478 ++++++++++++++++++++-
.../apache/spark/sql/paimon/shims/Spark3Shim.scala | 7 +
.../apache/spark/sql/paimon/shims/Spark4Shim.scala | 19 +-
45 files changed, 2066 insertions(+), 188 deletions(-)
diff --git a/docs/generated/spark_connector_configuration.html
b/docs/generated/spark_connector_configuration.html
index 281ac494c3..da3d89aa90 100644
--- a/docs/generated/spark_connector_configuration.html
+++ b/docs/generated/spark_connector_configuration.html
@@ -154,9 +154,9 @@ under the License.
</tr>
<tr>
<td><h5>write.use-v2-write</h5></td>
- <td style="word-wrap: break-word;">false</td>
+ <td style="word-wrap: break-word;">true</td>
<td>Boolean</td>
- <td>If true, v2 write will be used. Currently, only HASH_FIXED and
BUCKET_UNAWARE bucket modes are supported. Will fall back to v1 write for other
bucket modes. Currently, Spark V2 write does not support
TableCapability.STREAMING_WRITE.</td>
+ <td>If true, use DataSource V2 for batch writes. Path-based writes
without a catalog and unsupported table configurations fall back to V1.
Supports table, session and DataSource write options with the standard option
precedence. Set to false to use V1 batch writes. Streaming writes use V1.</td>
</tr>
</tbody>
</table>
diff --git
a/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
b/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
index 80e8aab86b..0e33b59859 100644
---
a/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
+++
b/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
@@ -21,7 +21,7 @@ package org.apache.paimon.spark.catalyst
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.analysis.TableOutputResolver
import org.apache.spark.sql.catalyst.expressions.{Attribute, Cast, Expression}
-import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan,
V2WriteCommand}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan,
RepartitionByExpression, V2WriteCommand}
import org.apache.spark.sql.catalyst.trees.TreeNodeTag
import org.apache.spark.sql.execution.ui.SQLPlanMetric
import org.apache.spark.sql.internal.SQLConf
@@ -29,6 +29,10 @@ import org.apache.spark.sql.types.DataType
object Compatibility {
+ def repartitionByExpression(expressions: Seq[Expression], query:
LogicalPlan): LogicalPlan = {
+ RepartitionByExpression(expressions, query, None)
+ }
+
def resolveTableOutputColumns(
tableName: String,
expected: Seq[Attribute],
diff --git
a/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PaimonTableAsSelectWriteExec.scala
b/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PaimonTableAsSelectWriteExec.scala
new file mode 100644
index 0000000000..82bc20e82f
--- /dev/null
+++
b/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PaimonTableAsSelectWriteExec.scala
@@ -0,0 +1,214 @@
+/*
+ * 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.execution.datasources.v2
+
+import org.apache.paimon.spark.PaimonTableAsSelectWrite
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.connector.catalog.{Identifier,
StagingTableCatalog, Table, TableCatalog}
+import org.apache.spark.sql.connector.expressions.Transform
+import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/** Keeps Spark's table creation and rollback semantics while preparing the
write distribution. */
+private[v2] trait PaimonTableAsSelectWriteExec extends TableWriteExecHelper {
+ def plan: LogicalPlan
+
+ override protected def writeToTable(
+ catalog: TableCatalog,
+ table: Table,
+ options: CaseInsensitiveStringMap,
+ ident: Identifier): Seq[InternalRow] = {
+ PaimonTableAsSelectWrite
+ .writeIfSupported(session, catalog, table, ident, plan, options)
+ .getOrElse(super.writeToTable(catalog, table, options, ident))
+ }
+}
+
+object PaimonTableAsSelectWriteExec {
+
+ def prepare(exec: SparkPlan): SparkPlan = exec match {
+ case create: CreateTableAsSelectExec => prepare(create)
+ case create: AtomicCreateTableAsSelectExec => prepare(create)
+ case replace: AtomicReplaceTableAsSelectExec => prepare(replace)
+ case replace: ReplaceTableAsSelectExec => prepare(replace)
+ case other => other
+ }
+
+ def prepare(exec: CreateTableAsSelectExec): CreateTableAsSelectExec = {
+ new PaimonCreateTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.properties,
+ exec.writeOptions,
+ exec.ifNotExists)
+ }
+
+ def prepare(exec: AtomicCreateTableAsSelectExec):
AtomicCreateTableAsSelectExec = {
+ new PaimonAtomicCreateTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.properties,
+ exec.writeOptions,
+ exec.ifNotExists)
+ }
+
+ def prepare(exec: AtomicReplaceTableAsSelectExec):
AtomicReplaceTableAsSelectExec = {
+ new PaimonAtomicReplaceTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.properties,
+ exec.writeOptions,
+ exec.orCreate,
+ exec.invalidateCache)
+ }
+
+ def prepare(exec: ReplaceTableAsSelectExec): ReplaceTableAsSelectExec = {
+ new PaimonReplaceTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.properties,
+ exec.writeOptions,
+ exec.orCreate,
+ exec.invalidateCache)
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonCreateTableAsSelectExec(
+ catalog: TableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ properties: Map[String, String],
+ writeOptions: CaseInsensitiveStringMap,
+ ifNotExists: Boolean)
+ extends CreateTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ properties,
+ writeOptions,
+ ifNotExists)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(newChild: SparkPlan):
CreateTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonAtomicCreateTableAsSelectExec(
+ catalog: StagingTableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ properties: Map[String, String],
+ writeOptions: CaseInsensitiveStringMap,
+ ifNotExists: Boolean)
+ extends AtomicCreateTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ properties,
+ writeOptions,
+ ifNotExists)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(
+ newChild: SparkPlan): AtomicCreateTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonAtomicReplaceTableAsSelectExec(
+ catalog: StagingTableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ properties: Map[String, String],
+ writeOptions: CaseInsensitiveStringMap,
+ orCreate: Boolean,
+ invalidateCache: (TableCatalog, Table, Identifier) => Unit)
+ extends AtomicReplaceTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ properties,
+ writeOptions,
+ orCreate,
+ invalidateCache)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(
+ newChild: SparkPlan): AtomicReplaceTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonReplaceTableAsSelectExec(
+ catalog: TableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ properties: Map[String, String],
+ writeOptions: CaseInsensitiveStringMap,
+ orCreate: Boolean,
+ invalidateCache: (TableCatalog, Table, Identifier) => Unit)
+ extends ReplaceTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ properties,
+ writeOptions,
+ orCreate,
+ invalidateCache)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(newChild: SparkPlan):
ReplaceTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
diff --git
a/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
b/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
index 37bf307b02..f2dbe46698 100644
---
a/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
+++
b/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
@@ -19,15 +19,15 @@
package org.apache.spark.sql.execution.shim
import org.apache.paimon.Snapshot
-import org.apache.paimon.spark.SparkCatalog
+import org.apache.paimon.spark.{SparkCatalog, SparkGenericCatalog}
import org.apache.paimon.spark.write.PaimonWriteOptions
import org.apache.spark.sql.{SparkSession, Strategy}
import org.apache.spark.sql.catalyst.plans.logical.{CreateTableAsSelect,
LogicalPlan}
-import org.apache.spark.sql.connector.catalog.CatalogV2Util
+import org.apache.spark.sql.connector.catalog.{CatalogV2Util, TableCatalog}
import org.apache.spark.sql.execution.{PaimonTableAsSelectHelper, SparkPlan}
import org.apache.spark.sql.execution.PaimonTableAsSelectHelper._
-import org.apache.spark.sql.execution.datasources.v2.CreateTableAsSelectExec
+import org.apache.spark.sql.execution.datasources.v2.{CreateTableAsSelectExec,
DataSourceV2Strategy, PaimonTableAsSelectWriteExec}
import org.apache.spark.sql.util.CaseInsensitiveStringMap
import scala.collection.JavaConverters._
@@ -53,19 +53,25 @@ case class PaimonCreateTableAsSelectStrategy(spark:
SparkSession) extends Strate
parts.nonEmpty,
newProps.asJava)
- CreateTableAsSelectExec(
- catalog,
- ident,
- parts,
- query,
- planLater(query),
- newProps,
- new CaseInsensitiveStringMap(
- (writeOptions +
- (PaimonWriteOptions.OPERATION_OPTION ->
Snapshot.Operation.CREATE_TABLE_AS_SELECT
- .name())).asJava),
- ifNotExists
- ) :: Nil
+ PaimonTableAsSelectWriteExec.prepare(
+ CreateTableAsSelectExec(
+ catalog,
+ ident,
+ parts,
+ query,
+ planLater(query),
+ newProps,
+ new CaseInsensitiveStringMap(
+ (writeOptions +
+ (PaimonWriteOptions.OPERATION_OPTION ->
Snapshot.Operation.CREATE_TABLE_AS_SELECT
+ .name())).asJava),
+ ifNotExists
+ )) :: Nil
+ case create @ CreateTableAsSelect(catalog: SparkGenericCatalog, _, _, _,
props, _, _)
+ if supportsCatalog(catalog,
props.get(TableCatalog.PROP_PROVIDER).orNull) =>
+ new DataSourceV2Strategy(spark)
+ .apply(create)
+ .map(exec => PaimonTableAsSelectWriteExec.prepare(exec))
case _ => Nil
}
}
diff --git
a/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
b/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
index 617f4a4252..c53f27188a 100644
---
a/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
+++
b/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
@@ -19,27 +19,37 @@
package org.apache.spark.sql.execution.shim
import org.apache.paimon.spark.SparkCatalog
+import org.apache.paimon.spark.catalog.SparkBaseCatalog
import org.apache.spark.sql.{SparkSession, Strategy}
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan,
ReplaceTableAsSelect}
import org.apache.spark.sql.connector.catalog.{CatalogV2Util, TableCatalog}
+import org.apache.spark.sql.execution.PaimonTableAsSelectHelper.supportsCatalog
import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Strategy,
PaimonTableAsSelectWriteExec}
import scala.collection.JavaConverters._
case class PaimonReplaceTableAsSelectStrategy(spark: SparkSession) extends
Strategy {
- // Spark plans the replace itself, which drops the old table before it
writes, so reject what
- // it cannot write before that. The check uses the properties Spark creates
the table with.
+ // Keep Spark's replacement planning and prepare the write after the target
table is created.
override def apply(plan: LogicalPlan): Seq[SparkPlan] = {
plan match {
- case ReplaceTableAsSelect(catalog: SparkCatalog, ident, parts, _, props,
_, _) =>
+ case ReplaceTableAsSelect(catalog: SparkBaseCatalog, ident, parts, _,
props, _, _)
+ if supportsCatalog(catalog,
props.get(TableCatalog.PROP_PROVIDER).orNull) =>
val properties = CatalogV2Util.withDefaultOwnership(props)
- catalog.checkPartitionedFormatTableCtas(
- ident,
- properties.get(TableCatalog.PROP_PROVIDER).orNull,
- parts.nonEmpty,
- properties.asJava)
+ catalog match {
+ case paimon: SparkCatalog =>
+ paimon.checkPartitionedFormatTableCtas(
+ ident,
+ properties.get(TableCatalog.PROP_PROVIDER).orNull,
+ parts.nonEmpty,
+ properties.asJava)
+ case _ =>
+ }
+ return new DataSourceV2Strategy(spark)
+ .apply(plan)
+ .map(exec => PaimonTableAsSelectWriteExec.prepare(exec))
case _ =>
}
Nil
diff --git
a/paimon-spark/paimon-spark-3.2/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
b/paimon-spark/paimon-spark-3.2/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
new file mode 100644
index 0000000000..8a71379c1b
--- /dev/null
+++
b/paimon-spark/paimon-spark-3.2/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
@@ -0,0 +1,21 @@
+/*
+ * 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
+
+class V2WriteDistributionTest extends V2WriteRequireDistributionTest {}
diff --git
a/paimon-spark/paimon-spark-3.2/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
b/paimon-spark/paimon-spark-3.2/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
new file mode 100644
index 0000000000..43ab99a6a2
--- /dev/null
+++
b/paimon-spark/paimon-spark-3.2/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
@@ -0,0 +1,37 @@
+/*
+ * 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.catalog.Identifier
+
+import scala.collection.JavaConverters._
+
+class V2WriteOptionTest extends PaimonOptionTest {
+
+ override protected def afterAll(): Unit = {
+ // Spark 3.2 cannot pass CASCADE through the SupportsNamespaces API.
+ try {
+ paimonCatalog.listTables(dbName0).asScala.foreach {
+ table => paimonCatalog.dropTable(Identifier.create(dbName0, table),
true)
+ }
+ } finally {
+ super.afterAll()
+ }
+ }
+}
diff --git
a/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
b/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
index 1f3753c999..9ad1dcfe0c 100644
---
a/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
+++
b/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
@@ -21,7 +21,7 @@ package org.apache.paimon.spark.catalyst
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.analysis.TableOutputResolver
import org.apache.spark.sql.catalyst.expressions.{Attribute, Cast, Expression}
-import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan,
V2WriteCommand}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan,
RepartitionByExpression, V2WriteCommand}
import org.apache.spark.sql.catalyst.trees.TreeNodeTag
import org.apache.spark.sql.execution.ui.SQLPlanMetric
import org.apache.spark.sql.internal.SQLConf
@@ -29,6 +29,10 @@ import org.apache.spark.sql.types.DataType
object Compatibility {
+ def repartitionByExpression(expressions: Seq[Expression], query:
LogicalPlan): LogicalPlan = {
+ RepartitionByExpression(expressions, query, None)
+ }
+
def resolveTableOutputColumns(
tableName: String,
expected: Seq[Attribute],
diff --git
a/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PaimonTableAsSelectWriteExec.scala
b/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PaimonTableAsSelectWriteExec.scala
new file mode 100644
index 0000000000..7c16bf875f
--- /dev/null
+++
b/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PaimonTableAsSelectWriteExec.scala
@@ -0,0 +1,214 @@
+/*
+ * 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.execution.datasources.v2
+
+import org.apache.paimon.spark.PaimonTableAsSelectWrite
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, TableSpec}
+import org.apache.spark.sql.connector.catalog.{Identifier,
StagingTableCatalog, Table, TableCatalog}
+import org.apache.spark.sql.connector.expressions.Transform
+import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/** Keeps Spark's table creation and rollback semantics while preparing the
write distribution. */
+private[v2] trait PaimonTableAsSelectWriteExec extends TableWriteExecHelper {
+ def plan: LogicalPlan
+
+ override protected def writeToTable(
+ catalog: TableCatalog,
+ table: Table,
+ options: CaseInsensitiveStringMap,
+ ident: Identifier): Seq[InternalRow] = {
+ PaimonTableAsSelectWrite
+ .writeIfSupported(session, catalog, table, ident, plan, options)
+ .getOrElse(super.writeToTable(catalog, table, options, ident))
+ }
+}
+
+object PaimonTableAsSelectWriteExec {
+
+ def prepare(exec: SparkPlan): SparkPlan = exec match {
+ case create: CreateTableAsSelectExec => prepare(create)
+ case create: AtomicCreateTableAsSelectExec => prepare(create)
+ case replace: AtomicReplaceTableAsSelectExec => prepare(replace)
+ case replace: ReplaceTableAsSelectExec => prepare(replace)
+ case other => other
+ }
+
+ def prepare(exec: CreateTableAsSelectExec): CreateTableAsSelectExec = {
+ new PaimonCreateTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.tableSpec,
+ exec.writeOptions,
+ exec.ifNotExists)
+ }
+
+ def prepare(exec: AtomicCreateTableAsSelectExec):
AtomicCreateTableAsSelectExec = {
+ new PaimonAtomicCreateTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.tableSpec,
+ exec.writeOptions,
+ exec.ifNotExists)
+ }
+
+ def prepare(exec: AtomicReplaceTableAsSelectExec):
AtomicReplaceTableAsSelectExec = {
+ new PaimonAtomicReplaceTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.tableSpec,
+ exec.writeOptions,
+ exec.orCreate,
+ exec.invalidateCache)
+ }
+
+ def prepare(exec: ReplaceTableAsSelectExec): ReplaceTableAsSelectExec = {
+ new PaimonReplaceTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.tableSpec,
+ exec.writeOptions,
+ exec.orCreate,
+ exec.invalidateCache)
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonCreateTableAsSelectExec(
+ catalog: TableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ tableSpec: TableSpec,
+ writeOptions: CaseInsensitiveStringMap,
+ ifNotExists: Boolean)
+ extends CreateTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ tableSpec,
+ writeOptions,
+ ifNotExists)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(newChild: SparkPlan):
CreateTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonAtomicCreateTableAsSelectExec(
+ catalog: StagingTableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ tableSpec: TableSpec,
+ writeOptions: CaseInsensitiveStringMap,
+ ifNotExists: Boolean)
+ extends AtomicCreateTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ tableSpec,
+ writeOptions,
+ ifNotExists)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(
+ newChild: SparkPlan): AtomicCreateTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonAtomicReplaceTableAsSelectExec(
+ catalog: StagingTableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ tableSpec: TableSpec,
+ writeOptions: CaseInsensitiveStringMap,
+ orCreate: Boolean,
+ invalidateCache: (TableCatalog, Table, Identifier) => Unit)
+ extends AtomicReplaceTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ tableSpec,
+ writeOptions,
+ orCreate,
+ invalidateCache)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(
+ newChild: SparkPlan): AtomicReplaceTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonReplaceTableAsSelectExec(
+ catalog: TableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ tableSpec: TableSpec,
+ writeOptions: CaseInsensitiveStringMap,
+ orCreate: Boolean,
+ invalidateCache: (TableCatalog, Table, Identifier) => Unit)
+ extends ReplaceTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ tableSpec,
+ writeOptions,
+ orCreate,
+ invalidateCache)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(newChild: SparkPlan):
ReplaceTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
diff --git
a/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
b/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
index 1f5bcb0209..54e7f98992 100644
---
a/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
+++
b/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
@@ -19,7 +19,7 @@
package org.apache.spark.sql.execution.shim
import org.apache.paimon.Snapshot
-import org.apache.paimon.spark.SparkCatalog
+import org.apache.paimon.spark.{SparkCatalog, SparkGenericCatalog}
import org.apache.paimon.spark.write.PaimonWriteOptions
import org.apache.spark.sql.{SparkSession, Strategy}
@@ -27,7 +27,7 @@ import
org.apache.spark.sql.catalyst.analysis.ResolvedDBObjectName
import org.apache.spark.sql.catalyst.plans.logical.{CreateTableAsSelect,
LogicalPlan, TableSpec}
import org.apache.spark.sql.execution.{PaimonTableAsSelectHelper, SparkPlan}
import org.apache.spark.sql.execution.PaimonTableAsSelectHelper._
-import org.apache.spark.sql.execution.datasources.v2.CreateTableAsSelectExec
+import org.apache.spark.sql.execution.datasources.v2.{CreateTableAsSelectExec,
DataSourceV2Strategy, PaimonTableAsSelectWriteExec}
import org.apache.spark.sql.util.CaseInsensitiveStringMap
import scala.collection.JavaConverters._
@@ -56,19 +56,30 @@ case class PaimonCreateTableAsSelectStrategy(spark:
SparkSession)
parts.nonEmpty,
qualifiedSpec.properties.asJava)
- CreateTableAsSelectExec(
- catalog.asTableCatalog,
- ident.asIdentifier,
- parts,
- query,
- planLater(query),
- qualifiedSpec,
- new CaseInsensitiveStringMap(
- (writeOptions +
- (PaimonWriteOptions.OPERATION_OPTION ->
Snapshot.Operation.CREATE_TABLE_AS_SELECT
- .name())).asJava),
- ifNotExists
- ) :: Nil
+ PaimonTableAsSelectWriteExec.prepare(
+ CreateTableAsSelectExec(
+ catalog.asTableCatalog,
+ ident.asIdentifier,
+ parts,
+ query,
+ planLater(query),
+ qualifiedSpec,
+ new CaseInsensitiveStringMap(
+ (writeOptions +
+ (PaimonWriteOptions.OPERATION_OPTION ->
Snapshot.Operation.CREATE_TABLE_AS_SELECT
+ .name())).asJava),
+ ifNotExists
+ )) :: Nil
+ case create @ CreateTableAsSelect(
+ ResolvedDBObjectName(catalog: SparkGenericCatalog, _),
+ _,
+ _,
+ tableSpec: TableSpec,
+ _,
+ _) if supportsCatalog(catalog, tableSpec.provider.orNull) =>
+ new DataSourceV2Strategy(spark)
+ .apply(create)
+ .map(exec => PaimonTableAsSelectWriteExec.prepare(exec))
case _ => Nil
}
}
diff --git
a/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
b/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
index 26d5dc58f1..c975e341d2 100644
---
a/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
+++
b/paimon-spark/paimon-spark-3.3/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
@@ -19,12 +19,15 @@
package org.apache.spark.sql.execution.shim
import org.apache.paimon.spark.SparkCatalog
+import org.apache.paimon.spark.catalog.SparkBaseCatalog
import org.apache.spark.sql.{SparkSession, Strategy}
import org.apache.spark.sql.catalyst.analysis.ResolvedDBObjectName
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan,
ReplaceTableAsSelect, TableSpec}
import org.apache.spark.sql.connector.catalog.CatalogV2Util
+import org.apache.spark.sql.execution.PaimonTableAsSelectHelper.supportsCatalog
import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Strategy,
PaimonTableAsSelectWriteExec}
import scala.collection.JavaConverters._
@@ -32,23 +35,29 @@ case class PaimonReplaceTableAsSelectStrategy(spark:
SparkSession) extends Strat
import org.apache.spark.sql.connector.catalog.CatalogV2Implicits._
- // Spark plans the replace itself, which drops the old table before it
writes, so reject what
- // it cannot write before that. The check uses the properties Spark creates
the table with.
+ // Keep Spark's replacement planning and prepare the write after the target
table is created.
override def apply(plan: LogicalPlan): Seq[SparkPlan] = {
plan match {
case ReplaceTableAsSelect(
- ResolvedDBObjectName(catalog: SparkCatalog, ident),
+ ResolvedDBObjectName(catalog: SparkBaseCatalog, ident),
parts,
_,
tableSpec: TableSpec,
_,
- _) =>
+ _) if supportsCatalog(catalog, tableSpec.provider.orNull) =>
val properties = CatalogV2Util.convertTableProperties(tableSpec)
- catalog.checkPartitionedFormatTableCtas(
- ident.asIdentifier,
- tableSpec.provider.orNull,
- parts.nonEmpty,
- properties.asJava)
+ catalog match {
+ case paimon: SparkCatalog =>
+ paimon.checkPartitionedFormatTableCtas(
+ ident.asIdentifier,
+ tableSpec.provider.orNull,
+ parts.nonEmpty,
+ properties.asJava)
+ case _ =>
+ }
+ return new DataSourceV2Strategy(spark)
+ .apply(plan)
+ .map(exec => PaimonTableAsSelectWriteExec.prepare(exec))
case _ =>
}
Nil
diff --git
a/paimon-spark/paimon-spark-3.3/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
b/paimon-spark/paimon-spark-3.3/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
new file mode 100644
index 0000000000..8a71379c1b
--- /dev/null
+++
b/paimon-spark/paimon-spark-3.3/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
@@ -0,0 +1,21 @@
+/*
+ * 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
+
+class V2WriteDistributionTest extends V2WriteRequireDistributionTest {}
diff --git
a/paimon-spark/paimon-spark-3.3/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
b/paimon-spark/paimon-spark-3.3/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
new file mode 100644
index 0000000000..cdf8092450
--- /dev/null
+++
b/paimon-spark/paimon-spark-3.3/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
@@ -0,0 +1,21 @@
+/*
+ * 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
+
+class V2WriteOptionTest extends PaimonOptionTest {}
diff --git
a/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
b/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
index 8f81a6668e..8efbacade1 100644
---
a/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
+++
b/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/paimon/spark/catalyst/Compatibility.scala
@@ -21,7 +21,7 @@ package org.apache.paimon.spark.catalyst
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.analysis.TableOutputResolver
import org.apache.spark.sql.catalyst.expressions.{Attribute, Cast, Expression}
-import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan,
V2WriteCommand}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan,
RepartitionByExpression, V2WriteCommand}
import org.apache.spark.sql.catalyst.trees.TreeNodeTag
import org.apache.spark.sql.execution.ui.SQLPlanMetric
import org.apache.spark.sql.internal.SQLConf
@@ -29,6 +29,10 @@ import org.apache.spark.sql.types.DataType
object Compatibility {
+ def repartitionByExpression(expressions: Seq[Expression], query:
LogicalPlan): LogicalPlan = {
+ RepartitionByExpression(expressions, query, None)
+ }
+
def resolveTableOutputColumns(
tableName: String,
expected: Seq[Attribute],
diff --git
a/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PaimonTableAsSelectWriteExec.scala
b/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PaimonTableAsSelectWriteExec.scala
new file mode 100644
index 0000000000..7c16bf875f
--- /dev/null
+++
b/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PaimonTableAsSelectWriteExec.scala
@@ -0,0 +1,214 @@
+/*
+ * 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.execution.datasources.v2
+
+import org.apache.paimon.spark.PaimonTableAsSelectWrite
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, TableSpec}
+import org.apache.spark.sql.connector.catalog.{Identifier,
StagingTableCatalog, Table, TableCatalog}
+import org.apache.spark.sql.connector.expressions.Transform
+import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/** Keeps Spark's table creation and rollback semantics while preparing the
write distribution. */
+private[v2] trait PaimonTableAsSelectWriteExec extends TableWriteExecHelper {
+ def plan: LogicalPlan
+
+ override protected def writeToTable(
+ catalog: TableCatalog,
+ table: Table,
+ options: CaseInsensitiveStringMap,
+ ident: Identifier): Seq[InternalRow] = {
+ PaimonTableAsSelectWrite
+ .writeIfSupported(session, catalog, table, ident, plan, options)
+ .getOrElse(super.writeToTable(catalog, table, options, ident))
+ }
+}
+
+object PaimonTableAsSelectWriteExec {
+
+ def prepare(exec: SparkPlan): SparkPlan = exec match {
+ case create: CreateTableAsSelectExec => prepare(create)
+ case create: AtomicCreateTableAsSelectExec => prepare(create)
+ case replace: AtomicReplaceTableAsSelectExec => prepare(replace)
+ case replace: ReplaceTableAsSelectExec => prepare(replace)
+ case other => other
+ }
+
+ def prepare(exec: CreateTableAsSelectExec): CreateTableAsSelectExec = {
+ new PaimonCreateTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.tableSpec,
+ exec.writeOptions,
+ exec.ifNotExists)
+ }
+
+ def prepare(exec: AtomicCreateTableAsSelectExec):
AtomicCreateTableAsSelectExec = {
+ new PaimonAtomicCreateTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.tableSpec,
+ exec.writeOptions,
+ exec.ifNotExists)
+ }
+
+ def prepare(exec: AtomicReplaceTableAsSelectExec):
AtomicReplaceTableAsSelectExec = {
+ new PaimonAtomicReplaceTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.tableSpec,
+ exec.writeOptions,
+ exec.orCreate,
+ exec.invalidateCache)
+ }
+
+ def prepare(exec: ReplaceTableAsSelectExec): ReplaceTableAsSelectExec = {
+ new PaimonReplaceTableAsSelectExec(
+ exec.catalog,
+ exec.ident,
+ exec.partitioning,
+ exec.plan,
+ exec.query,
+ exec.tableSpec,
+ exec.writeOptions,
+ exec.orCreate,
+ exec.invalidateCache)
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonCreateTableAsSelectExec(
+ catalog: TableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ tableSpec: TableSpec,
+ writeOptions: CaseInsensitiveStringMap,
+ ifNotExists: Boolean)
+ extends CreateTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ tableSpec,
+ writeOptions,
+ ifNotExists)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(newChild: SparkPlan):
CreateTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonAtomicCreateTableAsSelectExec(
+ catalog: StagingTableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ tableSpec: TableSpec,
+ writeOptions: CaseInsensitiveStringMap,
+ ifNotExists: Boolean)
+ extends AtomicCreateTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ tableSpec,
+ writeOptions,
+ ifNotExists)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(
+ newChild: SparkPlan): AtomicCreateTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonAtomicReplaceTableAsSelectExec(
+ catalog: StagingTableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ tableSpec: TableSpec,
+ writeOptions: CaseInsensitiveStringMap,
+ orCreate: Boolean,
+ invalidateCache: (TableCatalog, Table, Identifier) => Unit)
+ extends AtomicReplaceTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ tableSpec,
+ writeOptions,
+ orCreate,
+ invalidateCache)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(
+ newChild: SparkPlan): AtomicReplaceTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
+
+// Match the native constructor so Spark's reflective TreeNode.clone also
retains this wrapper.
+private[v2] class PaimonReplaceTableAsSelectExec(
+ catalog: TableCatalog,
+ ident: Identifier,
+ partitioning: Seq[Transform],
+ plan: LogicalPlan,
+ query: SparkPlan,
+ tableSpec: TableSpec,
+ writeOptions: CaseInsensitiveStringMap,
+ orCreate: Boolean,
+ invalidateCache: (TableCatalog, Table, Identifier) => Unit)
+ extends ReplaceTableAsSelectExec(
+ catalog,
+ ident,
+ partitioning,
+ plan,
+ query,
+ tableSpec,
+ writeOptions,
+ orCreate,
+ invalidateCache)
+ with PaimonTableAsSelectWriteExec {
+
+ override protected def withNewChildInternal(newChild: SparkPlan):
ReplaceTableAsSelectExec = {
+ PaimonTableAsSelectWriteExec.prepare(copy(query = newChild))
+ }
+}
diff --git
a/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
b/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
index a046d84314..26abd361a5 100644
---
a/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
+++
b/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/spark/sql/execution/shim/PaimonCreateTableAsSelectStrategy.scala
@@ -19,7 +19,7 @@
package org.apache.spark.sql.execution.shim
import org.apache.paimon.Snapshot
-import org.apache.paimon.spark.SparkCatalog
+import org.apache.paimon.spark.{SparkCatalog, SparkGenericCatalog}
import org.apache.paimon.spark.write.PaimonWriteOptions
import org.apache.spark.sql.{SparkSession, Strategy}
@@ -27,7 +27,7 @@ import
org.apache.spark.sql.catalyst.analysis.ResolvedIdentifier
import org.apache.spark.sql.catalyst.plans.logical.{CreateTableAsSelect,
LogicalPlan, TableSpec}
import org.apache.spark.sql.execution.{PaimonTableAsSelectHelper, SparkPlan}
import org.apache.spark.sql.execution.PaimonTableAsSelectHelper._
-import org.apache.spark.sql.execution.datasources.v2.CreateTableAsSelectExec
+import org.apache.spark.sql.execution.datasources.v2.{CreateTableAsSelectExec,
DataSourceV2Strategy, PaimonTableAsSelectWriteExec}
import org.apache.spark.sql.util.CaseInsensitiveStringMap
import scala.collection.JavaConverters._
@@ -58,19 +58,31 @@ case class PaimonCreateTableAsSelectStrategy(spark:
SparkSession)
parts.nonEmpty,
qualifiedSpec.properties.asJava)
- CreateTableAsSelectExec(
- catalog.asTableCatalog,
- ident,
- parts,
- analyzedQuery.get,
- planLater(query),
- qualifiedSpec,
- new CaseInsensitiveStringMap(
- (writeOptions +
- (PaimonWriteOptions.OPERATION_OPTION ->
Snapshot.Operation.CREATE_TABLE_AS_SELECT
- .name())).asJava),
- ifNotExists
- ) :: Nil
+ PaimonTableAsSelectWriteExec.prepare(
+ CreateTableAsSelectExec(
+ catalog.asTableCatalog,
+ ident,
+ parts,
+ analyzedQuery.get,
+ planLater(query),
+ qualifiedSpec,
+ new CaseInsensitiveStringMap(
+ (writeOptions +
+ (PaimonWriteOptions.OPERATION_OPTION ->
Snapshot.Operation.CREATE_TABLE_AS_SELECT
+ .name())).asJava),
+ ifNotExists
+ )) :: Nil
+ case create @ CreateTableAsSelect(
+ ResolvedIdentifier(catalog: SparkGenericCatalog, _),
+ _,
+ _,
+ tableSpec: TableSpec,
+ _,
+ _,
+ _) if supportsCatalog(catalog, tableSpec.provider.orNull) =>
+ new DataSourceV2Strategy(spark)
+ .apply(create)
+ .map(exec => PaimonTableAsSelectWriteExec.prepare(exec))
case _ => Nil
}
}
diff --git
a/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
b/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
index 3f19a1ddbf..bb8c2b77c4 100644
---
a/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
+++
b/paimon-spark/paimon-spark-3.4/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
@@ -29,7 +29,7 @@ import
org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, ReplaceTable, R
import org.apache.spark.sql.connector.catalog.{Identifier,
StagingTableCatalog, Table, TableCatalog}
import org.apache.spark.sql.execution.{PaimonTableAsSelectHelper, SparkPlan}
import org.apache.spark.sql.execution.PaimonTableAsSelectHelper._
-import
org.apache.spark.sql.execution.datasources.v2.{AtomicReplaceTableAsSelectExec,
ReplaceTableAsSelectExec}
+import
org.apache.spark.sql.execution.datasources.v2.{AtomicReplaceTableAsSelectExec,
PaimonTableAsSelectWriteExec, ReplaceTableAsSelectExec}
import org.apache.spark.sql.paimon.shims.SparkShimLoader
import org.apache.spark.sql.util.CaseInsensitiveStringMap
@@ -49,7 +49,7 @@ case class PaimonReplaceTableAsSelectStrategy(spark:
SparkSession)
tableSpec: TableSpec,
options,
orCreate,
- analyzedQuery) if supportsCatalog(catalog, tableSpec) =>
+ analyzedQuery) if supportsCatalog(catalog,
tableSpec.provider.orNull) =>
assert(analyzedQuery.isDefined)
// For V1 saveAsTable + overwrite on an existing table, rewrite to
// OverwriteByExpression to preserve table definition.
@@ -82,30 +82,32 @@ case class PaimonReplaceTableAsSelectStrategy(spark:
SparkSession)
val pinnedQuery =
pinSnapshotInQuery(catalog, ident, analyzedQuery.get)
if (canAtomicReplace(catalog, ident, qualifiedSpec, parts)) {
- AtomicReplaceTableAsSelectExec(
- catalog.asInstanceOf[StagingTableCatalog],
- ident,
- parts,
- pinnedQuery,
- planLater(query),
- qualifiedSpec,
- writeOpts,
- orCreate = orCreate,
- invalidateCache
- ) :: Nil
+ PaimonTableAsSelectWriteExec.prepare(
+ AtomicReplaceTableAsSelectExec(
+ catalog.asInstanceOf[StagingTableCatalog],
+ ident,
+ parts,
+ pinnedQuery,
+ planLater(query),
+ qualifiedSpec,
+ writeOpts,
+ orCreate = orCreate,
+ invalidateCache
+ )) :: Nil
} else {
checkNonAtomicSelfReference(catalog, ident, analyzedQuery.get)
- ReplaceTableAsSelectExec(
- catalog,
- ident,
- parts,
- pinnedQuery,
- planLater(query),
- qualifiedSpec,
- writeOpts,
- orCreate = orCreate,
- invalidateCache
- ) :: Nil
+ PaimonTableAsSelectWriteExec.prepare(
+ ReplaceTableAsSelectExec(
+ catalog,
+ ident,
+ parts,
+ pinnedQuery,
+ planLater(query),
+ qualifiedSpec,
+ writeOpts,
+ orCreate = orCreate,
+ invalidateCache
+ )) :: Nil
}
case _ => Nil
}
@@ -127,7 +129,7 @@ case class PaimonReplaceTableStrategy(spark: SparkSession)
schemaOrColumns,
parts,
tableSpec: TableSpec,
- orCreate) if supportsCatalog(catalog, tableSpec) =>
+ orCreate) if supportsCatalog(catalog, tableSpec.provider.orNull) =>
val columns =
SparkShimLoader.shim.toReplaceTableColumns(
replace.tableSchema,
diff --git
a/paimon-spark/paimon-spark-3.4/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
b/paimon-spark/paimon-spark-3.4/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
new file mode 100644
index 0000000000..8a71379c1b
--- /dev/null
+++
b/paimon-spark/paimon-spark-3.4/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
@@ -0,0 +1,21 @@
+/*
+ * 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
+
+class V2WriteDistributionTest extends V2WriteRequireDistributionTest {}
diff --git
a/paimon-spark/paimon-spark-3.4/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
b/paimon-spark/paimon-spark-3.4/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
new file mode 100644
index 0000000000..cdf8092450
--- /dev/null
+++
b/paimon-spark/paimon-spark-3.4/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
@@ -0,0 +1,21 @@
+/*
+ * 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
+
+class V2WriteOptionTest extends PaimonOptionTest {}
diff --git
a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala
b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala
index c42c7cda1b..3dc06231a3 100644
---
a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala
+++
b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/spark/sql/paimon/shims/Spark4Shim.scala
@@ -34,7 +34,7 @@ import org.apache.hadoop.fs.Path
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.analysis.{CTESubstitution,
SubstituteUnresolvedOrdinals}
-import org.apache.spark.sql.catalyst.expressions.{Attribute,
AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.expressions.{Attribute,
AttributeReference, Expression, Literal, MetadataAttribute}
import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
import org.apache.spark.sql.catalyst.parser.ParserInterface
import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, Assignment,
ColumnDefinition, CTERelationRef, InsertAction, LogicalPlan, MergeAction,
MergeIntoTable, MergeRows, SubqueryAlias, TableSpec, UnresolvedWith,
UpdateAction}
@@ -87,6 +87,16 @@ class Spark4Shim extends SparkShim {
Spark4ResolutionRules(spark)
}
+ override def resolveUpdateMetadata(assignments: Seq[Assignment]):
Seq[Assignment] = {
+ assignments.map {
+ case a @ Assignment(attr: Attribute, _)
+ if MetadataAttribute.isValid(attr.metadata) &&
+ !MetadataAttribute.isPreservedOnUpdate(attr) =>
+ a.copy(value = Literal(null, attr.dataType))
+ case a => a
+ }
+ }
+
override def createSparkInternalRow(rowType: RowType): SparkInternalRow = {
new Spark4InternalRow(rowType)
}
@@ -302,6 +312,13 @@ class Spark4Shim extends SparkShim {
relation.copy(table = table, output = output)
}
+ override def copyDataSourceV2Relation(
+ relation: DataSourceV2Relation,
+ catalog: CatalogPlugin,
+ identifier: Identifier): DataSourceV2Relation = {
+ relation.copy(catalog = Some(catalog), identifier = Some(identifier))
+ }
+
override def createDataSourceV2Relation(
table: Table,
catalog: Option[CatalogPlugin],
diff --git
a/paimon-spark/paimon-spark-4.0/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
b/paimon-spark/paimon-spark-4.0/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
new file mode 100644
index 0000000000..8a71379c1b
--- /dev/null
+++
b/paimon-spark/paimon-spark-4.0/src/test/scala/org/apache/paimon/spark/sql/V2WriteDistributionTest.scala
@@ -0,0 +1,21 @@
+/*
+ * 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
+
+class V2WriteDistributionTest extends V2WriteRequireDistributionTest {}
diff --git
a/paimon-spark/paimon-spark-4.0/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
b/paimon-spark/paimon-spark-4.0/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
new file mode 100644
index 0000000000..cdf8092450
--- /dev/null
+++
b/paimon-spark/paimon-spark-4.0/src/test/scala/org/apache/paimon/spark/sql/V2WriteOptionTest.scala
@@ -0,0 +1,21 @@
+/*
+ * 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
+
+class V2WriteOptionTest extends PaimonOptionTest {}
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 21ca7b6b8b..c54ceed557 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
@@ -53,7 +53,7 @@ class RollbackStagedTable implements StagedTable,
SupportsRead, SupportsWrite, S
private static final Action DO_NOTHING = () -> {};
- private final Table table;
+ private Table table;
private final StagedAction commitAction;
private final Action abortAction;
private boolean committed;
@@ -74,6 +74,14 @@ class RollbackStagedTable implements StagedTable,
SupportsRead, SupportsWrite, S
this.abortAction = abortAction;
}
+ Table wrappedTable() {
+ return table;
+ }
+
+ void replaceWrappedTable(Table replacement) {
+ table = replacement;
+ }
+
@Override
public String name() {
return table.name();
diff --git
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/SparkConnectorOptions.java
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/SparkConnectorOptions.java
index 7368a7a03f..4a9642bc34 100644
---
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/SparkConnectorOptions.java
+++
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/SparkConnectorOptions.java
@@ -91,9 +91,12 @@ public class SparkConnectorOptions {
public static final ConfigOption<Boolean> USE_V2_WRITE =
key("write.use-v2-write")
.booleanType()
- .defaultValue(false)
+ .defaultValue(true)
.withDescription(
- "If true, v2 write will be used. Currently, only
HASH_FIXED and BUCKET_UNAWARE bucket modes are supported. Will fall back to v1
write for other bucket modes. Currently, Spark V2 write does not support
TableCapability.STREAMING_WRITE.");
+ "If true, use DataSource V2 for batch writes. "
+ + "Path-based writes without a catalog and
unsupported table configurations fall back to V1. "
+ + "Supports table, session and DataSource
write options with the standard option precedence. "
+ + "Set to false to use V1 batch writes.
Streaming writes use V1.");
public static final ConfigOption<Boolean>
HIVE_STYLE_DYNAMIC_PARTITION_ENABLED =
key("write.hive-style-dynamic-partition.enabled")
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkTableBase.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkTableBase.scala
index b816f0edc6..aa537f22b3 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkTableBase.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonSparkTableBase.scala
@@ -30,7 +30,7 @@ import org.apache.paimon.spark.write.{PaimonV2WriteBuilder,
PaimonWriteBuilder}
import org.apache.paimon.table.{CatalogTableType, Table, _}
import org.apache.paimon.table.BucketMode.{BUCKET_UNAWARE, HASH_FIXED,
POSTPONE_MODE}
-import org.apache.spark.sql.connector.catalog._
+import org.apache.spark.sql.connector.catalog.{Table => SparkCatalogTable, _}
import org.apache.spark.sql.connector.read.ScanBuilder
import org.apache.spark.sql.connector.write.{LogicalWriteInfo, WriteBuilder}
import org.apache.spark.sql.types.StructType
@@ -49,12 +49,17 @@ abstract class PaimonSparkTableBase(val table: Table)
lazy val coreOptions = new CoreOptions(table.options())
- lazy val useV2Write: Boolean = {
- val v2WriteConfigured = OptionUtils.useV2Write()
- v2WriteConfigured && supportsV2Write
+ lazy val useV2Write: Boolean = useV2WriteWithOptions(Collections.emptyMap())
+
+ private def useV2WriteWithOptions(writeOptions: JMap[String, String]):
Boolean = {
+ val key = SparkConnectorOptions.USE_V2_WRITE.key()
+ val options = Option(new CaseInsensitiveStringMap(writeOptions).get(key))
+ .map(value => Collections.singletonMap(key, value))
+ .getOrElse(table.options())
+ OptionUtils.useV2Write(options) && supportsV2Write
}
- private def supportsV2Write: Boolean = {
+ protected def supportsV2Write: Boolean = {
!coreOptions.bucketFunctionProvider().isPresent &&
coreOptions.bucketFunctionType() == BucketFunctionType.DEFAULT && {
table match {
@@ -196,7 +201,7 @@ abstract class PaimonSparkTableBase(val table: Table)
table match {
case fileStoreTable: FileStoreTable =>
val options = Options.fromMap(info.options)
- if (useV2Write) {
+ if (useV2WriteWithOptions(info.options().asCaseSensitiveMap())) {
new PaimonV2WriteBuilder(fileStoreTable, info.schema(), options)
} else {
new PaimonWriteBuilder(fileStoreTable, options)
@@ -216,3 +221,28 @@ abstract class PaimonSparkTableBase(val table: Table)
true
}
}
+
+object PaimonSparkTableBase {
+
+ /** Bind the operation's switch before Spark selects write capabilities and
a writer. */
+ def withWriteOptions(
+ table: SparkCatalogTable,
+ options: JMap[String, String]): SparkCatalogTable = {
+ val key = SparkConnectorOptions.USE_V2_WRITE.key()
+ Option(new CaseInsensitiveStringMap(options).get(key)) match {
+ case Some(value) =>
+ table match {
+ case target: SparkTable if target.getTable.options().get(key) !=
value =>
+ SparkTable.of(target.getTable.copy(Collections.singletonMap(key,
value)))
+ case staged: RollbackStagedTable =>
+ val updated = withWriteOptions(staged.wrappedTable(), options)
+ if (updated ne staged.wrappedTable()) {
+ staged.replaceWrappedTable(updated)
+ }
+ staged
+ case _ => table
+ }
+ case None => table
+ }
+ }
+}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonTableAsSelectWrite.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonTableAsSelectWrite.scala
new file mode 100644
index 0000000000..cf1512752b
--- /dev/null
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonTableAsSelectWrite.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.paimon.spark
+
+import org.apache.paimon.spark.write.PaimonWriteRequirement
+import org.apache.paimon.table.FileStoreTable
+
+import org.apache.spark.sql.{PaimonUtils, SparkSession}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.plans.logical.{AppendData, LogicalPlan}
+import org.apache.spark.sql.connector.catalog.{Identifier, StagedTable, Table,
TableCatalog}
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+import scala.collection.JavaConverters._
+
+/** Routes Spark 3.2-3.4 table-as-select writes through the normal write
planning rules. */
+object PaimonTableAsSelectWrite {
+
+ /** Returns None when Spark should handle the write with its own failure
cleanup. */
+ def writeIfSupported(
+ spark: SparkSession,
+ catalog: TableCatalog,
+ table: Table,
+ ident: Identifier,
+ query: LogicalPlan,
+ options: CaseInsensitiveStringMap): Option[Seq[InternalRow]] = {
+ PaimonUtils.withFailureCleanup {
+ val writeTable = PaimonSparkTableBase.withWriteOptions(table,
options.asCaseSensitiveMap())
+ unwrapTable(writeTable) match {
+ case target: SparkTable if target.useV2Write =>
+ // PaimonAnalysis prepares ordinary SparkTable relations. Staged
tables delegate their
+ // writer but need their legacy distribution prepared here, using
the unwrapped table.
+ val writeQuery = table match {
+ case _: RollbackStagedTable =>
+ PaimonWriteRequirement.prepareQuery(
+ target.getTable.asInstanceOf[FileStoreTable],
+ query)
+ case _ => query
+ }
+ val relation = DataSourceV2Relation.create(writeTable,
Some(catalog), Some(ident))
+ val command =
+ AppendData.byPosition(relation, writeQuery,
options.asCaseSensitiveMap().asScala.toMap)
+ PaimonUtils.createDataset(spark, command).collect()
+ table match {
+ case staged: StagedTable => staged.commitStagedChanges()
+ case _ =>
+ }
+ Some(Nil)
+ case _ => None
+ }
+ } {
+ table match {
+ case staged: StagedTable => staged.abortStagedChanges()
+ case _ => catalog.dropTable(ident)
+ }
+ }
+ }
+
+ private def unwrapTable(table: Table): Table = table match {
+ case staged: RollbackStagedTable => unwrapTable(staged.wrappedTable())
+ case _ => table
+ }
+}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkSource.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkSource.scala
index 9767f4a57e..4cbebbd1c9 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkSource.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkSource.scala
@@ -69,7 +69,16 @@ class SparkSource
schema: StructType,
partitioning: Array[Transform],
properties: JMap[String, String]): Table = {
- SparkTable.of(loadTable(properties))
+ val table = loadTable(properties)
+ if (properties.containsKey(CATALOG)) {
+ // PaimonAnalysis attaches this catalog to the relation for V2
distribution planning.
+ SparkTable.of(table)
+ } else {
+ // Pure path relations have no FunctionCatalog to resolve the bucket
function in V2 writes.
+ new SparkTable(table) {
+ override protected def supportsV2Write: Boolean = false
+ }
+ }
}
override def createRelation(
@@ -97,18 +106,15 @@ class SparkSource
}
private def loadTable(options: JMap[String, String]): DataTable = {
- val path = CoreOptions.path(options)
val sessionState = PaimonSparkSession.active.sessionState
// Only if user specifies the catalog name, then use catalog to get table,
otherwise
// use FileStoreTableFactory to get table by path
val table = if (options.containsKey(CATALOG)) {
val catalogName = options.get(CATALOG)
- val dataBaseName =
Option(options.get(DATABASE)).getOrElse(CatalogUtils.database(path))
- val tableName =
Option(options.get(TABLE)).getOrElse(CatalogUtils.table(path))
val sparkCatalog =
sessionState.catalogManager.catalog(catalogName).asInstanceOf[TableCatalog]
sparkCatalog
- .loadTable(SparkIdentifier.of(Array(dataBaseName), tableName))
+ .loadTable(tableIdentifier(options))
.asInstanceOf[SparkTable]
.getTable
.asInstanceOf[FileStoreTable]
@@ -134,12 +140,19 @@ object SparkSource {
val FORMAT_NAMES: Seq[String] =
Format.values.map(_.toString.toLowerCase(Locale.ROOT)).toSeq
// Spark dataframe read options
- private val CATALOG = "catalog"
+ private[spark] val CATALOG = "catalog"
private val DATABASE = "database"
private val TABLE = "table"
+ private[spark] def tableIdentifier(options: JMap[String, String]):
SparkIdentifier = {
+ lazy val path = CoreOptions.path(options)
+ val database =
Option(options.get(DATABASE)).getOrElse(CatalogUtils.database(path))
+ val table = Option(options.get(TABLE)).getOrElse(CatalogUtils.table(path))
+ SparkIdentifier.of(Array(database), table)
+ }
+
private def toBaseRelation(table: FileStoreTable, _sqlContext: SQLContext):
BaseRelation = {
new BaseRelation {
override def sqlContext: SQLContext = _sqlContext
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 eaf1a6e0f3..3f22389fe5 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
@@ -21,7 +21,7 @@ package org.apache.paimon.spark.catalyst
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.analysis.TableOutputResolver
import org.apache.spark.sql.catalyst.expressions.{Attribute, Cast, Expression}
-import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan,
V2WriteCommand}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan,
RepartitionByExpression, V2WriteCommand}
import org.apache.spark.sql.catalyst.trees.TreeNodeTag
import org.apache.spark.sql.execution.ui.SQLPlanMetric
import org.apache.spark.sql.internal.SQLConf
@@ -29,6 +29,10 @@ import org.apache.spark.sql.types.DataType
object Compatibility {
+ def repartitionByExpression(expressions: Seq[Expression], query:
LogicalPlan): LogicalPlan = {
+ RepartitionByExpression(expressions, query, None)
+ }
+
def resolveTableOutputColumns(
tableName: String,
expected: Seq[Attribute],
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonAnalysis.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonAnalysis.scala
index 26f9c3209c..a6bba35a07 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonAnalysis.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonAnalysis.scala
@@ -19,13 +19,14 @@
package org.apache.paimon.spark.catalyst.analysis
import org.apache.paimon.options.Options
-import org.apache.paimon.spark.SparkTable
+import org.apache.paimon.spark.{PaimonSparkTableBase, SparkSource, SparkTable}
import org.apache.paimon.spark.catalyst.Compatibility
import org.apache.paimon.spark.catalyst.analysis.PaimonRelation.isPaimonTable
import org.apache.paimon.spark.catalyst.plans.logical.{PaimonDropPartitions,
PaimonHiveDynamicPartitionQuery}
import
org.apache.paimon.spark.commands.{PaimonAnalyzeFormatTablePartitionsCommand,
PaimonAnalyzeTableColumnCommand, PaimonDynamicPartitionOverwriteCommand,
PaimonShowColumnsCommand, SchemaEvolutionHelper}
import org.apache.paimon.spark.format.PaimonFormatTable
import org.apache.paimon.spark.util.OptionUtils
+import org.apache.paimon.spark.write.PaimonWriteRequirement
import org.apache.paimon.table.FileStoreTable
import org.apache.paimon.utils.GeneratedColumn
@@ -38,6 +39,7 @@ import org.apache.spark.sql.catalyst.trees.TreeNodeTag
import org.apache.spark.sql.catalyst.util.CharVarcharUtils
import org.apache.spark.sql.connector.catalog.TableCapability
import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Implicits,
DataSourceV2Relation}
+import org.apache.spark.sql.paimon.shims.SparkShimLoader
import scala.collection.JavaConverters._
@@ -47,28 +49,7 @@ class PaimonAnalysis(session: SparkSession) extends
Rule[LogicalPlan] {
override def apply(plan: LogicalPlan): LogicalPlan = {
val withPaimonWrites = AnalysisHelper.allowInvokingTransformsInAnalyzer {
- plan.transformDown {
- // Keep fallback conversion before the generic V2 rewrite; otherwise
an already-resolved
- // query can remain as OverwritePartitionsDynamic until Spark's
capability check rejects it.
- case o @ PaimonDynamicPartitionOverwrite(r, d) if o.resolved =>
- PaimonDynamicPartitionOverwriteCommand(r, d, o.query,
o.writeOptions, o.isByName)
-
- case a: V2WriteCommand if
PaimonFormatOutputResolver.isLegacyFormatWrite(a) =>
- PaimonFormatOutputResolver.resolve(a)
-
- case a @ PaimonV2WriteCommand(table)
- if a.query.getTagValue(PAIMON_WRITE_RESOLVED).isEmpty =>
- val options = Options.fromMap(writeOptions(a).asJava)
- val mergeSchemaEnabled =
SchemaEvolutionHelper.mergeSchemaEnabled(options)
- val newQuery = resolvePaimonWrite(a, table, options,
mergeSchemaEnabled)
- if (newQuery ne a.query) {
- // Tag to short-circuit the next Analyzer pass; otherwise
inline-kept extras would loop.
- newQuery.setTagValue(PAIMON_WRITE_RESOLVED, ())
- Compatibility.withNewQuery(a, newQuery)
- } else {
- a
- }
- }
+ plan.transformDown { case command: V2WriteCommand =>
resolveWrite(bindWriteOptions(command)) }
}
withPaimonWrites.resolveOperatorsDown {
@@ -106,6 +87,66 @@ class PaimonAnalysis(session: SparkSession) extends
Rule[LogicalPlan] {
}
}
+ private def resolveWrite(command: V2WriteCommand): LogicalPlan = command
match {
+ case a @ PaimonV2WriteCommand(relation)
+ if relation.catalog.isEmpty &&
relation.options.containsKey(SparkSource.CATALOG) =>
+ // The target table is not a child of V2WriteCommand. Bind it explicitly
rather than
+ // relying on relation traversal. TableProvider.getTable does not pass
its catalog to
+ // DataFrameWriter, but V2 distribution planning needs it to resolve the
bucket function.
+ val catalog = session.sessionState.catalogManager
+ .catalog(relation.options.get(SparkSource.CATALOG))
+ a.withNewTable(
+ SparkShimLoader.shim.copyDataSourceV2Relation(
+ relation,
+ catalog,
+ SparkSource.tableIdentifier(relation.options.asCaseSensitiveMap())))
+
+ // Keep fallback conversion before the generic V2 rewrite; otherwise an
already-resolved
+ // query can remain as OverwritePartitionsDynamic until Spark's capability
check rejects it.
+ case o @ PaimonDynamicPartitionOverwrite(r, d) if o.resolved =>
+ PaimonDynamicPartitionOverwriteCommand(r, d, o.query, o.writeOptions,
o.isByName)
+
+ case a: V2WriteCommand if
PaimonFormatOutputResolver.isLegacyFormatWrite(a) =>
+ PaimonFormatOutputResolver.resolve(a)
+
+ case a @ PaimonV2WriteCommand(table) if
a.query.getTagValue(PAIMON_WRITE_RESOLVED).isEmpty =>
+ val options = Options.fromMap(writeOptions(a).asJava)
+ val mergeSchemaEnabled =
SchemaEvolutionHelper.mergeSchemaEnabled(options)
+ val resolvedQuery = resolvePaimonWrite(a, table, options,
mergeSchemaEnabled)
+ val sparkTable = table.table.asInstanceOf[SparkTable]
+ val newQuery = if (sparkTable.useV2Write) {
+ PaimonWriteRequirement.prepareQuery(
+ sparkTable.getTable.asInstanceOf[FileStoreTable],
+ resolvedQuery)
+ } else {
+ resolvedQuery
+ }
+ if (newQuery ne a.query) {
+ // Tag to short-circuit the next Analyzer pass; otherwise inline-kept
extras would loop.
+ newQuery.setTagValue(PAIMON_WRITE_RESOLVED, ())
+ Compatibility.withNewQuery(a, newQuery)
+ } else {
+ a
+ }
+ case _ => command
+ }
+
+ private def bindWriteOptions(command: V2WriteCommand): V2WriteCommand = {
+ command.table match {
+ case relation: DataSourceV2Relation
+ if relation.catalog.nonEmpty ||
relation.options.containsKey(SparkSource.CATALOG) =>
+ val table =
+ PaimonSparkTableBase.withWriteOptions(relation.table,
writeOptions(command).asJava)
+ if (table eq relation.table) {
+ command
+ } else {
+ command.withNewTable(
+ SparkShimLoader.shim.copyDataSourceV2Relation(relation, table,
relation.output))
+ }
+ case _ => command
+ }
+ }
+
private def writeOptions(v2WriteCommand: V2WriteCommand): Map[String,
String] = {
v2WriteCommand match {
case a: AppendData => a.writeOptions
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonUpdateTable.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonUpdateTable.scala
index d0ec9f80a4..a4ec97ba8d 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonUpdateTable.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/PaimonUpdateTable.scala
@@ -26,11 +26,15 @@ import
org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeReference,
import org.apache.spark.sql.catalyst.expressions.Literal.TrueLiteral
import org.apache.spark.sql.catalyst.plans.logical.{AnalysisHelper,
LogicalPlan, UpdateTable}
import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.paimon.shims.SparkShimLoader
import scala.collection.JavaConverters._
object PaimonUpdateTable extends Rule[LogicalPlan] with RowLevelHelper with
ExpressionHelper {
+ private val ALIGNED = TreeNodeTag[Boolean]("paimon.update.aligned")
+
override val operation: RowLevelOp = Update
override def apply(plan: LogicalPlan): LogicalPlan = {
@@ -38,7 +42,8 @@ object PaimonUpdateTable extends Rule[LogicalPlan] with
RowLevelHelper with Expr
// short-circuit. Use `transformDown` under
`allowInvokingTransformsInAnalyzer` instead.
AnalysisHelper.allowInvokingTransformsInAnalyzer {
plan.transformDown {
- case u @ UpdateTable(PaimonRelation(table), assignments, condition) if
u.resolved =>
+ case u @ UpdateTable(PaimonRelation(table), assignments, condition)
+ if u.resolved && !u.getTagValue(ALIGNED).contains(true) =>
checkPaimonTable(table.getTable)
table.getTable match {
@@ -91,7 +96,14 @@ object PaimonUpdateTable extends Rule[LogicalPlan] with
RowLevelHelper with Expr
throw new RuntimeException(
"Update operation is not supported when data evolution is
enabled yet.")
}
- alignedUpdateTable
+ // Metadata columns can already be in the table output when
the condition uses
+ // them. Honor Spark's update policy instead of preserving
their old values.
+ val v2UpdateTable = alignedUpdateTable.copy(
+ assignments =
SparkShimLoader.shim.resolveUpdateMetadata(alignedAssignments))
+ // Spark re-applies post-hoc rules to check idempotence before
the V2 rewrite.
+ // Avoid rebuilding struct values and metadata assignments on
that second pass.
+ v2UpdateTable.setTagValue(ALIGNED, true)
+ v2UpdateTable
} else {
if (dataEvolutionEnabled) {
UpdatePaimonDataEvolutionTableCommand(
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/util/OptionUtils.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/util/OptionUtils.scala
index c357256b7c..3cd1210bc7 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/util/OptionUtils.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/util/OptionUtils.scala
@@ -29,7 +29,7 @@ import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.SQLConfHelper
import org.apache.spark.sql.internal.StaticSQLConf
-import java.util.{HashMap => JHashMap, Map => JMap}
+import java.util.{Collections, HashMap => JHashMap, Map => JMap}
import java.util.regex.Pattern
import scala.collection.JavaConverters._
@@ -52,21 +52,6 @@ object OptionUtils extends SQLConfHelper with Logging {
conf.getConfString(s"$PAIMON_OPTION_PREFIX${option.key()}",
option.defaultValue().toString)
}
- private def getSparkVersionSpecificDefault(option: ConfigOption[_]): String
= {
- val sparkVersion = org.apache.spark.SPARK_VERSION
-
- option.key() match {
- case key if key == SparkConnectorOptions.USE_V2_WRITE.key() =>
- if (sparkVersion >= "3.4") {
- "false"
- } else {
- option.defaultValue().toString
- }
- case _ =>
- option.defaultValue().toString
- }
- }
-
private def requiredSparkConfsCheckEnabled(sparkSession: SparkSession):
Boolean = {
sparkSession.sessionState.conf
.getConfString(
@@ -86,24 +71,12 @@ object OptionUtils extends SQLConfHelper with Logging {
}
}
- def useV2Write(): Boolean = {
- val defaultValue =
getSparkVersionSpecificDefault(SparkConnectorOptions.USE_V2_WRITE)
- val configuredValue = conf
- .getConfString(
- s"$PAIMON_OPTION_PREFIX${SparkConnectorOptions.USE_V2_WRITE.key()}",
- defaultValue
- )
+ def useV2Write(options: JMap[String, String] = Collections.emptyMap()):
Boolean = {
+ // Catalog and source loading already merge session and operation options
into table options.
+ // Reading the session flag again as a veto would discard more specific
overrides.
+ Option(options.get(SparkConnectorOptions.USE_V2_WRITE.key()))
+ .getOrElse(getOptionString(SparkConnectorOptions.USE_V2_WRITE))
.toBoolean
-
- val sparkVersion = org.apache.spark.SPARK_VERSION
- val isVersionSupported = sparkVersion >= "3.4"
-
- if (configuredValue && !isVersionSupported) {
- logWarning(
- "DataSourceV2 write is not supported in Spark versions prior to 3.4.
Falling back to DataSourceV1.")
- }
-
- configuredValue && isVersionSupported
}
def writeMergeSchemaEnabled(): Boolean = {
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/PaimonV2Write.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/PaimonV2Write.scala
index a6b49a7918..9102f120de 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/PaimonV2Write.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/PaimonV2Write.scala
@@ -28,7 +28,7 @@ import org.apache.paimon.table.BucketMode.BUCKET_UNAWARE
import org.apache.paimon.table.FileStoreTable
import org.apache.spark.internal.Logging
-import org.apache.spark.sql.connector.distributions.Distribution
+import org.apache.spark.sql.connector.distributions.{Distribution,
Distributions}
import org.apache.spark.sql.connector.expressions.SortOrder
import org.apache.spark.sql.connector.metric.CustomMetric
import org.apache.spark.sql.connector.write._
@@ -52,7 +52,11 @@ class PaimonV2Write(
private val writeRequirement = PaimonWriteRequirement(table)
override def requiredDistribution(): Distribution = {
- val distribution = writeRequirement.distribution
+ val distribution = if (PaimonWriteRequirement.requiresQueryPreparation) {
+ Distributions.unspecified()
+ } else {
+ writeRequirement.distribution
+ }
logInfo(s"Requesting $distribution as write distribution for table
${table.name()}")
distribution
}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/PaimonWriteRequirement.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/PaimonWriteRequirement.scala
index be661807e4..3909b2de29 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/PaimonWriteRequirement.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/PaimonWriteRequirement.scala
@@ -20,24 +20,60 @@ package org.apache.paimon.spark.write
import org.apache.paimon.CoreOptions
import org.apache.paimon.CoreOptions.PartitionSinkStrategy
+import org.apache.paimon.spark.catalyst.Compatibility
import org.apache.paimon.spark.commands.BucketExpression.quote
+import org.apache.paimon.spark.commands.FixedBucketExpression
import org.apache.paimon.table.{FileStoreTable, FormatTable}
import org.apache.paimon.table.BucketMode._
+import org.apache.spark.sql.catalyst.SQLConfHelper
+import org.apache.spark.sql.catalyst.expressions.{Expression =>
CatalystExpression, Literal => CatalystLiteral}
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.connector.distributions.{ClusteredDistribution,
Distribution, Distributions}
-import org.apache.spark.sql.connector.expressions.{Expression, Expressions,
SortOrder}
+import org.apache.spark.sql.connector.expressions.{Expression, Expressions,
Literal, NamedReference, SortOrder, Transform}
import scala.collection.JavaConverters._
/** Distribution requirements of Spark write. */
case class PaimonWriteRequirement(distribution: Distribution, ordering:
Array[SortOrder])
-object PaimonWriteRequirement {
+object PaimonWriteRequirement extends SQLConfHelper {
private val EMPTY_ORDERING: Array[SortOrder] = Array.empty
private val EMPTY: PaimonWriteRequirement =
PaimonWriteRequirement(Distributions.unspecified(), EMPTY_ORDERING)
+ // Spark 3.2/3.3 do not pass the FunctionCatalog when preparing V2 write
distributions.
+ // Bind the same distribution with Paimon's bucket expression before Spark
prepares the write.
+ private[spark] def requiresQueryPreparation: Boolean =
org.apache.spark.SPARK_VERSION < "3.4"
+
+ def prepareQuery(table: FileStoreTable, query: LogicalPlan): LogicalPlan = {
+ if (!requiresQueryPreparation) {
+ return query
+ }
+
+ def bind(expression: Expression): CatalystExpression = expression match {
+ case reference: NamedReference =>
+ query.output.find(a => conf.resolver(a.name,
reference.fieldNames().head)).get
+ case literal: Literal[_] => CatalystLiteral(literal.value(),
literal.dataType())
+ case transform: Transform if transform.name() == "identity" =>
+ bind(transform.arguments().head)
+ case transform: Transform if transform.name() == "bucket" =>
+ FixedBucketExpression(
+ CatalystLiteral(table.coreOptions().bucketFunctionType().toString) +:
+ transform.arguments().map(bind).toSeq)
+ case other =>
+ throw new UnsupportedOperationException(s"Unsupported write
distribution: $other")
+ }
+
+ apply(table).distribution match {
+ case clustered: ClusteredDistribution =>
+ // Leave the count unspecified so AQE can coalesce the bucket shuffle
on Spark 3.2/3.3.
+
Compatibility.repartitionByExpression(clustered.clustering().map(bind).toSeq,
query)
+ case _ => query
+ }
+ }
+
def apply(table: FileStoreTable): PaimonWriteRequirement = {
val bucketSpec = table.bucketSpec()
val bucketTransforms: Seq[Expression] = bucketSpec.getBucketMode match {
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/PaimonUtils.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/PaimonUtils.scala
index 7745a0f5b0..4d218f3d8c 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/PaimonUtils.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/PaimonUtils.scala
@@ -67,6 +67,11 @@ object PaimonUtils {
SparkShimLoader.shim.classicApi.createDataset(sparkSession, logicalPlan)
}
+ /** Runs failure cleanup on interruption too, preserving the original
exception. */
+ def withFailureCleanup[T](block: => T)(cleanup: => Unit): T = {
+ SparkUtils.tryWithSafeFinallyAndFailureCallbacks(block)(catchBlock =
cleanup)
+ }
+
/** Creates a command-local disk cache, retaining AQE; the caller must
invoke its cleanup. */
def createDiskCachedDataset(
sparkSession: SparkSession,
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/PaimonTableAsSelectHelper.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/PaimonTableAsSelectHelper.scala
index 0e6411dcfa..62a6d29b42 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/PaimonTableAsSelectHelper.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/PaimonTableAsSelectHelper.scala
@@ -164,10 +164,11 @@ object PaimonTableAsSelectHelper {
}
}
- def supportsCatalog(catalog: SparkBaseCatalog, tableSpec: TableSpec):
Boolean = catalog match {
+ // Spark 3.2 does not define TableSpec, so keep it out of this shared entry
point.
+ def supportsCatalog(catalog: SparkBaseCatalog, provider: String): Boolean =
catalog match {
case _: SparkCatalog => true
case _: SparkGenericCatalog =>
- tableSpec.provider.exists(_.equalsIgnoreCase(SparkSource.NAME))
+ SparkBaseCatalog.usePaimon(provider)
case _ => false
}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
index 17a25d1076..5c4b091d2a 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/execution/shim/PaimonReplaceTableAsSelectStrategy.scala
@@ -45,7 +45,7 @@ case class PaimonReplaceTableAsSelectStrategy(spark:
SparkSession)
tableSpec: TableSpec,
options,
orCreate,
- true) if supportsCatalog(catalog, tableSpec) =>
+ true) if supportsCatalog(catalog, tableSpec.provider.orNull) =>
// For V1 saveAsTable + overwrite on an existing table, rewrite to
// OverwriteByExpression to preserve table definition.
if (isV1SaveAsTableOverwrite) {
@@ -108,7 +108,7 @@ case class PaimonReplaceTableStrategy(spark: SparkSession)
schemaOrColumns,
parts,
tableSpec: TableSpec,
- orCreate) if supportsCatalog(catalog, tableSpec) =>
+ orCreate) if supportsCatalog(catalog, tableSpec.provider.orNull) =>
val columns =
SparkShimLoader.shim.toReplaceTableColumns(
replace.tableSchema,
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala
index 07b7da7c1e..f8a3d39b4a 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/SparkShim.scala
@@ -60,6 +60,9 @@ trait SparkShim {
def createCustomResolution(spark: SparkSession): Rule[LogicalPlan]
+ // Spark 4 can invalidate metadata values when a row is updated. Spark 3
preserves them.
+ def resolveUpdateMetadata(assignments: Seq[Assignment]): Seq[Assignment] =
assignments
+
def createSparkInternalRow(rowType: RowType): SparkInternalRow
def createSparkInternalRowWithBlob(
@@ -197,6 +200,11 @@ trait SparkShim {
table: Table,
output: Seq[AttributeReference]): DataSourceV2Relation
+ def copyDataSourceV2Relation(
+ relation: DataSourceV2Relation,
+ catalog: CatalogPlugin,
+ identifier: Identifier): DataSourceV2Relation
+
// Per-version shim: Spark 4.1 added a 5th `timeTravelSpec` parameter with a
default. A 4-arg call
// site compiled against 4.1 emits a `create$default$5()` lookup absent on
4.0.
def createDataSourceV2Relation(
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CustomBucketFunctionTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CustomBucketFunctionTest.scala
index 5c18e93176..d3f51bb636 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CustomBucketFunctionTest.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CustomBucketFunctionTest.scala
@@ -49,7 +49,7 @@ class CustomBucketFunctionTest extends PaimonSparkTestBase
with AdaptiveSparkPla
createTable("default_bucket", primaryKey = true, custom = false)
val table = loadTable("custom_bucket")
assert(table.coreOptions().bucketFunctionType() ==
BucketFunctionType.DEFAULT)
- assert(SparkTable(loadTable("default_bucket")).useV2Write ==
gteqSpark3_4)
+ assert(SparkTable(loadTable("default_bucket")).useV2Write)
assert(!SparkTable(table).useV2Write)
assert(!SparkTable(table).capabilities().contains(TableCapability.BATCH_WRITE))
}
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLTestBase.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLTestBase.scala
index a5222fc8a7..b8cfd81d9d 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLTestBase.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLTestBase.scala
@@ -22,6 +22,7 @@ import org.apache.paimon.catalog.Identifier
import org.apache.paimon.schema.Schema
import org.apache.paimon.spark.PaimonSparkTestBase
import org.apache.paimon.types.{DataTypes, VectorType}
+import org.apache.paimon.utils.ExceptionUtils
import org.apache.spark.sql.{AnalysisException, Row}
import org.apache.spark.sql.catalyst.analysis.NoSuchPartitionsException
@@ -44,7 +45,11 @@ abstract class DDLTestBase extends PaimonSparkTestBase {
val e1 = intercept[Exception] {
sql("""INSERT INTO T VALUES (1, "a"), (2, "b"), (null, "c")""")
}
- Assertions.assertTrue(e1.getMessage().contains("value appeared in
non-nullable field"))
+ assert(
+ ExceptionUtils
+ .findThrowableWithMessage(e1, "value appeared in non-nullable field")
+ .isPresent,
+ ExceptionUtils.stringifyException(e1))
sql("""INSERT INTO T VALUES (1, "a"), (2, "b"), (3, null)""")
checkAnswer(
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DataFrameWriteTestBase.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DataFrameWriteTestBase.scala
index 504ecfce7c..1198f9cd93 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DataFrameWriteTestBase.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DataFrameWriteTestBase.scala
@@ -19,6 +19,7 @@
package org.apache.paimon.spark.sql
import org.apache.paimon.spark.PaimonSparkTestBase
+import org.apache.paimon.utils.ExceptionUtils
import org.apache.spark.SparkConf
import org.apache.spark.sql.Row
@@ -1010,14 +1011,18 @@ abstract class DataFrameWriteTestBase extends
PaimonSparkTestBase {
assert(msg4.contains("Only support Overwrite with one filter for
each partition column"))
// Overwrite a partition which is not the specified
- val msg5 = intercept[Exception] {
+ val error = intercept[Exception] {
spark
.range(2)
.selectExpr("id as c1", "id as c2", "'a' as p1", "id as p2")
.writeTo("t")
.overwrite($"p1" === "b")
- }.getMessage
- assert(msg5.contains("does not belong to this partition"))
+ }
+ assert(
+ ExceptionUtils
+ .findThrowableWithMessage(error, "does not belong to this
partition")
+ .isPresent,
+ ExceptionUtils.stringifyException(error))
}
}
}
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonOptionTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonOptionTest.scala
index d37f109e7e..221168c97a 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonOptionTest.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonOptionTest.scala
@@ -18,20 +18,248 @@
package org.apache.paimon.spark.sql
-import org.apache.paimon.spark.PaimonSparkTestBase
+import org.apache.paimon.spark.{PaimonSparkTestBase, SparkConnectorOptions,
SparkTable}
import org.apache.paimon.spark.util.OptionUtils
import org.apache.paimon.table.FileStoreTableFactory
import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.{Row, SparkSession}
+import org.apache.spark.sql.catalyst.plans.logical.V2WriteCommand
+import org.apache.spark.sql.connector.catalog.{Identifier, TableCapability,
TableCatalog}
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.paimon.Utils
+import org.apache.spark.sql.util.QueryExecutionListener
import org.junit.jupiter.api.Assertions
+import java.util.concurrent.ConcurrentLinkedQueue
+
+import scala.collection.JavaConverters._
+
class PaimonOptionTest extends PaimonSparkTestBase {
import testImplicits._
+ test("Paimon Option: V2 write is enabled by default") {
+ assert(SparkConnectorOptions.USE_V2_WRITE.defaultValue())
+ SQLConf.withExistingConf(new SQLConf) {
+ assert(OptionUtils.useV2Write())
+ }
+ }
+
+ test("Paimon Option: V2 write respects explicit configuration") {
+ for (enabled <- Seq(true, false)) {
+ val conf = new SQLConf
+ conf.setConfString("spark.paimon.write.use-v2-write", enabled.toString)
+ SQLConf.withExistingConf(conf) {
+ assert(OptionUtils.useV2Write() == enabled)
+ }
+ }
+ }
+
+ test("Paimon Option: default V2 write preserves table fallbacks") {
+ val tableProperties = Seq(
+ "'bucket' = '-1'" -> true,
+ "'bucket-key' = 'id', 'bucket' = '2'" -> true,
+ "'primary-key' = 'id', 'bucket' = '2'" -> true,
+ "'primary-key' = 'id', 'bucket' = '-1'" -> false
+ )
+ for ((properties, supportsV2) <- tableProperties) {
+ withTable("T") {
+ sql(s"CREATE TABLE T (id INT) TBLPROPERTIES ($properties)")
+ val table = SparkTable(loadTable("T"))
+ assert(table.capabilities().contains(TableCapability.BATCH_WRITE) ==
supportsV2)
+ assert(table.capabilities().contains(TableCapability.V1_BATCH_WRITE)
== !supportsV2)
+ sql("INSERT INTO T VALUES (1), (2)")
+ checkAnswer(sql("SELECT * FROM T"), Seq(Row(1), Row(2)))
+ }
+ }
+ }
+
+ test("Paimon Option: V2 write can be disabled for supported tables") {
+ withSparkSQLConf("spark.paimon.write.use-v2-write" -> "false") {
+ sql("CREATE TABLE T (id INT) TBLPROPERTIES ('bucket-key' = 'id',
'bucket' = '2')")
+
assert(SparkTable(loadTable("T")).capabilities().contains(TableCapability.V1_BATCH_WRITE))
+ sql("INSERT INTO T VALUES (1), (2)")
+ checkAnswer(sql("SELECT * FROM T"), Seq(Row(1), Row(2)))
+ }
+ }
+
+ test("Paimon Option: V2 write follows merged table and session option
precedence") {
+ val globalKey = "spark.paimon.write.use-v2-write"
+ val tableKey = s"spark.paimon.paimon.$dbName0.T.write.use-v2-write"
+ for (tableEnabled <- Seq(false, true)) {
+ withTable("T") {
+ sql(s"""
+ |CREATE TABLE T (id INT) TBLPROPERTIES (
+ | 'bucket-key' = 'id', 'bucket' = '2',
+ | 'write.use-v2-write' = '$tableEnabled')
+ |""".stripMargin)
+ val cases = Seq(
+ Seq.empty[(String, String)] -> tableEnabled,
+ Seq(globalKey -> "true") -> true,
+ Seq(globalKey -> "false") -> false,
+ Seq(globalKey -> "false", tableKey -> "true") -> true,
+ Seq(globalKey -> "true", tableKey -> "false") -> false
+ )
+ for (((configs, expected), index) <- cases.zipWithIndex) {
+ withSparkSQLConf(configs: _*) {
+ val table = spark.sessionState.catalogManager.currentCatalog
+ .asInstanceOf[TableCatalog]
+ .loadTable(Identifier.of(Array(dbName0), "T"))
+ assert(table.capabilities().contains(TableCapability.BATCH_WRITE)
== expected)
+
assert(table.capabilities().contains(TableCapability.V1_BATCH_WRITE) ==
!expected)
+ sql(s"INSERT INTO T VALUES ($index)")
+ }
+ }
+ checkAnswer(sql("SELECT * FROM T"), (0 until cases.size).map(Row(_)))
+ assert(loadTable("T").options().get("write.use-v2-write") ==
tableEnabled.toString)
+ }
+ }
+ }
+
+ test("Paimon Option: table V2 write option cannot enable unsupported bucket
modes") {
+ sql("""
+ |CREATE TABLE T (id INT) TBLPROPERTIES (
+ | 'primary-key' = 'id', 'bucket' = '-1', 'write.use-v2-write' =
'true')
+ |""".stripMargin)
+
assert(SparkTable(loadTable("T")).capabilities().contains(TableCapability.V1_BATCH_WRITE))
+ sql("INSERT INTO T VALUES (1), (2)")
+ checkAnswer(sql("SELECT * FROM T"), Seq(Row(1), Row(2)))
+ }
+
+ test("Paimon Option: default V2 write distributes composite bucket keys and
quoted columns") {
+ withSparkSQLConf("spark.sql.shuffle.partitions" -> "3") {
+ sql("""
+ |CREATE TABLE T (`k.id` INT, k2 STRING, pt INT)
+ |PARTITIONED BY (pt)
+ |TBLPROPERTIES (
+ | 'primary-key' = 'k.id,k2,pt',
+ | 'bucket-key' = 'k.id,k2',
+ | 'bucket' = '4')
+ |""".stripMargin)
+ sql("""
+ |INSERT INTO T SELECT
+ |CAST(id % 12 AS INT), CAST(id % 3 AS STRING), CAST(id % 2 AS INT)
+ |FROM range(0, 120, 1, 4)
+ |""".stripMargin)
+ checkAnswer(sql("SELECT * FROM T"), (0 until 12).map(i => Row(i, (i %
3).toString, i % 2)))
+ }
+ }
+
+ test("Paimon Option: path-based writes fall back to V1 without a function
catalog") {
+ sql("CREATE TABLE T (id INT) TBLPROPERTIES ('bucket-key' = 'id', 'bucket'
= '2')")
+ for (enabled <- Seq(false, true)) {
+ val writes = captureV2Writes {
+ Seq(1, 2)
+ .toDF("id")
+ .write
+ .format("paimon")
+ .option("write.use-v2-write", enabled.toString)
+ .mode("append")
+ .save(loadTable("T").location().toString)
+ }
+ assert(writes.isEmpty)
+ }
+ checkAnswer(sql("SELECT * FROM T"), Seq(Row(1), Row(2), Row(1), Row(2)))
+ }
+
+ test("Paimon Option: DataSource catalog writes bind the catalog for V2
distribution") {
+ for (adaptive <- Seq(true, false)) {
+ withSparkSQLConf(
+ "spark.sql.adaptive.enabled" -> adaptive.toString,
+ "spark.sql.shuffle.partitions" -> "3",
+ "spark.sql.sources.partitionOverwriteMode" -> "dynamic") {
+ withTable("T") {
+ sql("""
+ |CREATE TABLE T (id INT, pt INT) PARTITIONED BY (pt)
+ |TBLPROPERTIES ('bucket-key' = 'id', 'bucket' = '1')
+ |""".stripMargin)
+ val location = loadTable("T").location().toString
+ val input = spark
+ .range(0, 40, 1, 4)
+ .selectExpr("CAST(id AS INT) AS id", "CAST(id % 2 AS INT) AS pt")
+ val writes = captureV2Writes {
+ input.write
+ .format("paimon")
+ .option("catalog", "paimon")
+ .option("database", dbName0)
+ .option("table", "T")
+ .mode("append")
+ .save(location)
+ }
+ assert(writes.size == 1)
+ val relation = writes.head.table.asInstanceOf[DataSourceV2Relation]
+ assert(relation.catalog.exists(_.name() == "paimon"))
+ assert(relation.identifier.contains(Identifier.of(Array(dbName0),
"T")))
+
assert(relation.table.capabilities().contains(TableCapability.BATCH_WRITE))
+ checkAnswer(sql("SELECT * FROM T"), (0 until 40).map(i => Row(i, i %
2)))
+ checkAnswer(sql("SELECT COUNT(*) FROM `T$files`"), Seq(Row(2L)))
+
+ // A path overwrite still replaces the whole table, including
partitions absent in input.
+ val overwrites = captureV2Writes {
+ Seq((100, 0))
+ .toDF("id", "pt")
+ .write
+ .format("paimon")
+ .option("catalog", "paimon")
+ .option("database", dbName0)
+ .option("table", "T")
+ .mode("overwrite")
+ .save(location)
+ }
+ assert(overwrites.size == 1)
+ checkAnswer(sql("SELECT * FROM T"), Seq(Row(100, 0)))
+ }
+ }
+ }
+ }
+
+ test("Paimon Option: DataSource write option overrides the session V2 write
option") {
+ withSparkSQLConf("spark.paimon.write.use-v2-write" -> "false") {
+ sql("CREATE TABLE T (id INT) TBLPROPERTIES ('bucket-key' = 'id',
'bucket' = '2')")
+ for (enabled <- Seq(false, true)) {
+ val writes = captureV2Writes {
+ Seq(1, 2)
+ .toDF("id")
+ .write
+ .format("paimon")
+ .option("catalog", "paimon")
+ // Infer the database and table from the path when only the
catalog is specified.
+ .option("write.use-v2-write", enabled.toString)
+ .mode("append")
+ .save(loadTable("T").location().toString)
+ }
+ assert(writes.nonEmpty == enabled)
+ }
+ checkAnswer(sql("SELECT * FROM T"), Seq(Row(1), Row(2), Row(1), Row(2)))
+ }
+ }
+
+ private def captureV2Writes(f: => Unit): Seq[V2WriteCommand] = {
+ val writes = new ConcurrentLinkedQueue[V2WriteCommand]()
+ val listener = new QueryExecutionListener {
+ override def onSuccess(funcName: String, qe: QueryExecution, durationNs:
Long): Unit = {
+ qe.analyzed match {
+ case write: V2WriteCommand => writes.add(write)
+ case _ =>
+ }
+ }
+
+ override def onFailure(funcName: String, qe: QueryExecution, exception:
Exception): Unit = {}
+ }
+ Utils.waitUntilEventEmpty(spark)
+ spark.listenerManager.register(listener)
+ try {
+ f
+ Utils.waitUntilEventEmpty(spark)
+ writes.asScala.toSeq
+ } finally {
+ spark.listenerManager.unregister(listener)
+ }
+ }
+
test("Paimon Option: create table with sql conf") {
withSparkSQLConf("spark.paimon.scan.snapshot-id" -> "2") {
sql("CREATE TABLE T (id INT)")
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowTrackingTestBase.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowTrackingTestBase.scala
index 1d26fa3c0e..395b145095 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowTrackingTestBase.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowTrackingTestBase.scala
@@ -713,6 +713,31 @@ abstract class RowTrackingTestBase extends
PaimonSparkTestBase with AdaptiveSpar
}
}
+ Seq(false, true).foreach {
+ useV2Write =>
+ test(s"Row Tracking: update struct columns with V2 write $useV2Write") {
+ withSparkSQLConf("spark.paimon.write.use-v2-write" ->
useV2Write.toString) {
+ withTable("t") {
+ sql("""CREATE TABLE t (id INT, data STRUCT<a: INT, b: STRING>,
other STRUCT<a: INT>)
+ |TBLPROPERTIES ('row-tracking.enabled' =
'true')""".stripMargin)
+ sql("""INSERT INTO t SELECT /*+ REPARTITION(1) */ * FROM VALUES
+ |(1, named_struct('a', 1, 'b', 'one'), named_struct('a',
10)),
+ |(2, NULL, NULL)""".stripMargin)
+
+ sql("UPDATE t SET data.a = data.a + 1 WHERE _ROW_ID = 0")
+ checkAnswer(
+ sql("SELECT *, _ROW_ID, _SEQUENCE_NUMBER FROM t"),
+ Seq(Row(1, Row(2, "one"), Row(10), 0L, 2L), Row(2, null, null,
1L, 1L)))
+
+ sql("UPDATE t SET data = named_struct('b', 'three', 'a', 3) WHERE
_ROW_ID = 0")
+ checkAnswer(
+ sql("SELECT *, _ROW_ID, _SEQUENCE_NUMBER FROM t"),
+ Seq(Row(1, Row(3, "three"), Row(10), 0L, 3L), Row(2, null, null,
1L, 1L)))
+ }
+ }
+ }
+ }
+
test("Row Tracking: update table without condition") {
withTable("t") {
sql("CREATE TABLE t (id INT, data INT) TBLPROPERTIES
('row-tracking.enabled' = 'true')")
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/V2WriteRequireDistributionTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/V2WriteRequireDistributionTest.scala
index 3ea7b2d8eb..69cbfa97be 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/V2WriteRequireDistributionTest.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/V2WriteRequireDistributionTest.scala
@@ -18,16 +18,37 @@
package org.apache.paimon.spark.sql
+import org.apache.paimon.catalog.{Identifier => PaimonIdentifier}
import org.apache.paimon.spark.PaimonSparkTestBase
+import org.apache.paimon.spark.catalog.WithPaimonCatalog
+import org.apache.paimon.spark.commands.FixedBucketExpression
+import org.apache.paimon.utils.ExceptionUtils
-import org.apache.spark.sql.Row
-import org.apache.spark.sql.execution.CommandResultExec
+import org.apache.spark.SparkConf
+import org.apache.spark.scheduler.{SparkListener, SparkListenerStageSubmitted,
SparkListenerTaskStart}
+import org.apache.spark.sql.{Row, SparkSession}
+import org.apache.spark.sql.connector.catalog.{Identifier, TableCapability,
TableCatalog}
+import org.apache.spark.sql.execution.{CommandResultExec, QueryExecution,
SparkPlan}
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
-import org.apache.spark.sql.execution.datasources.v2.{AppendDataExec,
AppendDataExecV1}
+import org.apache.spark.sql.execution.datasources.v2.{AppendDataExec,
AppendDataExecV1, V2TableWriteExec}
import org.apache.spark.sql.execution.exchange.ShuffleExchangeLike
+import org.apache.spark.sql.paimon.Utils
+import org.apache.spark.sql.util.QueryExecutionListener
+
+import java.util.UUID
+import java.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, TimeUnit}
+import java.util.concurrent.atomic.AtomicReference
+
+import scala.collection.JavaConverters._
class V2WriteRequireDistributionTest extends PaimonSparkTestBase with
AdaptiveSparkPlanHelper {
+ override protected def sparkConf: SparkConf = {
+ super.sparkConf
+ .set("spark.sql.catalog.spark_catalog",
"org.apache.paimon.spark.SparkGenericCatalog")
+ .set("spark.sql.catalog.spark_catalog.warehouse",
tempDBDir.getCanonicalPath)
+ }
+
test("V2 write primary key table") {
withTable("t1") {
@@ -63,7 +84,7 @@ class V2WriteRequireDistributionTest extends
PaimonSparkTestBase with AdaptiveSp
val node2 = nodes(1)
assert(
node2.isInstanceOf[ShuffleExchangeLike] &&
-
node2.toString.contains("org.apache.paimon.spark.catalog.functions.BucketFunction"),
+ hasBucketFunction(node2),
s"Expected ShuffleExchangeLike with BucketFunction, but got: $node2"
)
@@ -113,7 +134,7 @@ class V2WriteRequireDistributionTest extends
PaimonSparkTestBase with AdaptiveSp
val node2 = nodes(1)
assert(
node2.isInstanceOf[ShuffleExchangeLike] &&
-
node2.toString.contains("org.apache.paimon.spark.catalog.functions.BucketFunction"),
+ hasBucketFunction(node2),
s"Expected ShuffleExchangeLike with BucketFunction, but got: $node2"
)
}
@@ -156,4 +177,451 @@ class V2WriteRequireDistributionTest extends
PaimonSparkTestBase with AdaptiveSp
}
}
}
+
+ for (enabled <- Seq(false, true); primaryKey <- Seq(false, true); adaptive
<- Seq(false, true)) {
+ test(
+ s"Table-as-select bucket distribution: v2=$enabled,
primaryKey=$primaryKey, adaptive=$adaptive") {
+ withSparkSQLConf(
+ "spark.paimon.write.use-v2-write" -> enabled.toString,
+ "spark.sql.shuffle.partitions" -> "4",
+ "spark.sql.adaptive.enabled" -> adaptive.toString) {
+ val key = if (primaryKey) "'primary-key' = 'id'" else "'bucket-key' =
'id'"
+ val definition = s"USING paimon TBLPROPERTIES ($key, 'bucket'='1',
'file.format'='avro')"
+ val query = "SELECT CAST(id AS INT) AS id FROM range(0, 40, 1, 4)"
+ withTable("t1") {
+ sql(s"CREATE TABLE t1 $definition AS $query")
+ assertSingleBucketFile()
+ checkAnswer(sql("SELECT * FROM t1"), (0 until 40).map(Row(_)))
+
+ sql(s"REPLACE TABLE t1 $definition AS $query")
+ assertSingleBucketFile()
+ checkAnswer(sql("SELECT * FROM t1"), (0 until 40).map(Row(_)))
+
+ sql(s"CREATE OR REPLACE TABLE t1 $definition AS $query")
+ assertSingleBucketFile()
+ checkAnswer(sql("SELECT * FROM t1"), (0 until 40).map(Row(_)))
+ }
+ withTable("t1") {
+ sql(s"CREATE OR REPLACE TABLE t1 $definition AS $query")
+ assertSingleBucketFile()
+ checkAnswer(sql("SELECT * FROM t1"), (0 until 40).map(Row(_)))
+ }
+ }
+ }
+ }
+
+ test("Table-as-select bucket distribution with SparkGenericCatalog") {
+ val session = spark
+ val tableName = s"spark_catalog.$dbName0.generic_ctas"
+ val definition =
+ "USING paimon TBLPROPERTIES ('primary-key'='id', 'bucket'='1',
'file.format'='avro')"
+ val query = "SELECT CAST(id AS INT) AS id FROM range(0, 40, 1, 4)"
+ for (adaptive <- Seq(false, true)) {
+ withSparkSQLConf("spark.sql.adaptive.enabled" -> adaptive.toString) {
+ try {
+ for (command <- Seq("CREATE TABLE", "REPLACE TABLE", "CREATE OR
REPLACE TABLE")) {
+ session.sql(s"$command $tableName $definition AS $query")
+ val table = session.sessionState.catalogManager
+ .catalog("spark_catalog")
+ .asInstanceOf[TableCatalog]
+ .loadTable(Identifier.of(Array(dbName0), "generic_ctas"))
+ assert(table.capabilities().contains(TableCapability.BATCH_WRITE))
+ checkAnswer(
+ session.sql(s"SELECT COUNT(*) FROM
spark_catalog.$dbName0.`generic_ctas$$files`"),
+ Row(1L))
+ checkAnswer(session.sql(s"SELECT * FROM $tableName"), (0 until
40).map(Row(_)))
+ }
+ } finally {
+ session.sql(s"DROP TABLE IF EXISTS $tableName")
+ }
+ }
+ }
+ }
+
+ for (catalog <- Seq("paimon", "spark_catalog"); mode <- Seq("append",
"overwrite")) {
+ test(s"New-table saveAsTable honors the write option: catalog=$catalog,
mode=$mode") {
+ val tableName = s"save_as_table_${catalog}_$mode"
+ val target = s"$catalog.$dbName0.$tableName"
+ for (sessionEnabled <- Seq(true, false); enabled <- Seq(false, true)) {
+ withSparkSQLConf("spark.paimon.write.use-v2-write" ->
sessionEnabled.toString) {
+ withTable(target) {
+ val modes = captureWriteModes {
+ spark
+ .range(0, 40, 1, 4)
+ .selectExpr("CAST(id AS INT) AS id")
+ .write
+ .format("paimon")
+ .option("bucket-key", "id")
+ .option("bucket", "1")
+ .option("file.format", "avro")
+ .option(
+ if (enabled) "WRITE.USE-V2-WRITE" else "write.use-v2-write",
+ enabled.toString)
+ .mode(mode)
+ .saveAsTable(target)
+ }
+ assert(!enabled || modes.nonEmpty, "Expected to observe the V2
writer")
+ assert(modes.forall(_ == enabled), s"Expected V2=$enabled but
observed $modes")
+ checkAnswer(sql(s"SELECT * FROM $target"), (0 until
40).map(Row(_)))
+ assert(persistentWriteOption(catalog, tableName) == null)
+ val loaded = spark.sessionState.catalogManager
+ .catalog(catalog)
+ .asInstanceOf[TableCatalog]
+ .loadTable(Identifier.of(Array(dbName0), tableName))
+ assert(loaded.capabilities().contains(TableCapability.BATCH_WRITE)
== sessionEnabled)
+ }
+ }
+ }
+ }
+ }
+
+ for (catalog <- Seq("paimon", "spark_catalog")) {
+ test(s"DataFrameWriterV2 write option overrides persistent and session
switches: $catalog") {
+ val tableName = s"writer_v2_ctas_$catalog"
+ val target = s"$catalog.$dbName0.$tableName"
+ for (enabled <- Seq(false, true)) {
+ withSparkSQLConf("spark.paimon.write.use-v2-write" ->
(!enabled).toString) {
+ withTable(target) {
+ val modes = captureWriteModes {
+ spark
+ .range(0, 40, 1, 4)
+ .selectExpr("CAST(id AS INT) AS id")
+ .writeTo(target)
+ .using("paimon")
+ .tableProperty("bucket-key", "id")
+ .tableProperty("bucket", "1")
+ .tableProperty("write.use-v2-write", (!enabled).toString)
+ .option("write.use-v2-write", enabled.toString)
+ .create()
+ }
+ assert(!enabled || modes.nonEmpty, "Expected to observe the V2
writer")
+ assert(modes.forall(_ == enabled), s"Observed writers: $modes")
+ checkAnswer(sql(s"SELECT * FROM $target"), (0 until
40).map(Row(_)))
+ assert(persistentWriteOption(catalog, tableName) ==
(!enabled).toString)
+ }
+ }
+ }
+ }
+
+ test(s"Invalid CTAS write option cleans up and allows retry: $catalog") {
+ val target = s"$catalog.$dbName0.invalid_writer_option_ctas_$catalog"
+ withTable(target) {
+ val error = intercept[Exception] {
+ spark
+ .range(0, 2)
+ .selectExpr("CAST(id AS INT) AS id")
+ .write
+ .format("paimon")
+ .option("write.use-v2-write", "typo")
+ .saveAsTable(target)
+ }
+ assert(ExceptionUtils.findThrowableWithMessage(error,
"typo").isPresent)
+ val tableCatalog = spark.sessionState.catalogManager
+ .catalog(catalog)
+ .asInstanceOf[TableCatalog]
+ assert(
+ !tableCatalog.tableExists(
+ Identifier.of(Array(dbName0),
s"invalid_writer_option_ctas_$catalog")))
+ val modes = captureWriteModes {
+ spark
+ .range(0, 2)
+ .selectExpr("CAST(id AS INT) AS id")
+ .write
+ .format("paimon")
+ .option("write.use-v2-write", "false")
+ .saveAsTable(target)
+ }
+ assert(modes.forall(!_))
+ checkAnswer(sql(s"SELECT * FROM $target"), Seq(Row(0), Row(1)))
+ }
+ }
+ }
+
+ test("New-table saveAsTable cannot enable V2 for an unsupported table") {
+ withTable("unsupported_ctas") {
+ val modes = captureWriteModes {
+ spark
+ .range(0, 40, 1, 4)
+ .selectExpr("CAST(id AS INT) AS id")
+ .write
+ .format("paimon")
+ .option("primary-key", "id")
+ .option("bucket", "-1")
+ .option("write.use-v2-write", "true")
+ .saveAsTable("unsupported_ctas")
+ }
+ assert(modes.forall(!_))
+ val table = spark.sessionState.catalogManager.currentCatalog
+ .asInstanceOf[TableCatalog]
+ .loadTable(Identifier.of(Array(dbName0), "unsupported_ctas"))
+ assert(table.capabilities().contains(TableCapability.V1_BATCH_WRITE))
+ checkAnswer(sql("SELECT * FROM unsupported_ctas"), (0 until
40).map(Row(_)))
+ }
+ }
+
+ for (adaptive <- Seq(false, true)) {
+ test(
+ s"GenericCatalog prepares table-as-select writes with an omitted
provider: AQE=$adaptive") {
+ val target = s"spark_catalog.$dbName0.default_provider_ctas"
+ withSparkSQLConf(
+ "spark.sql.sources.default" -> "paimon",
+ "spark.sql.legacy.createHiveTableByDefault" -> "false",
+ "spark.sql.adaptive.enabled" -> adaptive.toString,
+ "spark.paimon.write.use-v2-write" -> "true"
+ ) {
+ withTable(target) {
+ for (operation <- Seq("create", "replace", "createOrReplace")) {
+ val writer = spark
+ .range(0, 40, 1, 4)
+ .selectExpr("CAST(id AS INT) AS id")
+ .writeTo(target)
+ .tableProperty("bucket-key", "id")
+ .tableProperty("bucket", "1")
+ .tableProperty("file.format", "avro")
+ operation match {
+ case "create" => writer.create()
+ case "replace" => writer.replace()
+ case "createOrReplace" => writer.createOrReplace()
+ }
+ checkAnswer(sql(s"SELECT * FROM $target"), (0 until
40).map(Row(_)))
+ checkAnswer(
+ sql(s"SELECT COUNT(*) FROM
spark_catalog.$dbName0.`default_provider_ctas$$files`"),
+ Row(1L))
+ }
+ }
+ }
+ }
+ }
+
+ test("Table-as-select write failure drops the newly created table") {
+ withTable("t1") {
+ val error = intercept[Exception] {
+ sql("""
+ |CREATE TABLE t1 USING paimon
+ |TBLPROPERTIES ('primary-key'='id', 'bucket'='1',
'file.format'='avro') AS
+ |SELECT CAST(IF(id = 20, raise_error('expected CTAS failure'),
id) AS INT) AS id
+ |FROM range(0, 40, 1, 4)
+ |""".stripMargin)
+ }
+ assert(
+ ExceptionUtils.findThrowableWithMessage(error, "expected CTAS
failure").isPresent,
+ ExceptionUtils.stringifyException(error))
+ assert(!spark.catalog.tableExists("t1"))
+ }
+ }
+
+ for (tableOption <- Seq(false, true); genericCatalog <- Seq(false, true)) {
+ test(
+ s"CTAS option failure cleans up and allows retry:
tableOption=$tableOption, staged=$genericCatalog") {
+ assume(org.apache.spark.SPARK_VERSION < "3.5")
+ val catalogName = if (genericCatalog) "spark_catalog" else "paimon"
+ val catalog =
+
spark.sessionState.catalogManager.catalog(catalogName).asInstanceOf[TableCatalog]
+ val ident = Identifier.of(Array(dbName0), "invalid_option_ctas")
+ val target = s"$catalogName.$dbName0.invalid_option_ctas"
+ val properties = "'bucket-key'='id', 'bucket'='1', 'file.format'='avro'"
+ val invalidOption = if (tableOption) ", 'write.use-v2-write'='typo'"
else ""
+ val sessionOptions =
+ if (tableOption) Seq.empty[(String, String)]
+ else Seq("spark.paimon.write.use-v2-write" -> "typo")
+ val query = "SELECT CAST(id AS INT) AS id FROM range(0, 40, 1, 4)"
+ try {
+ val error = intercept[Exception] {
+ withSparkSQLConf(sessionOptions: _*) {
+ sql(
+ s"CREATE TABLE $target USING paimon TBLPROPERTIES
($properties$invalidOption) AS $query")
+ .collect()
+ }
+ }
+ assert(
+ ExceptionUtils.findThrowableWithMessage(error, "typo").isPresent,
+ ExceptionUtils.stringifyException(error))
+ assert(!catalog.tableExists(ident), "Invalid write options left the
CTAS table registered")
+
+ withSparkSQLConf("spark.paimon.write.use-v2-write" -> "true") {
+ sql(
+ s"CREATE TABLE IF NOT EXISTS $target USING paimon TBLPROPERTIES
($properties) AS $query")
+ .collect()
+ checkAnswer(sql(s"SELECT * FROM $target"), (0 until 40).map(Row(_)))
+ }
+ } finally {
+ if (catalog.tableExists(ident)) {
+ catalog.dropTable(ident)
+ }
+ }
+ }
+ }
+
+ for (enabled <- Seq(false, true)) {
+ test(s"Bucket write retains adaptive shuffle coalescing: v2=$enabled") {
+ withSparkSQLConf(
+ "spark.paimon.write.use-v2-write" -> enabled.toString,
+ "spark.sql.adaptive.enabled" -> "true",
+ "spark.sql.adaptive.coalescePartitions.enabled" -> "true",
+ "spark.sql.adaptive.coalescePartitions.minPartitionNum" -> "1",
+ "spark.sql.shuffle.partitions" -> "200"
+ ) {
+ withTable("t1") {
+ sql("""
+ |CREATE TABLE t1 (id INT) USING paimon
+ |TBLPROPERTIES ('bucket-key'='id', 'bucket'='1',
'file.format'='avro')
+ |""".stripMargin)
+ val group = UUID.randomUUID().toString
+ val stageTasks = new ConcurrentLinkedQueue[Int]()
+ val listener = new SparkListener {
+ override def onStageSubmitted(event: SparkListenerStageSubmitted):
Unit = {
+ if (event.properties.getProperty("spark.jobGroup.id") == group) {
+ stageTasks.add(event.stageInfo.numTasks)
+ }
+ }
+ }
+ spark.sparkContext.addSparkListener(listener)
+ try {
+ spark.sparkContext.setJobGroup(group, group)
+ sql("INSERT INTO t1 SELECT CAST(id AS INT) FROM range(0, 40, 1,
4)").collect()
+ Utils.waitUntilEventEmpty(spark)
+ } finally {
+ spark.sparkContext.clearJobGroup()
+ spark.sparkContext.removeSparkListener(listener)
+ }
+ checkAnswer(sql("SELECT * FROM t1"), (0 until 40).map(Row(_)))
+ assertSingleBucketFile()
+ assert(stageTasks.asScala.toSeq == Seq(4, 1), s"Submitted stage
tasks: $stageTasks")
+ }
+ }
+ }
+ }
+
+ for (enabled <- Seq(false, true); genericCatalog <- Seq(false, true)) {
+ test(s"Interrupted CTAS cleans up its table: v2=$enabled,
staged=$genericCatalog") {
+ // Spark 3.5+ already uses native distribution preparation and native
failure cleanup.
+ assume(org.apache.spark.SPARK_VERSION < "3.5")
+ withSparkSQLConf("spark.paimon.write.use-v2-write" -> enabled.toString) {
+ val session = spark
+ val catalogName = if (genericCatalog) "spark_catalog" else "paimon"
+ val catalog = session.sessionState.catalogManager
+ .catalog(catalogName)
+ .asInstanceOf[TableCatalog]
+ val ident = Identifier.of(Array(dbName0), "interrupted_ctas")
+ val target = s"$catalogName.$dbName0.interrupted_ctas"
+ val group = UUID.randomUUID().toString
+ val taskStarted = new CountDownLatch(1)
+ val finished = new CountDownLatch(1)
+ val failure = new AtomicReference[Throwable]()
+ val listener = new SparkListener {
+ private val stages = scala.collection.mutable.Set.empty[Int]
+
+ override def onStageSubmitted(event: SparkListenerStageSubmitted):
Unit = {
+ if (event.properties.getProperty("spark.jobGroup.id") == group) {
+ stages.add(event.stageInfo.stageId)
+ }
+ }
+
+ override def onTaskStart(event: SparkListenerTaskStart): Unit = {
+ if (stages.contains(event.stageId)) {
+ taskStarted.countDown()
+ }
+ }
+ }
+ session.udf.register(
+ "ctas_interrupt_input",
+ (id: Long) => {
+ Thread.sleep(30000)
+ id.toInt
+ })
+ val driver = new Thread("interrupted-ctas-driver") {
+ override def run(): Unit = {
+ SparkSession.setActiveSession(session)
+ session.sparkContext.setJobGroup(group, group, interruptOnCancel =
true)
+ try {
+ session
+ .sql(s"""
+ |CREATE TABLE $target USING paimon
+ |TBLPROPERTIES ('bucket-key'='id', 'bucket'='1',
'file.format'='avro') AS
+ |SELECT ctas_interrupt_input(id) AS id FROM range(0,
40, 1, 4)
+ |""".stripMargin)
+ .collect()
+ } catch {
+ case error: Throwable => failure.set(error)
+ } finally {
+ session.sparkContext.clearJobGroup()
+ SparkSession.clearActiveSession()
+ finished.countDown()
+ }
+ }
+ }
+ driver.setDaemon(true)
+ session.sparkContext.addSparkListener(listener)
+ try {
+ driver.start()
+ assert(taskStarted.await(30, TimeUnit.SECONDS), "CTAS did not start
its input tasks")
+ assert(catalog.tableExists(ident), "CTAS must create the table
before interruption")
+ driver.interrupt()
+ assert(finished.await(30, TimeUnit.SECONDS), "Interrupted CTAS did
not finish")
+ assert(
+ failure.get().isInstanceOf[InterruptedException],
+ s"Expected the original InterruptedException, got
${failure.get()}")
+ // Assert before cancelling executor tasks: job cancellation must
not mask the failure.
+ assert(!catalog.tableExists(ident), "Interrupted CTAS left its table
registered")
+ } finally {
+ driver.interrupt()
+ session.sparkContext.cancelJobGroup(group)
+ driver.join(10000)
+ session.sparkContext.removeSparkListener(listener)
+ session.sql("DROP TEMPORARY FUNCTION IF EXISTS ctas_interrupt_input")
+ if (catalog.tableExists(ident)) {
+ catalog.dropTable(ident)
+ }
+ }
+ }
+ }
+ }
+
+ private def persistentWriteOption(catalog: String, tableName: String):
String = {
+ spark.sessionState.catalogManager
+ .catalog(catalog)
+ .asInstanceOf[WithPaimonCatalog]
+ .paimonCatalog()
+ .getTable(PaimonIdentifier.create(dbName0, tableName))
+ .options()
+ .get("write.use-v2-write")
+ }
+
+ private def captureWriteModes(f: => Unit): Seq[Boolean] = {
+ val modes = new ConcurrentLinkedQueue[Boolean]()
+ val listener = new QueryExecutionListener {
+ override def onSuccess(funcName: String, qe: QueryExecution, durationNs:
Long): Unit = {
+ val plan = qe.executedPlan match {
+ case result: CommandResultExec => result.commandPhysicalPlan
+ case other => other
+ }
+ collect(plan) {
+ case _: AppendDataExecV1 => false
+ case _: AppendDataExec => true
+ // Native CTAS writes directly, without an AppendData node.
+ case write: V2TableWriteExec if write.commitProgress.isDefined =>
true
+ }.foreach(modes.add)
+ }
+
+ override def onFailure(funcName: String, qe: QueryExecution, exception:
Exception): Unit = {}
+ }
+ Utils.waitUntilEventEmpty(spark)
+ spark.listenerManager.register(listener)
+ try {
+ f
+ Utils.waitUntilEventEmpty(spark)
+ modes.asScala.toList
+ } finally {
+ spark.listenerManager.unregister(listener)
+ }
+ }
+
+ private def assertSingleBucketFile(): Unit = {
+ checkAnswer(sql("SELECT COUNT(*) FROM `t1$files`"), Row(1L))
+ }
+
+ private def hasBucketFunction(plan: SparkPlan): Boolean = {
+
plan.toString.contains("org.apache.paimon.spark.catalog.functions.BucketFunction")
||
+ plan.expressions.exists(_.collect { case _: FixedBucketExpression => true
}.nonEmpty)
+ }
}
diff --git
a/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala
b/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala
index 66dc9828c9..2910babef0 100644
---
a/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala
+++
b/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Spark3Shim.scala
@@ -282,6 +282,13 @@ class Spark3Shim extends SparkShim {
relation.copy(table = table, output = output)
}
+ override def copyDataSourceV2Relation(
+ relation: DataSourceV2Relation,
+ catalog: CatalogPlugin,
+ identifier: Identifier): DataSourceV2Relation = {
+ relation.copy(catalog = Some(catalog), identifier = Some(identifier))
+ }
+
override def createDataSourceV2Relation(
table: Table,
catalog: Option[CatalogPlugin],
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 f98f43b294..69795c1317 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
@@ -34,7 +34,7 @@ import org.apache.hadoop.fs.Path
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.analysis.CTESubstitution
-import org.apache.spark.sql.catalyst.expressions.{Attribute,
AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.expressions.{Attribute,
AttributeReference, Expression, Literal, MetadataAttribute}
import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
import org.apache.spark.sql.catalyst.parser.ParserInterface
import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, Assignment,
ColumnDefinition, CTERelationRef, InsertAction, LogicalPlan, MergeAction,
MergeIntoTable, MergeRows, SubqueryAlias, TableSpec, UnresolvedWith,
UpdateAction}
@@ -71,6 +71,16 @@ class Spark4Shim extends SparkShim {
Spark4ResolutionRules(spark)
}
+ override def resolveUpdateMetadata(assignments: Seq[Assignment]):
Seq[Assignment] = {
+ assignments.map {
+ case a @ Assignment(attr: Attribute, _)
+ if MetadataAttribute.isValid(attr.metadata) &&
+ !MetadataAttribute.isPreservedOnUpdate(attr) =>
+ a.copy(value = Literal(null, attr.dataType))
+ case a => a
+ }
+ }
+
override def createSparkInternalRow(rowType: RowType): SparkInternalRow = {
new Spark4InternalRow(rowType)
}
@@ -286,6 +296,13 @@ class Spark4Shim extends SparkShim {
relation.copy(table = table, output = output)
}
+ override def copyDataSourceV2Relation(
+ relation: DataSourceV2Relation,
+ catalog: CatalogPlugin,
+ identifier: Identifier): DataSourceV2Relation = {
+ relation.copy(catalog = Some(catalog), identifier = Some(identifier))
+ }
+
override def createDataSourceV2Relation(
table: Table,
catalog: Option[CatalogPlugin],