pan3793 commented on code in PR #4999:
URL: https://github.com/apache/kyuubi/pull/4999#discussion_r1251508601


##########
extensions/spark/kyuubi-spark-connector-hive/src/main/scala/org/apache/kyuubi/spark/connector/hive/HiveConnectorUtils.scala:
##########
@@ -0,0 +1,262 @@
+/*
+ * 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.kyuubi.spark.connector.hive
+
+import org.apache.spark.SPARK_VERSION
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.catalog.{CatalogTable, 
CatalogTablePartition}
+import org.apache.spark.sql.connector.catalog.TableChange
+import org.apache.spark.sql.connector.catalog.TableChange.{AddColumn, After, 
ColumnPosition, DeleteColumn, First, RenameColumn, UpdateColumnComment, 
UpdateColumnNullability, UpdateColumnPosition, UpdateColumnType}
+import org.apache.spark.sql.execution.command.CommandUtils
+import 
org.apache.spark.sql.execution.command.CommandUtils.{calculateMultipleLocationSizes,
 calculateSingleLocationSize}
+import org.apache.spark.sql.execution.datasources.PartitionedFile
+import org.apache.spark.sql.types.{ArrayType, MapType, StructField, StructType}
+
+import org.apache.kyuubi.spark.connector.common.SparkUtils
+import org.apache.kyuubi.util.SemanticVersion
+import org.apache.kyuubi.util.reflect.ReflectUtils.invokeAs
+
+object HiveConnectorUtils extends Logging {
+
+  def partitionedFilePath(file: PartitionedFile): String = {
+    if (SparkUtils.isSparkVersionAtLeast("3.4")) {
+      invokeAs[String](file, "urlEncodedPath")
+    } else if (SparkUtils.isSparkVersionAtLeast("3.3")) {
+      invokeAs[String](file, "filePath")
+    } else {
+      throw KyuubiHiveConnectorException(s"Spark version $SPARK_VERSION " +
+        s"is not supported by Kyuubi spark hive connector.")
+    }
+  }
+
+  def calculateTotalSize(
+      spark: SparkSession,
+      catalogTable: CatalogTable,
+      hiveTableCatalog: HiveTableCatalog): (BigInt, 
Seq[CatalogTablePartition]) = {
+    val sessionState = spark.sessionState
+    val startTime = System.nanoTime()
+    val (totalSize, newPartitions) = if 
(catalogTable.partitionColumnNames.isEmpty) {
+      (
+        calculateSingleLocationSize(
+          sessionState,
+          catalogTable.identifier,
+          catalogTable.storage.locationUri),
+        Seq())
+    } else {
+      // Calculate table size as a sum of the visible partitions. See 
SPARK-21079
+      val partitions = hiveTableCatalog.listPartitions(catalogTable.identifier)
+      logInfo(s"Starting to calculate sizes for ${partitions.length} 
partitions.")
+      val paths = partitions.map(_.storage.locationUri)
+      val sizes = calculateMultipleLocationSizes(spark, 
catalogTable.identifier, paths)
+      val newPartitions = partitions.zipWithIndex.flatMap { case (p, idx) =>
+        val newStats = CommandUtils.compareAndGetNewStats(p.stats, sizes(idx), 
None)
+        newStats.map(_ => p.copy(stats = newStats))
+      }
+      (sizes.sum, newPartitions)
+    }
+    logInfo(s"It took ${(System.nanoTime() - startTime) / (1000 * 1000)} ms to 
calculate" +
+      s" the total size for table ${catalogTable.identifier}.")
+    (totalSize, newPartitions)
+  }
+
+  def applySchemaChanges(schema: StructType, changes: Seq[TableChange]): 
StructType = {
+    changes.foldLeft(schema) { (schema, change) =>
+      change match {
+        case add: AddColumn =>
+          add.fieldNames match {
+            case Array(name) =>
+              val field = StructField(name, add.dataType, nullable = 
add.isNullable)
+              val newField = 
Option(add.comment).map(field.withComment).getOrElse(field)
+              addField(schema, newField, add.position())
+
+            case names =>
+              replace(
+                schema,
+                names.init,
+                parent =>
+                  parent.dataType match {
+                    case parentType: StructType =>
+                      val field = StructField(names.last, add.dataType, 
nullable = add.isNullable)
+                      val newField = 
Option(add.comment).map(field.withComment).getOrElse(field)
+                      Some(parent.copy(dataType = addField(parentType, 
newField, add.position())))
+
+                    case _ =>
+                      throw new IllegalArgumentException(s"Not a struct: 
${names.init.last}")
+                  })
+          }
+
+        case rename: RenameColumn =>
+          replace(
+            schema,
+            rename.fieldNames,
+            field =>
+              Some(StructField(rename.newName, field.dataType, field.nullable, 
field.metadata)))
+
+        case update: UpdateColumnType =>
+          replace(
+            schema,
+            update.fieldNames,
+            field => {
+              Some(field.copy(dataType = update.newDataType))
+            })

Review Comment:
   ```suggestion
               field => Some(field.copy(dataType = update.newDataType)))
   ```



-- 
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.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to