|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.spark.sql.execution.command |
| 19 | + |
| 20 | +import org.apache.spark.sql.{AnalysisException, Column, Row, SparkSession} |
| 21 | +import org.apache.spark.sql.catalyst.TableIdentifier |
| 22 | +import org.apache.spark.sql.catalyst.analysis.{NoSuchPartitionException, UnresolvedAttribute} |
| 23 | +import org.apache.spark.sql.catalyst.catalog.{CatalogTable, CatalogTableType} |
| 24 | +import org.apache.spark.sql.catalyst.catalog.CatalogTypes.TablePartitionSpec |
| 25 | +import org.apache.spark.sql.catalyst.expressions.{And, EqualTo, Literal} |
| 26 | +import org.apache.spark.sql.execution.datasources.PartitioningUtils |
| 27 | + |
| 28 | +/** |
| 29 | + * Analyzes a given set of partitions to generate per-partition statistics, which will be used in |
| 30 | + * query optimizations. |
| 31 | + * |
| 32 | + * When `partitionSpec` is empty, statistics for all partitions are collected and stored in |
| 33 | + * Metastore. |
| 34 | + * |
| 35 | + * When `partitionSpec` mentions only some of the partition columns, all partitions with |
| 36 | + * matching values for specified columns are processed. |
| 37 | + * |
| 38 | + * If `partitionSpec` mentions unknown partition column, an `AnalysisException` is raised. |
| 39 | + * |
| 40 | + * By default, total number of rows and total size in bytes are calculated. When `noscan` |
| 41 | + * is `true`, only total size in bytes is computed. |
| 42 | + */ |
| 43 | +case class AnalyzePartitionCommand( |
| 44 | + tableIdent: TableIdentifier, |
| 45 | + partitionSpec: Map[String, Option[String]], |
| 46 | + noscan: Boolean = true) extends RunnableCommand { |
| 47 | + |
| 48 | + private def getPartitionSpec(table: CatalogTable): Option[TablePartitionSpec] = { |
| 49 | + val normalizedPartitionSpec = |
| 50 | + PartitioningUtils.normalizePartitionSpec(partitionSpec, table.partitionColumnNames, |
| 51 | + table.identifier.quotedString, conf.resolver) |
| 52 | + |
| 53 | + // Report an error if partition columns in partition specification do not form |
| 54 | + // a prefix of the list of partition columns defined in the table schema |
| 55 | + val isNotSpecified = |
| 56 | + table.partitionColumnNames.map(normalizedPartitionSpec.getOrElse(_, None).isEmpty) |
| 57 | + if (isNotSpecified.init.zip(isNotSpecified.tail).contains((true, false))) { |
| 58 | + val tableId = table.identifier |
| 59 | + val schemaColumns = table.partitionColumnNames.mkString(",") |
| 60 | + val specColumns = normalizedPartitionSpec.keys.mkString(",") |
| 61 | + throw new AnalysisException("The list of partition columns with values " + |
| 62 | + s"in partition specification for table '${tableId.table}' " + |
| 63 | + s"in database '${tableId.database.get}' is not a prefix of the list of " + |
| 64 | + "partition columns defined in the table schema. " + |
| 65 | + s"Expected a prefix of [${schemaColumns}], but got [${specColumns}].") |
| 66 | + } |
| 67 | + |
| 68 | + val filteredSpec = normalizedPartitionSpec.filter(_._2.isDefined).mapValues(_.get) |
| 69 | + if (filteredSpec.isEmpty) { |
| 70 | + None |
| 71 | + } else { |
| 72 | + Some(filteredSpec) |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + override def run(sparkSession: SparkSession): Seq[Row] = { |
| 77 | + val sessionState = sparkSession.sessionState |
| 78 | + val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase) |
| 79 | + val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db)) |
| 80 | + val tableMeta = sessionState.catalog.getTableMetadata(tableIdentWithDB) |
| 81 | + if (tableMeta.tableType == CatalogTableType.VIEW) { |
| 82 | + throw new AnalysisException("ANALYZE TABLE is not supported on views.") |
| 83 | + } |
| 84 | + |
| 85 | + val partitionValueSpec = getPartitionSpec(tableMeta) |
| 86 | + |
| 87 | + val partitions = sessionState.catalog.listPartitions(tableMeta.identifier, partitionValueSpec) |
| 88 | + |
| 89 | + if (partitions.isEmpty) { |
| 90 | + if (partitionValueSpec.isDefined) { |
| 91 | + throw new NoSuchPartitionException(db, tableIdent.table, partitionValueSpec.get) |
| 92 | + } else { |
| 93 | + // the user requested to analyze all partitions for a table which has no partitions |
| 94 | + // return normally, since there is nothing to do |
| 95 | + return Seq.empty[Row] |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + // Compute statistics for individual partitions |
| 100 | + val rowCounts: Map[TablePartitionSpec, BigInt] = |
| 101 | + if (noscan) { |
| 102 | + Map.empty |
| 103 | + } else { |
| 104 | + calculateRowCountsPerPartition(sparkSession, tableMeta, partitionValueSpec) |
| 105 | + } |
| 106 | + |
| 107 | + // Update the metastore if newly computed statistics are different from those |
| 108 | + // recorded in the metastore. |
| 109 | + val newPartitions = partitions.flatMap { p => |
| 110 | + val newTotalSize = CommandUtils.calculateLocationSize( |
| 111 | + sessionState, tableMeta.identifier, p.storage.locationUri) |
| 112 | + val newRowCount = rowCounts.get(p.spec) |
| 113 | + val newStats = CommandUtils.compareAndGetNewStats(tableMeta.stats, newTotalSize, newRowCount) |
| 114 | + newStats.map(_ => p.copy(stats = newStats)) |
| 115 | + } |
| 116 | + |
| 117 | + if (newPartitions.nonEmpty) { |
| 118 | + sessionState.catalog.alterPartitions(tableMeta.identifier, newPartitions) |
| 119 | + } |
| 120 | + |
| 121 | + Seq.empty[Row] |
| 122 | + } |
| 123 | + |
| 124 | + private def calculateRowCountsPerPartition( |
| 125 | + sparkSession: SparkSession, |
| 126 | + tableMeta: CatalogTable, |
| 127 | + partitionValueSpec: Option[TablePartitionSpec]): Map[TablePartitionSpec, BigInt] = { |
| 128 | + val filter = if (partitionValueSpec.isDefined) { |
| 129 | + val filters = partitionValueSpec.get.map { |
| 130 | + case (columnName, value) => EqualTo(UnresolvedAttribute(columnName), Literal(value)) |
| 131 | + } |
| 132 | + filters.reduce(And) |
| 133 | + } else { |
| 134 | + Literal.TrueLiteral |
| 135 | + } |
| 136 | + |
| 137 | + val tableDf = sparkSession.table(tableMeta.identifier) |
| 138 | + val partitionColumns = tableMeta.partitionColumnNames.map(Column(_)) |
| 139 | + |
| 140 | + val df = tableDf.filter(Column(filter)).groupBy(partitionColumns: _*).count() |
| 141 | + |
| 142 | + df.collect().map { r => |
| 143 | + val partitionColumnValues = partitionColumns.indices.map(r.get(_).toString) |
| 144 | + val spec = tableMeta.partitionColumnNames.zip(partitionColumnValues).toMap |
| 145 | + val count = BigInt(r.getLong(partitionColumns.size)) |
| 146 | + (spec, count) |
| 147 | + }.toMap |
| 148 | + } |
| 149 | +} |
0 commit comments