Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
a57aafc
add table partition API
Aug 3, 2020
6efca68
add AlterTableAddPartitionExec and AlterTableDropPartitionExec
Aug 3, 2020
f0bc357
redefine AlterTableAddPartitionExec and AlterTableDropPartitionExec
Aug 4, 2020
61cae52
fix test failed
Aug 5, 2020
b1fc84b
change the warning for purge
Aug 5, 2020
67fcb12
add SupportsAtomicPartitionManagement API support
Aug 6, 2020
f4a6ee3
reorder match cases
Aug 6, 2020
9bd20ba
fix errors
Aug 6, 2020
6327ead
change match cases
Aug 6, 2020
800c51a
add alter table add/drop partitions suites
Aug 7, 2020
60b0a12
Merge branch 'master' into SPARK-32512-new
Aug 13, 2020
a4c29a2
restart git action
Aug 21, 2020
a6caf68
change code for comments
Sep 27, 2020
3405f5b
use UnresolvedTableOrView to resolve the identifier
Sep 27, 2020
9bc2e76
add children for AlterTableAddPartitionsStatement and AlterTableDropP…
Sep 28, 2020
0740ef5
add ResolvedView analyzed
Sep 28, 2020
ad40d7b
add ResolvePartitionSpec rule
Sep 30, 2020
8fce669
change scala style
Oct 19, 2020
af4b50b
change scala style
Oct 19, 2020
b046909
fix scala-2.13 compile failed
Oct 19, 2020
fbc2b58
add more implicit method
Oct 19, 2020
dedb32a
remove unused imports
Oct 21, 2020
41cf069
Merge branch 'master'
Nov 6, 2020
96a62be
redefine ResolvePartitionSpec
Nov 6, 2020
d5d8f13
fix test failed
Nov 7, 2020
6bf49bd
add check in CheckAnalysis
Nov 7, 2020
cdd7085
restart test
Nov 9, 2020
0545538
change UnresolveTableOrView to UnresolvedTable
Nov 10, 2020
f1fcac1
remove implicit class
Nov 10, 2020
7014ba1
Merge branch 'master' into SPARK-32512-new
Nov 10, 2020
69bbbd5
fix build failed
Nov 10, 2020
effd0ed
Merge branch 'SPARK-32512-new' of https://github.com/stczwd/spark int…
Nov 10, 2020
7377469
use ResolvedV1TableIdentifier
Nov 10, 2020
c6711cd
fix suite test failed
Nov 10, 2020
dcd5060
fix suite test failed
Nov 10, 2020
d316e56
fix test failed
Nov 11, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ class Analyzer(
ResolveInsertInto ::
ResolveRelations ::
ResolveTables ::
ResolvePartitionSpec ::
ResolveReferences ::
ResolveCreateNamedStruct ::
ResolveDeserializer ::
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import org.apache.spark.sql.catalyst.optimizer.BooleanSimplification
import org.apache.spark.sql.catalyst.plans._
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.util.TypeUtils
import org.apache.spark.sql.connector.catalog.{SupportsAtomicPartitionManagement, SupportsPartitionManagement, Table}
import org.apache.spark.sql.connector.catalog.TableChange.{AddColumn, After, ColumnPosition, DeleteColumn, RenameColumn, UpdateColumnComment, UpdateColumnNullability, UpdateColumnPosition, UpdateColumnType}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
Expand Down Expand Up @@ -564,6 +565,12 @@ trait CheckAnalysis extends PredicateHelper {
// no validation needed for set and remove property
}

case AlterTableAddPartition(ResolvedTable(_, _, table), parts, _) =>
checkAlterTablePartition(table, parts)

case AlterTableDropPartition(ResolvedTable(_, _, table), parts, _, _, _) =>
checkAlterTablePartition(table, parts)

case _ => // Fallbacks to the following checks
}

Expand Down Expand Up @@ -976,4 +983,24 @@ trait CheckAnalysis extends PredicateHelper {
failOnOuterReferenceInSubTree(p)
}}
}

// Make sure that table is able to alter partition.
private def checkAlterTablePartition(
table: Table, parts: Seq[PartitionSpec]): Unit = {
(table, parts) match {
case (_, parts) if parts.exists(_.isInstanceOf[UnresolvedPartitionSpec]) =>
failAnalysis("PartitionSpecs are not resolved")

case (table, _) if !table.isInstanceOf[SupportsPartitionManagement] =>
failAnalysis(s"Table ${table.name()} can not alter partitions.")

// Skip atomic partition tables
case (_: SupportsAtomicPartitionManagement, _) =>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not related to this PR: I'm wondering if we do need this separation. Do we have a concern that it's hard for implementations to add/drop multiple partitions atomically?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Em, it depends on whether the third-party system or storage supports transaction. MySQL and Hive can support this very well.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As an example, TableCatalog.alterTable accepts a list of TableChange without adding a new atomic API. I don't know why partition API needs to be different.

case (_: SupportsPartitionManagement, parts) if parts.size > 1 =>
failAnalysis(
s"Nonatomic partition table ${table.name()} can not alter multiple partitions.")

case _ =>
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* 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.AnalysisException
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.catalog.CatalogTypes.TablePartitionSpec
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.types._

/**
* Resolve [[UnresolvedPartitionSpec]] to [[ResolvedPartitionSpec]] in partition related commands.
*/
object ResolvePartitionSpec extends Rule[LogicalPlan] {

def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators {
case r @ AlterTableAddPartition(
ResolvedTable(_, _, table: SupportsPartitionManagement), partSpecs, _) =>
r.copy(parts = resolvePartitionSpecs(partSpecs, table.partitionSchema()))

case r @ AlterTableDropPartition(
ResolvedTable(_, _, table: SupportsPartitionManagement), partSpecs, _, _, _) =>
r.copy(parts = resolvePartitionSpecs(partSpecs, table.partitionSchema()))
}

private def resolvePartitionSpecs(
partSpecs: Seq[PartitionSpec], partSchema: StructType): Seq[ResolvedPartitionSpec] =
partSpecs.map {
case unresolvedPartSpec: UnresolvedPartitionSpec =>
ResolvedPartitionSpec(
convertToPartIdent(unresolvedPartSpec.spec, partSchema), unresolvedPartSpec.location)
case resolvedPartitionSpec: ResolvedPartitionSpec =>
resolvedPartitionSpec
}

private def convertToPartIdent(
partSpec: TablePartitionSpec, partSchema: StructType): InternalRow = {
val conflictKeys = partSpec.keys.toSeq.diff(partSchema.map(_.name))
if (conflictKeys.nonEmpty) {
throw new AnalysisException(s"Partition key ${conflictKeys.mkString(",")} not exists")
}

val partValues = partSchema.map { part =>
val partValue = partSpec.get(part.name).orNull
if (partValue == null) {
null
} else {
// TODO: Support other datatypes, such as DateType
part.dataType match {
case _: ByteType =>
partValue.toByte
case _: ShortType =>
partValue.toShort
case _: IntegerType =>
partValue.toInt
case _: LongType =>
partValue.toLong
case _: FloatType =>
partValue.toFloat
case _: DoubleType =>
partValue.toDouble
case _: StringType =>
partValue
case _ =>
throw new AnalysisException(
s"Type ${part.dataType.typeName} is not supported for partition.")
}
}
}
InternalRow.fromSeq(partValues)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@

package org.apache.spark.sql.catalyst.analysis

import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.catalog.CatalogFunction
import org.apache.spark.sql.catalyst.catalog.CatalogTypes.TablePartitionSpec
import org.apache.spark.sql.catalyst.expressions.Attribute
import org.apache.spark.sql.catalyst.plans.logical.{LeafNode, LogicalPlan}
import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, SupportsNamespaces, Table, TableCatalog}
Expand Down Expand Up @@ -53,6 +55,12 @@ case class UnresolvedTableOrView(
override def output: Seq[Attribute] = Nil
}

sealed trait PartitionSpec

case class UnresolvedPartitionSpec(
spec: TablePartitionSpec,
location: Option[String] = None) extends PartitionSpec

/**
* Holds the name of a function that has yet to be looked up in a catalog. It will be resolved to
* [[ResolvedFunc]] during analysis.
Expand All @@ -78,6 +86,10 @@ case class ResolvedTable(catalog: TableCatalog, identifier: Identifier, table: T
override def output: Seq[Attribute] = Nil
}

case class ResolvedPartitionSpec(
spec: InternalRow,
location: Option[String] = None) extends PartitionSpec

/**
* A plan containing resolved (temp) views.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3411,7 +3411,7 @@ class AstBuilder(conf: SQLConf) extends SqlBaseBaseVisitor[AnyRef] with Logging
}

/**
* Create an [[AlterTableAddPartitionStatement]].
* Create an [[AlterTableAddPartition]].
*
* For example:
* {{{
Expand All @@ -3431,10 +3431,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(
UnresolvedTable(visitMultipartIdentifier(ctx.multipartIdentifier)),
specsAndLocs.toSeq,
ctx.EXISTS != null)
}
Expand All @@ -3456,7 +3456,7 @@ class AstBuilder(conf: SQLConf) extends SqlBaseBaseVisitor[AnyRef] with Logging
}

/**
* Create an [[AlterTableDropPartitionStatement]]
* Create an [[AlterTableDropPartition]]
*
* For example:
* {{{
Expand All @@ -3473,9 +3473,11 @@ class AstBuilder(conf: SQLConf) extends SqlBaseBaseVisitor[AnyRef] with Logging
if (ctx.VIEW != null) {
operationNotAllowed("ALTER VIEW ... DROP PARTITION", ctx)
}
AlterTableDropPartitionStatement(
visitMultipartIdentifier(ctx.multipartIdentifier),
ctx.partitionSpec.asScala.map(visitNonOptionalPartitionSpec).toSeq,
val partSpecs = ctx.partitionSpec.asScala.map(visitNonOptionalPartitionSpec)
.map(spec => UnresolvedPartitionSpec(spec))
AlterTableDropPartition(
UnresolvedTable(visitMultipartIdentifier(ctx.multipartIdentifier)),
partSpecs.toSeq,
ifExists = ctx.EXISTS != null,
purge = ctx.PURGE != null,
retainData = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -217,14 +217,6 @@ case class AlterTableSetLocationStatement(
case class AlterTableRecoverPartitionsStatement(
tableName: Seq[String]) extends ParsedStatement

/**
* ALTER TABLE ... ADD PARTITION command, as parsed from SQL
*/
case class AlterTableAddPartitionStatement(
tableName: Seq[String],
partitionSpecsAndLocs: Seq[(TablePartitionSpec, Option[String])],
ifNotExists: Boolean) extends ParsedStatement

/**
* ALTER TABLE ... RENAME PARTITION command, as parsed from SQL.
*/
Expand All @@ -233,16 +225,6 @@ case class AlterTableRenamePartitionStatement(
from: TablePartitionSpec,
to: TablePartitionSpec) extends ParsedStatement

/**
* ALTER TABLE ... DROP PARTITION command, as parsed from SQL
*/
case class AlterTableDropPartitionStatement(
tableName: Seq[String],
specs: Seq[TablePartitionSpec],
ifExists: Boolean,
purge: Boolean,
retainData: Boolean) extends ParsedStatement

/**
* ALTER TABLE ... SERDEPROPERTIES command, as parsed from SQL
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

package org.apache.spark.sql.catalyst.plans.logical

import org.apache.spark.sql.catalyst.analysis.{NamedRelation, UnresolvedException}
import org.apache.spark.sql.catalyst.analysis.{NamedRelation, PartitionSpec, ResolvedPartitionSpec, UnresolvedException}
import org.apache.spark.sql.catalyst.catalog.CatalogTypes.TablePartitionSpec
import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeReference, Expression, Unevaluable}
import org.apache.spark.sql.catalyst.plans.DescribeCommandSchema
Expand Down Expand Up @@ -611,6 +611,46 @@ case class AnalyzeColumn(
override def children: Seq[LogicalPlan] = child :: Nil
}

/**
* 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],
ifNotExists: Boolean) extends Command {
override lazy val resolved: Boolean =
childrenResolved && parts.forall(_.isInstanceOf[ResolvedPartitionSpec])

override def children: Seq[LogicalPlan] = child :: Nil
}

/**
* The logical plan of the ALTER TABLE DROP PARTITION command.
* This may remove the data and metadata for this partition.
*
* The syntax of this command is:
* {{{
* ALTER TABLE table DROP [IF EXISTS] PARTITION spec1[, PARTITION spec2, ...];
* }}}
*/
case class AlterTableDropPartition(
child: LogicalPlan,
parts: Seq[PartitionSpec],
ifExists: Boolean,
purge: Boolean,
retainData: Boolean) extends Command {
override lazy val resolved: Boolean =
childrenResolved && parts.forall(_.isInstanceOf[ResolvedPartitionSpec])

override def children: Seq[LogicalPlan] = child :: Nil
}

/**
* The logical plan of the LOAD DATA INTO TABLE command.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ package org.apache.spark.sql.execution.datasources.v2
import scala.collection.JavaConverters._

import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.connector.catalog.{SupportsDelete, SupportsRead, SupportsWrite, Table, TableCapability}
import org.apache.spark.sql.catalyst.analysis.{PartitionSpec, ResolvedPartitionSpec, UnresolvedPartitionSpec}
import org.apache.spark.sql.connector.catalog.{SupportsAtomicPartitionManagement, SupportsDelete, SupportsPartitionManagement, SupportsRead, SupportsWrite, Table, TableCapability}
import org.apache.spark.sql.util.CaseInsensitiveStringMap

object DataSourceV2Implicits {
Expand Down Expand Up @@ -52,6 +53,26 @@ object DataSourceV2Implicits {
}
}

def asPartitionable: SupportsPartitionManagement = {
table match {
case support: SupportsPartitionManagement =>
support
case _ =>
throw new AnalysisException(
s"Table does not support partition management: ${table.name}")
}
}

def asAtomicPartitionable: SupportsAtomicPartitionManagement = {
table match {
case support: SupportsAtomicPartitionManagement =>
support
case _ =>
throw new AnalysisException(
s"Table does not support atomic partition management: ${table.name}")
}
}

def supports(capability: TableCapability): Boolean = table.capabilities.contains(capability)

def supportsAny(capabilities: TableCapability*): Boolean = capabilities.exists(supports)
Expand All @@ -62,4 +83,12 @@ object DataSourceV2Implicits {
new CaseInsensitiveStringMap(options.asJava)
}
}

implicit class PartitionSpecsHelper(partSpecs: Seq[PartitionSpec]) {
def asUnresolvedPartitionSpecs: Seq[UnresolvedPartitionSpec] =
partSpecs.map(_.asInstanceOf[UnresolvedPartitionSpec])

def asResolvedPartitionSpecs: Seq[ResolvedPartitionSpec] =
partSpecs.map(_.asInstanceOf[ResolvedPartitionSpec])
}
}
Loading