This is an automated email from the ASF dual-hosted git repository.
HeartSaVioR pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 43744f5c5b91 [SPARK-60689][SS][SQL] Add the planning rules for
external lookup join
43744f5c5b91 is described below
commit 43744f5c5b918ffda501e3c964104f74f7b13b18
Author: Jungtaek Lim <[email protected]>
AuthorDate: Thu Nov 12 11:14:30 2026 +0900
[SPARK-60689][SS][SQL] Add the planning rules for external lookup join
### What changes were proposed in this pull request?
This PR adds the planning pieces of an external lookup join: a
stream-static join whose right side is a table that the connector serves by key
lookups. Nothing registers the new rules yet, so no query changes. SPARK-60690
registers them and runs the joins.
This PR implements
[SPARK-60689](https://issues.apache.org/jira/browse/SPARK-60689), part of
[SPARK-60031](https://issues.apache.org/jira/browse/SPARK-60031) (SPIP:
External Lookup Join; see the
[SPIP](https://docs.google.com/document/d/1fBPM5cku8UJXacG2fw9df1zqALJ-WFm8E9-b9oiFP5M/edit?tab=t.0)
and the [dev
discussion](https://lists.apache.org/thread/7s6tgy9cm18jnzykr8htrtrw4nxyrhp1)).
**Design and decisions.** The [design
document](https://gist.github.com/HeartSaVioR/0143cdaad3079d1455be8004ee401ec4)
explains the whole feature and the decisions behind it, including those agreed
in the SPIP discussion. Read it first for the whole picture, before the details
of this PR.
**Scope.** This PR is one of seven stacked PRs for external lookup join.
The connector API, #59908, is already merged. Please review only this PR's own
commits, listed in its first comment. The commits of the PRs it builds on are
reviewed there.
| PR | What it delivers |
|---|---|
| **#59909 (this PR)** | **Planning rules. They are not registered yet, so
no query changes.** |
| #59910 | Execution: stream-static equi-joins on lookup-only tables loaded
with `spark.read`; Spark's check of returned rows and values; the reader
lifecycle |
| #60019 | The `EXTERNAL_LOOKUP` hint; lookup sides reached through
aliases, temp views of DataFrames, SQL and catalog references |
| #60055 | Lookup-side projections and filters; semi and anti joins; `<=>`
and range comparisons; CHAR columns |
| #60087 | The lookup cache |
| #60198 | Predicate pushdown through lookup joins |
| #60313 | Real-time mode |
The connector API Javadoc describes the whole feature. Some of its promises
are kept only by the later PRs in this table.
- **Logical nodes.** `ExternalLookupRelation` stands for a lookup-only
table, one that supports `EXTERNAL_LOOKUP` but not `BATCH_READ`.
`ExternalLookupJoin` is the lookup join. `PreparedExternalLookupJoin` is the
join after Spark has agreed on the lookup with the connector.
- **Forming the join.** The analyzed plan keeps an ordinary `Join`.
`FormExternalLookupJoin` turns an eligible join into an `ExternalLookupJoin` at
the start of optimization. `CheckExternalLookupJoin` applies the same test at
analysis, so most ineligible joins fail with their reason when the DataFrame is
built. For a streaming write, it also rejects a join without a condition, so
`start()` throws that error. Eligible means a streaming left side, a
lookup-only table directly on the rig [...]
- **Agreeing on the lookup.** `PrepareExternalLookupJoin` offers each
`lookupColumn = <stream-side expression>` conjunct to the connector as a
possible lookup key. The connector selects the ones it can use. Spark evaluates
the rest of the condition on the joined rows, with equalities and conditions
that cannot fail first, as a hash join checks its keys first. From SPARK-60690,
Spark also evaluates the selected ones itself, on every row the connector
returns. The rule also validates wh [...]
- **Connector API Javadoc.** This PR also updates the connector API
Javadoc. It says which types Spark offers as lookup keys, that Spark checks the
selected predicates on every returned row (from #59910), that the read schema's
nullability may differ from the table's, at any nested level, when parameter
rows count as distinct, and that parameter rows are read-only.
Worth a reviewer's attention:
- **Lookup keys only on types with reliable equality.** A store's equality
can differ from Spark's, for example for NaN and `-0.0`, or for case and accent
rules. So Spark offers a comparison only on integral types, boolean, decimal,
date, timestamps, binary, and strings with the default binary collation. CHAR
columns are not offered, because a store may pad or compare them differently.
VARCHAR columns are offered, except under
`spark.sql.charVarchar.standardSemantics.enabled`. There, [...]
- A join strategy hint that attaches to a lookup join fails the query. A
lookup join cannot honor a physical strategy, and Spark does not silently drop
a hint the user wrote.
- Joins over tables that also support `BATCH_READ` are unchanged. So is a
join whose lookup-only table is not its direct right child: it still fails as a
plain scan.
New error conditions: `EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.*` for joins that
cannot run as lookup joins, and `DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.*` for
connectors that break the contract.
### Why are the changes needed?
A lookup join needs planning that other joins do not have. Spark must
decide which joins read a lookup-only table, and agree with the connector on
which conditions become lookup keys.
### Does this PR introduce _any_ user-facing change?
No. The rules are not registered yet.
### How was this patch tested?
New plan tests: `FormExternalLookupJoinSuite` (catalyst) covers eligibility
and its errors, and `PrepareExternalLookupJoinSuite` covers the negotiation and
the connector contract. They pass on JDK 21 at the top of the PR stack, which
includes this PR.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.
Closes #59909 from HeartSaVioR/SPARK-60689-external-lookup-planning-rules.
Authored-by: Jungtaek Lim <[email protected]>
Signed-off-by: Jungtaek Lim <[email protected]>
---
.../src/main/resources/error/error-conditions.json | 101 ++++
.../sql/connector/read/ExternalLookupReader.java | 4 +-
.../spark/sql/connector/read/LookupParameter.java | 3 +-
.../org/apache/spark/sql/connector/read/Scan.java | 11 +-
.../sql/connector/read/SupportsExternalLookup.java | 16 +-
.../catalyst/analysis/FormExternalLookupJoin.scala | 177 +++++++
.../plans/logical/ExternalLookupJoin.scala | 151 ++++++
.../spark/sql/catalyst/trees/TreePatterns.scala | 2 +
.../spark/sql/errors/QueryCompilationErrors.scala | 17 +
.../datasources/v2/DataSourceV2Relation.scala | 66 ++-
.../analysis/FormExternalLookupJoinSuite.scala | 222 +++++++++
.../datasources/v2/PrepareExternalLookupJoin.scala | 256 +++++++++++
.../connector/PrepareExternalLookupJoinSuite.scala | 510 +++++++++++++++++++++
13 files changed, 1524 insertions(+), 12 deletions(-)
diff --git a/common/utils/src/main/resources/error/error-conditions.json
b/common/utils/src/main/resources/error/error-conditions.json
index 752f58c13387..1af714b28e35 100644
--- a/common/utils/src/main/resources/error/error-conditions.json
+++ b/common/utils/src/main/resources/error/error-conditions.json
@@ -2388,6 +2388,49 @@
],
"sqlState" : "0A000"
},
+ "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP" : {
+ "message" : [
+ "Data source table <table> violates the external lookup contract:"
+ ],
+ "subClass" : {
+ "DUPLICATE_SCAN_FIELD" : {
+ "message" : [
+ "The lookup scan returned the field <field> more than once."
+ ]
+ },
+ "DUPLICATE_SELECTED_PREDICATE" : {
+ "message" : [
+ "`selectLookupPredicates()` returned the predicate <predicate> more
than once."
+ ]
+ },
+ "MISSING_SCAN_FIELD" : {
+ "message" : [
+ "The lookup scan did not return the table column <field>, which the
join requires."
+ ]
+ },
+ "NON_POSITIVE_MAX_PARAMETER_ROWS" : {
+ "message" : [
+ "`maxParameterRowsPerRequest()` returned <value>, but it must be
positive."
+ ]
+ },
+ "NULL_RESULT" : {
+ "message" : [
+ "`<method>` returned null."
+ ]
+ },
+ "UNKNOWN_SCAN_FIELD" : {
+ "message" : [
+ "The lookup scan returned the field <field>, which matches no table
column by name and data type."
+ ]
+ },
+ "UNOFFERED_SELECTED_PREDICATE" : {
+ "message" : [
+ "`selectLookupPredicates()` returned the predicate <predicate>,
which is not one of the candidate instances offered by Spark."
+ ]
+ }
+ },
+ "sqlState" : "KD000"
+ },
"DATA_SOURCE_INVALID_RUNTIME_FILTER_ATTRIBUTE" : {
"message" : [
"The runtime filter attribute <attribute> reported by `<method>` in data
source scan <scanClass> is invalid for the scan relation output
<relationOutput>."
@@ -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>. A lookup predicate is an equality `=` between a lookup column,
with no cast or other expression applied to it, and an expression over the
streaming side. The lookup column must have a type that stores compare as Spark
does; the Javadoc of `SupportsExternalLookup.selectLookupPredicates()` lists
these types. Instead of casting the lookup column, cast the streaming-side
expression to its type, if ev [...]
+ ]
+ },
+ "NO_LOOKUP_PREDICATE" : {
+ "message" : [
+ "The data source of table <table> did not select any of the lookup
predicates that Spark offered from the join condition."
+ ]
+ },
+ "SCAN_BUILDER" : {
+ "message" : [
+ "The scan builder of table <table> does not implement
`SupportsExternalLookup`."
+ ]
+ },
+ "STATIC_LEFT_SIDE" : {
+ "message" : [
+ "An external lookup join must be a stream-static join, but the left
side of the join over <relation> is not a streaming query."
+ ]
+ },
+ "TABLE" : {
+ "message" : [
+ "Table <table> does not support external lookup."
+ ]
+ }
+ },
+ "sqlState" : "0A000"
+ },
"FAILED_CREATE_CHECKPOINT_DIRECTORY" : {
"message" : [
"Failed to create the checkpoint directory <path> as FileSystem.mkdirs
returned false."
diff --git
a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/ExternalLookupReader.java
b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/ExternalLookupReader.java
index 8c0c05b2139b..fdb35ee027a9 100644
---
a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/ExternalLookupReader.java
+++
b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/ExternalLookupReader.java
@@ -54,8 +54,8 @@ public interface ExternalLookupReader extends Closeable {
* {@link ExternalLookup#maxParameterRowsPerRequest()} rows, none of them
null. Field {@code i}
* of each row is the value for the {@code i}-th selected predicate, in
Spark's internal
* representation.
- * Rows are distinct under Spark SQL equality (NaN equals NaN, {@code -0.0}
equals {@code 0.0},
- * strings compare by collation). Only {@code <=>} parameters may be null at
the top level.
+ * No two rows are equal; a null {@code <=>} parameter equals a null. Only
{@code <=>} parameters
+ * may be null at the top level.
* <p>
* The cursor must be non-null. Each row's results must be complete and
depend only on the row;
* Spark may reuse them for equal rows. The input is read-only and must not
be kept after the
diff --git
a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/LookupParameter.java
b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/LookupParameter.java
index cc839335e8b8..c116470aa347 100644
---
a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/LookupParameter.java
+++
b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/LookupParameter.java
@@ -28,7 +28,8 @@ import org.apache.spark.sql.types.DataType;
* {@code tenant = ?}; its values arrive in {@link
ExternalLookupReader#lookupBatch}. Each
* candidate has exactly one instance of its own, and equality is identity, so
same-shaped
* candidates are distinct. Instances are serializable, so a connector may
keep selected
- * predicates in its {@link ExternalLookupReaderFactory}.
+ * predicates in its {@link ExternalLookupReaderFactory}. Parameter rows are
read-only: the
+ * connector must not modify them.
*
* @since 4.4.0
*/
diff --git
a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/Scan.java
b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/Scan.java
index 3b0225726809..adf284e3b77f 100644
--- a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/Scan.java
+++ b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/Scan.java
@@ -86,10 +86,13 @@ public interface Scan {
* {@code DATA_SOURCE_EXTERNAL_LOOKUP_NOT_SUPPORTED}; data sources must
override it if the table
* reports {@link TableCapability#EXTERNAL_LOOKUP}. Spark calls it at most
once, on the driver.
* {@link #readSchema()} describes the returned value rows and must list
only top-level table
- * columns, each at most once, with the table's name and data type; its
nullability may be
- * weaker than the table's. The columns may be in any order. They must
include every column
- * passed to {@link SupportsPushDownRequiredColumns#pruneColumns}, or every
table column if the
- * builder was not pruned.
+ * columns, each at most once, with the table's name and data type; its
nullability may differ
+ * from the table's, at any nested level. Returned values must satisfy both,
nested values
+ * included: a field, array element or map value that the table or the read
schema declares NOT
+ * NULL, and any map key, must never hold a null, or the task fails. The
columns may be in any
+ * order.
+ * They must include every column passed to {@link
SupportsPushDownRequiredColumns#pruneColumns},
+ * or every table column if the builder was not pruned.
*
* @throws UnsupportedOperationException
* @since 4.4.0
diff --git
a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsExternalLookup.java
b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsExternalLookup.java
index 178ea2cc3ccb..b2f5f747193a 100644
---
a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsExternalLookup.java
+++
b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsExternalLookup.java
@@ -35,12 +35,17 @@ public interface SupportsExternalLookup extends ScanBuilder
{
* lookup-side {@link NamedReference} with a {@link LookupParameter}; the
array is never empty. In
* every offered comparison the reference is {@code children()[0]} and the
parameter is
* {@code children()[1]}: when the query writes the lookup column on the
right, Spark flips the
- * operator, so {@code s.ts < t.event_time} is offered as {@code event_time
> ?}. For example:
+ * operator, so {@code s.ts < t.event_time} is offered as {@code event_time
> ?}. Spark offers
+ * {@code =} and {@code <=>} only on a lookup column of an integral type,
BOOLEAN, DECIMAL, DATE,
+ * TIMESTAMP, TIMESTAMP_NTZ, BINARY, or a STRING or VARCHAR whose collation
compares bytes, such
+ * as UTF8_BINARY. It offers no comparison on VARCHAR under
+ * {@code spark.sql.charVarchar.standardSemantics.enabled}, and never one on
FLOAT, DOUBLE, CHAR,
+ * a string with another collation, a complex type or any other type. For
example:
* <pre>{@code
* candidates: [tenant = ?, event_time >= ?, event_time < ?, region = ?]
* returned: [event_time >= ?, tenant = ?]
* => each parameter row is (event_time lower bound, tenant);
- * Spark itself evaluates event_time < ? and region = ?
+ * event_time < ? and region = ? stay in Spark's join condition
* }</pre>
* <ul>
* <li>The result must be non-null and hold offered instances, unchanged,
without nulls or
@@ -48,8 +53,11 @@ public interface SupportsExternalLookup extends ScanBuilder {
* <li>Each offered predicate has exactly one {@link LookupParameter}, so
field {@code i} of
* every parameter row is the value for the {@code i}-th returned
predicate. A field may
* appear in several predicates, as range bounds do.</li>
- * <li>Each selected predicate must hold with Spark semantics, and results
must be complete
- * for their conjunction. Unsupported names or shapes must not be
selected.</li>
+ * <li>Spark evaluates every selected predicate again on each returned row
and drops a row
+ * that fails it, so extra rows do no harm. Spark cannot recover a missing
row: for each
+ * parameter row, the source must return every row that satisfies all
selected predicates under
+ * Spark semantics. Do not select a predicate that the source cannot
evaluate that way, and do
+ * not select unsupported names or shapes.</li>
* <li>An empty result means no access path fits; the query then
fails.</li>
* <li>The input array and its elements are read-only.</li>
* </ul>
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala
new file mode 100644
index 000000000000..3a9881c38beb
--- /dev/null
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala
@@ -0,0 +1,177 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.optimizer.EliminateResolvedHint
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join,
JoinStrategyHint,
+ LogicalPlan, ResolvedHint}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.streaming.WriteToStream
+import org.apache.spark.sql.catalyst.trees.TreePattern.JOIN
+import org.apache.spark.sql.connector.catalog.Table
+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. 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-only
+ * table is on the right side.
+ */
+object ExternalLookupJoinEligibility extends QueryErrorsBase {
+ sealed trait Eligibility
+ /**
+ * The join stays an ordinary join: the classifier recognizes no lookup-only
relation as either
+ * of its sides. A lookup-only relation under another operator, such as a
projection or an
+ * alias, is not recognized yet, 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 reads a lookup-only table, with a supported join type, but has
no condition. */
+ case object MissingCondition extends Eligibility
+ /** The join reads a lookup-only table, which no other join can read, but
cannot run. */
+ case class Ineligible(error: Throwable) extends Eligibility
+
+ private val SUPPORTED_JOIN_TYPES = Seq(Inner, LeftOuter)
+
+ def apply(join: Join): Eligibility = {
+ // The lookup-only table must be on the right side; the sides are never
swapped.
+ // TODO: look through projections, filters and aliases above the lookup
relation.
+ // TODO: allow the EXTERNAL_LOOKUP hint once it is introduced, and
classify the joins it opts
+ // in.
+ (ExternalLookupRelations.lookupOnlyTable(join.left),
lookupOnlyTableOnRight(join)) match {
+ case (Some(table), _) => ineligible("LOOKUP_TABLE_ON_LEFT", table)
+ case (None, Some(table)) => lookupJoinEligibility(join, table)
+ case (None, None) => NotLookupJoin
+ }
+ }
+
+ /**
+ * The lookup-only table on the join's right side, also under a strategy
hint, which is where a
+ * broadcast hint usually goes in a stream-static join. The hint is then
reported as conflicting.
+ */
+ private def lookupOnlyTableOnRight(join: Join): Option[Table] = {
+ def underStrategyHints(plan: LogicalPlan): LogicalPlan = plan match {
+ case ResolvedHint(child, hint) if hint.strategy.isDefined =>
underStrategyHints(child)
+ case other => other
+ }
+ ExternalLookupRelations.lookupOnlyTable(underStrategyHints(join.right))
+ }
+
+ private def lookupJoinEligibility(join: Join, table: Table): Eligibility = {
+ if (!join.left.isStreaming) return ineligible("STATIC_LEFT_SIDE", table)
+ // 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.
+ joinStrategyHint(join) match {
+ case Some(strategy) =>
+ ineligible("CONFLICTING_JOIN_STRATEGY", table,
+ Map("strategy" -> toSQLStmt(strategy.displayName)))
+ // 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", table, Map(
+ "joinType" -> toSQLStmt(join.joinType.sql),
+ "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES.map(t =>
toSQLStmt(t.sql)).mkString(", ")))
+ case None if join.condition.isEmpty => MissingCondition
+ case None => Eligible
+ }
+ }
+
+ private def ineligible(
+ subClass: String,
+ table: Table,
+ parameters: Map[String, String] = Map.empty): Ineligible =
+ Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+ subClass, parameters + ("relation" -> toSQLId(table.name()))))
+
+ 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 over a lookup-only table
cannot run as an
+ * external lookup join. 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 reported only for the query of a streaming
write, which is analyzed
+ * in full when the query starts, so that `start()` throws it. Other plans can
still get their
+ * condition: 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 = {
+ if (plan.containsPattern(JOIN)) {
+ val complete = plan.isInstanceOf[WriteToStream]
+ plan.foreachUp {
+ case join: Join if join.resolved =>
+ ExternalLookupJoinEligibility(join) match {
+ case ExternalLookupJoinEligibility.Ineligible(error) => throw error
+ case ExternalLookupJoinEligibility.MissingCondition if complete =>
+ throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+ "MISSING_JOIN_CONDITION")
+ case _ =>
+ }
+ case _ =>
+ }
+ }
+ }
+}
+
+/**
+ * Replaces each join that runs as an external lookup join with an
[[ExternalLookupJoin]].
+ *
+ * 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 =
+ plan.transformUpWithPruning(_.containsPattern(JOIN)) {
+ case join: Join =>
+ ExternalLookupJoinEligibility(join) match {
+ case Eligible =>
+ ExternalLookupJoin(
+ join.left,
+ join.right,
+ join.joinType,
+ join.condition,
+ join.right.output)
+ // Operator optimization could push a filter's predicate into the
join later, but the
+ // condition must be written in the join.
+ case MissingCondition =>
+ throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+ "MISSING_JOIN_CONDITION")
+ case Ineligible(error) => throw error
+ case NotLookupJoin => join
+ }
+ }
+}
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala
new file mode 100644
index 000000000000..cf4762a2d7e1
--- /dev/null
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala
@@ -0,0 +1,151 @@
+/*
+ * 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, AttributeSeq,
AttributeSet,
+ Expression}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter,
QueryPlan}
+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)
+
+ // The lookup-side attributes are not in the child's output, so the default
canonicalization
+ // gives each top-level one the next id, whichever column it is: two joins
that keep different
+ // lookup columns of one type would canonicalize alike. Each is normalized
by its place in the
+ // child's output and the read schema instead.
+ override protected def doCanonicalize(): LogicalPlan = {
+ val attributes: AttributeSeq = child.output ++ lookupInput
+ def normalize[T <: Expression](expression: T): T =
+ QueryPlan.normalizeExpressions(expression, attributes)
+ copy(
+ child = child.canonicalized,
+ lookupInput = lookupInput.map(normalize),
+ lookupOutput = lookupOutput.map(normalize),
+ lookupParameters = lookupParameters.map(normalize),
+ residualCondition = residualCondition.map(normalize))
+ }
+
+ // Connector descriptions may contain secrets, so the scan and the reader
factory are not shown.
+ // The physical node renders the scan's redacted description, and nothing of
the reader factory.
+ 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. Spark then
reads a value within the
+ * declared length unchanged, but 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 that Spark's equality matches.
+ *
+ * Analysis reads a CHAR or VARCHAR column as a STRING and keeps its
declared type in the
+ * metadata, so the column's data type alone does not tell.
+ */
+ def supportsEquality(column: Attribute): Boolean =
+
supportsEquality(CharVarcharUtils.getRawType(column.metadata).getOrElse(column.dataType))
+
+ private def supportsEquality(dataType: DataType): Boolean = dataType match {
+ case ByteType | ShortType | IntegerType | LongType | BooleanType |
DateType | TimestampType |
+ TimestampNTZType | BinaryType | _: DecimalType => true
+ case _: CharType => false
+ case varchar: VarcharType =>
+ !SQLConf.get.charVarcharStandardSemantics &&
varchar.supportsBinaryEquality
+ case stringType: StringType => stringType.supportsBinaryEquality
+ case _ => false
+ }
+}
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/trees/TreePatterns.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/trees/TreePatterns.scala
index c75b63569ade..a30657f25c52 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/trees/TreePatterns.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/trees/TreePatterns.scala
@@ -162,6 +162,7 @@ object TreePattern extends Enumeration {
val EVENT_TIME_WATERMARK: Value = Value
val EXCEPT: Value = Value
val EXECUTE_IMMEDIATE: Value = Value
+ val EXTERNAL_LOOKUP_JOIN: Value = Value
val INTERSECT: Value = Value
val FILTER: Value = Value
val GENERATE: Value = Value
@@ -173,6 +174,7 @@ object TreePattern extends Enumeration {
val LIMIT: Value = Value
val LOCAL_RELATION: Value = Value
val LOGICAL_QUERY_STAGE: Value = Value
+ val LOOKUP_ONLY_RELATION: Value = Value
val MERGE_INTO_TABLE: Value = Value
val METRIC_VIEW_PLACEHOLDER: Value = Value
val NATURAL_LIKE_JOIN: Value = Value
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala
index 4ba31b4ace47..81732e70defb 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala
@@ -4836,6 +4836,23 @@ private[sql] object QueryCompilationErrors extends
QueryErrorsBase with Compilat
cause = cause)
}
+ def unsupportedExternalLookupJoinError(
+ errorSubClass: String,
+ messageParameters: Map[String, String] = Map.empty): Throwable = {
+ new AnalysisException(
+ errorClass = s"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.$errorSubClass",
+ messageParameters = messageParameters)
+ }
+
+ def invalidDataSourceExternalLookupError(
+ table: String,
+ errorSubClass: String,
+ messageParameters: Map[String, String] = Map.empty): Throwable = {
+ new AnalysisException(
+ errorClass = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$errorSubClass",
+ messageParameters = Map("table" -> toSQLId(table)) ++ messageParameters)
+ }
+
def foundMultipleXMLDataSourceError(provider: String,
sourceNames: Seq[String],
externalSource: String): Throwable = {
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Relation.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Relation.scala
index 89f24bdc2030..732e4e41256f 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Relation.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Relation.scala
@@ -27,7 +27,7 @@ import org.apache.spark.sql.catalyst.plans.QueryPlan
import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat,
ExposesMetadataColumns, Histogram, HistogramBin, LeafNode, LogicalPlan,
Statistics}
import
org.apache.spark.sql.catalyst.plans.logical.statsEstimation.{EstimationUtils,
FilterEstimation}
import
org.apache.spark.sql.catalyst.streaming.{StreamingSourceIdentifyingName,
Unassigned}
-import
org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION,
DATA_SOURCE_V2_SCAN_RELATION, TreePattern}
+import
org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION,
DATA_SOURCE_V2_SCAN_RELATION, LOOKUP_ONLY_RELATION, TreePattern}
import org.apache.spark.sql.catalyst.types.DataTypeUtils.{fromAttributes,
toAttributes}
import org.apache.spark.sql.catalyst.util.{removeInternalMetadata,
truncatedString, CharVarcharUtils}
import org.apache.spark.sql.connector.catalog.{CatalogPlugin, FunctionCatalog,
Identifier, SupportsMetadataColumns, Table, TableCapability, TableCatalog,
V2TableUtil}
@@ -42,6 +42,7 @@ import
org.apache.spark.sql.internal.connector.{SupportsRuntimeCatalystFiltering
import org.apache.spark.sql.types.{DataType, StructType}
import org.apache.spark.sql.util.CaseInsensitiveStringMap
import org.apache.spark.util.Utils
+import org.apache.spark.util.collection.BitSet
/**
* A logical plan representing a data source v2 table.
@@ -151,6 +152,69 @@ case class DataSourceV2Relation(
def isVersioned: Boolean = table.version != null
override val nodePatterns: Seq[TreePattern] = Seq(DATA_SOURCE_V2_RELATION)
+
+ override protected def getDefaultTreePatternBits: BitSet =
+
ExternalLookupRelations.withLookupOnlyPattern(super.getDefaultTreePatternBits,
table)
+}
+
+/**
+ * A logical placeholder for a table that supports external lookup but not
batch scan.
+ *
+ * The placeholder lets a Dataset carry the table until an external lookup
join reads it as its
+ * lookup side. It must never be planned as an ordinary scan.
+ */
+case class ExternalLookupRelation(relation: DataSourceV2Relation)
+ extends DataSourceV2RelationBase(
+ relation.table,
+ relation.output,
+ relation.catalog,
+ relation.identifier,
+ relation.options,
+ relation.timeTravelSpec) {
+
+ def table: Table = relation.table
+
+ override def output: Seq[AttributeReference] = relation.output
+
+ override def newInstance(): ExternalLookupRelation =
+ copy(relation = relation.newInstance())
+
+ override def computeStats(): Statistics = Statistics(sizeInBytes =
conf.defaultSizeInBytes)
+
+ override val nodePatterns: Seq[TreePattern] = Seq(DATA_SOURCE_V2_RELATION)
+
+ override protected def getDefaultTreePatternBits: BitSet =
+
ExternalLookupRelations.withLookupOnlyPattern(super.getDefaultTreePatternBits,
table)
+}
+
+/** Finds the table that an external lookup join would read. */
+object ExternalLookupRelations {
+ /** The table of a DSv2 relation, including the placeholder of a lookup-only
table. */
+ def table(plan: LogicalPlan): Option[Table] = plan match {
+ case relation: DataSourceV2Relation => Some(relation.table)
+ case relation: ExternalLookupRelation => Some(relation.table)
+ case _ => None
+ }
+
+ /** Whether only an external lookup join can read the table, because it has
no batch scan. */
+ def isLookupOnly(table: Table): Boolean = {
+ val capabilities = table.capabilities()
+ capabilities.contains(TableCapability.EXTERNAL_LOOKUP) &&
+ !capabilities.contains(TableCapability.BATCH_READ)
+ }
+
+ /** The table of a relation that only an external lookup join can read. */
+ def lookupOnlyTable(plan: LogicalPlan): Option[Table] =
table(plan).filter(isLookupOnly)
+
+ /**
+ * The pattern bits `bits` of a relation of `table`, with
[[LOOKUP_ONLY_RELATION]] set when the
+ * table is lookup-only, so that a rule can tell from the bits of a plan,
without a walk, whether
+ * the plan reads such a table. A relation computes its bits once, so it
asks its table once.
+ */
+ private[v2] def withLookupOnlyPattern(bits: BitSet, table: Table): BitSet = {
+ if (isLookupOnly(table)) bits.set(LOOKUP_ONLY_RELATION.id)
+ bits
+ }
}
/**
diff --git
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoinSuite.scala
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoinSuite.scala
new file mode 100644
index 000000000000..c3809e18e94d
--- /dev/null
+++
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoinSuite.scala
@@ -0,0 +1,222 @@
+/*
+ * 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.jdk.CollectionConverters._
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.QueryPlanningTracker
+import org.apache.spark.sql.catalyst.dsl.expressions._
+import org.apache.spark.sql.catalyst.dsl.plans._
+import org.apache.spark.sql.catalyst.plans.{Cross, FullOuter, Inner,
LeftOuter, RightOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join,
JoinHint,
+ LocalRelation, LogicalPlan, Project}
+import org.apache.spark.sql.catalyst.streaming.WriteToStream
+import
org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION,
+ LOOKUP_ONLY_RELATION}
+import org.apache.spark.sql.connector.catalog.{Table, TableCapability}
+import org.apache.spark.sql.connector.catalog.TableCapability.{BATCH_READ,
EXTERNAL_LOOKUP}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation,
+ ExternalLookupRelation}
+import org.apache.spark.sql.streaming.OutputMode
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+class FormExternalLookupJoinSuite extends AnalysisTest {
+ // The stream side of a stream-static join.
+ private val stream = LocalRelation(Seq($"streamTenant".int,
$"streamId".int), isStreaming = true)
+ // A lookup-only table has no batch scan, so it reaches the join as this
placeholder.
+ private val lookupOnly = ExternalLookupRelation(tableWith(EXTERNAL_LOOKUP))
+ private val idsEqual = stream.output(1) === lookupOnly.output(1)
+
+ private def tableWith(capabilities: TableCapability*): DataSourceV2Relation =
+ DataSourceV2Relation.create(
+ LookupCapabilityTable(capabilities.toSet), None, None,
CaseInsensitiveStringMap.empty)
+
+ // An inner join of the stream with `right`, on the id column of each.
+ private def innerJoinOnId(right: LogicalPlan): Join =
+ Join(stream, right, Inner, Some(stream.output(1) === right.output(1)),
JoinHint.NONE)
+
+ // The parameters of a JOIN_TYPE error, besides the relation.
+ private def joinType(sql: String): Map[String, String] =
+ Map("joinType" -> sql, "supportedJoinTypes" -> "INNER, LEFT OUTER")
+
+ // Hints become ResolvedHint nodes, which only Finish Analysis moves into
the join.
+ private def analyze(plan: LogicalPlan): LogicalPlan =
+ getAnalyzer.executeAndCheck(plan, new QueryPlanningTracker)
+
+ test("an eligible join stays a Join in analysis and is converted when
optimization starts") {
+ val Seq(tenant, id) = stream.output
+ val compositeKey = tenant === lookupOnly.output(0) && idsEqual
+ for (condition <- Seq(idsEqual, compositeKey); joinType <- Seq(Inner,
LeftOuter)) {
+ val analyzed = analyze(stream.join(lookupOnly, joinType,
Some(condition)))
+ assert(analyzed.isInstanceOf[Join])
+ CheckExternalLookupJoin(analyzed)
+ FormExternalLookupJoin(analyzed) match {
+ case lookupJoin: ExternalLookupJoin =>
+ assert(lookupJoin.joinType == joinType && lookupJoin.condition ==
Some(condition))
+ assert(lookupJoin.requiredLookupOutput == lookupOnly.output)
+ assert(lookupJoin.output == analyzed.output)
+ assert(lookupJoin.output.drop(2).forall(_.nullable) == (joinType ==
LeftOuter))
+ assert(lookupJoin.missingInput.isEmpty)
+ assert(FormExternalLookupJoin(lookupJoin) == lookupJoin)
+ case other => fail(s"Expected an external lookup join: $other")
+ }
+ }
+ }
+
+ test("the relation of a lookup-only table carries the lookup-only pattern") {
+ Seq(lookupOnly, tableWith(EXTERNAL_LOOKUP)).foreach { relation =>
+ assert(relation.containsAllPatterns(DATA_SOURCE_V2_RELATION,
LOOKUP_ONLY_RELATION))
+ assert(innerJoinOnId(relation).containsPattern(LOOKUP_ONLY_RELATION))
+ }
+ Seq(tableWith(BATCH_READ, EXTERNAL_LOOKUP), tableWith(BATCH_READ),
tableWith()).foreach {
+ relation =>
+ assert(relation.containsPattern(DATA_SOURCE_V2_RELATION))
+ assert(relation.containsPattern(LOOKUP_ONLY_RELATION) === false)
+ assert(innerJoinOnId(relation).containsPattern(LOOKUP_ONLY_RELATION)
=== false)
+ }
+ }
+
+ test("keep ordinary joins that cannot become external lookup joins") {
+ val other = LocalRelation($"k".int, $"k2".int)
+ Seq(
+ innerJoinOnId(tableWith(BATCH_READ, EXTERNAL_LOOKUP)),
+ innerJoinOnId(tableWith(BATCH_READ)),
+ innerJoinOnId(other),
+ innerJoinOnId(Project(lookupOnly.output, lookupOnly))).foreach { join =>
+ CheckExternalLookupJoin(join)
+ assert(FormExternalLookupJoin(join) == join)
+ }
+ }
+
+ test("validation and conversion reject a lookup-only join with the same
reason") {
+ Seq(
+ // Only a stream-static join, with the lookup-only table on the right
side.
+ (stream.copy(isStreaming = false).join(lookupOnly, Inner,
Some(idsEqual)),
+ "STATIC_LEFT_SIDE", Map.empty[String, String]),
+ (lookupOnly.join(stream, Inner, Some(idsEqual)), "LOOKUP_TABLE_ON_LEFT",
+ Map.empty[String, String]),
+ (stream.join(lookupOnly, RightOuter, Some(idsEqual)), "JOIN_TYPE",
+ joinType("RIGHT OUTER")),
+ // A cross join fails with its join type, with or without a later filter.
+ (stream.join(lookupOnly, Cross), "JOIN_TYPE", joinType("CROSS")),
+ (stream.join(lookupOnly, Cross).where(idsEqual), "JOIN_TYPE",
joinType("CROSS")),
+ // No join strategy hint applies to an external lookup join; sort merge
is named MERGE.
+ (stream.hint("broadcast").join(lookupOnly, Inner, Some(idsEqual)),
+ "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "BROADCAST")),
+ (stream.hint("merge").join(lookupOnly, Inner, Some(idsEqual)),
+ "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "MERGE")),
+ (stream.hint("shuffle_hash").join(lookupOnly, Inner, Some(idsEqual)),
+ "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "SHUFFLE_HASH")),
+ (stream.hint("shuffle_replicate_nl").join(lookupOnly, Inner,
Some(idsEqual)),
+ "CONFLICTING_JOIN_STRATEGY", Map("strategy" ->
"SHUFFLE_REPLICATE_NL")),
+ // The same on the lookup side, where a broadcast hint usually goes in a
stream-static join.
+ (stream.join(lookupOnly.hint("broadcast"), Inner, Some(idsEqual)),
+ "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "BROADCAST")),
+ (stream.join(lookupOnly.hint("merge"), Inner, Some(idsEqual)),
+ "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "MERGE")),
+ (stream.join(lookupOnly.hint("shuffle_hash"), Inner, Some(idsEqual)),
+ "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "SHUFFLE_HASH")),
+ (stream.join(lookupOnly.hint("shuffle_replicate_nl"), Inner,
Some(idsEqual)),
+ "CONFLICTING_JOIN_STRATEGY", Map("strategy" ->
"SHUFFLE_REPLICATE_NL"))).foreach {
+ case (plan, subClass, parameters) =>
+ val analyzed = analyze(plan)
+ Seq[LogicalPlan => Any](CheckExternalLookupJoin,
FormExternalLookupJoin(_)).foreach {
+ rule =>
+ val error = intercept[AnalysisException] { rule(analyzed) }
+ assert(error.getCondition ==
s"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.$subClass")
+ assert(error.getMessageParameters.asScala.toMap ==
+ parameters + ("relation" -> "`LookupCapabilityTable`"))
+ }
+ }
+ }
+
+ test("a strategy hint inside a nested join on the stream side belongs to
that join") {
+ val static = LocalRelation($"k".int)
+ val nested =
+ stream.hint("broadcast").join(static, Inner, Some(stream.output(1) ===
static.output(0)))
+ val analyzed = analyze(nested.join(lookupOnly, Inner, Some(idsEqual)))
+ CheckExternalLookupJoin(analyzed)
+ assert(FormExternalLookupJoin(analyzed).isInstanceOf[ExternalLookupJoin])
+ }
+
+ test("a join without a condition passes analysis and fails when optimization
starts") {
+ // Even when a later filter holds the condition, which operator
optimization would push
+ // into the join.
+ Seq(
+ stream.join(lookupOnly),
+ stream.join(lookupOnly).where(idsEqual)).foreach { plan =>
+ val analyzed = analyze(plan)
+ // The classic Dataset API analyzes a USING join first as a join without
a condition.
+ CheckExternalLookupJoin(analyzed)
+ checkError(
+ exception = intercept[AnalysisException] {
FormExternalLookupJoin(analyzed) },
+ condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+ parameters = Map.empty)
+ }
+ }
+
+ test("validation of a streaming write rejects a join without a condition") {
+ def write(query: LogicalPlan): WriteToStream = WriteToStream("query",
None, "/checkpoint",
+ LookupCapabilityTable(Set.empty), OutputMode.Append(),
deleteCheckpointOnStop = false,
+ query, None, None)
+ Seq(
+ stream.join(lookupOnly),
+ stream.join(lookupOnly).where(idsEqual)).foreach { plan =>
+ val analyzed = analyze(plan)
+ // The query of a streaming write is analyzed in full, so the condition
cannot come later.
+ checkError(
+ exception = intercept[AnalysisException] {
CheckExternalLookupJoin(write(analyzed)) },
+ condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+ parameters = Map.empty)
+ }
+ CheckExternalLookupJoin(write(analyze(innerJoinOnId(lookupOnly))))
+ }
+
+ test("validation leaves a join that is not resolved to the analyzer's join
checks") {
+ // Each join would otherwise fail with JOIN_TYPE.
+ val sharedIds = LocalRelation(lookupOnly.output, isStreaming = true)
+ Seq(
+ Join(stream, lookupOnly, RightOuter, Some(stream.output(1)),
JoinHint.NONE),
+ Join(sharedIds, lookupOnly, RightOuter, Some(sharedIds.output(1) ===
lookupOnly.output(1)),
+ JoinHint.NONE)).foreach { join =>
+ assert(!join.resolved)
+ CheckExternalLookupJoin(join)
+ }
+ }
+
+ test("an external lookup join node rejects an unsupported join type
(internal invariant)") {
+ val lookupJoin =
+
FormExternalLookupJoin(innerJoinOnId(lookupOnly)).asInstanceOf[ExternalLookupJoin]
+ checkError(
+ exception = intercept[SparkException] { lookupJoin.copy(joinType =
FullOuter).output },
+ condition = "INTERNAL_ERROR",
+ parameters = Map("message" -> "Unexpected external lookup join type
FullOuter"))
+ }
+}
+
+/** A table with only what the lookup join classification reads: a name, a
schema, capabilities. */
+private case class LookupCapabilityTable(capabilitySet: Set[TableCapability])
extends Table {
+ override def name(): String = "LookupCapabilityTable"
+ override def schema(): StructType =
+ StructType.fromDDL(
+ "lookupTenant INT NOT NULL, lookupId INT NOT NULL, lookupValue STRING
NOT NULL")
+ override def capabilities(): java.util.Set[TableCapability] =
capabilitySet.asJava
+}
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala
new file mode 100644
index 000000000000..c6f01f21f665
--- /dev/null
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala
@@ -0,0 +1,256 @@
+/*
+ * 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, Coalesce,
+ EqualNullSafe, EqualTo, Expression, ExprUtils, Literal, 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)
+ }
+ // A conjunction evaluates its next conjunct after a NULL, so a NULL in
the first group reads
+ // as false: a hash join never matches a NULL key either. A row matches
only when the whole
+ // condition is true, so this changes no result.
+ val residual = if (residualRest.isEmpty) residualFirst else {
+ residualFirst.map { conjunct =>
+ if (conjunct.nullable) Coalesce(Seq(conjunct, Literal.FalseLiteral))
else conjunct
+ } ++ residualRest
+ }
+
+ def nonNull[T](value: T, method: String): T = Option(value).getOrElse {
+ throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+ tableName, "NULL_RESULT", Map("method" -> method))
+ }
+ val scan = nonNull(scanBuilder.build(), "ScanBuilder.build()")
+ // 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(), "Scan.readSchema()"))
+ val columnsByName = relation.output.groupBy(_.name)
+ val lookupInput = readSchema.fields.map { field =>
+ columnsByName.getOrElse(field.name, Nil).find { attr =>
+ DataType.equalsIgnoreNullability(attr.dataType, field.dataType)
+
}.map(_.withDataType(field.dataType).withNullability(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 =>
+ throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+ tableName, "MISSING_SCAN_FIELD", Map("field" ->
toSQLId(Seq(attr.name))))
+ }
+ val externalLookup = nonNull(scan.toExternalLookup(),
"Scan.toExternalLookup()")
+ val maxParameterRowsPerRequest =
externalLookup.maxParameterRowsPerRequest()
+ if (maxParameterRowsPerRequest <= 0) {
+ throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+ tableName,
+ "NON_POSITIVE_MAX_PARAMETER_ROWS",
+ Map("value" -> maxParameterRowsPerRequest.toString))
+ }
+ val readerFactory =
+ nonNull(externalLookup.createReaderFactory(),
"ExternalLookup.createReaderFactory()")
+
+ PreparedExternalLookupJoin(
+ join.left,
+ scan,
+ readerFactory,
+ maxParameterRowsPerRequest,
+ lookupInput,
+ lookupOutput,
+ selectedPredicates.map(_.parameter),
+ selectedPredicates.map(_.nullSafe),
+ join.joinType,
+ residual.reduceOption(And))
+ }
+
+ /**
+ * An equality between a bare lookup column and an expression over the
stream side, on a type
+ * that Spark offers as a lookup key.
+ */
+ private def isLookupEquality(
+ join: ExternalLookupJoin,
+ leftExpr: Expression,
+ rightAttr: Attribute): Boolean =
+ leftExpr.references.subsetOf(join.left.outputSet) &&
join.right.outputSet.contains(rightAttr) &&
+ ExternalLookupKeyTypes.supportsEquality(rightAttr)
+
+ /**
+ * An equality between an expression over the stream side and one over the
lookup side, each
+ * reading a column, which a hash join would use as a join key.
+ */
+ private def isJoinKeyEquality(join: ExternalLookupJoin, conjunct:
Expression): Boolean = {
+ def readsOnly(expression: Expression, plan: LogicalPlan): Boolean =
+ expression.references.nonEmpty &&
expression.references.subsetOf(plan.outputSet)
+ def betweenSides(first: Expression, second: Expression): Boolean =
+ (readsOnly(first, join.left) && readsOnly(second, join.right)) ||
+ (readsOnly(first, join.right) && readsOnly(second, join.left))
+ conjunct match {
+ case EqualTo(first, second) => betweenSides(first, second)
+ case EqualNullSafe(first, second) => betweenSides(first, second)
+ case _ => false
+ }
+ }
+
+ /**
+ * Maps the connector's selection back to the offered candidates, in the
connector's order, which
+ * defines the fields of each request parameter row. Selections are matched
by object identity
+ * rather than by equality, so two candidates of the same shape, for example
the same lookup field
+ * compared with two different join-side values, remain distinguishable.
+ */
+ private def selectedCandidates(
+ tableName: String,
+ offered: Array[V2Predicate],
+ candidates: Seq[OfferedLookupPredicate],
+ selected: Array[V2Predicate]): Seq[OfferedLookupPredicate] = {
+ if (selected == null) {
+ throw
QueryCompilationErrors.invalidDataSourceExternalLookupError(tableName,
"NULL_RESULT",
+ Map("method" -> "SupportsExternalLookup.selectLookupPredicates()"))
+ }
+ if (selected.isEmpty) {
+ throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+ "NO_LOOKUP_PREDICATE", Map("table" -> toSQLId(tableName)))
+ }
+ val candidateByPredicate = new IdentityHashMap[V2Predicate,
OfferedLookupPredicate]()
+ offered.zip(candidates).foreach { case (predicate, candidate) =>
+ candidateByPredicate.put(predicate, candidate)
+ }
+ val seen = Collections.newSetFromMap(new IdentityHashMap[V2Predicate,
java.lang.Boolean]())
+ selected.toSeq.map { predicate =>
+ // A null element is not an offered instance either.
+ val candidate = Option(predicate).map(candidateByPredicate.get).orNull
+ if (candidate == null) {
+ throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+ tableName, "UNOFFERED_SELECTED_PREDICATE",
+ Map("predicate" ->
Option(predicate).map(_.describe()).getOrElse("null")))
+ }
+ if (!seen.add(predicate)) {
+ throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+ tableName, "DUPLICATE_SELECTED_PREDICATE", Map("predicate" ->
predicate.describe()))
+ }
+ candidate
+ }
+ }
+
+ private case class OfferedLookupPredicate(
+ parameter: Expression,
+ projectedField: Attribute,
+ conjunctIndex: Int,
+ predicateName: String,
+ nullSafe: Boolean)
+
+ private def extractLookupPlan(plan: LogicalPlan):
Option[DataSourceV2Relation] = plan match {
+ case relation: DataSourceV2Relation => Some(relation)
+ case relation: ExternalLookupRelation => Some(relation.relation)
+ case _ => None
+ }
+}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala
new file mode 100644
index 000000000000..b40ebaae52f1
--- /dev/null
+++
b/sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala
@@ -0,0 +1,510 @@
+/*
+ * 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, AttributeMap,
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)", "VARCHAR(3)
COLLATE UTF8_LCASE",
+ "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)) {
+ assert(offeredCodeCandidate(codeType) === offered, codeType)
+ }
+ // Under standard CHAR/VARCHAR semantics, Spark reads a VARCHAR value
longer than the declared
+ // length without the trailing blanks past that length, so a store that
compares the value as
+ // stored could miss a row.
+ withSQLConf(SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS.key -> "true") {
+ assert(offeredCodeCandidate("VARCHAR(3)") === false)
+ assert(offeredCodeCandidate("STRING"))
+ }
+
+ // Without another candidate, the join cannot run.
+ Seq("DOUBLE", "STRING COLLATE UTF8_LCASE", "CHAR(3)").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("an equality within one side of the join is never a lookup candidate") {
+ var offered = Seq.empty[String]
+ val lookup = lookupRelation(PlanningExternalLookupTable("id INT, value
STRING, alt STRING",
+ select = { candidates =>
+ offered = candidates.map(_.toString).toSeq
+ candidates.take(1)
+ }))
+ val Seq(id, value, alt) = lookup.output
+ val streamCode = AttributeReference("streamCode", value.dataType)()
+ val left = LocalRelation(stream.output :+ streamCode, isStreaming = true)
+ val Seq(streamId, streamLabel) = stream.output
+ // `t.value = t.alt` would offer a parameter over a lookup column, and
`s.label = s.code` a
+ // candidate on a column that the lookup side does not have.
+ val withinSides = Seq(value === alt, alt === value, streamLabel ===
streamCode)
+ val prepared = prepare(
+ lookupJoin(lookup, ((streamId === id) +: withinSides).reduce(_ && _),
left = left))
+ assert(offered === Seq("id = ?"))
+ assert(prepared.lookupParameters === Seq(streamId))
+ assert(prepared.residualCondition === Some(withinSides.reduce(_ && _)))
+ }
+
+ test("the residual evaluates key equalities and conjuncts that cannot fail
first") {
+ // With ANSI mode on, a cast of a string to INT fails on a string that is
not a number. Without
+ // it, ExprUtils.canEvaluateUnconditionally may take the cast as unable to
fail.
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label
STRING, value STRING"))
+ val Seq(lookupId, lookupLabel, lookupValue) = lookup.output
+ val Seq(streamId, streamLabel) = stream.output
+ // The 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(orFalse(streamLabel === lookupLabel) && orFalse(lookupValue >
"a") && mayFail))
+
+ // Equalities between the sides go first even when they can fail, as a
hash join's keys: `=`
+ // and `<=>`, each comparing a lookup column with a cast of a stream
column, written after a
+ // conjunct that can fail. A `<=>` is never NULL.
+ val codes = lookupRelation(PlanningExternalLookupTable("id INT, code
INT, alt INT"))
+ val Seq(codeId, code, alt) = codes.output
+ val codeEqual = code === streamLabel.cast(IntegerType)
+ val altEqual = alt <=> streamLabel.cast(IntegerType)
+ val keyed = prepare(
+ lookupJoin(codes, Seq(codeId === streamId, mayFail, codeEqual,
altEqual).reduce(_ && _)))
+ assert(keyed.residualCondition === Some(orFalse(codeEqual) && altEqual
&& mayFail))
+ }
+ }
+
+ test("a NULL key equality in the residual stops the conjuncts that can
fail") {
+ val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label
STRING"))
+ val Seq(lookupId, lookupLabel) = lookup.output
+ val Seq(streamId, streamLabel) = stream.output
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ // Under ANSI mode, the cast fails on a label that is not a number.
+ val mayFail = streamLabel.cast(IntegerType) > 0
+ val keyEqual = streamLabel === lookupLabel
+ val prepared = prepare(lookupJoin(lookup, lookupId === streamId &&
keyEqual && mayFail))
+ val joinedOutput = stream.output ++ lookup.output
+ val residual = prepared.residualCondition.get
+ val conjunction = keyEqual && mayFail
+ def row(label: String, lookupLabelValue: String): InternalRow =
InternalRow(
+ 1, UTF8String.fromString(label), 1,
UTF8String.fromString(lookupLabelValue))
+ def matches(condition: Expression, input: InternalRow): Boolean = {
+ val interpreted = BindReferences.bindReference(condition,
joinedOutput).eval(input)
+ val generated = CatalystPredicate.create(condition,
joinedOutput).eval(input)
+ assert(generated === (interpreted == true))
+ generated
+ }
+
+ // A hash join never matches a NULL key, so it does not reach the cast.
Neither does the
+ // residual.
+ assert(matches(residual, row("x", null)) === false)
+ val error = intercept[Exception](matches(conjunction, row("x", null)))
+ // The catalyst DSL turns a String operand of `===` into an expression.
+ assert(error.asInstanceOf[SparkThrowable].getCondition ==
"CAST_INVALID_INPUT")
+ // Otherwise the residual matches the rows that the conjunction matches.
+ Seq(row("2", "2"), row("-2", "-2"), row("2", "3")).foreach { input =>
+ assert(matches(residual, input) === matches(conjunction, input))
+ }
+ }
+ }
+
+ 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))
+ val Seq(id, label, value) = lookup.output
+ // `value = 'a'` is offered as well; `streamId > 0` is not.
+ val conjuncts =
+ Seq(id === streamId, streamLabel === label, streamId > 0, value ===
Literal("a"))
+ val join = lookupJoin(lookup, conjuncts.reduce(_ && _), LeftOuter)
+ (prepare(join), join.output, conjuncts)
+ }
+
+ val (reversed, joinOutput, conjuncts) =
+ prepared(candidates => Array(candidates(1), candidates(0)))
+ assert(reversed.lookupParameters === Seq(streamLabel, streamId))
+ assert(reversed.nullSafeParameters === Seq(false, false))
+ assert(reversed.residualCondition === Some(conjuncts(2) && conjuncts(3)))
+ assert(reversed.output === joinOutput)
+ assert(PrepareExternalLookupJoin(reversed) === reversed)
+
+ // An unselected equality stays ahead of the conjuncts written after it.
+ val (idOnly, _, idOnlyConjuncts) = prepared(candidates =>
Array(candidates(0)))
+ assert(idOnly.lookupParameters === Seq(streamId))
+ assert(idOnly.residualCondition === Some(idOnlyConjuncts.drop(1).reduce(_
&& _)))
+ }
+
+ test("the read schema binds to the analyzed lookup attributes by exact
name") {
+ val lookup = lookupRelation(PlanningExternalLookupTable(
+ "id INT NOT NULL, value VARCHAR(8) NOT NULL, s STRUCT<a: INT NOT NULL>",
+ readSchemaDDL = Some("s STRUCT<a: INT>, value VARCHAR(8), id INT NOT
NULL")))
+ val join = lookupJoinOnId(lookup)
+ val prepared = prepare(join)
+ assert(prepared.lookupOutput === lookup.output)
+ assert(prepared.output === join.output)
+ // The value-row attributes follow the read schema, with its types and
nullability.
+ val relationAttrs = lookup.output.map(attr => attr.name -> attr).toMap
+ assert(prepared.lookupInput.map(_.name) === Seq("s", "value", "id"))
+ assert(prepared.lookupInput.map(_.nullable) === Seq(true, true, false))
+ assert(prepared.lookupInput.head.dataType === StructType.fromDDL("a INT"))
+ prepared.lookupInput.foreach { attr =>
+ assert(attr.exprId === relationAttrs(attr.name).exprId)
+ assert(attr.metadata === relationAttrs(attr.name).metadata)
+ }
+
+ withSQLConf(SQLConf.CASE_SENSITIVE.key -> "false") {
+ val caseVariant = lookupRelation(PlanningExternalLookupTable(
+ "id INT, a INT, A INT", readSchemaDDL = Some("A INT, id INT, a INT")))
+ val Seq(id, a, upperA) = caseVariant.output
+ val prepared = prepare(lookupJoinOnId(caseVariant))
+ assert(prepared.lookupInput.map(_.exprId) === Seq(upperA, id,
a).map(_.exprId))
+ }
+ }
+
+ test("a read schema may declare NOT NULL where the table allows nulls") {
+ // A connector that never returns a null may say so, at the top level and
in nested fields.
+ val lookup = lookupRelation(PlanningExternalLookupTable(
+ "id INT, value STRING, s STRUCT<a: INT>",
+ readSchemaDDL = Some("id INT, value STRING NOT NULL, s STRUCT<a: INT NOT
NULL>")))
+ val join = lookupJoinOnId(lookup)
+ val prepared = prepare(join)
+ assert(prepared.output === join.output)
+ assert(prepared.lookupInput.map(_.nullable) === Seq(true, false, true))
+ assert(prepared.lookupInput(2).dataType === StructType.fromDDL("a INT NOT
NULL"))
+ }
+
+ test("a candidate names the lookup column as the table schema spells it") {
+ var offered = Seq.empty[String]
+ val lookup = lookupRelation(PlanningExternalLookupTable(select = {
candidates =>
+ offered = candidates.map(_.toString).toSeq
+ candidates.filter(_.children()(0) == FieldReference.column("id"))
+ }))
+ // Under case-insensitive analysis, a condition that writes `ID` resolves
to the column `id`,
+ // with the same exprId and the query's spelling.
+ val idAsWritten = lookup.output.head.withName("ID")
+ val prepared = prepare(lookupJoin(lookup, stream.output.head ===
idAsWritten))
+ assert(offered === Seq("id = ?"))
+ assert(prepared.lookupParameters === Seq(stream.output.head))
+ }
+
+ test("the read schema must cover every lookup column with its data type") {
+ Seq(
+ ("id INT", "MISSING_SCAN_FIELD"),
+ ("id INT, value INT", "UNKNOWN_SCAN_FIELD")).foreach { case (readSchema,
subClass) =>
+ val lookup = lookupRelation(PlanningExternalLookupTable(readSchemaDDL =
Some(readSchema)))
+ checkError(
+ exception = prepareError(lookupJoinOnId(lookup)),
+ condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass",
+ parameters = Map("table" -> QUOTED_TABLE_NAME, "field" -> "`value`"))
+ }
+ }
+
+ test("a failed predicate selection blames Spark or the connector, whichever
caused it") {
+ // A wider stream key casts the lookup column, so Spark has no candidate
to offer.
+ val longStream = LocalRelation(Seq($"id".long), isStreaming = true)
+ val unreachable = lookupRelation(PlanningExternalLookupTable(
+ select = _ => fail("Spark must not ask the connector to select from no
candidates")))
+ checkError(
+ exception = prepareError(lookupJoin(unreachable,
+ longStream.output.head === unreachable.output.head.cast(LongType),
left = longStream)),
+ condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+ parameters = Map("table" -> QUOTED_TABLE_NAME))
+
+ Seq[(Array[Predicate] => Array[Predicate], String, Map[String, String])](
+ (_ => Array.empty,
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE", Map.empty),
+ (_ => null, "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.NULL_RESULT",
+ Map("method" -> "SupportsExternalLookup.selectLookupPredicates()")),
+ // A null element is not one of the offered instances.
+ (_ :+ null,
"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.UNOFFERED_SELECTED_PREDICATE",
+ Map("predicate" -> "null"))).foreach {
+ case (select, condition, parameters) =>
+ checkError(
+ exception = prepareError(lookupJoinOnId(
+ lookupRelation(PlanningExternalLookupTable(select = select)))),
+ condition = condition,
+ parameters = Map("table" -> QUOTED_TABLE_NAME) ++ parameters)
+ }
+ }
+
+ test("a left outer join makes NOT NULL lookup columns nullable") {
+ val lookup =
+ lookupRelation(PlanningExternalLookupTable("id INT NOT NULL, value
STRING NOT NULL"))
+ assert(lookup.output.forall(_.nullable === false))
+ val join = lookupJoin(lookup, stream.output.head === lookup.output.head,
LeftOuter)
+ val prepared = prepare(join)
+ assert(prepared.output === join.output)
+ assert(prepared.output.drop(stream.output.length).forall(_.nullable))
+ assert(prepared.copy(joinType = Inner).output.drop(stream.output.length)
+ .forall(_.nullable === false))
+ }
+
+ test("a prepared lookup join reads its parameters and the residual's stream
columns") {
+ val lookup = lookupRelation(PlanningExternalLookupTable())
+ val Seq(streamId, streamLabel) = stream.output
+ val Seq(id, value) = lookup.output
+ // The connector selects only `id = ?`, so the residual reads
`streamLabel` and `value`.
+ val prepared = prepare(lookupJoin(lookup, streamId === id && streamLabel
=== value))
+ assert(prepared.residualCondition === Some(streamLabel === value))
+ // It produces `value` itself, so it reads only stream columns.
+ assert(prepared.references === AttributeSet(Seq(streamId, streamLabel)))
+ assert(prepared.missingInput.isEmpty)
+ }
+
+ test("a prepared lookup join keeps its scan and reader factory out of its
plan string") {
+ val prepared =
prepare(lookupJoinOnId(lookupRelation(PlanningExternalLookupTable())))
+ assert(prepared.scan.toString.contains("secret-scan"))
+ assert(prepared.readerFactory.toString.contains("secret-factory"))
+ Seq(prepared.toString, prepared.simpleString(100),
prepared.verboseString(100)).foreach {
+ rendered => assert(rendered.contains("secret") === false, rendered)
+ }
+ }
+
+ test("a prepared lookup join shows its join type, parameters and residual in
its plan string") {
+ val lookup = lookupRelation(PlanningExternalLookupTable())
+ val Seq(streamId, streamLabel) = stream.output
+ val Seq(id, value) = lookup.output
+ val residual = streamLabel === value
+ val prepared = prepare(lookupJoin(lookup, streamId === id && residual,
LeftOuter))
+ Seq(prepared.toString, prepared.simpleString(100)).foreach { rendered =>
+ Seq(LeftOuter.toString, streamId.toString, residual.toString).foreach {
arg =>
+ assert(rendered.contains(arg), rendered)
+ }
+ }
+ }
+
+ test("a connector that reorders the offered array in place selects the
predicate it returns") {
+ val Seq(streamId, streamLabel) = stream.output
+ // The connector swaps the two candidates in the array it receives, and
returns the one now
+ // first, `value = ?`. Spark keeps its own copy, so it binds that
predicate to `streamLabel`.
+ val lookup = lookupRelation(PlanningExternalLookupTable(select = {
candidates =>
+ val first = candidates(0)
+ candidates(0) = candidates(1)
+ candidates(1) = first
+ Array(candidates(0))
+ }))
+ val Seq(id, value) = lookup.output
+ val prepared = prepare(lookupJoin(lookup, streamId === id && streamLabel
=== value))
+ assert(prepared.lookupParameters === Seq(streamLabel))
+ assert(prepared.residualCondition === Some(streamId === id))
+ }
+
+ test("a connector method that returns null fails with a named error") {
+ Seq(
+ "build" -> "ScanBuilder.build()",
+ "readSchema" -> "Scan.readSchema()",
+ "toExternalLookup" -> "Scan.toExternalLookup()",
+ "createReaderFactory" -> "ExternalLookup.createReaderFactory()").foreach
{
+ case (nullFrom, method) =>
+ val lookup = lookupRelation(PlanningExternalLookupTable(nullFrom =
nullFrom))
+ checkError(
+ exception = prepareError(lookupJoinOnId(lookup)),
+ condition = "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.NULL_RESULT",
+ parameters = Map("table" -> QUOTED_TABLE_NAME, "method" -> method))
+ }
+ }
+
+ test("a prepared lookup join keeps the size estimate of the join it
replaces") {
+ // Two stream rows, and a lookup side of Spark's default size.
+ withSQLConf(SQLConf.DEFAULT_SIZE_IN_BYTES.key -> "1000") {
+ val rows = Seq(1, 2).map(id => InternalRow(id,
UTF8String.fromString("a")))
+ val sizedStream = LocalRelation(stream.output, rows, isStreaming = true)
+ val lookup = lookupRelation(PlanningExternalLookupTable())
+ val join = lookupJoin(lookup, sizedStream.output.head ===
lookup.output.head,
+ left = sizedStream)
+ val prepared = prepare(join)
+ assert(sizedStream.stats.sizeInBytes > 0)
+ assert(prepared.stats.sizeInBytes === sizedStream.stats.sizeInBytes *
1000)
+ assert(prepared.stats.sizeInBytes === join.stats.sizeInBytes)
+ }
+ }
+
+ test("a prepared lookup join canonicalizes each lookup column by its place
in the read schema") {
+ val lookup = lookupRelation(PlanningExternalLookupTable("id INT, code
INT"))
+ val Seq(lookupId, lookupCode) = lookup.output
+ val streamId = stream.output.head
+ val prepared = prepare(lookupJoin(lookup, streamId === lookupId &&
streamId > lookupCode))
+
assert(prepared.residualCondition.exists(_.references.contains(lookupCode)))
+ // Another analysis of the query gives the lookup columns other ids.
+ val newIds = AttributeMap(prepared.lookupInput.map(attr => attr ->
attr.newInstance()))
+ val reanalyzed = prepared.transformExpressions {
+ case attr: Attribute if newIds.contains(attr) => newIds(attr)
+ }
+ assert(reanalyzed.lookupInput != prepared.lookupInput)
+ assert(reanalyzed.sameResult(prepared))
+ // Joins that keep different lookup columns of one type do not
canonicalize alike.
+ val keepsId = prepared.copy(lookupOutput = Seq(lookupId))
+ val keepsCode = prepared.copy(lookupOutput = Seq(lookupCode))
+ assert(keepsId.sameResult(keepsCode) === false)
+ assert(keepsId.sameResult(prepared.copy(lookupOutput = Seq(lookupId))))
+ }
+
+ test("column pruning never projects the lookup relation under a lookup
join") {
+ val lookup = lookupRelation(PlanningExternalLookupTable())
+ val pruned = ColumnPruning(Project(Seq(stream.output.head),
lookupJoinOnId(lookup)))
+ val (lookupLeft, lookupRight) =
+ pruned.collectFirst { case join: ExternalLookupJoin => (join.left,
join.right) }.get
+ assert(lookupLeft.output === Seq(stream.output.head))
+ assert(lookupRight === lookup)
+
assert(PrepareExternalLookupJoin(pruned).exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+ }
+}
+
+/**
+ * A lookup-only table that the planning rules can prepare. It is never read.
By default its
+ * connector selects every `id = ?` candidate and returns the table schema as
the read schema.
+ */
+case class PlanningExternalLookupTable(
+ schemaDDL: String = "id INT, value STRING NOT NULL",
+ readSchemaDDL: Option[String] = None,
+ select: Array[Predicate] => Array[Predicate] =
PlanningExternalLookupTable.selectIdEqualities,
+ nullFrom: String = "")
+ extends Table with SupportsRead {
+ override def name(): String = "PlanningExternalLookupTable"
+ override def schema(): StructType = StructType.fromDDL(schemaDDL)
+ override def capabilities(): java.util.Set[TableCapability] =
+ java.util.EnumSet.of(EXTERNAL_LOOKUP)
+
+ override def newScanBuilder(options: CaseInsensitiveStringMap): ScanBuilder =
+ new SupportsExternalLookup {
+ override def selectLookupPredicates(candidates: Array[Predicate]):
Array[Predicate] =
+ select(candidates)
+ override def build(): Scan = if (nullFrom == "build") null else new Scan
{
+ override def readSchema(): StructType = if (nullFrom == "readSchema")
null else {
+ readSchemaDDL.map(StructType.fromDDL).getOrElse(schema())
+ }
+ override def toExternalLookup(): ExternalLookup =
+ if (nullFrom == "toExternalLookup") null else new ExternalLookup {
+ override def maxParameterRowsPerRequest(): Int = 1
+ override def createReaderFactory(): ExternalLookupReaderFactory =
+ if (nullFrom == "createReaderFactory") null else new
ExternalLookupReaderFactory {
+ override def createReader(): ExternalLookupReader =
+ throw new UnsupportedOperationException("not read")
+ // A connector description may hold a secret.
+ override def toString: String =
"PlanningReaderFactory(token=secret-factory)"
+ }
+ }
+ override def toString: String = "PlanningScan(token=secret-scan)"
+ }
+ }
+}
+
+object PlanningExternalLookupTable {
+ private val selectIdEqualities: Array[Predicate] => Array[Predicate] =
+ _.filter(p => p.name() == "=" && p.children()(0) ==
FieldReference.column("id"))
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]