pan3793 commented on code in PR #7718:
URL: https://github.com/apache/kyuubi/pull/7718#discussion_r4681435535
##########
kyuubi-common/src/test/scala/org/apache/kyuubi/operation/SparkMetadataTests.scala:
##########
@@ -130,6 +147,61 @@ trait SparkMetadataTests extends HiveJDBCTestHelper {
}
}
+ test("get tables and views whose names equal the pattern prefix") {
+ val table = "prefix"
+ val tempView = "prefix"
+ val another = "prefixx"
+ withJdbcStatement(table, another) { statement =>
+ statement.execute(
+ s"CREATE TABLE IF NOT EXISTS $table(key int) USING parquet COMMENT
'$table'")
+ statement.execute(s"CREATE TABLE IF NOT EXISTS $another(key int) USING
parquet")
+ // Temp views shadow same-named tables in SQL, but the metadata APIs
report both.
+ statement.execute(s"CREATE OR REPLACE TEMPORARY VIEW $tempView AS SELECT
1 AS a")
+ try {
+ val metaData = statement.getConnection.getMetaData
+
+ val rsTable = metaData.getTables("spark_catalog", "default",
"prefix%", Array("TABLE"))
+ val tableNames = scala.collection.mutable.Set.empty[String]
+ while (rsTable.next()) {
+ tableNames += rsTable.getString(TABLE_NAME)
+ }
+ assert(tableNames == Set(table, another))
+
+ val rsView = metaData.getTables("spark_catalog", "default", "prefix%",
Array("VIEW"))
+ val viewNames = scala.collection.mutable.Set.empty[String]
+ while (rsView.next()) {
+ viewNames += rsView.getString(TABLE_NAME)
+ }
+ assert(viewNames == Set(tempView))
+ } finally {
+ // The qualified drops bypass the same-named temp view.
+ statement.execute(s"DROP VIEW IF EXISTS $tempView")
+ statement.execute(s"DROP TABLE IF EXISTS default.$table")
+ statement.execute(s"DROP TABLE IF EXISTS default.$another")
+ }
+ }
+ }
+
+ test("get functions whose names equal the pattern prefix") {
Review Comment:
[Test] This also runs in `TrinoFrontendSuite`, and the Trino JDBC driver
(411) throws `NotImplementedException` from `getFunctions`, so that suite will
fail. Move it to `SparkOperationSuite`, next to `get functions` (`:306`).
##########
externals/kyuubi-spark-sql-engine/src/main/scala/org/apache/kyuubi/engine/spark/util/SparkCatalogUtils.scala:
##########
@@ -259,33 +518,44 @@ object SparkCatalogUtils extends Logging {
val catalog = getCatalog(spark, catalogName)
catalog match {
+ case builtin if builtin.name() == SESSION_CATALOG &&
!hasCustomSessionCatalog(spark) =>
+ val sessionCatalog = spark.sessionState.catalog
+ val databases =
sessionCatalog.listDatabases(toV1Pattern(schemaPattern))
+ databases.flatMap { db =>
+ val identifiers =
+ sessionCatalog.listTables(
+ db,
+ toV1Pattern(tablePattern),
+ includeLocalTempViews = false)
+ sessionCatalog.getTablesByName(identifiers).flatMap { t =>
+ t.schema.zipWithIndex.filter(f =>
columnPattern.matcher(f._1.name).matches())
+ .map { case (f, i) =>
+ toColumnResult(builtin.name(), t.database, t.identifier.table,
f, i)
+ }
+ }
+ }
+
case tc: TableCatalog =>
- val namespaces = listNamespacesWithPattern(catalog, schemaPattern)
- val tp = tablePattern.r.pattern
+ val quote = catalog.name() != SESSION_CATALOG
+ val namespaces = listNamespacesWithPattern(catalog, schemaPattern,
quote = quote)
+ val tp = compilePattern(catalog, tablePattern)
val identifiers = namespaces.flatMap { ns =>
- tc.listTables(ns).filter(i =>
tp.matcher(quoteIfNeeded(i.name())).matches())
+ tc.listTables(ns).filter { i =>
+ i.namespace().nonEmpty &&
+ tp.matcher(if (quote) quoteIfNeeded(i.name()) else
i.name()).matches()
+ }
}
identifiers.flatMap { ident =>
val table = tc.loadTable(ident)
Review Comment:
[Minor] `loadTable` is unguarded, so one table that fails to load (the
v1-delegated ones described under Limitations) fails GetColumns for all matched
tables, while GetTables degrades the same table to an empty REMARKS. Use
`attempt`, warn, and skip its columns. Pre-existing, but the same inconsistency
this PR resolves for GetTables.
##########
externals/kyuubi-spark-sql-engine/src/main/scala/org/apache/kyuubi/engine/spark/util/SparkCatalogUtils.scala:
##########
@@ -153,23 +167,46 @@ object SparkCatalogUtils extends Logging {
val rootSchema = catalog.listNamespaces()
val allSchemas = listAllNamespaces(catalog, rootSchema)
allSchemas
+ case _ =>
+ Array.empty[Array[String]]
+ }
+ }
+
+ // Rewrites the Java regex produced by `toJavaRegex` back into a SQL-like
pattern: the v1
Review Comment:
[Nit] This comment and the test name in `SparkCatalogUtilsSuite` call the
result a SQL-like pattern, but the v1 APIs take Hive-style patterns (`*` and
`|`, the rest is regex). Suggest: "Converts the regex from `toJavaRegex` to the
pattern form of the v1 catalog APIs, which prepend `(?i)` and expand `*`
themselves."
##########
externals/kyuubi-spark-sql-engine/src/main/scala/org/apache/kyuubi/engine/spark/util/SparkCatalogUtils.scala:
##########
@@ -231,25 +272,243 @@ object SparkCatalogUtils extends Logging {
}
}
}
+
+ case tc: TableCatalog if tc.name() == SESSION_CATALOG =>
+ getCustomSessionCatalogTablesOrViews(
+ spark,
+ tc,
+ namespaces,
+ tablePattern,
+ tableTypes,
+ ignoreTableProperties)
+
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 { // load table is a time consuming operation
-
tc.loadTable(ident).properties().getOrDefault(TableCatalog.PROP_COMMENT, "")
+ if (ignoreTableProperties) {
+ namespaces.flatMap { ns =>
+ listTableSummaries(tc, ns).map { summaries =>
+ summaries.collect {
+ case (ident, tableType)
+ if ident.namespace().nonEmpty &&
+ tp.matcher(quoteIfNeeded(ident.name())).matches() =>
+ (ident, toTableType(tableType))
+ }.filter { case (_, typ) =>
tableTypes.exists(typ.equalsIgnoreCase) }
+ }.getOrElse {
+ tc.listTables(ns)
+ .filter(i => tp.matcher(quoteIfNeeded(i.name())).matches())
+ .map((_, TABLE))
+ .toSeq
+ }
+ }.map { case (ident, typ) =>
+ val schema = ident.namespace().map(quoteIfNeeded).mkString(".")
+ val tableName = quoteIfNeeded(ident.name())
+ Row(catalog.name(), schema, tableName, typ, "", null, null, null,
null, null)
+ }
+ } else {
+ val identifiers = namespaces.flatMap { ns =>
+ tc.listTables(ns).filter(i =>
tp.matcher(quoteIfNeeded(i.name())).matches())
+ }
+ identifiers.map { ident =>
+ // TODO: support view type once v2 ViewCatalog is mature enough.
+ // load table is a time consuming operation
+ val comment =
+
tc.loadTable(ident).properties().getOrDefault(TableCatalog.PROP_COMMENT, "")
+ val schema = ident.namespace().map(quoteIfNeeded).mkString(".")
+ val tableName = quoteIfNeeded(ident.name())
+ Row(catalog.name(), schema, tableName, TABLE, comment, null, null,
null, null, null)
}
- val schema = ident.namespace().map(quoteIfNeeded).mkString(".")
- val tableName = quoteIfNeeded(ident.name())
- Row(catalog.name(), schema, tableName, TABLE, comment, null, null,
null, null, null)
}
+
case _ => Seq.empty[Row]
}
}
+ private def getCustomSessionCatalogTablesOrViews(
+ spark: SparkSession,
+ tc: TableCatalog,
+ namespaces: Array[Array[String]],
+ tablePattern: String,
+ tableTypes: Set[String],
+ ignoreTableProperties: Boolean): Seq[Row] = {
+ val tp = compilePattern(tc, tablePattern)
+ val sessionCatalog = spark.sessionState.catalog
+
+ def loadComment(ident: Identifier): String = {
+ // loadTable may fail for v1-delegated tables, degrade REMARKS to "" on
failure.
+
attempt(tc.loadTable(ident).properties().getOrDefault(TableCatalog.PROP_COMMENT,
"")) match {
+ case Success(comment) => comment
+ case Failure(e) =>
+ warn(s"Failed to load table $ident for the comment", e)
+ ""
+ }
+ }
+
+ def listMatchingTables(ns: Array[String]): Seq[Identifier] = {
+ // listTables returns local temp views (empty namespace), skip them.
+ tc.listTables(ns).filter { t =>
+ t.namespace().nonEmpty && tp.matcher(t.name()).matches()
+ }.toSeq
+ }
+
+ val typedTables =
+ if (ignoreTableProperties) {
+ namespaces.flatMap { ns =>
+ listTableSummaries(tc, ns).map { summaries =>
+ summaries.collect {
+ case (ident, tableType)
+ if ident.namespace().nonEmpty &&
tp.matcher(ident.name()).matches() =>
+ (ident, toTableType(tableType), "")
+ }.filter { case (_, typ, _) =>
tableTypes.exists(typ.equalsIgnoreCase) }
+ }.getOrElse(listMatchingTables(ns).map((_, TABLE, "")))
+ }
+ } else {
+ namespaces.flatMap { ns =>
+ val tables = listMatchingTables(ns)
+ if (tables.isEmpty) {
+ Seq.empty
+ } else {
+ // Multi-level namespaces never refer to v1 tables, so only
single-level
+ // identifiers can join the batched metastore lookup below.
+ val (v1Candidates, nonV1Tables) =
tables.partition(_.namespace().length == 1)
+ // One batched metastore call per namespace returns both the table
type and the
+ // comment for v1-backed tables, avoiding per-table loads. A
failed batch degrades
+ // this namespace to one loadTable per table, logged once per
namespace below.
+ val batched = attempt(
+ sessionCatalog.getTablesByName(
+ v1Candidates.map(t => TableIdentifier(t.name(),
Some(t.namespace().head))))
+ .map(ct => (ct.database.toLowerCase,
ct.identifier.table.toLowerCase) -> ct)
+ .toMap)
+
+ // The v1 catalog is case-insensitive, so join case-insensitively
to survive
+ // catalogs whose identifiers differ in case from the metastore's.
+ def joinKey(ident: Identifier): (String, String) =
+ (ident.namespace().head.toLowerCase, ident.name().toLowerCase)
+
+ val (fromBatch, unmatched) = batched match {
+ case Success(byName) =>
+ // Identifiers a successful batch did not return are absent
from the
+ // metastore, so they cannot be v1 views.
+ (
+ v1Candidates.flatMap { ident =>
+ byName.get(joinKey(ident)).map { ct =>
+ val typ = if (ct.tableType == CatalogTableType.VIEW)
VIEW else TABLE
+ (ident, typ, ct.comment.getOrElse(""))
+ }
+ },
+ v1Candidates.filterNot(ident =>
byName.contains(joinKey(ident))))
+ case Failure(e) =>
+ warn(
Review Comment:
[Minor] This warn also fires for namespaces the metastore does not have,
e.g. DSv2-only namespaces of a custom catalog: `getTablesByName` checks the
database first and throws, so every GetTables logs a stack trace per such
namespace. In the `Failure` branch, check `databaseExists` once, skip the warn
when it is absent, and reuse the result for the view probe (`:413`).
##########
kyuubi-common/src/test/scala/org/apache/kyuubi/HMSIcebergSuiteMixin.scala:
##########
@@ -0,0 +1,39 @@
+/*
+ * 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
+
+/**
+ * Runs the Iceberg suites against a real Hive Metastore provided by
[[WithSimpleHMSContainer]],
+ * where the session catalog `spark_catalog` is backed by Iceberg's
`SparkSessionCatalog`,
+ * instead of the in-memory one from [[IcebergSuiteMixin]].
+ */
+trait HMSIcebergSuiteMixin extends IcebergSuiteMixin {
+ self: WithSimpleHMSContainer =>
+
+ override protected def extraConfigs: Map[String, String] =
super.extraConfigs ++ Map(
+ "spark.sql.catalogImplementation" -> "hive",
+ "spark.hadoop.hive.metastore.uris" -> hmsThriftUris,
+ "spark.sql.catalog.spark_catalog.uris" -> hmsThriftUris,
Review Comment:
[Nit] Iceberg's property is `uri`, so `spark.sql.catalog.spark_catalog.uris`
has no effect; the metastore URI comes from the line above. Remove it.
--
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]