viirya commented on code in PR #59909: URL: https://github.com/apache/spark/pull/59909#discussion_r4531486441
########## sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala: ########## @@ -0,0 +1,398 @@ +/* + * 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.InternalRow +import org.apache.spark.sql.catalyst.analysis.FormExternalLookupJoin +import org.apache.spark.sql.catalyst.dsl.expressions._ +import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeReference, AttributeSet, + 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, 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) } + + 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)) + + // 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. + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { Review Comment: You're right, I missed that SPARK-60882 came in with the rebase. Thanks for the comment in the test. -- 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]
