From bb9dc5efe80ec06e1987675b683ce72c7f9d7d74 Mon Sep 17 00:00:00 2001 From: yangjie01 Date: Sun, 22 Nov 2026 22:53:44 +0800 Subject: [PATCH 1/2] [spark] Fix CREATE TABLE LIKE on Spark 4.2 and 4.3 --- .../Spark42RewriteCreateTableLike.scala | 73 ++++++++++++++++++ .../org/apache/paimon/spark/sql/DDLTest.scala | 21 +++++ .../spark/sql/DDLWithHiveCatalogTest.scala | 21 +++++ ...2CatalogQualifiedCreateTableLikeTest.scala | 22 ++++++ ...stractPaimonSparkSqlExtensionsParser.scala | 32 +++++++- .../RewriteCreateTableLikeCommand.scala | 76 ++++++++++++++----- 6 files changed, 221 insertions(+), 24 deletions(-) create mode 100644 paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/Spark42RewriteCreateTableLike.scala create mode 100644 paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/DDLTest.scala create mode 100644 paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTest.scala create mode 100644 paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CatalogQualifiedCreateTableLikeTest.scala diff --git a/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/Spark42RewriteCreateTableLike.scala b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/Spark42RewriteCreateTableLike.scala new file mode 100644 index 000000000000..ac0ce9887220 --- /dev/null +++ b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/Spark42RewriteCreateTableLike.scala @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.parser.extensions + +import org.apache.spark.sql.SparkSession +import org.apache.spark.sql.catalyst.analysis.{UnresolvedIdentifier, UnresolvedTableOrView} +import org.apache.spark.sql.catalyst.plans.logical.{CreateTableLike, LogicalPlan} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.errors.QueryCompilationErrors +import org.apache.spark.sql.internal.HiveSerDe + +/** + * Spark 4.2 parses CREATE TABLE LIKE into the v2 [[CreateTableLike]] plan instead of + * `CreateTableLikeCommand`, so [[RewriteCreateTableLikeCommand]] never sees it. This rule hands the + * same fields to [[RewriteCreateTableLikeCommand.rewrite]]. + */ +case class Spark42RewriteCreateTableLike(spark: SparkSession) extends Rule[LogicalPlan] { + + private lazy val rewriter = RewriteCreateTableLikeCommand(spark) + + override def apply(plan: LogicalPlan): LogicalPlan = plan.resolveOperatorsUp { + case c @ CreateTableLike( + UnresolvedIdentifier(target, _), + source: UnresolvedTableOrView, + location, + provider, + serdeInfo, + properties, + ifNotExists) => + rewriter + .rewrite( + toV1Parts(target), + toV1Parts(source.multipartIdentifier), + provider, + // Spark builds the same storage format for its v1 fallback. + HiveSerDe.buildStorageFormat( + location, + serdeInfo, + QueryCompilationErrors.invalidFileFormatForStoredAsError), + properties, + ifNotExists + ) + .getOrElse(c) + } + + /** + * Joins the parts between the first and the last into one database name when there are more than + * three, as `PaimonSqlExtensionsAstBuilder` does for the names it parses. + */ + private def toV1Parts(parts: Seq[String]): Seq[String] = { + if (parts.length <= 3) { + parts + } else { + Seq(parts.head, parts.slice(1, parts.length - 1).mkString("."), parts.last) + } + } +} diff --git a/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/DDLTest.scala b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/DDLTest.scala new file mode 100644 index 000000000000..b729f57b33e7 --- /dev/null +++ b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/DDLTest.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 DDLTest extends DDLTestBase {} diff --git a/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTest.scala b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTest.scala new file mode 100644 index 000000000000..a9ea3efc89ba --- /dev/null +++ b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTest.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 DDLWithHiveCatalogTest extends DDLWithHiveCatalogTestBase {} diff --git a/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CatalogQualifiedCreateTableLikeTest.scala b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CatalogQualifiedCreateTableLikeTest.scala new file mode 100644 index 000000000000..317f8583e8d5 --- /dev/null +++ b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CatalogQualifiedCreateTableLikeTest.scala @@ -0,0 +1,22 @@ +/* + * 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 + +/** Runs the shared suite from `paimon-spark-ut`, whose own suites this module does not run. */ +class Spark42CatalogQualifiedCreateTableLikeTest extends CatalogQualifiedCreateTableLikeTest diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/AbstractPaimonSparkSqlExtensionsParser.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/AbstractPaimonSparkSqlExtensionsParser.scala index 6cede203d4b0..8c0d105f8a6d 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/AbstractPaimonSparkSqlExtensionsParser.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/AbstractPaimonSparkSqlExtensionsParser.scala @@ -116,12 +116,38 @@ abstract class AbstractPaimonSparkSqlExtensionsParser(val delegate: ParserInterf MarkHiveDynamicPartitionWrite, RewritePaimonViewCommands(sparkSession), RewritePaimonFunctionCommands(sparkSession), - SparkShimLoader.shim.rewritePaimonSQLFunctionCommands(sparkSession), + SparkShimLoader.shim.rewritePaimonSQLFunctionCommands(sparkSession) + ) ++ spark42CreateTableLikeRule.map(_.newInstance(sparkSession)) ++ Seq( RewriteCreateTableLikeCommand(sparkSession), RewriteSparkDDLCommands(sparkSession) ) } + /** + * Loaded by name because the class is compiled only for Spark 4.2 and later. Without it on the + * classpath CREATE TABLE LIKE is left to Spark. + */ + private lazy val spark42CreateTableLikeRule + : Option[java.lang.reflect.Constructor[Rule[LogicalPlan]]] = { + if (org.apache.spark.SPARK_VERSION >= "4.2") { + val className = + "org.apache.spark.sql.catalyst.parser.extensions.Spark42RewriteCreateTableLike" + try { + Some( + Class + .forName(className) + .getConstructor(classOf[SparkSession]) + .asInstanceOf[java.lang.reflect.Constructor[Rule[LogicalPlan]]]) + } catch { + case _: ClassNotFoundException => + logWarning(s"$className is not on the classpath; CREATE TABLE LIKE is left to Spark.") + None + } + } else { + None + } + } + /** Parses a string to an Expression. */ def parseExpression(sqlText: String): Expression = delegate.parseExpression(sqlText) @@ -184,10 +210,10 @@ abstract class AbstractPaimonSparkSqlExtensionsParser(val delegate: ParserInterf /** * Cheap token-level check for `CREATE TABLE [IF NOT EXISTS] x.y[.z] LIKE ...` shape. Used as a * gate for the Paimon parser fallback when the delegate parser rejects a catalog-qualified CREATE - * TABLE LIKE statement. + * TABLE LIKE statement. Spark 4.2 parses such names itself, into a plan the fallback cannot use. */ private def maybeCatalogCreateTableLike(sqlText: String): Boolean = { - if (org.apache.spark.SPARK_VERSION < "3.4") { + if (org.apache.spark.SPARK_VERSION < "3.4" || org.apache.spark.SPARK_VERSION >= "4.2") { return false } if (!startsWithCreateTable(sqlText)) { diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewriteCreateTableLikeCommand.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewriteCreateTableLikeCommand.scala index 018644e9f389..8547a97b8315 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewriteCreateTableLikeCommand.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewriteCreateTableLikeCommand.scala @@ -27,6 +27,7 @@ import org.apache.spark.sql.catalyst.catalog.CatalogStorageFormat import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan import org.apache.spark.sql.catalyst.rules.Rule import org.apache.spark.sql.connector.catalog.{CatalogManager, Identifier, LookupCatalog, TableCatalog} +import org.apache.spark.sql.connector.catalog.CatalogV2Implicits.MultipartIdentifierHelper import org.apache.spark.sql.execution.command.{CreateTableLikeCommand => SparkCreateTableLikeCommand} case class RewriteCreateTableLikeCommand(spark: SparkSession) @@ -43,43 +44,76 @@ case class RewriteCreateTableLikeCommand(spark: SparkSession) plan.resolveOperatorsUp { case c: SparkCreateTableLikeCommand => - val targetParts = toMultipartIdentifier(c.targetTable) + rewrite( + toMultipartIdentifier(c.targetTable), + toMultipartIdentifier(c.sourceTable), + c.provider, + c.fileFormat, + c.properties, + c.ifNotExists).getOrElse(c) + } + } - targetParts match { - case CatalogAndIdentifier(targetCatalog: SparkCatalog, targetIdent) => - if (usesHiveStorageSyntax(c.fileFormat)) { - throw new UnsupportedOperationException( - "CREATE TABLE LIKE ... STORED AS is not supported for SparkCatalog.") - } - createTableLikeCommand(c, targetCatalog, targetIdent) - case CatalogAndIdentifier(targetCatalog: SparkGenericCatalog, targetIdent) - if !usesHiveStorageSyntax(c.fileFormat) && - c.provider.exists(SparkBaseCatalog.usePaimon) => - createTableLikeCommand(c, targetCatalog, targetIdent) - case _ => c + /** + * The Paimon command for a CREATE TABLE LIKE whose target is a Paimon table, or None to leave the + * statement to Spark. `fileFormat` is evaluated only for a Paimon target. + */ + private[extensions] def rewrite( + targetParts: Seq[String], + sourceParts: Seq[String], + provider: Option[String], + fileFormat: => CatalogStorageFormat, + properties: Map[String, String], + ifNotExists: Boolean): Option[LogicalPlan] = { + val target: Option[(SparkBaseCatalog, Identifier)] = targetParts match { + case CatalogAndIdentifier(targetCatalog: SparkCatalog, targetIdent) => + if (usesHiveStorageSyntax(fileFormat)) { + throw new UnsupportedOperationException( + "CREATE TABLE LIKE ... STORED AS is not supported for SparkCatalog.") } + Some((targetCatalog, targetIdent)) + case CatalogAndIdentifier(targetCatalog: SparkGenericCatalog, targetIdent) + if provider.exists(SparkBaseCatalog.usePaimon) && !usesHiveStorageSyntax(fileFormat) => + Some((targetCatalog, targetIdent)) + case _ => None + } + target.map { + case (targetCatalog, targetIdent) => + createTableLikeCommand( + targetCatalog, + targetIdent, + sourceParts, + provider, + fileFormat.locationUri.map(_.toString), + properties, + ifNotExists) } } private def createTableLikeCommand( - command: SparkCreateTableLikeCommand, targetCatalog: SparkBaseCatalog, - targetIdent: Identifier): LogicalPlan = { - toMultipartIdentifier(command.sourceTable) match { + targetIdent: Identifier, + sourceParts: Seq[String], + provider: Option[String], + location: Option[String], + properties: Map[String, String], + ifNotExists: Boolean): LogicalPlan = { + sourceParts match { case CatalogAndIdentifier(sourceCatalog: TableCatalog, sourceIdent) => PaimonCreateTableLikeCommand( targetCatalog, targetIdent, sourceCatalog, sourceIdent, - command.provider, - command.fileFormat.locationUri.map(_.toString), - command.properties, - command.ifNotExists + provider, + location, + properties, + ifNotExists ) case _ => throw new UnsupportedOperationException( - s"CREATE TABLE LIKE source table must be resolved from TableCatalog: ${command.sourceTable}.") + s"CREATE TABLE LIKE source table must be resolved from TableCatalog: " + + s"${sourceParts.quoted}.") } } From 6e76ca579d34a5bcd54940579ba7def6e2c668c3 Mon Sep 17 00:00:00 2001 From: yangjie01 Date: Mon, 23 Nov 2026 22:56:40 +0800 Subject: [PATCH 2/2] [spark] Resolve CREATE TABLE LIKE names per catalog and reject temporary view sources --- .../Spark42RewriteCreateTableLike.scala | 16 +-- .../PaimonCreateTableLikeStatement.scala | 33 ++++++ .../PaimonSqlExtensionsAstBuilder.scala | 22 +--- .../RewriteCreateTableLikeCommand.scala | 68 ++++++++++- .../CatalogQualifiedCreateTableLikeTest.scala | 108 ++++++++++++++++++ .../sql/DDLWithHiveCatalogTestBase.scala | 17 +++ 6 files changed, 227 insertions(+), 37 deletions(-) create mode 100644 paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/plans/logical/PaimonCreateTableLikeStatement.scala diff --git a/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/Spark42RewriteCreateTableLike.scala b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/Spark42RewriteCreateTableLike.scala index ac0ce9887220..c0f78a0a0b5f 100644 --- a/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/Spark42RewriteCreateTableLike.scala +++ b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/Spark42RewriteCreateTableLike.scala @@ -45,8 +45,8 @@ case class Spark42RewriteCreateTableLike(spark: SparkSession) extends Rule[Logic ifNotExists) => rewriter .rewrite( - toV1Parts(target), - toV1Parts(source.multipartIdentifier), + target, + source.multipartIdentifier, provider, // Spark builds the same storage format for its v1 fallback. HiveSerDe.buildStorageFormat( @@ -58,16 +58,4 @@ case class Spark42RewriteCreateTableLike(spark: SparkSession) extends Rule[Logic ) .getOrElse(c) } - - /** - * Joins the parts between the first and the last into one database name when there are more than - * three, as `PaimonSqlExtensionsAstBuilder` does for the names it parses. - */ - private def toV1Parts(parts: Seq[String]): Seq[String] = { - if (parts.length <= 3) { - parts - } else { - Seq(parts.head, parts.slice(1, parts.length - 1).mkString("."), parts.last) - } - } } diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/plans/logical/PaimonCreateTableLikeStatement.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/plans/logical/PaimonCreateTableLikeStatement.scala new file mode 100644 index 000000000000..6e6586b97ecf --- /dev/null +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/plans/logical/PaimonCreateTableLikeStatement.scala @@ -0,0 +1,33 @@ +/* + * 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.catalyst.plans.logical + +import org.apache.paimon.spark.leafnode.PaimonLeafParsedStatement + +import org.apache.spark.sql.execution.command.{CreateTableLikeCommand => SparkCreateTableLikeCommand} + +/** + * A CREATE TABLE LIKE statement parsed by Paimon's grammar, with the target and source names as + * written. `command` carries the other clauses; its table names are placeholders. + */ +case class PaimonCreateTableLikeStatement( + targetParts: Seq[String], + sourceParts: Seq[String], + command: SparkCreateTableLikeCommand) + extends PaimonLeafParsedStatement diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/PaimonSqlExtensionsAstBuilder.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/PaimonSqlExtensionsAstBuilder.scala index a4aaf3ab69b9..8272dbd00108 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/PaimonSqlExtensionsAstBuilder.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/PaimonSqlExtensionsAstBuilder.scala @@ -26,7 +26,6 @@ import org.antlr.v4.runtime._ import org.antlr.v4.runtime.misc.Interval import org.antlr.v4.runtime.tree.{ParseTree, TerminalNode} import org.apache.spark.internal.Logging -import org.apache.spark.sql.catalyst.TableIdentifier import org.apache.spark.sql.catalyst.expressions.Expression import org.apache.spark.sql.catalyst.parser.ParserInterface import org.apache.spark.sql.catalyst.parser.extensions.PaimonParserUtils.withOrigin @@ -105,9 +104,10 @@ class PaimonSqlExtensionsAstBuilder(delegate: ParserInterface) /** Create a CREATE TABLE LIKE logical command. */ override def visitCreateTableLike(ctx: CreateTableLikeContext): LogicalPlan = withOrigin(ctx) { - sparkCreateTableLikeCommand(ctx).copy( - targetTable = toTableIdentifier(typedVisit[Seq[String]](ctx.target)), - sourceTable = toTableIdentifier(typedVisit[Seq[String]](ctx.source))) + PaimonCreateTableLikeStatement( + typedVisit[Seq[String]](ctx.target), + typedVisit[Seq[String]](ctx.source), + sparkCreateTableLikeCommand(ctx)) } /** Create a CREATE OR REPLACE TAG logical command. */ @@ -311,20 +311,6 @@ class PaimonSqlExtensionsAstBuilder(delegate: ParserInterface) private def toSeq[T](list: java.util.List[T]) = toBuffer(list) - private def toTableIdentifier(identifier: Seq[String]): TableIdentifier = { - identifier match { - case Seq(table) => - TableIdentifier(table) - case Seq(database, table) => - TableIdentifier(table, Some(database)) - case parts => - TableIdentifier( - parts.last, - Some(parts.slice(1, parts.length - 1).mkString(".")), - Some(parts.head)) - } - } - private def sparkCreateTableLikeCommand( ctx: CreateTableLikeContext): SparkCreateTableLikeCommand = { delegate.parsePlan(createSparkCreateTableLikeSql(ctx)) match { diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewriteCreateTableLikeCommand.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewriteCreateTableLikeCommand.scala index 8547a97b8315..d47186386a30 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewriteCreateTableLikeCommand.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/RewriteCreateTableLikeCommand.scala @@ -20,13 +20,15 @@ package org.apache.spark.sql.catalyst.parser.extensions import org.apache.paimon.spark.{SparkCatalog, SparkGenericCatalog} import org.apache.paimon.spark.catalog.SparkBaseCatalog +import org.apache.paimon.spark.catalyst.plans.logical.PaimonCreateTableLikeStatement import org.apache.paimon.spark.commands.PaimonCreateTableLikeCommand import org.apache.spark.sql.SparkSession +import org.apache.spark.sql.catalyst.TableIdentifier import org.apache.spark.sql.catalyst.catalog.CatalogStorageFormat import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan import org.apache.spark.sql.catalyst.rules.Rule -import org.apache.spark.sql.connector.catalog.{CatalogManager, Identifier, LookupCatalog, TableCatalog} +import org.apache.spark.sql.connector.catalog.{CatalogManager, CatalogPlugin, CatalogV2Util, Identifier, LookupCatalog, TableCatalog} import org.apache.spark.sql.connector.catalog.CatalogV2Implicits.MultipartIdentifierHelper import org.apache.spark.sql.execution.command.{CreateTableLikeCommand => SparkCreateTableLikeCommand} @@ -51,12 +53,16 @@ case class RewriteCreateTableLikeCommand(spark: SparkSession) c.fileFormat, c.properties, c.ifNotExists).getOrElse(c) + case PaimonCreateTableLikeStatement(targetParts, sourceParts, c) => + rewrite(targetParts, sourceParts, c.provider, c.fileFormat, c.properties, c.ifNotExists) + .getOrElse(sessionCatalogCommand(targetParts, sourceParts, c)) } } /** * The Paimon command for a CREATE TABLE LIKE whose target is a Paimon table, or None to leave the - * statement to Spark. `fileFormat` is evaluated only for a Paimon target. + * statement to Spark. `fileFormat` is evaluated only when the target is in `SparkCatalog`, or in + * `SparkGenericCatalog` with a Paimon provider. */ private[extensions] def rewrite( targetParts: Seq[String], @@ -66,13 +72,13 @@ case class RewriteCreateTableLikeCommand(spark: SparkSession) properties: Map[String, String], ifNotExists: Boolean): Option[LogicalPlan] = { val target: Option[(SparkBaseCatalog, Identifier)] = targetParts match { - case CatalogAndIdentifier(targetCatalog: SparkCatalog, targetIdent) => + case CatalogAndTableIdentifier(targetCatalog: SparkCatalog, targetIdent) => if (usesHiveStorageSyntax(fileFormat)) { throw new UnsupportedOperationException( "CREATE TABLE LIKE ... STORED AS is not supported for SparkCatalog.") } Some((targetCatalog, targetIdent)) - case CatalogAndIdentifier(targetCatalog: SparkGenericCatalog, targetIdent) + case CatalogAndTableIdentifier(targetCatalog: SparkGenericCatalog, targetIdent) if provider.exists(SparkBaseCatalog.usePaimon) && !usesHiveStorageSyntax(fileFormat) => Some((targetCatalog, targetIdent)) case _ => None @@ -98,8 +104,13 @@ case class RewriteCreateTableLikeCommand(spark: SparkSession) location: Option[String], properties: Map[String, String], ifNotExists: Boolean): LogicalPlan = { + if (spark.sessionState.catalog.isTempView(sourceParts)) { + throw new UnsupportedOperationException( + "CREATE TABLE LIKE with a temporary view as the source is not supported for a Paimon " + + s"table: ${sourceParts.quoted}.") + } sourceParts match { - case CatalogAndIdentifier(sourceCatalog: TableCatalog, sourceIdent) => + case CatalogAndTableIdentifier(sourceCatalog: TableCatalog, sourceIdent) => PaimonCreateTableLikeCommand( targetCatalog, targetIdent, @@ -117,6 +128,53 @@ case class RewriteCreateTableLikeCommand(spark: SparkSession) } } + /** + * [[CatalogAndIdentifier]], except that when a name of more than three parts resolves to a Paimon + * catalog, the parts between the first and the last are joined into one namespace part. Other + * catalogs keep every namespace part. + */ + private object CatalogAndTableIdentifier { + def unapply(parts: Seq[String]): Option[(CatalogPlugin, Identifier)] = parts match { + case CatalogAndIdentifier(_: SparkBaseCatalog, _) if parts.length > 3 => + CatalogAndIdentifier.unapply( + Seq(parts.head, parts.slice(1, parts.length - 1).mkString("."), parts.last)) + case CatalogAndIdentifier(catalog, ident) => Some((catalog, ident)) + case _ => None + } + } + + /** + * Spark's command for a statement only Paimon's grammar accepted and whose target is not a Paimon + * table. That command resolves names in the session catalog by database and table and ignores the + * catalog name, so the target, and a source that is not a temporary view, must be such names. + */ + private def sessionCatalogCommand( + targetParts: Seq[String], + sourceParts: Seq[String], + command: SparkCreateTableLikeCommand): LogicalPlan = { + val sourceTable = if (spark.sessionState.catalog.isTempView(sourceParts)) { + Some(TableIdentifier(sourceParts.last, sourceParts.init.lastOption)) + } else { + sessionCatalogTable(sourceParts) + } + (sessionCatalogTable(targetParts), sourceTable) match { + case (Some(target), Some(source)) => command.copy(targetTable = target, sourceTable = source) + case _ => + throw new UnsupportedOperationException( + s"CREATE TABLE ${targetParts.quoted} LIKE ${sourceParts.quoted} is not supported: " + + "the target is not a Paimon table, and Spark's command for it needs the target, and " + + "a source that is not a temporary view, to be a database and a table in the " + + "session catalog.") + } + } + + private def sessionCatalogTable(parts: Seq[String]): Option[TableIdentifier] = parts match { + case CatalogAndIdentifier(catalog, ident) + if CatalogV2Util.isSessionCatalog(catalog) && ident.namespace().length == 1 => + Some(TableIdentifier(ident.name(), Some(ident.namespace().head))) + case _ => None + } + private def usesHiveStorageSyntax(fileFormat: CatalogStorageFormat): Boolean = { fileFormat.inputFormat.isDefined } diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CatalogQualifiedCreateTableLikeTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CatalogQualifiedCreateTableLikeTest.scala index 350462fc1ca0..dc8dc901fb92 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CatalogQualifiedCreateTableLikeTest.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CatalogQualifiedCreateTableLikeTest.scala @@ -21,12 +21,120 @@ package org.apache.paimon.spark.sql import org.apache.paimon.spark.PaimonSparkTestBase import org.apache.paimon.spark.commands.PaimonCreateTableLikeCommand +import org.apache.spark.SparkConf +import org.apache.spark.sql.catalyst.TableIdentifier +import org.apache.spark.sql.connector.catalog.InMemoryTableCatalog import org.junit.jupiter.api.Assertions import scala.collection.JavaConverters._ class CatalogQualifiedCreateTableLikeTest extends PaimonSparkTestBase { + override protected def sparkConf: SparkConf = + super.sparkConf.set("spark.sql.catalog.external", classOf[InMemoryTableCatalog].getName) + + test("Create table like keeps the nested namespace of a source in another catalog") { + assume(gteqSpark3_4) + withTable( + "external.outer.inner.source", + "external.`outer.inner`.source", + s"paimon.$dbName0.target_tbl") { + sql("CREATE TABLE external.outer.inner.source (intended INT)") + sql("CREATE TABLE external.`outer.inner`.source (wrong STRING)") + + sql(s"CREATE TABLE paimon.$dbName0.target_tbl LIKE external.outer.inner.source USING paimon") + + Assertions.assertEquals( + Seq("intended"), + spark.table(s"paimon.$dbName0.target_tbl").schema.fieldNames.toSeq) + } + } + + test("Create table like rejects a temporary view source for a Paimon target") { + assume(gteqSpark3_4) + withTable("shadowed", "target_tbl") { + sql("CREATE TABLE shadowed (from_table STRING)") + withTempView("shadowed") { + sql("CREATE TEMPORARY VIEW shadowed AS SELECT 1 AS from_view") + + val e = intercept[UnsupportedOperationException] { + sql("CREATE TABLE target_tbl LIKE shadowed") + } + + Assertions.assertTrue(e.getMessage.contains("temporary view"), e.getMessage) + Assertions.assertFalse(spark.catalog.tableExists(s"paimon.$dbName0.target_tbl")) + } + } + } + + test("Create table like never puts a target of another catalog into the session catalog") { + assume(gteqSpark3_4) + withTable( + "spark_catalog.default.src", + "spark_catalog.default.t_external", + "external.default.t_external") { + sql("CREATE NAMESPACE IF NOT EXISTS external.default") + sql("CREATE TABLE spark_catalog.default.src (a INT) USING parquet") + + val statement = "CREATE TABLE external.default.t_external LIKE spark_catalog.default.src" + if (sparkVersion >= "4.2") { + // Spark 4.2 parses the statement itself and creates the table in `external`. + sql(statement) + Assertions.assertEquals( + Seq("a"), + spark.table("external.default.t_external").schema.fieldNames.toSeq) + } else { + val e = intercept[UnsupportedOperationException](sql(statement)) + Assertions.assertTrue(e.getMessage.contains("session catalog"), e.getMessage) + } + + Assertions.assertFalse( + spark.sessionState.catalog.tableExists(TableIdentifier("t_external", Some("default")))) + } + } + + test("Create table like rejects a source of another catalog for a session catalog target") { + // Spark 4.2 parses this statement itself and Paimon leaves this non-Paimon target to it, so + // only earlier versions reach the check in `sessionCatalogCommand`. + assume(gteqSpark3_4 && sparkVersion < "4.2") + withTable("spark_catalog.default.src2", "spark_catalog.default.t2", "external.default.src2") { + sql("CREATE NAMESPACE IF NOT EXISTS external.default") + sql("CREATE TABLE external.default.src2 (from_external INT)") + sql("CREATE TABLE spark_catalog.default.src2 (from_session STRING) USING parquet") + + val e = intercept[UnsupportedOperationException] { + sql("CREATE TABLE spark_catalog.default.t2 LIKE external.default.src2") + } + + Assertions.assertTrue(e.getMessage.contains("session catalog"), e.getMessage) + Assertions.assertFalse( + spark.sessionState.catalog.tableExists(TableIdentifier("t2", Some("default")))) + } + } + + test("Create table like keeps Spark's command for tables in the session catalog") { + assume(gteqSpark3_4) + withTable( + "spark_catalog.default.src3", + "spark_catalog.default.t3", + "spark_catalog.default.t4") { + sql("CREATE TABLE spark_catalog.default.src3 (a INT) USING parquet") + + sql("CREATE TABLE spark_catalog.default.t3 LIKE spark_catalog.default.src3") + Assertions.assertEquals( + Seq("a"), + spark.table("spark_catalog.default.t3").schema.fieldNames.toSeq) + + withTempView("v") { + sql("CREATE TEMPORARY VIEW v AS SELECT 1 AS from_view") + sql("CREATE TABLE spark_catalog.default.t4 LIKE v USING parquet") + Assertions.assertEquals( + Seq("from_view"), + spark.table("spark_catalog.default.t4").schema.fieldNames.toSeq) + } + } + } + test("Create table like with catalog-qualified identifiers") { assume(gteqSpark3_4) withTable("source_tbl", "target_tbl", "target_from_qualified_source", "qualified_target") { diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTestBase.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTestBase.scala index 42d7c0747cff..802f12f391f3 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTestBase.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTestBase.scala @@ -757,6 +757,23 @@ abstract class DDLWithHiveCatalogTestBase extends PaimonHiveTestBase { } } + test("Paimon DDL with hive catalog: create table like rejects a temporary view source") { + assume(gteqSpark3_4) + spark.sql(s"USE $sparkCatalogName") + withTable("view_like") { + withTempView("v") { + spark.sql("CREATE TEMPORARY VIEW v AS SELECT 1 AS from_view") + + val e = intercept[UnsupportedOperationException] { + spark.sql("CREATE TABLE view_like LIKE v USING paimon") + } + + Assertions.assertTrue(e.getMessage.contains("temporary view"), e.getMessage) + Assertions.assertFalse(spark.catalog.tableExists("view_like")) + } + } + } + test("Paimon DDL with hive catalog: SparkGenericCatalog explicit Paimon replace") { assume(gteqSpark3_4) spark.sql(s"USE $sparkCatalogName")