HeartSaVioR commented on code in PR #60019:
URL: https://github.com/apache/spark/pull/60019#discussion_r4512832389
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/TableCapabilityCheck.scala:
##########
@@ -73,6 +84,16 @@ object TableCapabilityCheck extends (LogicalPlan => Unit) {
case _ => // OK
}
+ // A command may drop, truncate or replace its target before it optimizes
its query, where
+ // PrepareExternalLookupJoin would reject a lookup-only table that no
lookup join reads. So a
+ // command whose query reads one outside a lookup join fails here, during
analysis. A view
+ // definition stores its query without reading it, for a lookup join that
reads the view.
+ plan.foreach {
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
[7412930c368](https://github.com/apache/spark/commit/7412930c3688d84fc17527b204fcbbc5a6d3a751)
(#59910, which owns this code). The command walk now runs only when the plan
contains the `COMMAND` pattern, so plans without a command skip it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -0,0 +1,258 @@
+/*
+ * 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 scala.annotation.tailrec
+
+import org.apache.spark.sql.catalyst.expressions.SubqueryExpression
+import org.apache.spark.sql.catalyst.optimizer.EliminateResolvedHint
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupHint,
ExternalLookupJoin, Join,
+ JoinStrategyHint, LogicalPlan, ResolvedHint, SubqueryAlias, UnaryNode, View}
+import org.apache.spark.sql.catalyst.rules.Rule
+import
org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION,
+ EXTERNAL_LOOKUP_HINT, JOIN}
+import org.apache.spark.sql.connector.catalog.TableCapability
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.execution.datasources.v2.ExternalLookupRelations
+
+/**
+ * Classifies a join for external lookup. [[CheckExternalLookupJoin]] and
[[FormExternalLookupJoin]]
+ * share it, so analysis rejects every join that the optimizer cannot convert,
except one without
+ * a condition: see [[CheckExternalLookupJoin]].
+ *
+ * A join is an external lookup join when its right side reads a table that
supports external
+ * lookup but not batch read, or when the right side carries an
`EXTERNAL_LOOKUP` hint. A table
+ * that supports both keeps the ordinary join strategies unless the hint opts
in. It must be a
+ * stream-static join: the left side is a streaming query, whose micro-batches
tolerate lookup
+ * results that change between requests, and the lookup table is on the right
side. The join reads
+ * the table directly, or through hints, aliases and views only, so a join
that must be a lookup
+ * join either runs as one or fails here, whatever the optimizer later does to
its lookup side.
+ */
+object ExternalLookupJoinEligibility extends QueryErrorsBase {
+ sealed trait Eligibility
+ /**
+ * The join stays an ordinary join: it has no `EXTERNAL_LOOKUP` hint, and
neither of its inputs is
+ * a lookup-only relation, directly or below unary operators. A lookup-only
relation below another
+ * operator, such as a union, is not recognized, and fails later as a batch
scan.
+ */
+ case object NotLookupJoin extends Eligibility
+ /** The join runs as an external lookup join. */
+ case object Eligible extends Eligibility
+ /**
+ * The join must run as an external lookup join, with a supported join type,
but has no
+ * condition.
+ */
+ case object MissingCondition extends Eligibility
+ /** The join must run as an external lookup join but cannot. */
+ case class Ineligible(error: Throwable) extends Eligibility
+
+ private val SUPPORTED_JOIN_TYPES = Seq(Inner, LeftOuter)
+
+ def apply(join: Join): Eligibility = {
+ if (lookupHints(join.left).nonEmpty) {
+ return
Ineligible(QueryCompilationErrors.invalidExternalLookupHintError("NOT_ON_LOOKUP_SIDE"))
+ }
+ // The lookup-only table must be on the right side; the sides are never
swapped.
+ val leftLookupOnlyTable =
ExternalLookupRelations.lookupOnlyTable(input(join.left))
+ if (leftLookupOnlyTable.isDefined) {
+ return ineligible("LOOKUP_TABLE_ON_LEFT",
toSQLId(leftLookupOnlyTable.get.name()))
+ }
+ val markers = lookupHints(join.right)
+ val lookupOnly =
ExternalLookupRelations.lookupOnlyTable(input(join.right)).isDefined
+ // A lookup-only table can be read only by a lookup join, and the hint
opts a join in. Either
+ // way the join must run as an external lookup join, and the checks below
apply.
+ if (!lookupOnly && markers.isEmpty) return NotLookupJoin
+ if (markers.length > 1) {
+ return
Ineligible(QueryCompilationErrors.invalidExternalLookupHintError("MULTIPLE_HINTS"))
+ }
+ if (join.right.isStreaming) {
+ return
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+ "STREAMING_LOOKUP_SIDE"))
+ }
+ // The DSv2 table that the lookup side reads through hints, aliases and
views only. There is
+ // none when another operator stands in between or the side reads no DSv2
table.
+ val table = ExternalLookupRelations.table(lookupRelation(join.right))
match {
+ case Some(table) => table
+ case None =>
+ return
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN"))
+ }
+ val relation = toSQLId(table.name())
+ if (!table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP)) {
+ return
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+ "TABLE", Map("table" -> relation)))
+ }
+ if (!join.left.isStreaming) return ineligible("STATIC_LEFT_SIDE", relation)
+ // A join hint the user wrote is never silently dropped: an external
lookup join cannot run a
+ // physical join strategy, and a lookup-only table has no batch scan for
one. On a table that
+ // also supports batch reads, the strategy hint conflicts with the
`EXTERNAL_LOOKUP` hint.
+ joinStrategyHint(join) match {
+ // The user asked for a physical join, which an external lookup join
cannot run.
+ case Some(strategy) if lookupOnly =>
+ ineligible("CONFLICTING_JOIN_STRATEGY", relation,
+ Map("strategy" -> toSQLStmt(strategy.displayName)))
+ case Some(strategy) =>
+ Ineligible(QueryCompilationErrors.invalidExternalLookupHintError(
+ "CONFLICTING_JOIN_STRATEGY",
+ Map("strategy" -> toSQLStmt(strategy.displayName), "relation" ->
relation)))
+ // No physical join was asked for: the join runs as an external lookup
join unless a check
+ // below fails.
+ // Checked before the condition, so that a cross join fails while it is
analyzed.
+ case None if !SUPPORTED_JOIN_TYPES.contains(join.joinType) =>
+ ineligible("JOIN_TYPE", relation, Map(
+ "joinType" -> toSQLStmt(join.joinType.sql),
+ "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES.map(t =>
toSQLStmt(t.sql)).mkString(", ")))
+ case None if join.condition.isEmpty => MissingCondition
+ // The optimizer rewrites a subquery in a join condition only for a
Join, which a lookup join
+ // no longer is by then.
+ case None if join.condition.exists(SubqueryExpression.hasSubquery) =>
+ ineligible("SUBQUERY_IN_JOIN_CONDITION", relation)
+ case None => Eligible
+ }
+ }
+
+ /**
+ * The lookup side of an eligible join, without its `EXTERNAL_LOOKUP` hint.
The lookup side of an
+ * eligible join is a chain of hints, aliases and views over the table, so
every marker in it is
+ * the join's own.
+ */
+ def lookupSide(join: Join): LogicalPlan =
+ join.right.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_HINT))
{
+ case marker: ExternalLookupHint => marker.child
+ }
+
+ private def ineligible(
+ subClass: String,
+ relation: String,
+ parameters: Map[String, String] = Map.empty): Ineligible =
+ Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+ subClass, parameters + ("relation" -> relation)))
+
+ /** The relation that a join input reads: the first operator that has no
single child. */
+ @tailrec
+ private def input(plan: LogicalPlan): LogicalPlan = plan match {
+ case unary: UnaryNode => input(unary.child)
+ case other => other
+ }
+
+ /** The first operator below a join input that is not a hint, an alias or a
view. */
+ @tailrec
+ private def lookupRelation(plan: LogicalPlan): LogicalPlan = plan match {
+ case node @ (_: ExternalLookupHint | _: ResolvedHint | _: SubqueryAlias |
_: View) =>
+ lookupRelation(node.children.head)
+ case other => other
+ }
+
+ /**
+ * The `EXTERNAL_LOOKUP` hints on a join input. Like a join strategy hint,
the hint applies to the
+ * join that the input feeds, through any unary operator.
+ */
+ @tailrec
+ private def lookupHints(
+ plan: LogicalPlan,
+ found: Seq[ExternalLookupHint] = Nil): Seq[ExternalLookupHint] = plan
match {
+ case marker: ExternalLookupHint => lookupHints(marker.child, found :+
marker)
+ case unary: UnaryNode => lookupHints(unary.child, found)
+ case _ => found
+ }
+
+ /**
+ * The physical join strategy hint, such as `BROADCAST` or `MERGE`, that
EliminateResolvedHint
+ * would attach to the join, or None if there is none. The `EXTERNAL_LOOKUP`
hint is never
+ * returned: it is an [[ExternalLookupHint]] marker, not a
[[JoinStrategyHint]]. A `HintInfo`
+ * without a strategy asks for nothing, so it is skipped.
+ */
+ private def joinStrategyHint(join: Join): Option[JoinStrategyHint] = {
+ // Only the hints that EliminateResolvedHint will attach to this join
count; a strategy hint
+ // on a nested join belongs to that join.
+ val attached = join.hint.leftHint.toSeq ++ join.hint.rightHint.toSeq ++
+ Seq(join.left,
join.right).flatMap(EliminateResolvedHint.extractHintsFromPlan(_)._2)
+ attached.flatMap(_.strategy).headOption
+ }
+}
+
+/**
+ * Reports, while a query is analyzed, why a join cannot run as the external
lookup join it must
+ * be. It does not change the plan: the join stays a [[Join]] until
[[FormExternalLookupJoin]]
+ * converts it, so the APIs and rules that expect an analyzed join keep
working. A join that is not
+ * resolved, for example one whose condition is not boolean, is left to the
analyzer's own join
+ * checks.
+ *
+ * A missing join condition is not reported here, because the classic Dataset
API analyzes a USING
+ * join first as a join without a condition.
+ */
+object CheckExternalLookupJoin extends (LogicalPlan => Unit) {
+ override def apply(plan: LogicalPlan): Unit = {
+ // A join must run as a lookup join only over a lookup-only table, which
is a DSv2 relation, or
+ // under the hint, so other plans need no walk.
+ if (plan.containsPattern(JOIN) &&
+ plan.containsAnyPattern(DATA_SOURCE_V2_RELATION,
EXTERNAL_LOOKUP_HINT)) {
+ plan.foreachUp {
+ case join: Join if join.resolved =>
+ ExternalLookupJoinEligibility(join) match {
+ case ExternalLookupJoinEligibility.Ineligible(error) => throw error
+ case _ =>
+ }
+ case _ =>
+ }
+ }
+ }
+}
+
+/**
+ * Replaces each join that runs as an external lookup join with an
[[ExternalLookupJoin]], and
+ * removes the `EXTERNAL_LOOKUP` hints that no join consumed.
+ *
+ * It must run at the start of optimization, before Finish Analysis and
operator optimization, so
+ * that it sees the join and its lookup side as analysis left them: no hint or
alias eliminated,
+ * no predicate pushed into the join and no column pruned. These are the
shapes that
+ * [[CheckExternalLookupJoin]] validated.
+ */
+object FormExternalLookupJoin extends Rule[LogicalPlan] {
+ import ExternalLookupJoinEligibility._
+
+ override def apply(plan: LogicalPlan): LogicalPlan = {
+ val formed = plan.transformUpWithPruning(_.containsPattern(JOIN), ruleId) {
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. The batch now runs only on a plan that contains a DSv2 relation
([7412930c368](https://github.com/apache/spark/commit/7412930c3688d84fc17527b204fcbbc5a6d3a751)),
or, from this PR, an `EXTERNAL_LOOKUP` hint
([bceaf1d1d2a](https://github.com/apache/spark/commit/bceaf1d1d2a3188ed183978044ff6494fec92702)),
the same guard that `CheckExternalLookupJoin` uses. Plans that join only V1 or
local relations are returned unchanged.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -68,6 +69,17 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
case r: DataSourceV2Relation =>
ApplyCharTypePaddingHelper.readSidePadding(r, () =>
r.copy(output = r.output.map(CharVarcharUtils.cleanAttrMetadata)))
+ // A lookup-only table is read only through an external lookup join,
which cannot apply
+ // the read-side CHAR padding or VARCHAR check. It is rejected rather
than read without it.
+ case r: ExternalLookupRelation =>
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. I'd leave this one. It is an interim state that ends in #60055, the
next PR in the stack: it pads CHAR and VARCHAR columns on every lookup side as
a lookup-side stage, and removes `CHAR_VARCHAR_COLUMN`. Until then, such a
query fails either way, so I'd rather not add plumbing for a better message
that the next PR removes.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,324 @@
+/*
+ * 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.{Alias, And, Attribute,
AttributeMap,
+ EqualNullSafe, EqualTo, Expression, ExprUtils, ExternalUserDefinedFunction,
Literal,
+ PredicateHelper, PythonUDF}
+import org.apache.spark.sql.catalyst.plans.LeftOuter
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin,
ExternalLookupKeyTypes,
+ Filter, LogicalPlan, PreparedExternalLookupJoin, Project}
+import org.apache.spark.sql.catalyst.rules.Rule
+import
org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION,
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.{ArrayType, BooleanType, DataType, MapType,
StructType}
+
+/** 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 if provablyEmpty(join) =>
emptyJoinResult(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.
+ if (prepared.containsPattern(DATA_SOURCE_V2_RELATION)) {
+ prepared.foreach { node =>
+ ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+ throw QueryCompilationErrors.unsupportedBatchReadError(table)
+ }
+ }
+ }
+ prepared
+ }
+
+ // The optimizer folds `WHERE false` on the lookup side into an empty
relation, and a condition
+ // such as `s.id = r.id AND false` into `false`. Such a join needs no
connector call.
+ private def provablyEmpty(join: ExternalLookupJoin): Boolean =
+ join.right.maxRows.contains(0L) || (join.condition match {
+ case Some(Literal(value, BooleanType)) => value == null || value == false
+ case _ => false
+ })
+
+ private def emptyJoinResult(join: ExternalLookupJoin): LogicalPlan = {
+ val nullLookupColumns = join.right.output.map { attr =>
+ Alias(Literal(null, attr.dataType), attr.name)(attr.exprId)
+ }
+ val unmatched = Project(join.left.output ++ nullLookupColumns, join.left)
+ join.joinType match {
+ case LeftOuter => unmatched
+ // The stream side is kept under a false filter rather than replaced by
an empty relation,
+ // so that its sources, watermarks and stateful operators still run in
every micro-batch.
+ // PruneFilters decides whether a streaming subplan may be pruned.
+ case _ => Filter(Literal.FalseLiteral, unmatched)
+ }
+ }
+
+ private def prepare(join: ExternalLookupJoin): LogicalPlan = {
+ 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)
+ // A Python or external UDF over lookup columns cannot run in the
residual. The rules that move
+ // one out of a join condition match only Join and run later, so this rule
does it: an inner
+ // join evaluates the conjunct in a filter above the join, and an outer
join is rejected.
+ if (join.joinType == LeftOuter) {
+ conjuncts.flatMap(lookupSideUDF(join, _)).headOption.foreach {
+ case _: ExternalUserDefinedFunction =>
+ throw
QueryCompilationErrors.useExternalUDFInJoinConditionUnsupportedError(join.joinType)
+ case _ =>
+ throw
QueryCompilationErrors.usePythonUDFInJoinConditionUnsupportedError(join.joinType)
+ }
+ }
+ 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 (residualConjuncts, joinFilter) = conjuncts.zipWithIndex.collect {
+ case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct
+ }.partition(lookupSideUDF(join, _).isEmpty)
+ val (residualFirst, residualRest) = residualConjuncts.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,
where a column, nested
+ // field, array element or map value is nullable only when both the table
and the read schema
+ // allow nulls: the join fails the task on a null that either rules out,
because Spark relied
+ // on the table's nullability while it optimized the query.
+ val readSchema = CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+ nonNull(scan.readSchema(), "NULL_READ_SCHEMA"))
+ val lookupInput = readSchema.fields.map { field =>
+ relation.output.find { attr =>
+ attr.name == field.name &&
DataType.equalsIgnoreNullability(attr.dataType, field.dataType)
+ }.map { attr =>
+ attr.withDataType(withStricterNullability(attr.dataType,
field.dataType))
+ .withNullability(attr.nullable && field.nullable)
+ }.getOrElse {
+ throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+ tableName, "UNKNOWN_SCAN_FIELD", Map("field" ->
toSQLId(Seq(field.name))))
+ }
+ }.toSeq
+ lookupInput.groupBy(_.name).collectFirst {
+ case (name, fields) if fields.size > 1 => name
+ }.foreach { name =>
+ throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+ tableName, "DUPLICATE_SCAN_FIELD", Map("field" -> toSQLId(Seq(name))))
+ }
+ // The prepared join replaces the analyzed one, so it keeps the analyzed
lookup attributes in
+ // their analyzed order; execution projects the value rows into them.
+ // TODO: prune lookup output to the columns required above the join.
+ val lookupOutput = join.right.output
+ val readExprIds = lookupInput.map(_.exprId).toSet
+ lookupOutput.find(attr => !readExprIds.contains(attr.exprId)).foreach {
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
[bceaf1d1d2a](https://github.com/apache/spark/commit/bceaf1d1d2a3188ed183978044ff6494fec92702).
A metadata column on the lookup side now fails during analysis with
`EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.METADATA_COLUMN`, which names the table. It
no longer blames the connector during optimization. The message names the table
rather than the column, because the analyzer adds all of a table's metadata
columns once the query reads one of them. A test covers it.
--
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]