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

    https://github.com/apache/spark/pull/10583#discussion_r48988457
  
    --- Diff: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/CatalystQl.scala ---
    @@ -0,0 +1,961 @@
    +/*
    + * 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.catalyst
    +
    +import java.sql.Date
    +
    +import org.apache.spark.sql.AnalysisException
    +import org.apache.spark.sql.catalyst.analysis._
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate.Count
    +import org.apache.spark.sql.catalyst.plans._
    +import org.apache.spark.sql.catalyst.plans.logical._
    +import org.apache.spark.sql.catalyst.trees.CurrentOrigin
    +import org.apache.spark.sql.catalyst.parser._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.CalendarInterval
    +import org.apache.spark.util.random.RandomSampler
    +
    +/**
    + * This class translates a HQL String to a Catalyst [[LogicalPlan]] or 
[[Expression]].
    + */
    +private[sql] class CatalystQl(val conf: ParserConf = SimpleParserConf()) {
    +  object Token {
    +    def unapply(node: ASTNode): Some[(String, List[ASTNode])] = {
    +      CurrentOrigin.setPosition(node.line, node.positionInLine)
    +      node.pattern
    +    }
    +  }
    +
    +
    +  /**
    +   * Returns the AST for the given SQL string.
    +   */
    +  protected def getAst(sql: String): ASTNode = ParseDriver.parse(sql, conf)
    +
    +  /** Creates LogicalPlan for a given HiveQL string. */
    +  def createPlan(sql: String): LogicalPlan = {
    +    try {
    +      createPlan(sql, ParseDriver.parse(sql, conf))
    +    } catch {
    +      case e: MatchError => throw e
    +      case e: AnalysisException => throw e
    +      case e: Exception =>
    +        throw new AnalysisException(e.getMessage)
    +      case e: NotImplementedError =>
    +        throw new AnalysisException(
    +          s"""
    +             |Unsupported language features in query: $sql
    +             |${getAst(sql).treeString}
    +             |$e
    +             |${e.getStackTrace.head}
    +          """.stripMargin)
    +    }
    +  }
    +
    +  protected def createPlan(sql: String, tree: ASTNode): LogicalPlan = 
nodeToPlan(tree)
    +
    +  def parseDdl(ddl: String): Seq[Attribute] = {
    +    val tree = getAst(ddl)
    +    assert(tree.text == "TOK_CREATETABLE", "Only CREATE TABLE supported.")
    +    val tableOps = tree.children
    +    val colList = tableOps
    +      .find(_.text == "TOK_TABCOLLIST")
    +      .getOrElse(sys.error("No columnList!"))
    +
    +    colList.children.map(nodeToAttribute)
    +  }
    +
    +  protected def getClauses(
    +      clauseNames: Seq[String],
    +      nodeList: Seq[ASTNode]): Seq[Option[ASTNode]] = {
    +    var remainingNodes = nodeList
    +    val clauses = clauseNames.map { clauseName =>
    +      val (matches, nonMatches) = 
remainingNodes.partition(_.text.toUpperCase == clauseName)
    +      remainingNodes = nonMatches ++ (if (matches.nonEmpty) matches.tail 
else Nil)
    +      matches.headOption
    +    }
    +
    +    if (remainingNodes.nonEmpty) {
    +      sys.error(
    +        s"""Unhandled clauses: 
${remainingNodes.map(_.treeString).mkString("\n")}.
    +            |You are likely trying to use an unsupported Hive 
feature."""".stripMargin)
    +    }
    +    clauses
    +  }
    +
    +  protected def getClause(clauseName: String, nodeList: Seq[ASTNode]): 
ASTNode =
    +    getClauseOption(clauseName, nodeList).getOrElse(sys.error(
    +      s"Expected clause $clauseName missing from 
${nodeList.map(_.treeString).mkString("\n")}"))
    +
    +  protected def getClauseOption(clauseName: String, nodeList: 
Seq[ASTNode]): Option[ASTNode] = {
    +    nodeList.filter { case ast: ASTNode => ast.text == clauseName } match {
    +      case Seq(oneMatch) => Some(oneMatch)
    +      case Seq() => None
    +      case _ => sys.error(s"Found multiple instances of clause 
$clauseName")
    +    }
    +  }
    +
    +  protected def nodeToAttribute(node: ASTNode): Attribute = node match {
    +    case Token("TOK_TABCOL", Token(colName, Nil) :: dataType :: Nil) =>
    +      AttributeReference(colName, nodeToDataType(dataType), nullable = 
true)()
    +    case _ =>
    +      noParseRule("Attribute", node)
    +  }
    +
    +  protected def nodeToDataType(node: ASTNode): DataType = node match {
    +    case Token("TOK_DECIMAL", precision :: scale :: Nil) =>
    +      DecimalType(precision.text.toInt, scale.text.toInt)
    +    case Token("TOK_DECIMAL", precision :: Nil) =>
    +      DecimalType(precision.text.toInt, 0)
    +    case Token("TOK_DECIMAL", Nil) => DecimalType.USER_DEFAULT
    +    case Token("TOK_BIGINT", Nil) => LongType
    +    case Token("TOK_INT", Nil) => IntegerType
    +    case Token("TOK_TINYINT", Nil) => ByteType
    +    case Token("TOK_SMALLINT", Nil) => ShortType
    +    case Token("TOK_BOOLEAN", Nil) => BooleanType
    +    case Token("TOK_STRING", Nil) => StringType
    +    case Token("TOK_VARCHAR", Token(_, Nil) :: Nil) => StringType
    +    case Token("TOK_FLOAT", Nil) => FloatType
    +    case Token("TOK_DOUBLE", Nil) => DoubleType
    +    case Token("TOK_DATE", Nil) => DateType
    +    case Token("TOK_TIMESTAMP", Nil) => TimestampType
    +    case Token("TOK_BINARY", Nil) => BinaryType
    +    case Token("TOK_LIST", elementType :: Nil) => 
ArrayType(nodeToDataType(elementType))
    +    case Token("TOK_STRUCT", Token("TOK_TABCOLLIST", fields) :: Nil) =>
    +      StructType(fields.map(nodeToStructField))
    +    case Token("TOK_MAP", keyType :: valueType :: Nil) =>
    +      MapType(nodeToDataType(keyType), nodeToDataType(valueType))
    +    case _ =>
    +      noParseRule("DataType", node)
    +  }
    +
    +  protected def nodeToStructField(node: ASTNode): StructField = node match 
{
    +    case Token("TOK_TABCOL", Token(fieldName, Nil) :: dataType :: Nil) =>
    +      StructField(fieldName, nodeToDataType(dataType), nullable = true)
    +    case Token("TOK_TABCOL", Token(fieldName, Nil) :: dataType :: _ /* 
comment */:: Nil) =>
    +      StructField(fieldName, nodeToDataType(dataType), nullable = true)
    +    case _ =>
    +      noParseRule("StructField", node)
    +  }
    +
    +  protected def extractTableIdent(tableNameParts: ASTNode): 
TableIdentifier = {
    +    tableNameParts.children.map {
    +      case Token(part, Nil) => cleanIdentifier(part)
    +    } match {
    +      case Seq(tableOnly) => TableIdentifier(tableOnly)
    +      case Seq(databaseName, table) => TableIdentifier(table, 
Some(databaseName))
    +      case other => sys.error("Hive only supports tables names like 
'tableName' " +
    +        s"or 'databaseName.tableName', found '$other'")
    +    }
    +  }
    +
    +  /**
    +   * SELECT MAX(value) FROM src GROUP BY k1, k2, k3 GROUPING SETS((k1, 
k2), (k2))
    +   * is equivalent to
    +   * SELECT MAX(value) FROM src GROUP BY k1, k2 UNION SELECT MAX(value) 
FROM src GROUP BY k2
    +   * Check the following link for details.
    +   *
    
+https://cwiki.apache.org/confluence/display/Hive/Enhanced+Aggregation%2C+Cube%2C+Grouping+and+Rollup
    +   *
    +   * The bitmask denotes the grouping expressions validity for a grouping 
set,
    +   * the bitmask also be called as grouping id (`GROUPING__ID`, the 
virtual column in Hive)
    +   * e.g. In superset (k1, k2, k3), (bit 0: k1, bit 1: k2, and bit 2: k3), 
the grouping id of
    +   * GROUPING SETS (k1, k2) and (k2) should be 3 and 2 respectively.
    +   */
    +  protected def extractGroupingSet(children: Seq[ASTNode]): 
(Seq[Expression], Seq[Int]) = {
    +    val (keyASTs, setASTs) = children.partition {
    +      case Token("TOK_GROUPING_SETS_EXPRESSION", _) => false // grouping 
sets
    +      case _ => true // grouping keys
    +    }
    +
    +    val keys = keyASTs.map(nodeToExpr)
    +    val keyMap = keyASTs.zipWithIndex.toMap
    +
    +    val bitmasks: Seq[Int] = setASTs.map {
    +      case Token("TOK_GROUPING_SETS_EXPRESSION", null) => 0
    --- End diff --
    
    what do you mean?


---
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 infrastruct...@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org
For additional commands, e-mail: reviews-h...@spark.apache.org

Reply via email to