dtenedor commented on code in PR #60367: URL: https://github.com/apache/spark/pull/60367#discussion_r4649109091
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.scala: ########## @@ -0,0 +1,402 @@ +/* + * 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, + SubqueryExpression, + UnaryExpression, + Unevaluable +} +import org.apache.spark.sql.catalyst.plans.logical.{ + Aggregate, + DefaultValueExpression, + Filter, + GeneratedColumnExpression, + LateralJoin, + LogicalPlan, + RepartitionByExpression, + Sort, + 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.errors.QueryCompilationErrors +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, + variableResolution: VariableResolution) + 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 attributeGroups = visibleAttributeGroups(operator) + operator.mapExpressions(replace(_, attributeGroups, 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 attributeGroups = visibleAttributeGroups(aggregate) + aggregate.copy(aggregateExpressions = aggregate.aggregateExpressions.map { expression => + replace(expression, attributeGroups, isTopLevel = true).asInstanceOf[NamedExpression] + }) + } + + /** + * Replaces the optional references of `expression` that resolve to NULL against + * `attributeGroups`. + * A top-level reference keeps its name through an [[Alias]] of its last name part. + */ + private def replace( + expression: Expression, + attributeGroups: => Seq[Seq[Attribute]], + isTopLevel: Boolean): Expression = expression match { + // The parser rejects optional references in these clauses of SQL text, but a column definition + // of an API, such as `Catalog.createTable`, parses its expressions on its own. + case default: DefaultValueExpression => Review Comment: Agreed, moved. `CheckOptionalReferencesInDml` is now `CheckOptionalReferences`, and it rejects an optional reference in a `DefaultValueExpression` (context DEFAULT) or a `GeneratedColumnExpression` (context GENERATED ALWAYS AS) of any command plan. That covers the `CreateTable` plan of `Catalog.createTable` and any other API-built command with column definitions. `ResolveOptionalReferences` only resolves again. The check on defaults read from column metadata stays in `ResolveDefaultColumns.analyze`, because those don't go through a command plan. The existing `Catalog.createTable` tests pass unchanged and fail if the new check is disabled. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/ParameterHandler.scala: ########## @@ -156,6 +158,17 @@ object ParameterHandler { def substituteParameters( sqlText: String, context: ParameterContext): (String, PositionMapper) = { + val substitution = substituteParametersForParsing(sqlText, context) + (substitution.sqlText, substitution.positionMapper) + } + + /** + * Same as [[substituteParameters]], but returns the whole [[ParameterSubstitution]], whose SQL + * text the parser has to parse with the optional references that the substitution chose. + */ + def substituteParametersForParsing( Review Comment: Thanks, agreed on both points. There's now one form of each method, and each returns `ParameterSubstitution`: `ParameterHandler.substituteParameters`, `substituteNamedParameters`, `substitutePositionalParameters`, `SubstituteParamsParser.substitute`, and `object SubstituteParamsParser.substitute`. `substituteParametersForParsing` is gone, so no entry point can drop the flag. The tuple callers were all tests (`ParameterSubstitutionSuite`, `PlanParserSuite`, `AnalysisSuite`, `OptionalReferencesParserSuite`); they now destructure the case class or read `.sqlText`. I also moved `ParameterSubstitution` above the class doc, so `SubstituteParamsParser` has its scaladoc back. -- 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]
