dtenedor commented on code in PR #60367:
URL: https://github.com/apache/spark/pull/60367#discussion_r4649106515


##########
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 =>
+      rejectInDdl(default, "DEFAULT")
+    case generation: GeneratedColumnExpression =>
+      rejectInDdl(generation, "GENERATED ALWAYS AS")
+    case unresolvedAttribute: UnresolvedAttribute
+        if 
OptionalReferences.optionalNamePartIndices(unresolvedAttribute).nonEmpty &&
+        OptionalReferences.resolvesToNull(
+          nameParts = unresolvedAttribute.nameParts,
+          optionalNamePartIndices = 
OptionalReferences.optionalNamePartIndices(unresolvedAttribute),
+          attributeGroups = attributeGroups,
+          resolver = conf.resolver,
+          isVariableQualifier = variableResolution.isVariableQualifier(
+            _,
+            includeScopeLabels = !isViewQuery)

Review Comment:
   Thanks, fixed. A label now doesn't qualify a name in the body of a 
persistent function, and that holds when the function is created as well as 
when it's called. `CreateSQLFunctionCommand` now analyzes the body with 
`isPersistentSQLFunctionBody` set (through a new parameter of 
`executeWithReferredTempVariablesUnderIdentifier`), so the body resolves at 
CREATE FUNCTION as it will at every call. Your example now fails at CREATE 
FUNCTION with UNRESOLVED_COLUMN `lbl`.`x`, with or without a `DECLARE x` in the 
block, as a view does. The `SQLFunctionSuite` test now covers that for a scalar 
and a table function. It replaces the case that only called the function inside 
`lbl:`.



-- 
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]

Reply via email to