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

    https://github.com/apache/spark/pull/16655#discussion_r97189247
  
    --- Diff: 
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/rules.scala 
---
    @@ -199,31 +199,52 @@ case class AnalyzeCreateTable(sparkSession: 
SparkSession) extends Rule[LogicalPl
         //   * can't use all table columns as partition columns.
         //   * partition columns' type must be AtomicType.
         //   * sort columns' type must be orderable.
    +    //   * reorder table schema or output of query plan, to put partition 
columns at the end.
         case c @ CreateTable(tableDesc, _, query) =>
    -      val analyzedQuery = query.map { q =>
    -        // Analyze the query in CTAS and then we can do the normalization 
and checking.
    -        val qe = sparkSession.sessionState.executePlan(q)
    +      if (query.isDefined) {
    +        val qe = sparkSession.sessionState.executePlan(query.get)
             qe.assertAnalyzed()
    -        qe.analyzed
    -      }
    -      val schema = if (analyzedQuery.isDefined) {
    -        analyzedQuery.get.schema
    -      } else {
    -        tableDesc.schema
    -      }
    +        val analyzedQuery = qe.analyzed
    +
    +        val normalizedTable = normalizeCatalogTable(analyzedQuery.schema, 
tableDesc)
    +
    +        val output = analyzedQuery.output
    +        val partitionAttrs = normalizedTable.partitionColumnNames.map { 
partCol =>
    +          output.find(_.name == partCol).get
    +        }
    +        val newOutput = output.filterNot(partitionAttrs.contains) ++ 
partitionAttrs
    +        val reorderedQuery = if (newOutput == output) {
    +          analyzedQuery
    +        } else {
    +          Project(newOutput, analyzedQuery)
    +        }
     
    -      val columnNames = if 
(sparkSession.sessionState.conf.caseSensitiveAnalysis) {
    -        schema.map(_.name)
    +        c.copy(tableDesc = normalizedTable, query = Some(reorderedQuery))
    --- End diff --
    
    How about adding one more check here?
    ```Scala
            assert(normalizedTable.schema.isEmpty,
              "Schema may not be specified in a Create Table As Select (CTAS) 
statement")
    ```


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