-
Notifications
You must be signed in to change notification settings - Fork 29.2k
[WIP][SPARK-27856][SQL] Only allow type upcasting when inserting table #24806
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
5651224
4258665
62d9e70
c5b626c
b91498f
babb288
98dd42e
c520108
900e2d6
85fa370
7f5c159
d9e7e4e
75b3bf4
a72d3a2
f182938
3e29491
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| /* | ||
| * 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._ | ||
| import org.apache.spark.sql.catalyst.rules.Rule | ||
| import org.apache.spark.sql.internal.SQLConf | ||
| import org.apache.spark.sql.types.{DataType, NullType} | ||
|
|
||
| /** | ||
| * Resolves columns of an output table from the data in a logical plan. This rule will: | ||
| * | ||
| * - Reorder columns when the write is by name | ||
| * - Insert safe casts when data types do not match | ||
| * - Insert aliases when column names do not match | ||
| * - Detect plans that are not compatible with the output table and throw AnalysisException | ||
| */ | ||
| object ResolveOutputRelation extends Rule[LogicalPlan] { | ||
| override def apply(plan: LogicalPlan): LogicalPlan = plan.resolveOperators { | ||
| case append @ AppendData(table, query, isByName) | ||
| if table.resolved && query.resolved && !append.outputResolved => | ||
| val projection = resolveOutputColumns(table.name, table.output, query, isByName) | ||
|
|
||
| if (projection != query) { | ||
| append.copy(query = projection) | ||
| } else { | ||
| append | ||
| } | ||
|
|
||
| case overwrite @ OverwriteByExpression(table, _, query, isByName) | ||
| if table.resolved && query.resolved && !overwrite.outputResolved => | ||
| val projection = resolveOutputColumns(table.name, table.output, query, isByName) | ||
|
|
||
| if (projection != query) { | ||
| overwrite.copy(query = projection) | ||
| } else { | ||
| overwrite | ||
| } | ||
|
|
||
| case overwrite @ OverwritePartitionsDynamic(table, query, isByName) | ||
| if table.resolved && query.resolved && !overwrite.outputResolved => | ||
| val projection = resolveOutputColumns(table.name, table.output, query, isByName) | ||
|
|
||
| if (projection != query) { | ||
| overwrite.copy(query = projection) | ||
| } else { | ||
| overwrite | ||
| } | ||
| } | ||
|
|
||
| def resolveOutputColumns( | ||
| tableName: String, | ||
| expected: Seq[Attribute], | ||
| query: LogicalPlan, | ||
| byName: Boolean): 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 resolver = SQLConf.get.resolver | ||
| val errors = new mutable.ArrayBuffer[String]() | ||
| val resolved: Seq[NamedExpression] = if (byName) { | ||
| expected.flatMap { tableAttr => | ||
| query.resolveQuoted(tableAttr.name, resolver) match { | ||
| case Some(queryExpr) => | ||
| checkField(tableAttr, queryExpr, byName, resolver, 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, resolver, err => errors += err) | ||
| } | ||
| } | ||
|
|
||
| if (errors.nonEmpty) { | ||
| throw new AnalysisException( | ||
| s"Cannot write incompatible data to table '$tableName':\n- ${errors.mkString("\n- ")}") | ||
| } | ||
|
|
||
| Project(resolved, query) | ||
| } | ||
|
|
||
| def checkField( | ||
| tableAttr: Attribute, | ||
| queryExpr: NamedExpression, | ||
| byName: Boolean, | ||
| resolver: Resolver, | ||
| addError: String => Unit): Option[NamedExpression] = { | ||
|
|
||
| // run the type check first to ensure type errors are present | ||
| lazy val canWrite = DataType.canWrite( | ||
| queryExpr.dataType, tableAttr.dataType, byName, resolver, tableAttr.name, addError) | ||
|
|
||
| if (queryExpr.nullable && !tableAttr.nullable) { | ||
| addError(s"Cannot write nullable values to non-null column '${tableAttr.name}'") | ||
| None | ||
|
|
||
| } else if (queryExpr.dataType == NullType && tableAttr.nullable) { | ||
| Some(Alias(Cast(queryExpr, tableAttr.dataType, Option(SQLConf.get.sessionLocalTimeZone)), | ||
| tableAttr.name)(explicitMetadata = Option(tableAttr.metadata))) | ||
|
|
||
| } 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 | ||
| )( | ||
| explicitMetadata = Option(tableAttr.metadata) | ||
| )) | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -128,8 +128,10 @@ object Cast { | |
| case _ if from == to => true | ||
| case (from: NumericType, to: DecimalType) if to.isWiderThan(from) => true | ||
| case (from: DecimalType, to: NumericType) if from.isTighterThan(to) => true | ||
| case (f, t) if legalNumericPrecedence(f, t) => true | ||
| case (f: NumericType, t: NumericType) if legalNumericPrecedence(f, t) => true | ||
|
|
||
| case (DateType, TimestampType) => true | ||
| case (NullType, _) => false | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why can't we upcast null to other nullable types? I think it's pretty common to write
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here we can't know the nullability of the
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I agree with @cloud-fan that this should be allowed. Nullability is an additional check, but the types are compatible. |
||
| case (_, StringType) => true | ||
|
|
||
| // Spark supports casting between long and timestamp, please see `longToTimestamp` and | ||
|
|
@@ -153,7 +155,7 @@ object Cast { | |
| case _ => false | ||
| } | ||
|
|
||
| private def legalNumericPrecedence(from: DataType, to: DataType): Boolean = { | ||
| private def legalNumericPrecedence(from: NumericType, to: NumericType): Boolean = { | ||
| val fromPrecedence = TypeCoercion.numericPrecedence.indexOf(from) | ||
| val toPrecedence = TypeCoercion.numericPrecedence.indexOf(to) | ||
| fromPrecedence >= 0 && fromPrecedence < toPrecedence | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why was this moved?
It is difficult to see whether anything changed in this class. If the move was not required, please move it back.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As per @cloud-fan commented in https://github.com/apache/spark/pull/24721/files#r287800626
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Were there any modifications other than moving this?
I think that the right way to expose those functions is to move them to a utility class, not to expose this rule itself.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm OK with moving them to a utility class, but it's better to put analyzer/optimizer rules in its own file, instead of in the
Analyzerobject (can be done in another PR if we decide to create the util class in this PR)