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

[GitHub] [kyuubi] bowenliang123 opened a new pull request, #4963: [KYUUBI #4937] Cleanup spark catalog shim and renamed to catalog utils

bowenliang123 opened a new pull request, #4963:
URL: https://github.com/apache/kyuubi/pull/4963

   <!--
   Thanks for sending a pull request!
   
   Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://kyuubi.readthedocs.io/en/latest/community/CONTRIBUTING.html
     2. If the PR is related to an issue in https://github.com/apache/kyuubi/issues, add '[KYUUBI #XXXX]' in your PR title, e.g., '[KYUUBI #XXXX] Your PR title ...'.
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][KYUUBI #XXXX] Your PR title ...'.
   -->
   
   ### _Why are the changes needed?_
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you add a feature, you can talk about the use case of it.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   
   
   ### _How was this patch tested?_
   - [ ] Add some test cases that check the changes thoroughly including negative and positive cases if possible
   
   - [ ] Add screenshots for manual tests if appropriate
   
   - [ ] [Run test](https://kyuubi.readthedocs.io/en/master/develop_tools/testing.html#running-tests) locally before make a pull request
   


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


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

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#issuecomment-1592449209

   The change of this PR is already big, it's valuable to do some further changes in follow-up PRs.


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


[GitHub] [kyuubi] codecov-commenter commented on pull request #4963: [KYUUBI #4937] Cleanup spark catalog shim and renamed to catalog utils

Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#issuecomment-1592514677

   ## [Codecov](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   > Merging [#4963](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) (f0c93b4) into [master](https://app.codecov.io/gh/apache/kyuubi/commit/050b5aa7df148fc11cdbe164f72061739566fdc4?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) (050b5aa) will **not change** coverage.
   > The diff coverage is `0.00%`.
   
   ```diff
   @@          Coverage Diff           @@
   ##           master   #4963   +/-   ##
   ======================================
     Coverage    0.00%   0.00%           
   ======================================
     Files         563     561    -2     
     Lines       30964   30956    -8     
     Branches     4035    4052   +17     
   ======================================
   + Misses      30964   30956    -8     
   ```
   
   
   | [Impacted Files](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [...he/kyuubi/engine/spark/operation/GetCatalogs.scala](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZXh0ZXJuYWxzL2t5dXViaS1zcGFyay1zcWwtZW5naW5lL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUva3l1dWJpL2VuZ2luZS9zcGFyay9vcGVyYXRpb24vR2V0Q2F0YWxvZ3Muc2NhbGE=) | `0.00% <0.00%> (ø)` | |
   | [...che/kyuubi/engine/spark/operation/GetColumns.scala](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZXh0ZXJuYWxzL2t5dXViaS1zcGFyay1zcWwtZW5naW5lL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUva3l1dWJpL2VuZ2luZS9zcGFyay9vcGVyYXRpb24vR2V0Q29sdW1ucy5zY2FsYQ==) | `0.00% <0.00%> (ø)` | |
   | [...ubi/engine/spark/operation/GetCurrentCatalog.scala](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZXh0ZXJuYWxzL2t5dXViaS1zcGFyay1zcWwtZW5naW5lL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUva3l1dWJpL2VuZ2luZS9zcGFyay9vcGVyYXRpb24vR2V0Q3VycmVudENhdGFsb2cuc2NhbGE=) | `0.00% <0.00%> (ø)` | |
   | [...bi/engine/spark/operation/GetCurrentDatabase.scala](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZXh0ZXJuYWxzL2t5dXViaS1zcGFyay1zcWwtZW5naW5lL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUva3l1dWJpL2VuZ2luZS9zcGFyay9vcGVyYXRpb24vR2V0Q3VycmVudERhdGFiYXNlLnNjYWxh) | `0.00% <0.00%> (ø)` | |
   | [...che/kyuubi/engine/spark/operation/GetSchemas.scala](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZXh0ZXJuYWxzL2t5dXViaS1zcGFyay1zcWwtZW5naW5lL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUva3l1dWJpL2VuZ2luZS9zcGFyay9vcGVyYXRpb24vR2V0U2NoZW1hcy5zY2FsYQ==) | `0.00% <0.00%> (ø)` | |
   | [.../kyuubi/engine/spark/operation/GetTableTypes.scala](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZXh0ZXJuYWxzL2t5dXViaS1zcGFyay1zcWwtZW5naW5lL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUva3l1dWJpL2VuZ2luZS9zcGFyay9vcGVyYXRpb24vR2V0VGFibGVUeXBlcy5zY2FsYQ==) | `0.00% <0.00%> (ø)` | |
   | [...ache/kyuubi/engine/spark/operation/GetTables.scala](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZXh0ZXJuYWxzL2t5dXViaS1zcGFyay1zcWwtZW5naW5lL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUva3l1dWJpL2VuZ2luZS9zcGFyay9vcGVyYXRpb24vR2V0VGFibGVzLnNjYWxh) | `0.00% <0.00%> (ø)` | |
   | [...ubi/engine/spark/operation/SetCurrentCatalog.scala](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZXh0ZXJuYWxzL2t5dXViaS1zcGFyay1zcWwtZW5naW5lL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUva3l1dWJpL2VuZ2luZS9zcGFyay9vcGVyYXRpb24vU2V0Q3VycmVudENhdGFsb2cuc2NhbGE=) | `0.00% <0.00%> (ø)` | |
   | [...bi/engine/spark/operation/SetCurrentDatabase.scala](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZXh0ZXJuYWxzL2t5dXViaS1zcGFyay1zcWwtZW5naW5lL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUva3l1dWJpL2VuZ2luZS9zcGFyay9vcGVyYXRpb24vU2V0Q3VycmVudERhdGFiYXNlLnNjYWxh) | `0.00% <0.00%> (ø)` | |
   | [...ine/spark/operation/SparkSQLOperationManager.scala](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZXh0ZXJuYWxzL2t5dXViaS1zcGFyay1zcWwtZW5naW5lL3NyYy9tYWluL3NjYWxhL29yZy9hcGFjaGUva3l1dWJpL2VuZ2luZS9zcGFyay9vcGVyYXRpb24vU3BhcmtTUUxPcGVyYXRpb25NYW5hZ2VyLnNjYWxh) | `0.00% <0.00%> (ø)` | |
   | ... and [2 more](https://app.codecov.io/gh/apache/kyuubi/pull/4963?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | |
   
   ... and [3 files with indirect coverage changes](https://app.codecov.io/gh/apache/kyuubi/pull/4963/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   
   :mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   


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


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

Posted by "bowenliang123 (via GitHub)" <gi...@apache.org>.
bowenliang123 commented on PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#issuecomment-1592942158

   Thanks, merged to master.


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


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

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#discussion_r1230332448


##########
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
+      }
+    }.distinct
+  }
+
+  // ///////////////////////////////////////////////////////////////////////////////////////////////
+  //                                        Table & View                                         //
+  // ///////////////////////////////////////////////////////////////////////////////////////////////
+
+  def getCatalogTablesOrViews(
+      spark: SparkSession,
+      catalogName: String,
+      schemaPattern: String,
+      tablePattern: String,
+      tableTypes: Set[String],
+      ignoreTableProperties: Boolean = false): Seq[Row] = {
+    val catalog = getCatalog(spark, catalogName)
+    val namespaces = listNamespacesWithPattern(catalog, schemaPattern)
+    catalog match {
+      case builtin if builtin.name() == SESSION_CATALOG =>
+        val catalog = spark.sessionState.catalog
+        val databases = catalog.listDatabases(schemaPattern)
+
+        def isMatchedTableType(tableTypes: Set[String], tableType: String): Boolean = {
+          val typ = if (tableType.equalsIgnoreCase(VIEW)) VIEW else TABLE
+          tableTypes.exists(typ.equalsIgnoreCase)
+        }
+
+        databases.flatMap { db =>
+          val identifiers = catalog.listTables(db, tablePattern, includeLocalTempViews = false)
+          catalog.getTablesByName(identifiers)
+            .filter(t => isMatchedTableType(tableTypes, t.tableType.name)).map { t =>
+              val typ = if (t.tableType.name == VIEW) VIEW else TABLE
+              Row(
+                catalogName,
+                t.database,
+                t.identifier.table,
+                typ,
+                t.comment.getOrElse(""),
+                null,
+                null,
+                null,
+                null,
+                null)
+            }
+        }
+      case tc: TableCatalog =>
+        val tp = tablePattern.r.pattern
+        val identifiers = namespaces.flatMap { ns =>
+          tc.listTables(ns).filter(i => tp.matcher(quoteIfNeeded(i.name())).matches())
+        }
+        identifiers.map { ident =>
+          // TODO: restore view type for session catalog
+          val comment = if (ignoreTableProperties) ""
+          else tc.loadTable(ident).properties().getOrDefault(TableCatalog.PROP_COMMENT, "")

Review Comment:
   It was reported by dozen users that metadata refresh takes a long time, let's add the comment to the code to make the learner easy to understand.
   
   ```suggestion
             val comment = if (ignoreTableProperties) ""
             else { // load table is a time consuming operation
               tc.loadTable(ident).properties().getOrDefault(TableCatalog.PROP_COMMENT, "")
             }
   ```



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


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

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#discussion_r1230495593


##########
externals/kyuubi-spark-sql-engine/src/main/scala/org/apache/kyuubi/engine/spark/util/SparkCatalogUtils.scala:
##########
@@ -0,0 +1,375 @@
+/*
+ * 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.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.DynMethods
+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(catalog =>
+      DynMethods.builder("name").impl(catalog.getClass).buildChecked(catalog).invoke[String]())

Review Comment:
   sgtm



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


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

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
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


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

Posted by "bowenliang123 (via GitHub)" <gi...@apache.org>.
bowenliang123 commented on code in PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#discussion_r1230493672


##########
externals/kyuubi-spark-sql-engine/src/main/scala/org/apache/kyuubi/engine/spark/util/SparkCatalogUtils.scala:
##########
@@ -0,0 +1,375 @@
+/*
+ * 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.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.DynMethods
+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(catalog =>
+      DynMethods.builder("name").impl(catalog.getClass).buildChecked(catalog).invoke[String]())

Review Comment:
   Shall I refactor the `ReflectUtils.invokeAs` for this, by calling declared methods first and then the inherited methods? And I will throw corresponding method candidates to either one.



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


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

Posted by "bowenliang123 (via GitHub)" <gi...@apache.org>.
bowenliang123 commented on code in PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#discussion_r1230482248


##########
externals/kyuubi-spark-sql-engine/src/main/scala/org/apache/kyuubi/engine/spark/util/SparkCatalogUtils.scala:
##########
@@ -0,0 +1,375 @@
+/*
+ * 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.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.DynMethods
+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(catalog =>
+      DynMethods.builder("name").impl(catalog.getClass).buildChecked(catalog).invoke[String]())

Review Comment:
   While `ReflectUtils.invokeAs` supports declared method only, I have to use DynMethods for calling method of inherited methods here manually.  cc @pan3793 



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


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

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#issuecomment-1592444759

   > Seems not enough evidence for the necessity of the suggested changes in that PR.
   
   The key is order, there were some issues(see https://github.com/apache/kyuubi/pull/4219) when `DelegatingCatalogExtension` is used as `spark_catalog`.
   


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


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

Posted by "bowenliang123 (via GitHub)" <gi...@apache.org>.
bowenliang123 commented on code in PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#discussion_r1230520454


##########
externals/kyuubi-spark-sql-engine/src/main/scala/org/apache/kyuubi/engine/spark/util/SparkCatalogUtils.scala:
##########
@@ -0,0 +1,375 @@
+/*
+ * 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.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.DynMethods
+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(catalog =>
+      DynMethods.builder("name").impl(catalog.getClass).buildChecked(catalog).invoke[String]())

Review Comment:
   OK, let's make it in the  follow-ups.



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


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

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#issuecomment-1592266801

   A related PR may worth to evaluate https://github.com/apache/kyuubi/pull/4465


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


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

Posted by "pan3793 (via GitHub)" <gi...@apache.org>.
pan3793 commented on code in PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#discussion_r1230490326


##########
externals/kyuubi-spark-sql-engine/src/main/scala/org/apache/kyuubi/engine/spark/util/SparkCatalogUtils.scala:
##########
@@ -0,0 +1,375 @@
+/*
+ * 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.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.DynMethods
+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(catalog =>
+      DynMethods.builder("name").impl(catalog.getClass).buildChecked(catalog).invoke[String]())

Review Comment:
   Is it possible to access all methods by an unified reflection api? 



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


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

Posted by "bowenliang123 (via GitHub)" <gi...@apache.org>.
bowenliang123 commented on PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#issuecomment-1592433648

   > A related PR may worth to evaluate #4465
   
   Seems not enough evidence for the necessity of the suggested changes in that PR.
   As for me, checking the catalog name to `spark_catalog` is more strict than matching in TableCatalog class, and it's appropriate to be placed in the first matching case here.


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


[GitHub] [kyuubi] bowenliang123 closed pull request #4963: [KYUUBI #4937] Cleanup spark catalog shim and renamed to catalog utils

Posted by "bowenliang123 (via GitHub)" <gi...@apache.org>.
bowenliang123 closed pull request #4963: [KYUUBI #4937] Cleanup spark catalog shim and renamed to catalog utils
URL: https://github.com/apache/kyuubi/pull/4963


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


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

Posted by "bowenliang123 (via GitHub)" <gi...@apache.org>.
bowenliang123 commented on code in PR #4963:
URL: https://github.com/apache/kyuubi/pull/4963#discussion_r1230334558


##########
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
+      }
+    }.distinct
+  }
+
+  // ///////////////////////////////////////////////////////////////////////////////////////////////
+  //                                        Table & View                                         //
+  // ///////////////////////////////////////////////////////////////////////////////////////////////
+
+  def getCatalogTablesOrViews(
+      spark: SparkSession,
+      catalogName: String,
+      schemaPattern: String,
+      tablePattern: String,
+      tableTypes: Set[String],
+      ignoreTableProperties: Boolean = false): Seq[Row] = {
+    val catalog = getCatalog(spark, catalogName)
+    val namespaces = listNamespacesWithPattern(catalog, schemaPattern)
+    catalog match {
+      case builtin if builtin.name() == SESSION_CATALOG =>
+        val catalog = spark.sessionState.catalog
+        val databases = catalog.listDatabases(schemaPattern)
+
+        def isMatchedTableType(tableTypes: Set[String], tableType: String): Boolean = {
+          val typ = if (tableType.equalsIgnoreCase(VIEW)) VIEW else TABLE
+          tableTypes.exists(typ.equalsIgnoreCase)
+        }
+
+        databases.flatMap { db =>
+          val identifiers = catalog.listTables(db, tablePattern, includeLocalTempViews = false)
+          catalog.getTablesByName(identifiers)
+            .filter(t => isMatchedTableType(tableTypes, t.tableType.name)).map { t =>
+              val typ = if (t.tableType.name == VIEW) VIEW else TABLE
+              Row(
+                catalogName,
+                t.database,
+                t.identifier.table,
+                typ,
+                t.comment.getOrElse(""),
+                null,
+                null,
+                null,
+                null,
+                null)
+            }
+        }
+      case tc: TableCatalog =>
+        val tp = tablePattern.r.pattern
+        val identifiers = namespaces.flatMap { ns =>
+          tc.listTables(ns).filter(i => tp.matcher(quoteIfNeeded(i.name())).matches())
+        }
+        identifiers.map { ident =>
+          // TODO: restore view type for session catalog
+          val comment = if (ignoreTableProperties) ""
+          else tc.loadTable(ident).properties().getOrDefault(TableCatalog.PROP_COMMENT, "")

Review Comment:
   Adopted.



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