Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions common/utils/src/main/resources/error/error-conditions.json
Original file line number Diff line number Diff line change
Expand Up @@ -8049,6 +8049,11 @@
"<variableName> is a VARIABLE and cannot be updated using the SET statement. Use SET VARIABLE <variableName> = ... instead."
]
},
"SHOW_TABLE_EXTENDED_JSON_WITH_PARTITION" : {
"message" : [
"SHOW TABLE EXTENDED with PARTITION does not support AS JSON output."
]
},
"SQL_CURSOR" : {
"message" : [
"SQL cursor operations (DECLARE CURSOR, OPEN, FETCH, CLOSE) are not supported."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -360,9 +360,9 @@ statement
| EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)?
(statement|setResetStatement) #explain
| SHOW TABLES ((FROM | IN) identifierReference)?
(LIKE? pattern=stringLit)? #showTables
(LIKE? pattern=stringLit)? (AS JSON)? #showTables
| SHOW TABLE EXTENDED ((FROM | IN) ns=identifierReference)?
LIKE pattern=stringLit partitionSpec? #showTableExtended
LIKE pattern=stringLit partitionSpec? (AS JSON)? #showTableExtended
| SHOW TBLPROPERTIES table=identifierReference
(LEFT_PAREN key=propertyKeyOrStringLit RIGHT_PAREN)? #showTblProperties
| SHOW COLUMNS (FROM | IN) table=identifierReference
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ private[sql] trait CompilationErrors extends DataTypeErrorsBase {
messageParameters = Map.empty)
}

def showTableExtendedJsonWithPartitionError(): AnalysisException = {
new AnalysisException(
errorClass = "UNSUPPORTED_FEATURE.SHOW_TABLE_EXTENDED_JSON_WITH_PARTITION",
messageParameters = Map.empty)
}

def cannotFindDescriptorFileError(filePath: String, cause: Throwable): AnalysisException = {
new AnalysisException(
errorClass = "PROTOBUF_DESCRIPTOR_FILE_NOT_FOUND",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5795,14 +5795,21 @@ class AstBuilder extends DataTypeAstBuilder
} else {
CurrentNamespace
}
ShowTables(ns, Option(ctx.pattern).map(x => string(visitStringLit(x))))
val asJson = ctx.JSON != null
val pattern = Option(ctx.pattern).map(x => string(visitStringLit(x)))
val output = if (asJson) ShowTables.getJsonOutputAttrs else ShowTables.getOutputAttrs
ShowTables(ns, pattern, asJson, output)
}

/**
* Create a [[ShowTablesExtended]] or [[ShowTablePartition]] command.
*/
override def visitShowTableExtended(
ctx: ShowTableExtendedContext): LogicalPlan = withOrigin(ctx) {
val asJson = ctx.JSON != null
if (asJson && ctx.partitionSpec != null) {
throw QueryCompilationErrors.showTableExtendedJsonWithPartitionError()
}
Option(ctx.partitionSpec).map { spec =>
val table = withOrigin(ctx.pattern) {
if (ctx.identifierReference() != null) {
Expand All @@ -5822,7 +5829,8 @@ class AstBuilder extends DataTypeAstBuilder
} else {
CurrentNamespace
}
ShowTablesExtended(ns, string(visitStringLit(ctx.pattern)))
val output = if (asJson) ShowTables.getJsonOutputAttrs else ShowTablesUtils.getOutputAttrs
ShowTablesExtended(ns, string(visitStringLit(ctx.pattern)), asJson, output)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1371,17 +1371,22 @@ case class RenameTable(
case class ShowTables(
namespace: LogicalPlan,
pattern: Option[String],
asJson: Boolean = false,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently have duplicated JSON emission code across Exec classes. Consider a ShowTablesJsonCommand which takes the resolved namespace/catalog and handles all variants centrally, similar to DescribeRelationJsonCommand

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed. We extracted a single ShowTablesJsonExec physical plan node covering both SHOW TABLES AS JSON and SHOW TABLE EXTENDED AS JSON, controlled by an isExtended: Boolean flag.

override val output: Seq[Attribute] = ShowTables.getOutputAttrs) extends UnaryCommand {
override def child: LogicalPlan = namespace
override protected def withNewChildInternal(newChild: LogicalPlan): ShowTables =
copy(namespace = newChild)
override protected def stringArgs: Iterator[Any] = Iterator(pattern, output)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The asJson: Boolean = false field added to ShowTables (and
the parallel field on ShowTablesExtended and ShowTablesCommand) is then
immediately hidden from treeString by an override protected def stringArgs: Iterator[Any] = Iterator(pattern, output) further down. SHOW TABLES
(3-column schema) and SHOW TABLES AS JSON (1-column json_metadata schema)
produce different output schemas; their treeString should differ. The
override exists to keep golden files passing, but that hides a real plan-level
distinction.

Suggestion: Drop the stringArgs overrides and regenerate the affected
explain/golden files. If a specific suite needs the legacy string, scope the
override narrowly to that suite's plan view rather than to the case class.

}

object ShowTables {
def getOutputAttrs: Seq[Attribute] = Seq(
AttributeReference("namespace", StringType, nullable = false)(),
AttributeReference("tableName", StringType, nullable = false)(),
AttributeReference("isTemporary", BooleanType, nullable = false)())

def getJsonOutputAttrs: Seq[Attribute] = Seq(
AttributeReference("json_metadata", StringType, nullable = false)())
}

/**
Expand All @@ -1390,10 +1395,12 @@ object ShowTables {
case class ShowTablesExtended(
namespace: LogicalPlan,
pattern: String,
asJson: Boolean = false,
override val output: Seq[Attribute] = ShowTablesUtils.getOutputAttrs) extends UnaryCommand {
override def child: LogicalPlan = namespace
override protected def withNewChildInternal(newChild: LogicalPlan): ShowTablesExtended =
copy(namespace = newChild)
override protected def stringArgs: Iterator[Any] = Iterator(pattern, output)
}

object ShowTablesUtils {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -366,19 +366,23 @@ class ResolveSessionCatalog(val catalogManager: CatalogManager)
case d @ DropNamespace(ResolvedV1Database(db), _, _) if conf.useV1Command =>
DropDatabaseCommand(db, d.ifExists, d.cascade)

case ShowTables(ResolvedV1Database(db), pattern, output) if conf.useV1Command =>
ShowTablesCommand(Some(db), pattern, output)
case ShowTables(ResolvedV1Database(db), pattern, asJson, output) if conf.useV1Command =>
ShowTablesCommand(Some(db), pattern, output, asJson = asJson)

case ShowTablesExtended(
ResolvedV1Database(db),
pattern,
asJson,
output) =>
val newOutput = if (conf.getConf(SQLConf.LEGACY_KEEP_COMMAND_OUTPUT_SCHEMA)) {
val newOutput = if (asJson) {
output
} else if (conf.getConf(SQLConf.LEGACY_KEEP_COMMAND_OUTPUT_SCHEMA)) {
output.head.withName("database") +: output.tail
} else {
output
}
ShowTablesCommand(Some(db), Some(pattern), newOutput, isExtended = true)
ShowTablesCommand(Some(db), Some(pattern), newOutput,
isExtended = true, asJson = asJson)

case ShowTablePartition(
ResolvedTable(catalog, _, table: V1Table, _),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ class Catalog(sparkSession: SparkSession) extends catalog.Catalog with Logging {
private def makeTablesDataset(plan: ShowTables): Dataset[Table] = {
val qe = sparkSession.sessionState.executePlan(plan)
val catalog = qe.analyzed.collectFirst {
case ShowTables(r: ResolvedNamespace, _, _) => r.catalog
case ShowTables(r: ResolvedNamespace, _, _, _) => r.catalog
case _: ShowTablesCommand =>
sparkSession.sessionState.catalogManager.v2SessionCatalog
}.get
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import scala.util.control.NonFatal

import org.apache.hadoop.fs.{FileContext, FsConstants, Path}
import org.apache.hadoop.fs.permission.{AclEntry, AclEntryScope, AclEntryType, FsAction, FsPermission}
import org.json4s._
import org.json4s.jackson.JsonMethods._

import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.catalyst.{SQLConfHelper, TableIdentifier}
Expand Down Expand Up @@ -927,9 +929,21 @@ case class ShowTablesCommand(
tableIdentifierPattern: Option[String],
override val output: Seq[Attribute],
isExtended: Boolean = false,
partitionSpec: Option[TablePartitionSpec] = None) extends LeafRunnableCommand {
partitionSpec: Option[TablePartitionSpec] = None,
asJson: Boolean = false) extends LeafRunnableCommand {

override protected def stringArgs: Iterator[Any] =
Iterator(databaseName, tableIdentifierPattern, output, isExtended, partitionSpec)

override def run(sparkSession: SparkSession): Seq[Row] = {
if (asJson) {
runAsJson(sparkSession)
} else {
runAsText(sparkSession)
}
}

private def runAsText(sparkSession: SparkSession): Seq[Row] = {
// Since we need to return a Seq of rows, we will call getTables directly
// instead of calling tables in sparkSession.
val catalog = sparkSession.sessionState.catalog
Expand Down Expand Up @@ -972,6 +986,45 @@ case class ShowTablesCommand(
Seq(Row(database, tableName, isTemp, s"$information\n"))
}
}

private def runAsJson(sparkSession: SparkSession): Seq[Row] = {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ShowTablesCommand.runAsJson (V1) and ShowTablesJsonExec (V2)
are two emitters that have already drifted: extended catalog name is
v2SessionCatalog.name() here vs catalog.name() in V2; V1 uses
SessionCatalog.listTables (includes temp views) while V2 has a guarded
listTempViews branch.

Suggestion: collapse V1 + V2 into one ShowTablesJsonCommand built in
AstBuilder.visitShowTables / visitShowTableExtended after resolution,
pattern-matching on the resolved child (V1 session, V2 session, non-session
V2). Drop asJson from ShowTables / ShowTablesExtended /
ShowTablesCommand and the corresponding stringArgs overrides. The two emit
functions become one and the drift class closes.

val catalog = sparkSession.sessionState.catalog
val db = databaseName.getOrElse(catalog.getCurrentDatabase)
val tables =
tableIdentifierPattern.map(catalog.listTables(db, _)).getOrElse(catalog.listTables(db))

val jsonTables = tables.map { tableIdent =>
val isTemp = catalog.isTempView(tableIdent)
val ns = tableIdent.database.toList

if (isExtended) {
val tableType = if (isTemp) {
"VIEW"
} else {
val meta = catalog.getTempViewOrPermanentTableMetadata(tableIdent)
if (meta.tableType == CatalogTableType.VIEW) "VIEW" else "TABLE"
}

JObject(
"name" -> JString(tableIdent.table),
"catalog" -> JString(
sparkSession.sessionState.catalogManager.v2SessionCatalog.name()),
"namespace" -> JArray(ns.map(JString(_))),
"type" -> JString(tableType),
"isTemporary" -> JBool(isTemp)
)
} else {
JObject(
"name" -> JString(tableIdent.table),
"namespace" -> JArray(ns.map(JString(_))),
"isTemporary" -> JBool(isTemp)
)
}
}.toList

val jsonOutput = JObject("tables" -> JArray(jsonTables))
Seq(Row(compact(render(jsonOutput))))
}
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -658,8 +658,13 @@ class DataSourceV2Strategy(session: SparkSession) extends Strategy with Predicat
case DropNamespace(ResolvedNamespace(catalog, ns, _), ifExists, cascade) =>
DropNamespaceExec(catalog, ns, ifExists, cascade) :: Nil

case ShowTables(ResolvedNamespace(catalog, ns, _), pattern, output) =>
ShowTablesExec(output, catalog.asTableCatalog, ns, pattern) :: Nil
case ShowTables(ResolvedNamespace(catalog, ns, _), pattern, asJson, output) =>
if (asJson) {
ShowTablesJsonExec(
output, catalog.asTableCatalog, ns, pattern.getOrElse("*"), isExtended = false) :: Nil
} else {
ShowTablesExec(output, catalog.asTableCatalog, ns, pattern) :: Nil
}

// SHOW VIEWS on a v2 ViewCatalog. `ResolveSessionCatalog` rewrites the SHOW VIEWS plan to
// v1 `ShowViewsCommand` only when the catalog is NOT a `ViewCatalog`; non-`ViewCatalog`
Expand All @@ -673,8 +678,14 @@ class DataSourceV2Strategy(session: SparkSession) extends Strategy with Predicat
case ShowTablesExtended(
ResolvedNamespace(catalog, ns, _),
pattern,
asJson,
output) =>
ShowTablesExtendedExec(output, catalog.asTableCatalog, ns, pattern) :: Nil
if (asJson) {
ShowTablesJsonExec(
output, catalog.asTableCatalog, ns, pattern, isExtended = true) :: Nil
} else {
ShowTablesExtendedExec(output, catalog.asTableCatalog, ns, pattern) :: Nil
}

case ShowTablePartition(r: ResolvedTable, part, output) =>
ShowTablePartitionExec(output, r.catalog, r.identifier,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,19 @@ case class ShowTablesExec(
namespace: Seq[String],
pattern: Option[String]) extends V2CommandExec with LeafExecNode {
override protected def run(): Seq[InternalRow] = {
val rows = new ArrayBuffer[InternalRow]()

val identifiers: Array[Identifier] = catalog match {
case mc: TableViewCatalog =>
mc.listTableAndViewSummaries(namespace.toArray).map(_.identifier())
case _ => catalog.listTables(namespace.toArray)
}
identifiers.foreach { ident =>
if (pattern.map(StringUtils.filterPattern(Seq(ident.name()), _).nonEmpty).getOrElse(true)) {
rows += toCatalystRow(ident.namespace().quoted, ident.name(), isTempView(ident, catalog))
}
val filteredIdents = identifiers.filter { ident =>
pattern.map(StringUtils.filterPattern(Seq(ident.name()), _).nonEmpty).getOrElse(true)
}

val rows = new ArrayBuffer[InternalRow]()
filteredIdents.foreach { ident =>
rows += toCatalystRow(ident.namespace().quoted, ident.name(), isTempView(ident, catalog))
}
rows.toSeq
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* 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.spark.sql.execution.datasources.v2

import scala.collection.mutable.ArrayBuffer

import org.json4s._
import org.json4s.jackson.JsonMethods._

import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.Attribute
import org.apache.spark.sql.catalyst.util.StringUtils
import org.apache.spark.sql.connector.catalog.{CatalogV2Util, Identifier, TableCatalog, TableViewCatalog}
import org.apache.spark.sql.execution.LeafExecNode

/**
* Physical plan node for `SHOW TABLES AS JSON` and `SHOW TABLE EXTENDED AS JSON`.
*
* For a [[TableViewCatalog]] (non-extended only), listing is done via
* [[TableViewCatalog#listTableAndViewSummaries]] so that views appear alongside tables,
* matching the v1 `SHOW TABLES` semantics.
*/
case class ShowTablesJsonExec(
output: Seq[Attribute],
catalog: TableCatalog,
namespace: Seq[String],
pattern: String,
isExtended: Boolean) extends V2CommandExec with LeafExecNode {

override protected def run(): Seq[InternalRow] = {
val identifiers: Array[Identifier] = if (!isExtended) {
catalog match {
case mc: TableViewCatalog =>
mc.listTableAndViewSummaries(namespace.toArray).map(_.identifier())
case _ => catalog.listTables(namespace.toArray)
}
} else {
catalog.listTables(namespace.toArray)
}

val filteredIdents = identifiers.filter { ident =>
StringUtils.filterPattern(Seq(ident.name()), pattern).nonEmpty
}

val jsonRows = new ArrayBuffer[JObject]()
filteredIdents.foreach { ident =>
jsonRows += toJsonEntry(ident.name(), ident.namespace(), isTempView(ident))
}

// For non-session V2 catalogs that don't surface temp views via listTables() or
// listTableAndViewSummaries(), fetch them separately. For V2SessionCatalog,
// listTables() already includes local temp views, so we skip this to avoid duplicates.
// For TableViewCatalog (non-extended path), views come from listTableAndViewSummaries().
if (!CatalogV2Util.isSessionCatalog(catalog) &&
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This non-session V2 catalog branch
(!CatalogV2Util.isSessionCatalog(catalog) && (isExtended || !catalog.isInstanceOf[TableViewCatalog])) fetches session temp views from
sparkSession.sessionState.catalog and passes the V2 catalog's namespace as
the db argument. Local temp views live in the session catalog's reserved
temp database; global temp views live under global_temp. There is no
semantic in which a non-session V2 catalog's namespace contains session temp
views. Two potential problems:

  1. The first match arm passes namespace.head as db. Passing a non-session
    V2 catalog's namespace as the session catalog's temp DB is a category error.
  2. The fallback arm assigns db = "" for multi-component namespaces.
    SessionCatalog.listTempViews interprets "" as local temp DB - silent
    semantic mismatch.

Suggestion: Remove the branch

(isExtended || !catalog.isInstanceOf[TableViewCatalog])) {
val sessionCatalog = session.sessionState.catalog
val db = namespace match {
case Seq(db) => db
case _ => ""
}
sessionCatalog.listTempViews(db, pattern).foreach { tempView =>
jsonRows += toJsonEntry(
tempView.identifier.table,
tempView.identifier.database.toArray,
isTemporary = true)
}
}

val jsonOutput = JObject("tables" -> JArray(jsonRows.toList))
Seq(toCatalystRow(compact(render(jsonOutput))))
}

private def toJsonEntry(
name: String,
namespace: Array[String],
isTemporary: Boolean): JObject = {
val nsArray = JArray(namespace.map(JString(_)).toList)
if (isExtended) {
JObject(
"name" -> JString(name),
"catalog" -> JString(catalog.name()),
"namespace" -> nsArray,
"type" -> JString(if (isTemporary) "VIEW" else "TABLE"),
"isTemporary" -> JBool(isTemporary)
)
} else {
JObject(
"name" -> JString(name),
"namespace" -> nsArray,
"isTemporary" -> JBool(isTemporary)
)
}
}

private def isTempView(ident: Identifier): Boolean = {
if (CatalogV2Util.isSessionCatalog(catalog)) {
session.sessionState.catalog.isTempView((ident.namespace() :+ ident.name()).toSeq)
} else false
}
}
Loading