dtenedor commented on code in PR #60367: URL: https://github.com/apache/spark/pull/60367#discussion_r4593851285
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala: ########## @@ -0,0 +1,122 @@ +/* + * 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 org.apache.spark.sql.catalyst.expressions.{Expression, SubqueryExpression} +import org.apache.spark.sql.catalyst.plans.logical.{ + DeleteFromTable, + LogicalPlan, + MergeIntoTable, + OverwriteByExpression, + UpdateTable, + View +} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND +import org.apache.spark.sql.errors.QueryCompilationErrors + +/** + * Rejects optional references in the expressions of a statement that modifies table data and + * that was built without the SQL parser, which rejects them in SQL text (see + * `OptionalReferenceValidation`). A missing column must not silently change which rows a + * statement deletes or updates. + * + * The source of a MERGE is checked too, like the source query of the SQL statement. + * `Dataset.mergeInto` and the Spark Connect MERGE command put the plan of the source DataFrame + * there, in which only the last operation is sure to be unanalyzed: a Dataset operation builds on + * the analyzed plan of the one before, and Spark Connect analyzes some relations, such as + * `withColumns`, when it plans them. In an analyzed operation, an optional reference that matched + * nothing is the NULL that it resolved to, which is rejected as well. + * + * {{{ + * df.writeTo("t").overwrite(expr("deleted_at? IS NULL")) + * spark.table("s").selectExpr("pk", "archived? AS archived").as("s").mergeInto("t", ...) + * }}} + */ +object CheckOptionalReferencesInDml extends Rule[LogicalPlan] { + + override def apply(plan: LogicalPlan): LogicalPlan = { + if (plan.containsPattern(COMMAND)) { Review Comment: Done: the class doc now says that the rule runs whether or not optional references are enabled, because a source DataFrame built while they were enabled keeps the NULLs of its analyzed operations, also in a MERGE that runs after they are disabled. `MergeIntoDataFrameSuite` covers that case: a source built with the conf on, merged with it off. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala: ########## @@ -0,0 +1,122 @@ +/* + * 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 org.apache.spark.sql.catalyst.expressions.{Expression, SubqueryExpression} +import org.apache.spark.sql.catalyst.plans.logical.{ + DeleteFromTable, + LogicalPlan, + MergeIntoTable, + OverwriteByExpression, + UpdateTable, + View +} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND +import org.apache.spark.sql.errors.QueryCompilationErrors + +/** + * Rejects optional references in the expressions of a statement that modifies table data and + * that was built without the SQL parser, which rejects them in SQL text (see + * `OptionalReferenceValidation`). A missing column must not silently change which rows a + * statement deletes or updates. + * + * The source of a MERGE is checked too, like the source query of the SQL statement. + * `Dataset.mergeInto` and the Spark Connect MERGE command put the plan of the source DataFrame + * there, in which only the last operation is sure to be unanalyzed: a Dataset operation builds on + * the analyzed plan of the one before, and Spark Connect analyzes some relations, such as + * `withColumns`, when it plans them. In an analyzed operation, an optional reference that matched + * nothing is the NULL that it resolved to, which is rejected as well. + * + * {{{ + * df.writeTo("t").overwrite(expr("deleted_at? IS NULL")) + * spark.table("s").selectExpr("pk", "archived? AS archived").as("s").mergeInto("t", ...) + * }}} + */ +object CheckOptionalReferencesInDml extends Rule[LogicalPlan] { + + override def apply(plan: LogicalPlan): LogicalPlan = { + if (plan.containsPattern(COMMAND)) { + plan.foreach { operator => + statementName(operator).foreach { statement => + operator.expressions.foreach(checkExpression(_, statement)) + } + operator match { + case merge: MergeIntoTable => Review Comment: Done: a TODO at the MERGE source check says that an unbound `:p?` in the SQL text of a source DataFrame is not rejected. By default `SubstituteParamsParser` replaces it with the text NULL before the text is parsed, which leaves nothing in the plan for the check to find. The PR description now names the gap in its list of IN_DML statements. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.scala: ########## @@ -0,0 +1,376 @@ +/* + * 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 org.apache.spark.sql.catalyst.expressions.{ + Attribute, + Expression, + LambdaFunction, + LateralColumnAliasReference, + NamedExpression, + PipeOperator, + SubqueryExpression, + UnaryExpression, + Unevaluable +} +import org.apache.spark.sql.catalyst.plans.logical.{ + Aggregate, + Distinct, + Filter, + LateralJoin, + LogicalPlan, + RepartitionByExpression, + Sort, + SubqueryAlias, + UnaryNode +} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.CurrentOrigin +import org.apache.spark.sql.catalyst.trees.TreePattern.{PARAMETERIZED_QUERY, PLAN_EXPRESSION} +import org.apache.spark.sql.types.DataType + +/** + * Replaces the optional references that the fixed-point "Resolution" batch could not resolve + * with a static NULL, and then resolves the plan again with `resolveAgain`. + * + * {{{ + * -- `t` has no column `name`: + * SELECT id, name? FROM t; + * -- Project [id#1, 'name] becomes Project [id#1, null AS name#2] + * }}} + * + * Only the expressions of operators with resolved children are replaced, because a reference in + * an operator with unresolved children can still resolve once the children are resolved. The + * rule is meant to run in a fixed-point batch: every application replaces the references of the + * lowest operators that cannot be resolved, which can make the operators above them resolvable. + * References that a later resolution step is still waiting for, such as the body of an unbound + * lambda function or a lateral column alias reference, are left in place. + * + * The analyzer resolves the plan of a subquery expression on its own, while the operator of the + * subquery expression is still being resolved. A reference of the subquery that is unresolved at + * the end of that can still resolve later, e.g. once the outer query binds its parameter markers + * or resolves the alias of a generator. The rule therefore only replaces the references of a + * subquery plan after it could not resolve the operator of the subquery expression, which it + * signals by wrapping the subquery plan in [[ResolveOptionalReferencesInSubquery]]. + * + * The rule never changes the plan that it is given, which can be analyzed again later, e.g. from a + * plan cache: its decisions are nodes of the plan that it returns. + */ +class ResolveOptionalReferences(resolveAgain: LogicalPlan => LogicalPlan) + extends Rule[LogicalPlan] { + import ResolveOptionalReferences._ + + override def apply(plan: LogicalPlan): LogicalPlan = plan match { + case subquery: ResolveOptionalReferencesInSubquery => + val resolvedPlan = replaceAndResolveAgain(subquery.child) + if (resolvedPlan.fastEquals(subquery.child)) subquery.child else subquery.copy(resolvedPlan) + case _ if plan.resolved || isPlanOfSubquery || plan.containsPattern(PARAMETERIZED_QUERY) => + plan + case _ if hasUnresolvedOptionalReferences(plan) => + replaceAndResolveAgain(plan) + case _ => + plan + } + + private def replaceAndResolveAgain(plan: LogicalPlan): LogicalPlan = { + val replacedPlan = replaceUnresolvableOptionalReferences(plan) + val resolvedPlan = if (replacedPlan.fastEquals(plan)) { + plan + } else { + unwrapSubqueryPlans(resolveAgain(replacedPlan)) + } + if (!resolvedPlan.fastEquals(plan)) { + resolvedPlan + } else { + val wrappedPlan = wrapOptionalFieldsAsLastResort(plan) + if (wrappedPlan.fastEquals(plan)) { + plan + } else { + unwrapLastResortExtractValues(resolveAgain(wrappedPlan)) + } + } + } + + /** + * Replaces the optional references of the lowest operators of `plan` that are not resolved, and + * wraps the unresolved plans of their subquery expressions for the analysis of these plans. + * + * The traversal is top-down so that an operator is only considered while its children are the + * ones that the "Resolution" batch resolved its references against. An operator above a + * replaced one waits for `resolveAgain`, which can still resolve its references in other ways, + * for example as lateral column aliases or as variables. + */ + private def replaceUnresolvableOptionalReferences(plan: LogicalPlan): LogicalPlan = { + plan.resolveOperatorsDown { + case aggregate: Aggregate + if aggregate.childrenResolved && !aggregate.aggregateExpressions.forall(_.resolved) => + replaceInAggregateExpressions(aggregate) + case lateralJoin: LateralJoin + if lateralJoin.left.resolved && !lateralJoin.right.plan.resolved => + // The join condition can reference the output of the subquery, which is not known yet. + if (hasUnresolvedOptionalReferences(lateralJoin.right.plan)) { + lateralJoin.copy(right = wrapSubqueryPlan(lateralJoin.right)) + } else { + lateralJoin + } + case operator if operator.childrenResolved && !operator.resolved => + lazy val attributes = visibleAttributes(operator) + operator.mapExpressions(replace(_, attributes, isTopLevel = true)) + } + } + + /** + * Replaces the optional references in the aggregate expressions of `aggregate` only, because + * its grouping expressions can reference aliases of the aggregate expressions, which can only + * be resolved once all the aggregate expressions are resolved. + * + * {{{ + * -- `archived` in GROUP BY resolves to the alias `archived` of the SELECT list. + * SELECT coalesce(archived?, false) AS archived FROM t GROUP BY archived?; + * }}} + */ + private def replaceInAggregateExpressions(aggregate: Aggregate): Aggregate = { + lazy val attributes = visibleAttributes(aggregate) + aggregate.copy(aggregateExpressions = aggregate.aggregateExpressions.map { expression => + replace(expression, attributes, isTopLevel = true).asInstanceOf[NamedExpression] + }) + } + + /** + * Replaces the optional references of `expression` that resolve to NULL against `attributes`. + * A top-level reference keeps its name through an [[Alias]] of its last name part. + */ + private def replace( + expression: Expression, + attributes: => Seq[Attribute], + isTopLevel: Boolean): Expression = expression match { + case unresolvedAttribute: UnresolvedAttribute + if OptionalReferences.optionalNamePartIndices(unresolvedAttribute).nonEmpty && + OptionalReferences.resolvesToNull( + nameParts = unresolvedAttribute.nameParts, + optionalNamePartIndices = OptionalReferences.optionalNamePartIndices(unresolvedAttribute), + attributes = attributes, + resolver = conf.resolver, + isViewQuery = AnalysisContext.get.catalogAndNamespace.nonEmpty || + AnalysisContext.get.isViewDefinition + ) => + // The NULL keeps the position of the reference, e.g. for `CheckOptionalReferencesInDml`. + CurrentOrigin.withOrigin(unresolvedAttribute.origin) { + val nullReference = OptionalReferences.nullReference() + if (isTopLevel) { + OptionalReferences.implicitAlias(nullReference, unresolvedAttribute.nameParts.last) + } else { + nullReference + } + } + case namedParameter: NamedParameter if OptionalReferences.isOptional(namedParameter) => + CurrentOrigin.withOrigin(namedParameter.origin)(OptionalReferences.nullReference()) + case lambdaFunction: LambdaFunction if !lambdaFunction.bound => + lambdaFunction + case lateralColumnAliasReference: LateralColumnAliasReference => + lateralColumnAliasReference + case subquery: SubqueryExpression if hasUnresolvedOptionalReferences(subquery.plan) => + wrapSubqueryPlan(subquery) + case other if !other.resolved => + other.mapChildren(replace(_, attributes, isTopLevel = false)) + case other => + other + } + + private def wrapSubqueryPlan[T <: SubqueryExpression](subquery: T): T = subquery.plan match { + case _: ResolveOptionalReferencesInSubquery => subquery + case plan => subquery.withNewPlan(ResolveOptionalReferencesInSubquery(plan)).asInstanceOf[T] + } + + /** + * Unwraps the subquery plans of `plan` that are still wrapped because the analyzer did not + * resolve them again. + */ + private def unwrapSubqueryPlans(plan: LogicalPlan): LogicalPlan = { + plan.resolveExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) { + case subquery: SubqueryExpression => + subquery.plan match { + case wrapped: ResolveOptionalReferencesInSubquery => subquery.withNewPlan(wrapped.child) + case _ => subquery + } + } + } + + /** + * Wraps the optional field extractions of the lowest operators of `plan` that are not resolved + * in [[LastResortExtractValue]]. + */ + private def wrapOptionalFieldsAsLastResort(plan: LogicalPlan): LogicalPlan = { + plan.resolveOperatorsDown { + case operator if operator.childrenResolved && !operator.resolved => + operator.mapExpressions(wrapOptionalFields) + } + } + + private def wrapOptionalFields(expression: Expression): Expression = expression match { + case lastResort: LastResortExtractValue => + lastResort + case extractValue: UnresolvedExtractValue if OptionalReferences.isOptional(extractValue) => + // The children are wrapped first, so the wrapped extraction is still an extraction. + LastResortExtractValue( + extractValue.mapChildren(wrapOptionalFields).asInstanceOf[UnresolvedExtractValue]) + case other if !other.resolved => + other.mapChildren(wrapOptionalFields) + case other => + other + } + + /** Unwraps the extractions of `plan` that the analyzer did not resolve. */ + private def unwrapLastResortExtractValues(plan: LogicalPlan): LogicalPlan = { + plan.resolveExpressions { + case LastResortExtractValue(extractValue) => extractValue + } + } + + /** + * Returns the attributes that the name resolution of `operator` can match a multipart name + * against: the output of its children, the attributes that `Sort`, `Filter`, HAVING, and + * QUALIFY can reference from below their child, the output of the subquery of a lateral join, + * and the attributes of the outer query of a subquery. + */ + private def visibleAttributes(operator: LogicalPlan): Seq[Attribute] = { + val localAttributes = operator.children.flatMap(namedAttributes) + val attributesFromBelow = operator match { + case sort: Sort => attributesForMissingReferences(sort.child) + case filter: Filter => attributesForMissingReferences(filter.child) Review Comment: Done: the `DataFrameSuite` test "selectExpr, expr, and filter with optional references" now filters `df.groupBy("id").count().select("id")` on `name? IS NULL` and on `name IS NULL`, where `name` is a column below the aggregate. Both fail with UNRESOLVED_COLUMN for `name`. With the Filter case of `visibleAttributes` removed locally, the `?` filter no longer fails, so the test does. ########## sql/core/src/test/resources/sql-tests/inputs/optional-references.sql: ########## @@ -0,0 +1,575 @@ +-- Tests for optional column, field, variable, and named parameter references: a `?` after an +-- identifier makes that identifier optional, so that a reference that cannot be resolved +-- evaluates to a static NULL of type VOID instead of raising a not-found error. + +--SET spark.sql.optionalReferences.enabled=true + +CREATE TEMPORARY VIEW people AS SELECT * FROM VALUES + (1, named_struct('city', 'SF', 'zip', '94105')), + (2, named_struct('city', 'NYC', 'zip', '10001')) + AS t(id, addr); + +CREATE TEMPORARY VIEW orgs AS SELECT * FROM VALUES + (1, named_struct('addr', named_struct('city', 'SF', 'zip', '94105'))) + AS t(id, info); + +CREATE TEMPORARY VIEW orders AS SELECT * FROM VALUES + (1, array(named_struct('sku', 'a', 'qty', 5))), + (2, array(named_struct('sku', 'b', 'qty', 9))) + AS t(id, items); + +-- A missing column resolves to NULL and an existing column resolves normally. Either way, the Review Comment: Done, all three: - The first comment now says that a reference that is a whole SELECT item keeps its name, and that an expression over a missing reference is named after NULL. - The errors heading now covers the ORDER BY case: a name that matches more than one column of the FROM clause keeps its not-found error, since it is not a missing column. - The disabled block now says "while the session disables optional references". It also gained a scalar and a table SQL function created while they were enabled (see the SQLConf thread). -- 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. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
