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


##########
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:
   **Nit (P3):** This `find` runs once per read-schema field, and the 
`MISSING_SCAN_FIELD` check below makes the read schema list every table column 
while the builder is unpruned, so binding is quadratic in table width. That is 
about 500,000 name comparisons for a 1,000-column lookup table and about 50 
million for 10,000 columns, repeated on every preparation, which for a 
streaming query means every micro-batch once the rules are registered. Typical 
tables of tens of columns are unaffected. `PushDownUtils.toOutputAttrs`, which 
the comment cites, builds its name map once. Building 
`relation.output.groupBy(_.name)` once and finding the type-compatible 
attribute within the field's group keeps the bound attributes, their order and 
the first `UNKNOWN_SCAN_FIELD` unchanged, at linear cost, because `groupBy` 
keeps each group in output order.
   
   **Verification:**
   - **Compatibility:** Reordered, case-variant, weaker-nullability, 
stricter-nullability, missing-field and type-mismatch read schemas produce the 
same value-row attributes and the same errors as before.
   - **Inspection:** Binding looks each read-schema field's name up in a map 
built once from the relation's output instead of scanning the output per field.



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