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


##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,489 @@
+/*
+ * 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.connector
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.analysis.FormExternalLookupJoin
+import org.apache.spark.sql.catalyst.dsl.expressions._
+import org.apache.spark.sql.catalyst.expressions.{Attribute, 
AttributeReference, AttributeSet,
+  BindReferences, Coalesce, Expression, Literal, Predicate => 
CatalystPredicate}
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter, 
PlanTest}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, 
JoinHint,
+  LocalRelation, LogicalPlan, PreparedExternalLookupJoin, Project}
+import org.apache.spark.sql.connector.catalog.{SupportsRead, Table, 
TableCapability}
+import org.apache.spark.sql.connector.catalog.TableCapability.EXTERNAL_LOOKUP
+import org.apache.spark.sql.connector.expressions.FieldReference
+import org.apache.spark.sql.connector.expressions.filter.Predicate
+import org.apache.spark.sql.connector.read.{ExternalLookup, 
ExternalLookupReader,
+  ExternalLookupReaderFactory, Scan, ScanBuilder, SupportsExternalLookup}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation,
+  ExternalLookupRelation, PrepareExternalLookupJoin}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, LongType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.unsafe.types.UTF8String
+
+class PrepareExternalLookupJoinSuite extends PlanTest {
+  private val stream =
+    LocalRelation(Seq($"streamId".int, $"streamLabel".string), isStreaming = 
true)
+  private val QUOTED_TABLE_NAME = "`PlanningExternalLookupTable`"
+
+  private def lookupRelation(table: PlanningExternalLookupTable): 
ExternalLookupRelation =
+    ExternalLookupRelation(
+      DataSourceV2Relation.create(table, None, None, 
CaseInsensitiveStringMap.empty))
+
+  private def lookupJoin(
+      lookup: LogicalPlan,
+      condition: Expression,
+      joinType: JoinType = Inner,
+      left: LogicalPlan = stream): LogicalPlan =
+    FormExternalLookupJoin(Join(left, lookup, joinType, Some(condition), 
JoinHint.NONE))
+
+  private def lookupJoinOnId(lookup: LogicalPlan): LogicalPlan =
+    lookupJoin(lookup, stream.output.head === lookup.output.head)
+
+  private def prepare(plan: LogicalPlan): PreparedExternalLookupJoin =
+    PrepareExternalLookupJoin(plan) match {
+      case lookup: PreparedExternalLookupJoin => lookup
+      case other => fail(s"Expected a prepared external lookup join: $other")
+    }
+
+  private def prepareError(plan: LogicalPlan): AnalysisException =
+    intercept[AnalysisException] { PrepareExternalLookupJoin(plan) }
+
+  // A conjunct of the residual's first group, read as false when it is NULL.
+  private def orFalse(conjunct: Expression): Expression =
+    Coalesce(Seq(conjunct, Literal.FalseLiteral))
+
+  /**
+   * Whether Spark offers `code = ?` on a lookup column `code` of the given 
type. The connector
+   * selects only `id = ?`, so Spark evaluates the code equality either way.
+   */
+  private def offeredCodeCandidate(codeType: String): Boolean = {
+    var offeredCandidates = Seq.empty[String]
+    val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code 
$codeType", select = {
+      candidates =>
+        offeredCandidates = candidates.map(_.toString).toSeq
+        candidates.take(1)
+    }))
+    val Seq(lookupId, lookupCode) = lookup.output
+    val streamId = stream.output.head
+    val streamCode = AttributeReference("streamCode", lookupCode.dataType)()
+    val codesEqual = streamCode === lookupCode
+    val prepared = prepare(lookupJoin(lookup, streamId === lookupId && 
codesEqual,
+      left = LocalRelation(Seq(streamId, streamCode), isStreaming = true)))
+    assert(prepared.residualCondition === Some(codesEqual), codeType)
+    offeredCandidates match {
+      case Seq("id = ?") => false
+      case Seq("id = ?", "code = ?") => true
+      case other => fail(s"Unexpected candidates for $codeType: $other")
+    }
+  }
+
+  test("a lookup-only relation that no lookup join reads is rejected") {
+    val lookup = lookupRelation(PlanningExternalLookupTable())
+    prepare(lookupJoinOnId(lookup))
+    checkError(
+      exception = prepareError(Project(lookup.output, lookup)),
+      condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+      parameters = Map("tableName" -> QUOTED_TABLE_NAME, "operation" -> "batch 
scan"))
+  }
+
+  test("an equality is a lookup candidate only on a type that stores compare 
as Spark does") {
+    val offeredTypes = Seq("TINYINT", "SMALLINT", "INT", "BIGINT", "BOOLEAN", 
"DECIMAL(10, 2)",
+      "DATE", "TIMESTAMP", "TIMESTAMP_NTZ", "BINARY", "STRING", "STRING 
COLLATE UTF8_BINARY",
+      "VARCHAR(3)")
+    val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)",

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.
   
   Added in 
[10381da78d9](https://github.com/apache/spark/commit/10381da78d99a4c4f375c6ca1522bc933cf9da41):
 `VARCHAR(3) COLLATE UTF8_LCASE` is in `notOfferedTypes`. With the 
`supportsBinaryEquality` check removed, the test now fails.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,132 @@
+/*
+ * 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.plans.logical
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, 
Expression}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{EXTERNAL_LOOKUP_JOIN, 
TreePattern}
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, 
CharType, DataType,
+  DateType, DecimalType, IntegerType, LongType, ShortType, StringType, 
TimestampNTZType,
+  TimestampType, VarcharType}
+
+/**
+ * A lookup join retained through ordinary expression and operator 
optimization.
+ *
+ * @param requiredLookupOutput Every output attribute of the lookup side. They 
are all part of this
+ *   node's references, so column pruning never puts a projection over the 
lookup relation, which
+ *   preparation needs directly under the join. A narrower list would let it 
do so.
+ */
+case class ExternalLookupJoin(
+    left: LogicalPlan,
+    right: LogicalPlan,
+    joinType: JoinType,
+    condition: Option[Expression],
+    requiredLookupOutput: Seq[Attribute]) extends BinaryNode {
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_JOIN)
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => left.output ++ right.output
+    case LeftOuter => left.output ++ right.output.map(_.withNullability(true))
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  override protected def withNewChildrenInternal(
+      newLeft: LogicalPlan,
+      newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right 
= newRight)
+}
+
+/** A lookup join after its optimized lookup side has been converted to an 
external operation. */
+case class PreparedExternalLookupJoin(
+    child: LogicalPlan,
+    @transient scan: Scan,
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    lookupInput: Seq[Attribute],
+    lookupOutput: Seq[Attribute],
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    joinType: JoinType,
+    residualCondition: Option[Expression]) extends UnaryNode {
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => child.output ++ lookupOutput
+    case LeftOuter => child.output ++ lookupOutput.map(_.withNullability(true))
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  override def references: AttributeSet =
+    AttributeSet(lookupParameters.flatMap(_.references)) ++
+      residualCondition.map(_.references.intersect(child.outputSet))
+        .getOrElse(AttributeSet.empty)
+
+  override protected def withNewChildInternal(newChild: LogicalPlan): 
PreparedExternalLookupJoin =
+    copy(child = newChild)
+
+  // Connector descriptions may contain secrets, so the scan and the reader 
factory are not shown.
+  // The physical node renders a redacted description of them.
+  override protected def stringArgs: Iterator[Any] =
+    Iterator(joinType, lookupParameters, residualCondition, child)
+
+  // The join keeps the size estimate it had before preparation, as an 
ordinary join's: the product
+  // of the stream side's size and the lookup side's, Spark's default size for 
a table it cannot
+  // scan. The stream side's size alone would ignore the lookup columns and 
the rows that a stream
+  // row can match.
+  override def stats: Statistics = statsCache.getOrElse {
+    statsCache = Some(Statistics(sizeInBytes =
+      Seq(child.stats.sizeInBytes, BigInt(conf.defaultSizeInBytes)).filter(_ > 
0L).product))
+    statsCache.get
+  }
+}
+
+/**
+ * The types of lookup columns on which Spark offers a comparison to the 
connector as a lookup
+ * candidate. The connector evaluates a selected candidate in its store, so 
Spark offers only types
+ * whose values a store compares as Spark does. A comparison on any other type 
stays in Spark's
+ * residual condition.
+ */
+object ExternalLookupKeyTypes {
+  /**
+   * Whether Spark offers `=` on the lookup column `column`, by its declared 
type: integral types,
+   * BOOLEAN, DECIMAL, DATE, TIMESTAMP, TIMESTAMP_NTZ, BINARY, and STRING and 
VARCHAR whose
+   * collation compares bytes, such as UTF8_BINARY. FLOAT and DOUBLE are not 
offered, because
+   * stores treat NaN and -0.0 in different ways, nor CHAR, which Spark pads 
on read, nor strings
+   * with another collation, nor complex types, nor any other type. VARCHAR is 
not offered under
+   * `spark.sql.charVarchar.standardSemantics.enabled` either, because Spark 
then trims trailing

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.
   
   Thanks, you're right. Fixed in 
[10381da78d9](https://github.com/apache/spark/commit/10381da78d99a4c4f375c6ca1522bc933cf9da41):
 the scaladoc and the test comment now say that Spark reads a value within the 
declared length unchanged, drops the trailing blanks past that length from a 
longer value, and fails if it is still too long. So a store that compares such 
a longer value as stored could miss a row. The description now says the same, 
and #60055 uses the same wording for `<=>`.
   



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