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

    https://github.com/apache/spark/pull/12313#discussion_r63912066
  
    --- Diff: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala
 ---
    @@ -498,6 +499,117 @@ class Analyzer(
         }
       }
     
    +  val ResolveOutputColumns = new ResolveOutputColumns
    +  class ResolveOutputColumns extends Rule[LogicalPlan] {
    +    def apply(plan: LogicalPlan): LogicalPlan = plan.transform {
    +      case ins @ InsertIntoTable(relation: LogicalPlan, partition, _, _, 
_, _)
    +          if ins.childrenResolved && !ins.resolved =>
    +        resolveOutputColumns(ins, expectedColumns(relation, partition), 
relation.toString)
    +    }
    +
    +    protected def resolveOutputColumns(insertInto: InsertIntoTable,
    +                                       columns: Seq[Attribute],
    +                                       relation: String) = {
    +      val resolved = if (insertInto.isMatchByName) {
    +        projectAndCastOutputColumns(columns, insertInto.child, relation)
    +      } else {
    +        castAndRenameOutputColumns(columns, insertInto.child, relation)
    +      }
    +
    +      if (resolved == insertInto.child.output) {
    +        insertInto
    +      } else {
    +        insertInto.copy(child = Project(resolved, insertInto.child))
    +      }
    +    }
    +
    +    /**
    +     * Resolves output columns by input column name, adding casts if 
necessary.
    +     */
    +    private def projectAndCastOutputColumns(output: Seq[Attribute],
    +                                            data: LogicalPlan,
    +                                            relation: String): 
Seq[NamedExpression] = {
    +      output.map { col =>
    +        data.resolveQuoted(col.name, resolver) match {
    +          case Some(inCol) if col.dataType != inCol.dataType =>
    +            Alias(UpCast(inCol, col.dataType, Seq()), col.name)()
    +          case Some(inCol) => inCol
    +          case None =>
    +            throw new AnalysisException(
    +              s"Cannot resolve ${col.name} in 
${data.output.mkString(",")}")
    +        }
    +      }
    +    }
    +
    +    private def castAndRenameOutputColumns(output: Seq[Attribute],
    +                                           data: LogicalPlan,
    +                                           relation: String): 
Seq[NamedExpression] = {
    +      val outputNames = output.map(_.name)
    +      // incoming expressions may not have names
    +      val inputNames = data.output.flatMap(col => Option(col.name))
    +      if (output.size > data.output.size) {
    +        // always a problem
    +        throw new AnalysisException(
    +          s"""Not enough data columns to write into $relation:
    +             |Data columns: ${data.output.mkString(",")}
    +             |Table columns: ${outputNames.mkString(",")}""".stripMargin)
    +      } else if (output.size < data.output.size) {
    +        if (outputNames.toSet.subsetOf(inputNames.toSet)) {
    +          throw new AnalysisException(
    +            s"""Table column names are a subset of the input data columns:
    +               |Data columns: ${inputNames.mkString(",")}
    +               |Table columns: ${outputNames.mkString(",")}
    +               |To write a subset of the columns by name, use 
df.write.byName.insertInto(...)"""
    +                .stripMargin)
    +        } else {
    +          // be conservative and fail if there are too many columns
    +          throw new AnalysisException(
    +            s"""Extra data columns to write into $relation:
    +               |Data columns: ${data.output.mkString(",")}
    +               |Table columns: ${outputNames.mkString(",")}""".stripMargin)
    +        }
    +      } else {
    +        // check for reordered names and warn. this may be on purpose, so 
it isn't an error.
    +        if (outputNames.toSet == inputNames.toSet && outputNames != 
inputNames) {
    +          logWarning(
    +            s"""Data column names match the table in a different order:
    +                |Data columns: ${inputNames.mkString(",")}
    +                |Table columns: ${outputNames.mkString(",")}
    +                |To map columns by name, use 
df.write.byName.insertInto(...)""".stripMargin)
    +        }
    +      }
    +
    +      data.output.zip(output).map {
    +        case (in, out) if !in.dataType.sameType(out.dataType) =>
    +          Alias(Cast(in, out.dataType), out.name)()
    +        case (in, out) if in.name != out.name =>
    +          Alias(in, out.name)()
    +        case (in, _) => in
    +      }
    +    }
    +
    +    private def expectedColumns(data: LogicalPlan,
    +                                partitionData: Map[String, 
Option[String]]): Seq[Attribute] = {
    --- End diff --
    
    Same as above.


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