Github user liancheng commented on a diff in the pull request:

    https://github.com/apache/spark/pull/10541#discussion_r49044129
  
    --- Diff: 
sql/hive/src/main/scala/org/apache/spark/sql/hive/SQLBuilder.scala ---
    @@ -0,0 +1,236 @@
    +/*
    + * 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.hive
    +
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.catalyst.expressions.{Expression, Attribute, 
NamedExpression, SortOrder}
    +import org.apache.spark.sql.catalyst.optimizer.ProjectCollapsing
    +import org.apache.spark.sql.catalyst.plans.logical._
    +import org.apache.spark.sql.catalyst.rules.{Rule, RuleExecutor}
    +import org.apache.spark.sql.catalyst.util.sequenceOption
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.execution.datasources.parquet.ParquetRelation
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +
    +class SQLBuilder(logicalPlan: LogicalPlan, sqlContext: SQLContext) extends 
Logging {
    +  def this(df: DataFrame) = this(df.queryExecution.analyzed, df.sqlContext)
    +
    +  def toSQL: Option[String] = {
    +    val canonicalizedPlan = Canonicalizer.execute(logicalPlan)
    +    val maybeSQL = toSQL(canonicalizedPlan)
    +
    +    if (maybeSQL.isDefined) {
    +      logDebug(
    +        s"""Built SQL query string successfully from given logical plan:
    +           |
    +           |# Original logical plan:
    +           |${logicalPlan.treeString}
    +           |# Canonicalized logical plan:
    +           |${canonicalizedPlan.treeString}
    +           |# Built SQL query string:
    +           |${maybeSQL.get}
    +         """.stripMargin)
    +    } else {
    +      logDebug(
    +        s"""Failed to build SQL query string from given logical plan:
    +           |
    +           |# Original logical plan:
    +           |${logicalPlan.treeString}
    +           |# Canonicalized logical plan:
    +           |${canonicalizedPlan.treeString}
    +         """.stripMargin)
    +    }
    +
    +    maybeSQL
    +  }
    +
    +  private def projectToSQL(
    +      projectList: Seq[NamedExpression],
    +      child: LogicalPlan,
    +      isDistinct: Boolean): Option[String] = {
    +    for {
    +      listSQL <- sequenceOption(projectList.map(_.sql))
    +      childSQL <- toSQL(child)
    +      from = child match {
    +        case OneRowRelation => ""
    +        case _ => " FROM "
    +      }
    +      distinct = if (isDistinct) " DISTINCT" else ""
    +    } yield s"SELECT$distinct ${listSQL.mkString(", ")}$from$childSQL"
    +  }
    +
    +  private def aggregateToSQL(
    +      groupingExprs: Seq[Expression],
    +      aggExprs: Seq[Expression],
    +      child: LogicalPlan): Option[String] = {
    +    for {
    +      aggSQL <- sequenceOption(aggExprs.map(_.sql))
    +      groupingSQL <- sequenceOption(groupingExprs.map(_.sql))
    +      maybeGroupBy = if (groupingSQL.isEmpty) "" else " GROUP BY "
    +      maybeFrom = child match {
    +        case OneRowRelation => ""
    +        case _ => " FROM "
    +      }
    +      childSQL <- toSQL(child).map(maybeFrom + _)
    +    } yield {
    +      s"SELECT ${aggSQL.mkString(", 
")}$childSQL$maybeGroupBy${groupingSQL.mkString(", ")}"
    +    }
    +  }
    +
    +  private def toSQL(node: LogicalPlan): Option[String] = node match {
    +    case Distinct(Project(list, child)) =>
    +      projectToSQL(list, child, isDistinct = true)
    +
    +    case Project(list, child) =>
    +      projectToSQL(list, child, isDistinct = false)
    +
    +    case Aggregate(groupingExprs, aggExprs, Aggregate(_, _, Expand(_, _, 
child))) =>
    +      aggregateToSQL(groupingExprs, aggExprs, child)
    +
    +    case Aggregate(groupingExprs, aggExprs, child) =>
    +      aggregateToSQL(groupingExprs, aggExprs, child)
    +
    +    case Limit(limit, child) =>
    +      for {
    +        limitSQL <- limit.sql
    +        childSQL <- toSQL(child)
    +      } yield s"$childSQL LIMIT $limitSQL"
    +
    +    case Filter(condition, child) =>
    +      for {
    +        conditionSQL <- condition.sql
    +        childSQL <- toSQL(child)
    +        whereOrHaving = child match {
    +          case _: Aggregate => "HAVING"
    +          case _ => "WHERE"
    +        }
    +      } yield s"$childSQL $whereOrHaving $conditionSQL"
    +
    +    case Union(left, right) =>
    +      for {
    +        leftSQL <- toSQL(left)
    +        rightSQL <- toSQL(right)
    +      } yield s"$leftSQL UNION ALL $rightSQL"
    +
    +    // ParquetRelation converted from Hive metastore table
    +    case Subquery(alias, LogicalRelation(r: ParquetRelation, _)) =>
    +      Some(s"`$alias`")
    --- End diff --
    
    Oh yeah. I probably hit a bug related to Parquet table conversion. In some 
cases the original database and table names are not passed to `ParquetRelation` 
via data source options correctly. Haven't investigated this issue yet. I'm 
using subquery alias as a workaround here. Will add a comment.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---

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

Reply via email to