cloud-fan commented on code in PR #57264:
URL: https://github.com/apache/spark/pull/57264#discussion_r3591859448


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala:
##########
@@ -2621,7 +2624,287 @@ object AsOfJoin {
       usingColumns = usingColumns,
       matchLeftOperand = Some(leftExpr),
       matchOperator = Some(operator),
-      matchRightOperand = Some(rightExpr))
+      matchRightOperand = Some(rightExpr),
+      requiresSortMergeAsOfJoin = true)
+  }
+
+  def resolveMatchComparison(

Review Comment:
   `resolveMatchComparison` has no callers now — `ResolveAsOfJoin` calls 
`normalizeMatchOperands` and `materializeMatchComparison` directly, and there's 
no other caller in the tree. Drop it, unless it's meant as the DataFrame-path 
entry point for the follow-up, in which case wire that up so it isn't dead.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveAsOfJoin.scala:
##########
@@ -0,0 +1,253 @@
+/*
+ * 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.SQLConfHelper
+import org.apache.spark.sql.catalyst.expressions.{
+  Expression,
+  RowOrdering,
+  SubqueryExpression,
+  WindowExpression
+}
+import org.apache.spark.sql.catalyst.expressions.AttributeSet
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, LogicalPlan, 
Project}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.{AS_OF_JOIN, GENERATOR}
+import org.apache.spark.sql.catalyst.util._
+import org.apache.spark.sql.errors.QueryErrorsBase
+import org.apache.spark.sql.types.{
+  ArrayType,
+  CalendarIntervalType,
+  DataType,
+  DatetimeType,
+  DateType,
+  DayTimeIntervalType,
+  NumericType,
+  StringType,
+  StructType,
+  TimestampNTZType,
+  TimestampType,
+  YearMonthIntervalType
+}
+
+/**
+ * Resolves SQL [[AsOfJoin]] operators: materializes `MATCH_CONDITION` into 
`asOfCondition` and
+ * `orderExpression`, and expands `USING` column lists into equi-join 
predicates.
+ */
+object ResolveAsOfJoin extends Rule[LogicalPlan] with SQLConfHelper {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = 
plan.resolveOperatorsUpWithPruning(
+    _.containsPattern(AS_OF_JOIN), ruleId) {
+    case j @ AsOfJoin(
+        left,
+        right,
+        _,
+        condition,
+        _,
+        _,
+        _,
+        usingColumns,
+        matchLeft,
+        matchOp,
+        matchRight,
+        _,
+        _,
+        _)
+        if left.resolved && right.resolved && condition.forall(_.resolved) =>
+      val (joinBase, usingProjection) = usingColumns match {
+        case Some(cols) if condition.isEmpty =>
+          val (projectList, hiddenList, newCondition) =
+            NaturalAndUsingJoinResolution.computeJoinOutputsAndNewCondition(
+              left,
+              left.output,
+              right,
+              right.output,
+              j.joinType,
+              cols,
+              None,
+              (l, r) => conf.resolver(l, r))
+          (j.copy(condition = newCondition, usingColumns = None), 
Some((projectList, hiddenList)))
+        case _ => (j, None)
+      }
+      val resolvedJoin = (matchLeft, matchOp, matchRight) match {
+        case (Some(leftExpr), Some(operator), Some(rightExpr)) =>
+          AsOfJoinValidation.validateMatchConditionTableReferences(
+            joinBase, left, right, leftExpr, rightExpr)
+          if (leftExpr.resolved && rightExpr.resolved) {
+            AsOfJoinValidation.validateMatchConditionOperands(joinBase, 
leftExpr, rightExpr)
+            val (leftOperand, rightOperand, normalizedOp) =
+              AsOfJoin.normalizeMatchOperands(left, right, leftExpr, operator, 
rightExpr)
+            AsOfJoinValidation.validateMatchConditionPlannerSupport(
+              joinBase, leftOperand, rightOperand)
+            val (asOfCondition, orderExpression, leftSortExprs, 
rightSortExprs) =
+              AsOfJoin.materializeMatchComparison(leftOperand, rightOperand, 
normalizedOp)
+            joinBase.copy(
+              asOfCondition = asOfCondition,
+              orderExpression = orderExpression,
+              leftSortExprs = leftSortExprs,
+              rightSortExprs = rightSortExprs,
+              matchLeftOperand = None,
+              matchOperator = None,
+              matchRightOperand = None)
+          } else {
+            joinBase
+          }
+        case (None, None, None) => joinBase
+        case _ => joinBase
+      }
+      usingProjection match {
+        case Some((projectList, hiddenList)) =>
+          val project = Project(projectList, resolvedJoin)
+          project.setTagValue(
+            Project.hiddenOutputTag,
+            hiddenList.map(_.markAsQualifiedAccessOnly()))
+          project
+        case None => resolvedJoin
+      }
+  }
+}
+
+private[analysis] object AsOfJoinValidation extends QueryErrorsBase {
+
+  def validateMatchConditionTableReferences(
+      join: AsOfJoin,
+      left: LogicalPlan,
+      right: LogicalPlan,
+      leftExpr: Expression,
+      rightExpr: Expression): Unit = {
+    val leftSet = left.outputSet
+    val rightSet = right.outputSet
+
+    def referencesBothJoinSides(refs: AttributeSet): Boolean = {
+      refs.nonEmpty &&
+        refs.intersect(leftSet).nonEmpty &&
+        refs.intersect(rightSet).nonEmpty
+    }
+
+    val leftRefs = leftExpr.references
+    val rightRefs = rightExpr.references
+    if (referencesBothJoinSides(leftRefs) || 
referencesBothJoinSides(rightRefs)) {
+      join.failAnalysis(
+        errorClass = "ASOF_JOIN_MATCH_CONDITION_TABLE_REFERENCE",
+        messageParameters = Map(
+          "refs1" -> toSQLExpr(leftExpr),
+          "refs2" -> toSQLExpr(rightExpr)))
+    }
+  }
+
+  def validateMatchConditionOperands(
+      join: AsOfJoin,
+      leftExpr: Expression,
+      rightExpr: Expression): Unit = {
+    Seq(leftExpr, rightExpr).foreach { expr =>
+      findInvalidMatchConditionExpression(expr).foreach { invalidExpr =>
+        join.failAnalysis(
+          errorClass = "ASOF_JOIN_MATCH_CONDITION_INVALID_EXPRESSION",
+          messageParameters = Map("expr" -> toSQLExpr(invalidExpr)))
+      }
+    }
+    if (!RowOrdering.isOrderable(leftExpr.dataType) ||
+        !RowOrdering.isOrderable(rightExpr.dataType) ||
+        !areMatchConditionTypesCompatible(leftExpr.dataType, 
rightExpr.dataType)) {
+      join.failAnalysis(
+        errorClass = "ASOF_JOIN_MATCH_CONDITION_INVALID_TYPE",
+        messageParameters = Map(
+          "type1" -> toSQLType(leftExpr.dataType),
+          "type2" -> toSQLType(rightExpr.dataType)))
+    }
+  }
+
+  def validateMatchConditionPlannerSupport(
+      join: AsOfJoin,
+      leftOperand: Expression,
+      rightOperand: Expression): Unit = {
+    if (!areScalarSubtractBasedOperands(leftOperand, rightOperand)) {
+      join.failAnalysis(
+        errorClass = "AS_OF_JOIN.UNSUPPORTED_MATCH_CONDITION_OPERAND",
+        messageParameters = Map(
+          "type1" -> toSQLType(leftOperand.dataType),
+          "type2" -> toSQLType(rightOperand.dataType)))
+    }
+  }
+
+  /**
+   * Until multi-column sort-merge ASOF execution lands (SPARK-58124), the 
planner can only
+   * consume MATCH_CONDITION plans whose `orderExpression` is a scalar 
`Subtract`. STRING and
+   * composite operands use other distance expressions that `findFromOrder` 
cannot parse.
+   */
+  private def areScalarSubtractBasedOperands(
+      leftExpr: Expression,
+      rightExpr: Expression): Boolean = {
+    supportsSubtractForPlanner(leftExpr.dataType) && 
supportsSubtractForPlanner(rightExpr.dataType)
+  }
+
+  private def supportsSubtractForPlanner(dataType: DataType): Boolean = {

Review Comment:
   This is a verbatim copy of `AsOfJoin.supportsSubtract` (same type list). The 
two are coupled by construction — the planner-support gate must accept exactly 
the types `buildLeafOrderExpression` routes down the `Subtract` path — so 
keeping two copies invites silent drift if one side later gains a type. Reuse 
the existing predicate rather than duplicating it (e.g. expose 
`AsOfJoin.supportsSubtract` and call it here).



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