spark-test commented on code in PR #59909:
URL: https://github.com/apache/spark/pull/59909#discussion_r4511403712


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,245 @@
+/*
+ * 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.execution.datasources.v2
+
+import java.util.{Collections, IdentityHashMap}
+
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
AttributeMap, EqualNullSafe,
+  EqualTo, Expression, ExprUtils, PredicateHelper}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 
ExternalLookupKeyTypes,
+  LogicalPlan, PreparedExternalLookupJoin}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.EXTERNAL_LOOKUP_JOIN
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, 
FieldReference}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => 
V2Predicate}
+import org.apache.spark.sql.connector.read.{LookupParameter, 
SupportsExternalLookup}
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.types.DataType
+
+/** Finalizes an optimized external lookup side immediately before ordinary V2 
scan preparation. */
+object PrepareExternalLookupJoin extends Rule[LogicalPlan] with PredicateHelper
+  with QueryErrorsBase {
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val prepared = 
plan.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_JOIN)) {
+      case join: ExternalLookupJoin => prepare(join)
+    }
+    // Prepared lookup joins no longer contain their lookup relation, so a 
lookup-only table that
+    // is still read here cannot run.
+    prepared.foreach { node =>
+      ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+        throw QueryCompilationErrors.unsupportedBatchReadError(table)
+      }
+    }
+    prepared
+  }
+
+  private def prepare(join: ExternalLookupJoin): PreparedExternalLookupJoin = {
+    val relation = extractLookupPlan(join.right).getOrElse {
+      throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN")
+    }
+    val tableName = relation.table.name()
+    val supportsRead = relation.table match {
+      case table: SupportsRead
+          if table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP) => 
table
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "TABLE", Map("table" -> toSQLId(tableName)))
+    }
+    val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates)
+    val offeredCandidates = conjuncts.zipWithIndex.collect {
+      case (EqualTo(leftExpr, rightAttr: Attribute), index)
+          if isLookupEquality(join, leftExpr, rightAttr) =>
+        OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false)
+      case (EqualTo(rightAttr: Attribute, leftExpr), index)
+          if isLookupEquality(join, leftExpr, rightAttr) =>
+        OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false)
+    }
+    if (offeredCandidates.isEmpty) {
+      throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "NO_LOOKUP_CANDIDATE", Map("table" -> toSQLId(tableName)))
+    }
+
+    val scanBuilder = supportsRead.newScanBuilder(relation.options)
+    val lookupBuilder = scanBuilder match {
+      case builder: SupportsExternalLookup => builder
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "SCAN_BUILDER", Map("table" -> toSQLId(tableName)))
+    }
+    // A column is offered under the table's name for it. Under 
case-insensitive analysis, the
+    // condition may spell it in another case, as `ID` for `id`, with the same 
exprId; filter
+    // pushdown renames it the same way, with 
DataSourceStrategy.normalizeExprs.
+    val columnNames = AttributeMap(relation.output.map(attr => attr -> 
attr.name))
+    val offeredPredicates = offeredCandidates.map { candidate =>
+      new V2Predicate(candidate.predicateName, Array[V2Expression](
+        FieldReference.column(columnNames(candidate.projectedField)),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    // A copy, so a connector that reorders the array in place cannot break 
the identity mapping.
+    val selectedPredicates = selectedCandidates(tableName, offeredPredicates, 
offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates.clone()))
+    val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet
+    // As a hash join matches its keys before it evaluates its other 
conditions, the residual
+    // evaluates the equalities between the two sides first, together with the 
conjuncts that
+    // cannot fail. A conjunct that can fail then runs only for rows that pass 
them. Each group
+    // keeps the written order.
+    val (residualFirst, residualRest) = conjuncts.zipWithIndex.collect {
+      case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct
+    }.partition { conjunct =>
+      isJoinKeyEquality(join, conjunct) || 
ExprUtils.canEvaluateUnconditionally(conjunct)
+    }
+    val residual = residualFirst ++ residualRest

Review Comment:
   **Nit (P3):** The comment above says that a conjunct that can fail runs only 
for rows that pass the key equalities, as in a hash join. That holds when a key 
equality is false, but not when it is NULL: `And.eval` and its generated code 
skip the right side only for a non-null false, so a NULL key equality lets the 
later conjuncts run. A hash join never gets that far for a NULL key, because 
`HashedRelation` does not store build rows with NULL keys 
(`HashedRelation.scala:481`) and a probe key with a NULL field matches nothing.
   
   For example, take `ON t.id = s.id AND t.region = s.region AND s.amount / 
t.divisor > 1` under ANSI mode, with a connector that selects only `id = ?`. 
The residual is `t.region = s.region AND s.amount / t.divisor > 1`, so a 
returned row with a NULL `region` and a zero `divisor` fails the task with 
`DIVIDE_BY_ZERO`, where a hash join on `(id, region)` would simply not match 
it. The same applies to a NULL stream-side key, and to other conjuncts that can 
fail, such as a cast that raises `CAST_INVALID_INPUT` under ANSI mode or 
`assert_true`. This matters once SPARK-60690 registers the rules. Because the 
residual only decides whether a row matches, treating a NULL `=` key equality 
as false, for example `coalesce(t.region = s.region, false)`, stops the 
evaluation without changing which rows match.
   
   **Verification:**
   - **Regression:** Evaluating the prepared residual on a joined row whose 
unselected key equality is NULL, with a later conjunct that fails under ANSI 
mode such as a division by a zero lookup value, yields no match instead of 
raising the error.
   - **Behavior:** For joined rows whose key equalities are true, false or 
NULL, the residual's match decision equals that of the plain conjunction of the 
same conjuncts.
   - **Compatibility:** The residual still places key equalities and conjuncts 
that cannot fail ahead of the rest, in written order within each group, for 
both `=` and `<=>` key equalities.



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