You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2020/11/06 16:44:50 UTC

[GitHub] [spark] stczwd commented on a change in pull request #29339: [SPARK-32512][SQL] add alter table add/drop partition command for datasourcev2

stczwd commented on a change in pull request #29339:
URL: https://github.com/apache/spark/pull/29339#discussion_r518655126



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala
##########
@@ -551,3 +552,37 @@ case class ShowFunctions(
     pattern: Option[String]) extends Command {
   override def children: Seq[LogicalPlan] = child.toSeq
 }
+
+/**
+ * The logical plan of the ALTER TABLE ADD PARTITION command.
+ *
+ * The syntax of this command is:
+ * {{{
+ *     ALTER TABLE table ADD [IF NOT EXISTS]
+ *                 PARTITION spec1 [LOCATION 'loc1'][, PARTITION spec2 [LOCATION 'loc2'], ...];
+ * }}}
+ */
+case class AlterTableAddPartition(
+    child: LogicalPlan,
+    parts: Seq[PartitionSpec],
+    ignoreIfExists: Boolean) extends Command {

Review comment:
       ok

##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/catalog/interface.scala
##########
@@ -635,6 +636,16 @@ object CatalogTypes {
   lazy val emptyTablePartitionSpec: TablePartitionSpec = Map.empty[String, String]
 }
 
+trait PartitionSpec

Review comment:
       sure

##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Implicits.scala
##########
@@ -62,4 +86,74 @@ object DataSourceV2Implicits {
       new CaseInsensitiveStringMap(options.asJava)
     }
   }
+
+  implicit class PartitionSpecsHelper(partSpecs: Seq[PartitionSpec]) {
+    def resolved: Boolean = partSpecs.forall(_.isInstanceOf[ResolvedPartitionSpec])
+
+    def asResolved(partSchema: StructType): Seq[ResolvedPartitionSpec] =

Review comment:
       sure, I can remove these two functions. However, we still need this implicit class to cast PartitionSpec to UnresolvedPartitionSpec or ResolvedPartitionSpec.

##########
File path: sql/core/src/test/scala/org/apache/spark/sql/connector/DataSourceV2SQLSuite.scala
##########
@@ -74,6 +76,7 @@ class DataSourceV2SQLSuite
 
   before {
     spark.conf.set("spark.sql.catalog.testcat", classOf[InMemoryTableCatalog].getName)
+    spark.conf.set("spark.sql.catalog.testpart", classOf[InMemoryPartitionTableCatalog].getName)

Review comment:
       sure, sounds good to me.

##########
File path: sql/core/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolvePartitionSpec.scala
##########
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.plans.logical.{AlterTableAddPartition, AlterTableDropPartition, LogicalPlan}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.connector.catalog.SupportsPartitionManagement
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Implicits
+
+/**
+ * Analyze PartitionSpecs in datasource v2 commands.
+ */
+object ResolvePartitionSpec extends Rule[LogicalPlan] {
+  import DataSourceV2Implicits._
+
+  def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators {
+    case r@ AlterTableAddPartition(

Review comment:
       sure

##########
File path: sql/core/src/test/scala/org/apache/spark/sql/connector/DataSourceV2SQLSuite.scala
##########
@@ -2066,13 +2069,68 @@ class DataSourceV2SQLSuite
   }
 
   test("ALTER TABLE ADD PARTITION") {
-    val t = "testcat.ns1.ns2.tbl"
+    val t = "testpart.ns1.ns2.tbl"
     withTable(t) {
       spark.sql(s"CREATE TABLE $t (id bigint, data string) USING foo PARTITIONED BY (id)")
-      val e = intercept[AnalysisException] {
-        sql(s"ALTER TABLE $t ADD PARTITION (id=1) LOCATION 'loc'")
-      }
-      assert(e.message.contains("ALTER TABLE ADD PARTITION is only supported with v1 tables"))
+      spark.sql(s"ALTER TABLE $t ADD PARTITION (id=1) LOCATION 'loc'")
+
+      val partTable = catalog("testpart").asTableCatalog
+        .loadTable(Identifier.of(Array("ns1", "ns2"), "tbl")).asInstanceOf[InMemoryPartitionTable]
+      assert(partTable.partitionExists(InternalRow.fromSeq(Seq(1))))
+
+      val partMetadata = partTable.loadPartitionMetadata(InternalRow.fromSeq(Seq(1)))
+      assert(partMetadata.containsKey("location"))
+      assert(partMetadata.get("location") == "loc")
+
+      partTable.clearPartitions()

Review comment:
       Just to make sure partition all cleared, I will remove this.

##########
File path: sql/core/src/main/scala/org/apache/spark/sql/internal/BaseSessionStateBuilder.scala
##########
@@ -179,6 +179,7 @@ abstract class BaseSessionStateBuilder(
         ResolveEncodersInScalaAgg +:
         new ResolveSessionCatalog(
           catalogManager, conf, catalog.isTempView, catalog.isTempFunction) +:
+        ResolvePartitionSpec +:

Review comment:
       sure

##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/AlterTableAddPartitionExec.scala
##########
@@ -0,0 +1,66 @@
+/*
+ * 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 scala.collection.JavaConverters._
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.analysis.PartitionsAlreadyExistException
+import org.apache.spark.sql.catalyst.catalog.ResolvedPartitionSpec
+import org.apache.spark.sql.catalyst.expressions.Attribute
+import org.apache.spark.sql.connector.catalog.{SupportsAtomicPartitionManagement, SupportsPartitionManagement}
+
+/**
+ * Physical plan node for adding partitions of table.
+ */
+case class AlterTableAddPartitionExec(
+    table: SupportsPartitionManagement,
+    partSpecs: Seq[ResolvedPartitionSpec],
+    ignoreIfExists: Boolean) extends V2CommandExec {
+  import DataSourceV2Implicits._
+
+  override def output: Seq[Attribute] = Seq.empty
+
+  override protected def run(): Seq[InternalRow] = {
+    val (existsParts, notExistsParts) =
+      partSpecs.partition(p => table.partitionExists(p.spec))
+
+    if (existsParts.nonEmpty && !ignoreIfExists) {
+      throw new PartitionsAlreadyExistException(
+        table.name(), existsParts.map(_.spec), table.partitionSchema())
+    }
+
+    notExistsParts match {
+      case Seq() => // Nothing will be done
+      case Seq(partitionSpec) =>
+        val partProp = partitionSpec.location.map(loc => "location" -> loc).toMap
+        table.createPartition(partitionSpec.spec, partProp.asJava)
+      case Seq(_ *) if table.isInstanceOf[SupportsAtomicPartitionManagement] =>
+        val partIdents = notExistsParts.map(_.spec)
+        val partProps = notExistsParts.map(_.location.map(loc => "location" -> loc).toMap)
+        table.asAtomicPartitionable
+          .createPartitions(
+            partIdents.toArray,
+            partProps.map(_.asJava).toArray)
+      case _ =>
+        throw new UnsupportedOperationException(
+          s"Nonatomic partition table ${table.name()} can not add multiple partitions.")

Review comment:
       sure.

##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala
##########
@@ -3415,10 +3415,10 @@ class AstBuilder(conf: SQLConf) extends SqlBaseBaseVisitor[AnyRef] with Logging
     val specsAndLocs = ctx.partitionSpecLocation.asScala.map { splCtx =>
       val spec = visitNonOptionalPartitionSpec(splCtx.partitionSpec)
       val location = Option(splCtx.locationSpec).map(visitLocationSpec)
-      spec -> location
+      UnresolvedPartitionSpec(spec, location)
     }
-    AlterTableAddPartitionStatement(
-      visitMultipartIdentifier(ctx.multipartIdentifier),
+    AlterTableAddPartition(
+      UnresolvedTableOrView(visitMultipartIdentifier(ctx.multipartIdentifier)),

Review comment:
       ok




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org