dtenedor commented on code in PR #60367:
URL: https://github.com/apache/spark/pull/60367#discussion_r4636795851
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -8749,6 +8714,33 @@ object SQLConf {
.booleanConf
.createWithDefault(true)
+ val OPTIONAL_REFERENCES_ENABLED =
+ buildConf("spark.sql.optionalReferences.enabled")
+ .internal()
+ .doc("When true, a `?` after an identifier of a column, field, or
variable reference, or " +
+ "after a named parameter marker, makes that identifier optional: when
no name matches " +
+ "the identifier, the reference evaluates to a NULL of type VOID
instead of raising a " +
+ "not-found error. Ambiguous references and type errors are still
raised. UPDATE, " +
+ "DELETE, MERGE, the REPLACE condition of INSERT, AUTO CDC flows,
partition " +
+ "specifications, metric view definitions, and the DEFAULT, GENERATED
ALWAYS AS, CHECK, " +
+ "and OPTIONS clauses of table and function definitions reject optional
references.")
+ .version("4.4.0")
Review Comment:
Thanks, right: `dev/next_version_candidates.py` gives 4.5.0 for branch-4.x,
and this isn't a master-only change. The three confs now say
`.version("4.5.0")`. The migration note says "Since Spark 4.5" and moved to a
new "Upgrading from Spark SQL 4.4 to 4.5" section.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.scala:
##########
@@ -0,0 +1,377 @@
+/*
+ * 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,
+ * DISTRIBUTE BY, 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] = {
Review Comment:
Thanks. The descent predicate is now
`ColumnResolutionHelper.canAddMissingAttrsThrough`, which
`resolveExprsAndAddMissingAttrs` and this rule both call. The outer-plan
sources are now `ColumnResolutionHelper.outerReferenceSources`:
`resolveOuterRef` resolves against them, and this rule takes its outer
attributes from them, so the HAVING case lives in one place.
The list of operators that resolve from below (Sort, Filter,
RepartitionByExpression, UnresolvedQualify, UnresolvedHaving, LateralJoin) is
still matched here. In `ResolveReferences`, each of those cases resolves in its
own way, interleaved with aggregate and last-resort resolution. Driving this
rule from them would mean restructuring those cases, which I'd rather leave to
a separate change. The rule now also returns these attributes as the groups
that the resolution tries one after the other, which the ambiguity fix above
needs.
--
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]