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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveAsOfJoin.scala:
##########
@@ -0,0 +1,202 @@
+/*
+ * 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, DataType, DatetimeType, 
StringType, StructType}
+
+/**
+ * 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 (asOfCondition, orderExpression, leftSortExprs, 
rightSortExprs) =
+              AsOfJoin.resolveMatchComparison(left, right, leftExpr, operator, 
rightExpr)
+            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) ||

Review Comment:
   This type check accepts any orderable, type-compatible operands, but the 
only planner consumer can't handle all of them. When 
`sortMergeAsOfJoin.enabled` is on, a SQL AsOfJoin isn't rewritten and reaches 
`AsOfJoinSelection.findFromOrder` (SparkStrategies.scala:514-528), which only 
recognizes `Subtract` / `If(_, Subtract, _)`. But a plain STRING operand 
produces `If(EqualTo, 0, If(GreaterThan, 1, -1))` (via 
`buildSignedComparisonDistance`), and struct/array operands produce 
`CreateStruct`/`ZipWith` — none of which `findFromOrder` matches. So e.g. 
`MATCH_CONDITION (t.symbol >= q.symbol)` (both confs on) passes analysis, skips 
the rewrite, then throws `IllegalStateException("Cannot extract as-of keys from 
order expression: ...")` at planning.
   
   I traced this from source but didn't run a build — can you confirm the 
planning-time throw? If it reproduces, gating the operand types this analysis 
supports down to what the physical path can consume (with a clear analysis 
error for the rest) until the composite/multi-column sort-merge operator lands 
would keep supported-syntax queries from failing with an internal error.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala:
##########
@@ -2563,6 +2566,8 @@ case class AsOfJoin(
       matchOperator.isEmpty &&
       matchRightOperand.isEmpty &&
       expressions.forall(_.resolved) &&
+      leftSortExprs.forall(_.resolved) &&

Review Comment:
   These two clauses are redundant: `expressions.forall(_.resolved)` on the 
line above already covers `leftSortExprs`/`rightSortExprs`, since 
`QueryPlan._expressions` recurses into `Seq[Expression]` case-class fields. 
Harmless, but can be dropped.



##########
sql/core/src/test/scala/org/apache/spark/sql/AsOfJoinSQLSuite.scala:
##########
@@ -38,6 +38,19 @@ class AsOfJoinSQLSuite extends QueryTest with 
SharedSparkSession {
     super.afterAll()
   }
 
+  private def setupTradeQuoteViews(): Unit = {

Review Comment:
   All the added tests are negative; the one test with a valid 
`MATCH_CONDITION` ("requires sort-merge conf") asserts failure with the conf 
off. A positive analyze-only test with `sortMergeAsOfJoin.enabled=true` — 
asserting a valid condition resolves to the expected plan, no execution backend 
needed — would cover the resolution path directly, and a case with a STRING (or 
struct) operand would have surfaced the planner-capability gap flagged in 
`ResolveAsOfJoin`.



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