spark-test commented on code in PR #59909:
URL: https://github.com/apache/spark/pull/59909#discussion_r4506125649
##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -2855,6 +2898,64 @@
],
"sqlState" : "42822"
},
+ "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED" : {
+ "message" : [
+ "The join cannot be executed as an external lookup join:"
+ ],
+ "subClass" : {
+ "CONFLICTING_JOIN_STRATEGY" : {
+ "message" : [
+ "The join strategy hint <strategy> cannot be honored by an external
lookup join over <relation>. Remove the <strategy> hint."
+ ]
+ },
+ "JOIN_TYPE" : {
+ "message" : [
+ "The join type <joinType> is not supported by an external lookup
join over <relation>. Supported join types are <supportedJoinTypes>."
+ ]
+ },
+ "LOOKUP_PLAN" : {
+ "message" : [
+ "The lookup side must be a DSv2 table, with no other operator
between the table and the join."
+ ]
+ },
+ "LOOKUP_TABLE_ON_LEFT" : {
+ "message" : [
+ "The lookup-only table <relation> must be on the right side of the
join."
+ ]
+ },
+ "MISSING_JOIN_CONDITION" : {
+ "message" : [
+ "The join has no join condition. Write the lookup condition in the
join itself, such as in its `ON` clause or the condition argument of `join()`,
rather than in a later `WHERE` clause or filter."
+ ]
+ },
+ "NO_LOOKUP_CANDIDATE" : {
+ "message" : [
+ "The join condition has no lookup predicate that Spark can offer to
table <table>. Spark offers only an equality `=` between a lookup column, with
no cast or other expression applied to it, and an expression over the streaming
side. If the lookup column is cast to match the streaming side, cast the
streaming-side expression to the lookup column's type instead. Spark offers it
only on lookup columns whose type a store compares as Spark does: integral
types, BOOLEAN, DECIMAL, DATE, TIMESTAMP, TIMESTAMP_NTZ, BINARY, and strings
with a binary collation such as UTF8_BINARY. It never offers one on FLOAT,
DOUBLE, CHAR, VARCHAR, a string with another collation, a complex type or any
other type."
Review Comment:
**Non-blocking (P2):** The advice to cast the streaming-side expression is
equivalent only when every streaming-side value is exactly representable in the
lookup column's type. It applies exactly when type coercion widened the lookup
column, so following it always narrows the streaming-side value:
- `t.id INT = s.id BIGINT` becomes `t.id = CAST(s.id AS INT)`. Under ANSI
mode, the default, a stream key outside the INT range fails the query with
`CAST_OVERFLOW`, where the written condition just finds no match. With ANSI
mode off, the key wraps and can match an unrelated lookup row.
- For a DECIMAL(10,3) stream key and a DECIMAL(10,2) column, `CAST(s.x AS
DECIMAL(10,2))` rounds 1.005 to 1.01, which then matches the lookup row 1.01.
The written condition compares 1.005 with 1.010 and finds no match.
- For a TIMESTAMP stream key and a DATE column, `CAST(s.ts AS DATE) = t.d`
matches every timestamp of that day instead of only midnight.
The suite's own trigger for this error, a BIGINT stream key against an INT
lookup column, is the first case, and the sentence grew out of the first
review's suggestion to mention casting the stream side. Limiting the advice to
streaming-side values that the lookup column's type represents exactly, and
saying that otherwise the rewrite changes which rows match, keeps the hint
without presenting a lossy cast as a drop-in fix. Dropping the sentence would
also work. The message is raised once SPARK-60690 registers the rule.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59909#discussion_r4418015171).
**Verification:**
- **Inspection:** The rendered NO_LOOKUP_CANDIDATE message says that casting
the streaming-side expression to the lookup column's type keeps the join's
meaning only when every streaming-side value is exactly representable in that
type.
- **Compatibility:** The existing NO_LOOKUP_CANDIDATE checks still pass with
the same condition and parameters, and the error-condition catalog stays well
formed and sorted.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.SparkException
+import org.apache.spark.sql.AnalysisException
+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, Expression,
+ Literal}
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.{FullOuter, 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,
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
+
+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) }
+
+ 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")
+ val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)", "VARCHAR(3)",
+ "STRING COLLATE UTF8_LCASE", "STRING COLLATE UNICODE", "STRING COLLATE
UTF8_BINARY_RTRIM",
+ "STRUCT<a: INT>", "ARRAY<INT>", "INTERVAL DAY TO SECOND")
+ for ((codeType, offered) <- offeredTypes.map(_ -> true) ++
notOfferedTypes.map(_ -> false)) {
+ 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)))
+ val expected = if (offered) Seq("id = ?", "code = ?") else Seq("id = ?")
+ assert(offeredCandidates === expected, codeType)
+ // The connector selects only `id = ?`, so Spark evaluates the code
equality either way.
+ assert(prepared.residualCondition === Some(codesEqual), codeType)
+ }
+
+ // Without another candidate, the join cannot run.
+ Seq("DOUBLE", "STRING COLLATE UTF8_LCASE").foreach { codeType =>
+ val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code
$codeType"))
+ val lookupCode = lookup.output(1)
+ val streamCode = AttributeReference("streamCode", lookupCode.dataType)()
+ checkError(
+ exception = prepareError(lookupJoin(lookup, streamCode === lookupCode,
+ left = LocalRelation(Seq(streamCode), isStreaming = true))),
+ condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+ parameters = Map("table" -> QUOTED_TABLE_NAME))
+ }
+ }
+
+ test("the residual evaluates key equalities and conjuncts that cannot fail
first") {
+ val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label
STRING, value STRING"))
+ val Seq(lookupId, lookupLabel, lookupValue) = lookup.output
+ val Seq(streamId, streamLabel) = stream.output
+ // A cast can fail, so it runs after the equality and the comparison
written after it, which
+ // keep their written order. The connector selects only `id = ?`.
+ val mayFail = streamLabel.cast(IntegerType) > 0
+ val conjuncts =
+ Seq(lookupId === streamId, mayFail, streamLabel === lookupLabel,
lookupValue > "a")
+ val prepared = prepare(lookupJoin(lookup, conjuncts.reduce(_ && _)))
+ assert(prepared.residualCondition ===
+ Some(streamLabel === lookupLabel && lookupValue > "a" && mayFail))
+ }
+
+ test("selected predicates bind in the connector's order, and the residual in
written order") {
+ val Seq(streamId, streamLabel) = stream.output
+ def prepared(select: Array[Predicate] => Array[Predicate])
+ : (PreparedExternalLookupJoin, Seq[Attribute], Seq[Expression]) = {
+ val lookup = lookupRelation(
+ PlanningExternalLookupTable("id INT, label STRING, value STRING",
select = select))
Review Comment:
**Nit (P3):** This is the suite's only LeftOuter preparation, and its table
is all nullable, so `reversed.output === joinOutput` holds whether or not
`PreparedExternalLookupJoin.output` widens the lookup columns. With a NOT NULL
lookup column, losing the widening would make the node declare that column NOT
NULL although it is null for unmatched stream rows. Three more parts of
preparation have no failing test either:
- `PreparedExternalLookupJoin.references` excludes the lookup attributes
that the node produces and keeps the residual's stream-side columns. Nothing
asserts it or `missingInput`, so dropping `.intersect(child.outputSet)` would
leave lookup attributes dangling, and dropping the residual term would let a
later `ColumnPruning` remove stream columns that the residual reads.
- Its `stringArgs` keeps the scan and the reader factory out of the logical
plan string. No test renders the node, and the redaction tests that SPARK-60690
adds are for the physical node.
- `PrepareExternalLookupJoin` passes `selectLookupPredicates` a copy of the
offered array. Every selection function here returns a new array, so removing
`.clone()` keeps the suite green, although a connector that reorders its input
in place would then have each parameter bound to another predicate's value.
A LeftOuter case over NOT NULL lookup columns, an assertion on `references`
and `missingInput`, a rendering check with a scan that has a distinctive
`toString`, and a selector that reorders its input in place before returning a
subset would cover all four with the existing stub.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59909#discussion_r4418015194).
**Verification:**
- **Regression:** Dropping the LeftOuter nullability widening from the
prepared node's output fails a test.
- **Regression:** Dropping either the child-output intersection or the
residual term from the prepared node's references fails a test.
- **Regression:** Removing the prepared node's plan-string override fails a
test because the scan appears in the rendered plan.
- **Regression:** Removing the copy of the offered array before the
connector call makes the in-place reordering case bind parameters to the wrong
predicates and fail.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,116 @@
+/*
+ * 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.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 Lookup-side attributes still required above
this join. They are
Review Comment:
**Nit (P3):** `FormExternalLookupJoin` always sets this field to the whole
`join.right.output`, and nothing narrows it. The second sentence holds only
because the list is complete: `ColumnPruning`'s Project case already adds the
parent's references to the required set, so a list narrowed to the attributes
required above the join would add nothing to it, and `ColumnPruning` would put
a Project over the lookup relation. `PrepareExternalLookupJoin` would then fail
with `LOOKUP_PLAN`. Together with the TODO in `PrepareExternalLookupJoin` to
prune lookup output, the first sentence invites exactly that change. Saying
that the field lists every lookup attribute, so that column pruning never
projects the lookup relation that preparation needs directly under the join,
would keep the comment true.
**Verification:**
- **Inspection:** The field's documentation matches what the conversion rule
passes, the whole lookup output, and names the column-pruning property that
preparation relies on.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.SparkException
+import org.apache.spark.sql.AnalysisException
+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, Expression,
+ Literal}
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.{FullOuter, 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,
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
+
+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) }
+
+ 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")
+ val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)", "VARCHAR(3)",
+ "STRING COLLATE UTF8_LCASE", "STRING COLLATE UNICODE", "STRING COLLATE
UTF8_BINARY_RTRIM",
+ "STRUCT<a: INT>", "ARRAY<INT>", "INTERVAL DAY TO SECOND")
+ for ((codeType, offered) <- offeredTypes.map(_ -> true) ++
notOfferedTypes.map(_ -> false)) {
+ 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)))
+ val expected = if (offered) Seq("id = ?", "code = ?") else Seq("id = ?")
+ assert(offeredCandidates === expected, codeType)
+ // The connector selects only `id = ?`, so Spark evaluates the code
equality either way.
+ assert(prepared.residualCondition === Some(codesEqual), codeType)
+ }
+
+ // Without another candidate, the join cannot run.
+ Seq("DOUBLE", "STRING COLLATE UTF8_LCASE").foreach { codeType =>
+ val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code
$codeType"))
+ val lookupCode = lookup.output(1)
+ val streamCode = AttributeReference("streamCode", lookupCode.dataType)()
+ checkError(
+ exception = prepareError(lookupJoin(lookup, streamCode === lookupCode,
+ left = LocalRelation(Seq(streamCode), isStreaming = true))),
+ condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+ parameters = Map("table" -> QUOTED_TABLE_NAME))
+ }
+ }
+
+ test("the residual evaluates key equalities and conjuncts that cannot fail
first") {
+ val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label
STRING, value STRING"))
+ val Seq(lookupId, lookupLabel, lookupValue) = lookup.output
+ val Seq(streamId, streamLabel) = stream.output
+ // A cast can fail, so it runs after the equality and the comparison
written after it, which
+ // keep their written order. The connector selects only `id = ?`.
+ val mayFail = streamLabel.cast(IntegerType) > 0
+ val conjuncts =
+ Seq(lookupId === streamId, mayFail, streamLabel === lookupLabel,
lookupValue > "a")
Review Comment:
**Nit (P3):** `streamLabel === lookupLabel` compares two bare columns, and
`ExprUtils.canEvaluateUnconditionally` accepts any comparison of columns, so it
goes first whether or not `isJoinKeyEquality` recognizes it. The same holds for
every residual equality in the binding test below. Making `isJoinKeyEquality`
always return false, or dropping its `EqualNullSafe` case, keeps both tests
green, and no test has a `<=>` conjunct or a key equality that can fail. The
key-first order this test is named for therefore has no failure signal: a key
equality such as `t.code = CAST(s.label AS INT)` could end up after a fallible
conjunct written before it, instead of first, the way a hash join evaluates its
keys. A case whose fallible non-key conjunct comes before an `=` and a `<=>`
that each compare a lookup column with a cast of a stream column would pin both
branches. The equalities need the cast because the cannot-fail check already
puts a `<=>` between bare columns first.
**Verification:**
- **Regression:** For a condition whose fallible non-key conjunct is written
before a fallible `=` equality and a fallible `<=>` equality between the sides,
with the connector selecting another predicate, the residual places both
equalities ahead of the non-key conjunct. Making the key-equality rule always
false fails the assertion, and so does dropping its `<=>` case.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.SparkException
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.QueryTest
+import org.apache.spark.sql.catalyst.analysis.ResolveExternalLookupJoin
+import org.apache.spark.sql.catalyst.expressions.{And, AttributeReference,
EqualTo, Literal}
+import org.apache.spark.sql.catalyst.plans.{FullOuter, Inner, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{Join, JoinHint,
LocalRelation,
+ 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,
ExternalLookupReaderFactory, Scan,
+ ScanBuilder, SupportsExternalLookup}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation,
+ PrepareExternalLookupJoin}
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{IntegerType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+class PrepareExternalLookupJoinSuite extends QueryTest with SharedSparkSession
{
+
+ test("a lookup-only relation that no lookup join reads is rejected") {
+ val left = LocalRelation(Seq(AttributeReference("id", IntegerType)()),
isStreaming = true)
+ val relation = DataSourceV2Relation.create(
+ PlanningExternalLookupTable, None, None, CaseInsensitiveStringMap.empty)
+ val lookupJoin = ResolveExternalLookupJoin(Join(
+ left, relation, Inner, Some(EqualTo(left.output.head,
relation.output.head)), JoinHint.NONE))
+
+
assert(PrepareExternalLookupJoin(lookupJoin).isInstanceOf[PreparedExternalLookupJoin])
+ checkError(
+ exception = intercept[AnalysisException] {
+ PrepareExternalLookupJoin(Project(relation.output, relation))
+ },
+ condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+ parameters = Map(
+ "tableName" -> "`PlanningExternalLookupTable`",
+ "operation" -> "batch scan"))
+ }
+
+ test("PrepareExternalLookupJoin binds the selected predicates and keeps the
rest as residual") {
+ val left = LocalRelation(Seq(AttributeReference("id", IntegerType)()),
isStreaming = true)
+ val relation = DataSourceV2Relation.create(
+ PlanningExternalLookupTable, None, None, CaseInsensitiveStringMap.empty)
+ val Seq(id, value) = relation.output
+ // Offered to the connector as `value = ?`, but not selected.
+ val unselected = EqualTo(value, Literal("a"))
+ val join = Join(left, relation, LeftOuter,
Some(And(EqualTo(left.output.head, id), unselected)),
+ JoinHint.NONE)
+
+ val prepared = PrepareExternalLookupJoin(ResolveExternalLookupJoin(join))
+ prepared match {
+ case lookup: PreparedExternalLookupJoin =>
+ assert(lookup.lookupParameters === left.output)
+ assert(lookup.residualCondition === Some(unselected))
+ assert(lookup.output === join.output)
+ checkError(
+ exception = intercept[SparkException] { lookup.copy(joinType =
FullOuter).output },
+ condition = "INTERNAL_ERROR",
+ parameters = Map("message" -> "Unexpected external lookup join type
FullOuter"))
+ case other => fail(s"Expected a prepared external lookup join: $other")
+ }
+ assert(PrepareExternalLookupJoin(prepared) === prepared)
+ }
+
+ test("a join without a condition over a lookup-only table fails on the final
plan") {
+ val left = LocalRelation(Seq(AttributeReference("id", IntegerType)()),
isStreaming = true)
+ val relation = DataSourceV2Relation.create(
+ PlanningExternalLookupTable, None, None, CaseInsensitiveStringMap.empty)
+ // Analysis keeps such a join, because the Dataset API analyzes a USING
join first as one.
+ checkError(
+ exception = intercept[AnalysisException] {
+ PrepareExternalLookupJoin(ResolveExternalLookupJoin(
+ Join(left, relation, Inner, None, JoinHint.NONE)))
+ },
+ condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+ parameters = Map.empty)
+ }
+}
+
+/** A lookup-only table that the planning rules can prepare. It is never read.
*/
+object PlanningExternalLookupTable extends Table with SupportsRead {
Review Comment:
Thanks, the configurable stub now covers most of this list, and keeping the
connector-contract error tests in SPARK-60690's end-to-end suite is fine for
those errors. Two of the remaining gaps are worth closing here: a connector
that reorders the candidate array in place, which is what the defensive copy
guards against, and the logical node's plan string, which the redaction tests
for the physical node in SPARK-60690 do not cover. This review raises both in a
test-coverage finding, together with two other properties of the prepared node
that no test checks.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4418015194","thread_id":"inline:4418015194","verdict_sha256":"73b63704768a20dd221590770ad50b2e0d9c8075f888a900bc00161b8e28f9e1"}
-->
--
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]