cloud-fan commented on a change in pull request #25453: [WIP][SPARK-28730][SQL] 
Configurable type coercion policy for table insertion
URL: https://github.com/apache/spark/pull/25453#discussion_r315283099
 
 

 ##########
 File path: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableOutputResolver.scala
 ##########
 @@ -0,0 +1,117 @@
+/*
+ * 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.analysis
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, Cast, 
NamedExpression, UpCast}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.internal.SQLConf.StoreAssignmentPolicy
+import org.apache.spark.sql.types.DataType
+
+object TableOutputResolver {
+  def resolveOutputColumns(
+      tableName: String,
+      expected: Seq[Attribute],
+      query: LogicalPlan,
+      byName: Boolean,
+      conf: SQLConf): LogicalPlan = {
+
+    if (expected.size < query.output.size) {
+      throw new AnalysisException(
+        s"""Cannot write to '$tableName', too many data columns:
+           |Table columns: ${expected.map(c => s"'${c.name}'").mkString(", ")}
+           |Data columns: ${query.output.map(c => s"'${c.name}'").mkString(", 
")}""".stripMargin)
+    }
+
+    val errors = new mutable.ArrayBuffer[String]()
+    val resolved: Seq[NamedExpression] = if (byName) {
+      expected.flatMap { tableAttr =>
+        query.resolveQuoted(tableAttr.name, conf.resolver) match {
+          case Some(queryExpr) =>
+            checkField(tableAttr, queryExpr, byName, conf, err => errors += 
err)
+          case None =>
+            errors += s"Cannot find data for output column '${tableAttr.name}'"
+            None
+        }
+      }
+
+    } else {
+      if (expected.size > query.output.size) {
+        throw new AnalysisException(
+          s"""Cannot write to '$tableName', not enough data columns:
+             |Table columns: ${expected.map(c => s"'${c.name}'").mkString(", 
")}
+             |Data columns: ${query.output.map(c => 
s"'${c.name}'").mkString(", ")}"""
+            .stripMargin)
+      }
+
+      query.output.zip(expected).flatMap {
+        case (queryExpr, tableAttr) =>
+          checkField(tableAttr, queryExpr, byName, conf, err => errors += err)
+      }
+    }
+
+    if (errors.nonEmpty) {
+      throw new AnalysisException(
+        s"Cannot write incompatible data to table '$tableName':\n- 
${errors.mkString("\n- ")}")
+    }
+
+    Project(resolved, query)
+  }
+
+  private def checkField(
+      tableAttr: Attribute,
+      queryExpr: NamedExpression,
+      byName: Boolean,
+      conf: SQLConf,
+      addError: String => Unit): Option[NamedExpression] = {
+
+    val useStrictRules = conf.storeAssignmentPolicy == 
StoreAssignmentPolicy.STRICT
+
+    if (!useStrictRules) {
+      // Renaming is needed for handling the following cases like
+      // 1) Column names/types do not match, e.g., INSERT INTO TABLE tab1 
SELECT 1, 2
+      // 2) Target tables have column metadata
+      Some(Alias(
+        Cast(queryExpr, tableAttr.dataType, Option(conf.sessionLocalTimeZone)),
+        tableAttr.name)(explicitMetadata = Option(tableAttr.metadata)))
+    } else {
+      // run the type check first to ensure type errors are present
+      val canWrite = DataType.canWrite(
+        queryExpr.dataType, tableAttr.dataType, byName, useStrictRules,
+        conf.resolver, tableAttr.name, addError)
+      if (queryExpr.nullable && !tableAttr.nullable) {
+        addError(s"Cannot write nullable values to non-null column 
'${tableAttr.name}'")
+        None
+
+      } else if (!canWrite) {
+        None
+
+      } else {
+        // always add an UpCast. it will be removed in the optimizer if it is 
unnecessary.
+        Some(Alias(
+          UpCast(queryExpr, tableAttr.dataType), tableAttr.name
 
 Review comment:
   shall we use `Cast` here? The upcast logic is already checked in 
`DataType.canWrite`. Then we can remove 
https://github.com/apache/spark/pull/25453/files#diff-7690f56bde3f7a3dd76fab9c136c1494R181

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

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

Reply via email to