HeartSaVioR commented on code in PR #59909:
URL: https://github.com/apache/spark/pull/59909#discussion_r4518666429


##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Good catch. Fixed in 
[e3212ca903a](https://github.com/apache/spark/commit/e3212ca903ab0d829feab6150bda53ea5ad88cfa):
 in the residual, a NULL from the key equalities and the conjuncts that cannot 
fail now reads as false, through `coalesce(..., false)`. So the conjuncts that 
can fail never run for such a row, as in a hash join. A row joins only when the 
whole condition is true, so no result changes. A new test checks that a NULL 
key equality stops a cast that would fail under ANSI mode, and that other rows 
match as with the plain condition.
   



##########
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
+
+    def nonNull[T](value: T, subClass: String): T = Option(value).getOrElse {
+      throw 
QueryCompilationErrors.invalidDataSourceExternalLookupError(tableName, subClass)
+    }
+    val scan = nonNull(scanBuilder.build(), "NULL_SCAN")
+    // Fields bind to table columns by exact name, as in 
`PushDownUtils.toOutputAttrs`. CHAR and
+    // VARCHAR are read as STRING, and nullability, including nested 
nullability, does not count
+    // for the match. The value-row attributes take the read schema's type and 
nullability, so they
+    // describe every value the connector may return.
+    val readSchema = CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+      nonNull(scan.readSchema(), "NULL_READ_SCHEMA"))
+    val lookupInput = readSchema.fields.map { field =>
+      relation.output.find { attr =>

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Fixed in 
[e3212ca903a](https://github.com/apache/spark/commit/e3212ca903ab0d829feab6150bda53ea5ad88cfa):
 the read schema now binds through a map by name, built once, so binding is 
linear in the table width. The bound attributes, their order and the first 
`UNKNOWN_SCAN_FIELD` stay the same.
   



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