You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@kyuubi.apache.org by "pan3793 (via GitHub)" <gi...@apache.org> on 2023/06/15 01:52:27 UTC

[GitHub] [kyuubi] pan3793 commented on a diff in pull request #4963: [KYUUBI #4937] Cleanup spark catalog shim and renamed to catalog utils

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


##########
externals/kyuubi-spark-sql-engine/src/main/scala/org/apache/kyuubi/engine/spark/util/SparkCatalogUtils.scala:
##########
@@ -0,0 +1,366 @@
+/*
+ * 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.engine.spark.util
+
+import java.util.regex.Pattern
+
+import org.apache.commons.lang3.StringUtils
+import org.apache.spark.sql.{Row, SparkSession}
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.util.quoteIfNeeded
+import org.apache.spark.sql.connector.catalog.{CatalogExtension, CatalogPlugin, SupportsNamespaces, TableCatalog}
+import org.apache.spark.sql.types.StructField
+
+import org.apache.kyuubi.Logging
+import org.apache.kyuubi.engine.spark.schema.SchemaHelper
+import org.apache.kyuubi.util.reflect.ReflectUtils.{getField, invokeAs}
+
+/**
+ * A shim that defines the interface interact with Spark's catalogs
+ */
+object SparkCatalogUtils extends Logging {
+
+  private val VIEW = "VIEW"
+  private val TABLE = "TABLE"
+
+  val SESSION_CATALOG: String = "spark_catalog"
+  val sparkTableTypes: Set[String] = Set(VIEW, TABLE)
+
+  // ///////////////////////////////////////////////////////////////////////////////////////////////
+  //                                          Catalog                                            //
+  // ///////////////////////////////////////////////////////////////////////////////////////////////
+
+  /**
+   * Get all register catalogs in Spark's `CatalogManager`
+   */
+  def getCatalogs(spark: SparkSession): Seq[Row] = {
+
+    // A [[CatalogManager]] is session unique
+    val catalogMgr = spark.sessionState.catalogManager
+    // get the custom v2 session catalog or default spark_catalog
+    val sessionCatalog = invokeAs[AnyRef](catalogMgr, "v2SessionCatalog")
+    val defaultCatalog = catalogMgr.currentCatalog
+
+    val defaults = Seq(sessionCatalog, defaultCatalog).distinct
+      .map(invokeAs[String](_, "name"))
+    val catalogs = getField[scala.collection.Map[String, _]](catalogMgr, "catalogs")
+    (catalogs.keys ++: defaults).distinct.map(Row(_))
+  }
+
+  def getCatalog(spark: SparkSession, catalogName: String): CatalogPlugin = {
+    val catalogManager = spark.sessionState.catalogManager
+    if (StringUtils.isBlank(catalogName)) {
+      catalogManager.currentCatalog
+    } else {
+      catalogManager.catalog(catalogName)
+    }
+  }
+
+  def setCurrentCatalog(spark: SparkSession, catalog: String): Unit = {
+    // SPARK-36841(3.3.0) Ensure setCurrentCatalog method catalog must exist
+    if (spark.sessionState.catalogManager.isCatalogRegistered(catalog)) {
+      spark.sessionState.catalogManager.setCurrentCatalog(catalog)
+    } else {
+      throw new IllegalArgumentException(s"Cannot find catalog plugin class for catalog '$catalog'")
+    }
+  }
+
+  // ///////////////////////////////////////////////////////////////////////////////////////////////
+  //                                           Schema                                            //
+  // ///////////////////////////////////////////////////////////////////////////////////////////////
+
+  /**
+   * a list of [[Row]]s, with 2 fields `schemaName: String, catalogName: String`
+   */
+  def getSchemas(
+      spark: SparkSession,
+      catalogName: String,
+      schemaPattern: String): Seq[Row] = {
+    if (catalogName == SparkCatalogUtils.SESSION_CATALOG) {
+      (spark.sessionState.catalog.listDatabases(schemaPattern) ++
+        getGlobalTempViewManager(spark, schemaPattern))
+        .map(Row(_, SparkCatalogUtils.SESSION_CATALOG))
+    } else {
+      val catalog = getCatalog(spark, catalogName)
+      getSchemasWithPattern(catalog, schemaPattern).map(Row(_, catalog.name))
+    }
+  }
+
+  private def getGlobalTempViewManager(
+      spark: SparkSession,
+      schemaPattern: String): Seq[String] = {
+    val database = spark.sharedState.globalTempViewManager.database
+    Option(database).filter(_.matches(schemaPattern)).toSeq
+  }
+
+  private def listAllNamespaces(
+      catalog: SupportsNamespaces,
+      namespaces: Array[Array[String]]): Array[Array[String]] = {
+    val children = namespaces.flatMap { ns =>
+      catalog.listNamespaces(ns)
+    }
+    if (children.isEmpty) {
+      namespaces
+    } else {
+      namespaces ++: listAllNamespaces(catalog, children)
+    }
+  }
+
+  private def listAllNamespaces(catalog: CatalogPlugin): Array[Array[String]] = {
+    catalog match {
+      case catalog: CatalogExtension =>
+        // DSv2 does not support pass schemaPattern transparently
+        catalog.defaultNamespace() +: catalog.listNamespaces(Array())
+      case catalog: SupportsNamespaces =>
+        val rootSchema = catalog.listNamespaces()
+        val allSchemas = listAllNamespaces(catalog, rootSchema)
+        allSchemas
+    }
+  }
+
+  private def listNamespacesWithPattern(
+      catalog: CatalogPlugin,
+      schemaPattern: String): Array[Array[String]] = {
+    listAllNamespaces(catalog).filter { ns =>
+      val quoted = ns.map(quoteIfNeeded).mkString(".")
+      schemaPattern.r.pattern.matcher(quoted).matches()
+    }.distinct
+  }
+
+  private def getSchemasWithPattern(catalog: CatalogPlugin, schemaPattern: String): Seq[String] = {
+    val p = schemaPattern.r.pattern
+    listAllNamespaces(catalog).flatMap { ns =>
+      val quoted = ns.map(quoteIfNeeded).mkString(".")
+      if (p.matcher(quoted).matches()) {
+        Some(quoted)
+      } else {
+        None
+      }

Review Comment:
   ```suggestion
         if (p.matcher(quoted).matches()) Some(quoted) else None
   ```



-- 
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: notifications-unsubscribe@kyuubi.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@kyuubi.apache.org
For additional commands, e-mail: notifications-help@kyuubi.apache.org