dtenedor commented on code in PR #60367: URL: https://github.com/apache/spark/pull/60367#discussion_r4569159873
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.scala: ########## @@ -0,0 +1,301 @@ +/* + * 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 +} +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.TreePattern.{PARAMETERIZED_QUERY, PLAN_EXPRESSION} + +/** + * 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]]. + */ +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 if (markOptionalFieldsAsLastResort(plan)) { + resolveAgain(plan) + } else { + plan + } + } + + /** + * 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 + ) => + val nullReference = OptionalReferences.nullReference() + if (isTopLevel) { + OptionalReferences.implicitAlias(nullReference, unresolvedAttribute.nameParts.last) + } else { + nullReference + } + case namedParameter: NamedParameter if OptionalReferences.isOptional(namedParameter) => + 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 + } + } + } + + /** + * Marks the optional field extractions of the lowest operators of `plan` that are not resolved + * as a last resort, and returns whether it marked any. See + * [[OptionalReferences.markLastResort]]. + */ + private def markOptionalFieldsAsLastResort(plan: LogicalPlan): Boolean = { + var marked = false + plan.foreach { operator => + if (operator.childrenResolved && !operator.resolved) { + operator.expressions.foreach(_.foreach { + case extractValue: UnresolvedExtractValue + if OptionalReferences.isOptional(extractValue) && + !OptionalReferences.isLastResort(extractValue) => + OptionalReferences.markLastResort(extractValue) Review Comment: Fixed as recommended. The tag is gone: `ResolveOptionalReferences` now wraps the optional extractions of the lowest unresolved operators in a new node, `LastResortExtractValue`, in the plan that it returns, reruns the Resolution batch, and unwraps the wrappers that are left. `ColumnResolutionHelper` resolves a wrapped extraction with final semantics (the missing field is NULL in the first step that resolves its child) and keeps it wrapped while the child is unresolved; the wrapper also unwraps itself when a transform replaces its child with a resolved expression. `LAST_RESORT`, `markLastResort`, and `isLastResort` are removed, and the plan that the rule receives is never written to. Test: the new `OptionalReferencesSuite` analyzes the same unresolved plan instance twice through `Dataset.ofRows`: `SELECT id, array(named_struct('a', 1)) AS arr FROM t ORDER BY arr[0].b?, id` sorts by NULL while neither `arr` has `b`, and by `t.arr[0].b` after the view is redefined with the field, with the same result as a newly parsed plan; it fails on the previous code. The Spark Connect plan cache re-analyzes the same unresolved `LogicalPlan` object through this path, so I did not add a Connect-level test; tell me if you want one. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ColumnResolutionHelper.scala: ########## @@ -155,7 +156,13 @@ trait ColumnResolutionHelper extends Logging with DataTypeErrorsBase { // Real columns from relations -- which don't carry the // SQL_FUNCTION_PARAMETER_ALIAS_METADATA_KEY -- continue to win as before. // Gated by a legacy kill-switch conf so the pre-fix behavior can be restored. - val column = resolveColumnByName(nameParts) + // A missing optional field is only NULL here if the error of the same name without + // `?` is final. Otherwise another resolution step can still resolve the name, e.g. as + // a column from below the SELECT list in ORDER BY, and `ResolveOptionalReferences` + // decides if none does. + val optionalNamePartIndices = + if (throws) OptionalReferences.optionalNamePartIndices(u) else Set.empty[Int] Review Comment: Fixed as suggested: the two `t.copy(hasTried = true)` sites copy the tags of the column (`markTried`), the attribute rebuilt from a tried column gets its optional name parts through the new `OptionalReferences.withOptionalNamePartsOf`, and `resolveVariables` forwards them too. The golden file has `SELECT named_struct('state', 'CA') AS addr FROM people GROUP BY id HAVING addr.city? IS NULL`, which returns both groups in both analyzers. The `OptionalReferences` doc now states which tags are statement facts and that rebuilds forward them with that helper. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/OptionalReferenceValidation.scala: ########## @@ -0,0 +1,103 @@ +/* + * 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.parser + +import org.antlr.v4.runtime.ParserRuleContext +import org.antlr.v4.runtime.tree.ParseTree + +import org.apache.spark.sql.catalyst.parser.SqlBaseParser._ +import org.apache.spark.sql.catalyst.util.SparkParserUtils +import org.apache.spark.sql.errors.QueryParsingErrors + +/** Checks where the `?` optional-reference operator can appear in a SQL statement. */ +object OptionalReferenceValidation { + + /** + * Throws an error for the optional reference `ctx`, i.e. the parse tree of a reference with a + * `?` after one of its name parts, if `ctx` is part of an UPDATE, DELETE, MERGE, or AUTO CDC + * statement, of the condition of INSERT ... REPLACE, of a partition specification, or of an + * expression that defines a table object. + * + * {{{ + * UPDATE t SET a = b?; -- IN_DML + * WITH s AS (SELECT a? FROM u) DELETE FROM t WHERE ...; -- IN_DML + * CREATE TABLE t (a INT, b INT DEFAULT a?); -- IN_DDL + * INSERT INTO t SELECT a? FROM s; -- allowed: the query only reads data + * }}} + */ + def validate(ctx: ParserRuleContext): Unit = { + Iterator + .iterate(ctx.getParent)(_.getParent) + .takeWhile(_ != null) + .flatMap(unsupportedContextError(_, ctx)) + .nextOption() + .foreach(error => throw error) + } + + /** + * Validates the optional named parameter markers in the parse tree `tree` with [[validate]]. + * This is for the markers that are substituted in `sqlText`, the text that `tree` was parsed + * from, before the statement is parsed into a plan. + */ + def validateNamedParameterMarkers(tree: ParseTree, sqlText: String): Unit = tree match { + case namedParameter: NamedParameterLiteralContext if namedParameter.optionalMarker != null => + SparkParserUtils.withOrigin(namedParameter, Some(sqlText)) { + validate(namedParameter) + } + case _ => + (0 until tree.getChildCount).foreach { index => + validateNamedParameterMarkers(tree.getChild(index), sqlText) + } + } + + /** + * Returns the error for the optional reference `ctx` if its ancestor `ancestor` is a statement + * or a clause that does not support optional references. + */ + private def unsupportedContextError( + ancestor: ParserRuleContext, + ctx: ParserRuleContext): Option[Throwable] = ancestor match { + case _: DeleteFromTableContext => + Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("DELETE", ctx)) + case _: UpdateTableContext => + Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("UPDATE", ctx)) + case _: MergeIntoTableContext => + Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("MERGE", ctx)) + case _: InsertIntoReplaceBooleanCondContext => + Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("INSERT", ctx)) + case dmlStatement: DmlStatementContext => + // The common table expressions of a statement are siblings of its DELETE, UPDATE, or MERGE. + unsupportedContextError(dmlStatement.dmlStatementNoWith, ctx) + case _: AutoCdcParametersContext => Review Comment: Fixed. `PipelinesHandler.buildAutoCdcFlow` passes every change argument that it receives as an expression (`sequence_by`, `apply_as_deletes`, keys, and the column lists) through `OptionalReferences.unresolvedOptionalReference`, the walk that `CheckOptionalReferencesInDml` now uses as well, and raises the same `IN_DML` error with the `AUTO CDC` context through the same helper as the SQL form. `SparkDeclarativePipelinesServerSuite` covers the five argument kinds, an optional reference inside a subquery of the delete condition, and the same argument without `?`. ########## sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4: ########## @@ -1727,8 +1778,8 @@ primaryExpression | identifier ARROW expression #lambda | LEFT_PAREN identifier (COMMA identifier)+ RIGHT_PAREN ARROW expression #lambda | value=primaryExpression LEFT_BRACKET index=valueExpression RIGHT_BRACKET #subscript - | identifier #columnReference - | base=primaryExpression DOT fieldName=identifier #dereference + | leadingReferenceNamePart #columnReference Review Comment: Done. The `?` is inlined into `#columnReference` and `#dereference`, `IDENTIFIER(expr)?` is its own alternative (`#optionalIdentifierClause`), and `#overlay` moved to a rule of its own, `overlayExpression`, so a reference without `?` enters no rule that the base grammar did not enter. `primaryExpression` is 7,904 bytes of javac bytecode (7,851 on master). The grammar comment states the remaining cost. Parse time of the generated parser alone (lexer and parser, SLL then LL, no plan building, conf off; median of three JVM runs each, master against this branch): 103 TPC-DS queries +2.1% (9.19 ms vs 9.38 ms per pass), 500 short statements +3.7%, a WHERE clause with 500 predicates +3.6%, 2,000 column references +6.1%, 2,000 qualified columns +6.5%, 1,000 nested fields +8.6%. The description reports these numbers. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala: ########## @@ -313,6 +313,9 @@ object AnalysisContext { } else { mutable.LinkedHashSet.empty }, + // The body of a SQL function is not a part of the query that calls it. If the call is in a + // subquery, the body must not resolve its names as outer references of that query. + outerPlan = None, Review Comment: Done. `spark.sql.legacy.sqlFunctionBodyResolvesOuterReferences` (internal, default `false`, version 4.4.0, SESSION binding) keeps the caller's outer plan for the body when it is `true` and `spark.sql.optionalReferences.enabled` is off; its doc states that exception. `docs/sql-migration-guide.md` has an entry under "Upgrading from Spark SQL 4.3 to 4.4". `SQLFunctionSuite` checks the default (100), the legacy conf (5, for a function created before the conf was set), and the legacy conf with optional references on (100); the golden file has the last case too. ########## common/utils/src/main/resources/error/error-conditions.json: ########## @@ -7039,6 +7039,24 @@ ], "sqlState" : "HY008" }, + "OPTIONAL_COLUMN_REFERENCE_NOT_SUPPORTED" : { Review Comment: Done: the condition is `OPTIONAL_REFERENCE_NOT_SUPPORTED`, with `IN_DDL`, `IN_DML`, and the new `IN_PARTITION_SPEC` ("Partition specifications must not contain optional references."), SQLSTATE `0A000`, in sorted order. Partition specifications raise the new subclass whether the statement reads or writes the partition. The golden-file comment now says which statements reject `?` and why. -- 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]
