cloud-fan commented on code in PR #60661:
URL: https://github.com/apache/spark/pull/60661#discussion_r4626467405
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -161,6 +182,74 @@ object ApplyCharTypePaddingHelper {
case other => other
}
+ // How an element of `value IN (list)` is padded in its comparison with the
value.
+ private sealed trait InElementPadding
+ private case object NotPadded extends InElementPadding
+ // A string literal compared with a CHAR value, padded like in an IN list of
literals.
+ private case object PaddedLiteral extends InElementPadding
+ // A column whose type has CHAR, padded together with the columns of the
same type, regardless
+ // of the CHAR and VARCHAR lengths.
+ private case class PaddedColumn(typeWithoutLengths: DataType) extends
InElementPadding
+
+ private def inElementPadding(valueIsChar: Boolean, element: Expression):
InElementPadding =
+ element match {
+ case e if e.foldable => if (valueIsChar) PaddedLiteral else NotPadded
Review Comment:
Fixed in acda41b8b0a. I confirmed it first: `SELECT CASE WHEN i > 0 THEN c
IN (c2, element_at(array('a'), 10)) END FROM t` returned `[true]` before this
PR and failed to analyze with it, and so did reading the schema of `c IN (c2,
element_at(array('a'), 10))`. A list of only constants, `c IN ('a',
element_at(array('a'), 10))`, already failed the same way on master, as the
literal-IN padding evaluates every element.
I went with a smaller fix than the separate-IN one: the literal-IN padding
now evaluates each element under a non-fatal guard, and an element that fails
gets no length and is left unpadded, like a NULL. It can never match, so this
changes no result. The fix covers both cases. The comparison of a CHAR column
with a constant had the same `eval()`, so it uses the same guard.
##########
sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala:
##########
@@ -619,6 +619,137 @@ trait CharVarcharTestSuite extends QueryTest {
}
}
+ test("char type comparison: IN list mixing CHAR columns with other
elements") {
+ // `c IN (e1, e2)` must return what `c = e1 OR c = e2` returns, where each
equality pads its
+ // own sides: c is padded against a CHAR column of another length and a
string literal, but
+ // not against a STRING or VARCHAR column.
+ val lists = Seq(
+ Seq("c5", "s"), Seq("s", "c5"), Seq("c5", "v"), Seq("c5", "'x'"),
Seq("s", "'a'"),
+ Seq("c5", "s", "v", "'x'", "null"), Seq("c5b", "s"), Seq("c5b", "v"),
Seq("c5b", "s", "'b'"),
+ Seq("s", "v"))
+
+ def checkInAsOr(table: String, value: String): Unit = {
+ val df = spark.table(table)
+ val ins = lists.flatMap { list =>
+ val elems = list.mkString(", ")
+ Seq(s"$value IN ($elems)", s"$value NOT IN ($elems)")
+ }
+ val ors = lists.flatMap { list =>
+ val or = list.map(e => s"$value = $e").mkString(" OR ")
+ Seq(s"$or", s"NOT ($or)")
+ }
+ checkAnswer(df.selectExpr(ins: _*), df.selectExpr(ors: _*))
+ }
+
+ withTable("t") {
+ sql(s"CREATE TABLE t(c CHAR(2), c5 CHAR(5), c5b CHAR(5), s STRING, v
VARCHAR(5)) " +
+ s"USING $format")
+ sql("INSERT INTO t VALUES ('a', 'a', 'b', 'a', 'a')")
+ testConditions(spark.table("t"), Seq(
+ ("c = c5", true),
+ ("c = s", false),
+ ("c = v", false),
+ ("c IN (c5, s)", true),
+ ("c IN (s, c5)", true),
+ ("c NOT IN (c5, s)", false),
+ ("c IN (c5, v)", true),
+ ("c IN (c5, 'x')", true),
+ ("c IN (s, 'a')", true),
+ ("c IN (c5, s, v, 'x', null)", true),
+ // s and v hold 'a' without the padding of c, so they must not be
padded to match it.
+ ("c IN (c5b, s)", false),
+ ("c IN (c5b, v)", false),
+ ("c IN (c5b, s, 'b')", false),
+ ("c IN (s, v)", false)))
+ checkInAsOr("t", "c")
+
+ // A list of only columns and literals keeps all its literals in one IN.
+ val ins = spark.table("t").selectExpr("c IN (c5, 'x', s,
'y')").queryExecution.analyzed
+ .flatMap(_.expressions.flatMap(_.collect { case i: In => i }))
+ assert(ins.length == 3 && ins.exists(i => i.list.length == 2 &&
i.list.forall(_.foldable)))
+ }
+
+ // Without read-side padding the CHAR columns are padded in the predicate
instead.
+ withSQLConf(SQLConf.READ_SIDE_CHAR_PADDING.key -> "false") {
+ withTable("t") {
+ sql(s"CREATE TABLE t(c CHAR(2), c5 CHAR(5), c5b CHAR(5), s STRING, v
VARCHAR(5)) " +
+ s"USING $format")
+ sql("INSERT INTO t VALUES ('a', 'a', 'b', 'a', 'a')")
+ testConditions(spark.table("t"), Seq(
+ ("c IN (c5, s)", true),
+ ("c IN (c5, v)", true),
+ ("c IN (c5, 'x')", true),
+ ("c IN (s, 'a')", true)))
+ checkInAsOr("t", "c")
+ }
+ }
+
+ // s and v hold the value that c reads, so they match c only if c is not
padded for them.
+ Seq("true", "false").foreach { readSidePadding =>
+ withSQLConf(SQLConf.READ_SIDE_CHAR_PADDING.key -> readSidePadding) {
+ withTable("t") {
+ sql(s"CREATE TABLE t(c CHAR(2), c5 CHAR(5), c5b CHAR(5), s STRING, v
VARCHAR(5)) " +
+ s"USING $format")
+ sql("INSERT INTO t VALUES ('a', 'a', 'b', 'a ', 'a ')")
+ testConditions(spark.table("t"), Seq(
+ ("c = s", true),
+ ("c = v", true),
+ ("c IN (c5b, s)", true),
+ ("c IN (c5b, v)", true)))
+ checkInAsOr("t", "c")
+ }
+ }
+ }
+
+ // The value is an OuterReference in a correlated subquery.
+ withTable("t1", "t2") {
+ sql(s"CREATE TABLE t1(c CHAR(2)) USING $format")
+ sql(s"CREATE TABLE t2(c5 CHAR(5), c5b CHAR(5), s STRING) USING $format")
+ sql("INSERT INTO t1 VALUES ('a')")
+ sql("INSERT INTO t2 VALUES ('a', 'b', 'a')")
+ checkAnswer(
+ sql("SELECT c FROM t1 WHERE EXISTS (SELECT 1 FROM t2 WHERE t1.c IN
(t2.c5, t2.s))"),
+ Row("a "))
+ checkAnswer(
+ sql("SELECT c FROM t1 WHERE EXISTS (SELECT 1 FROM t2 WHERE t1.c IN
(t2.c5b, t2.s))"),
+ Nil)
+ }
+
+ // CHAR fields nested in structs.
+ withTable("t") {
+ sql(s"CREATE TABLE t(c STRUCT<f: CHAR(2)>, c5 STRUCT<f: CHAR(5)>, s
STRUCT<f: STRING>) " +
+ s"USING $format")
+ sql("INSERT INTO t VALUES (struct('a'), struct('a'), struct('a'))")
+ testConditions(spark.table("t"), Seq(
+ ("c = c5", true),
+ ("c = s", false),
+ ("c IN (c5, s)", true),
+ ("c IN (s, c5)", true),
+ ("c IN (s)", false)))
+ // Padding a struct that is an outer reference references it more than
once.
+ Seq("t.c = t2.c5", "t.c IN (t2.c5, t2.s)").foreach { cond =>
+ checkAnswer(
+ sql(s"SELECT 1 FROM t WHERE EXISTS (SELECT 1 FROM t AS t2 WHERE
$cond)"),
+ Row(1))
+ }
+ }
+ }
+
+ test("char type comparison: IN list keeps the order of elements that can
fail") {
+ // Like the OR of the equalities, the IN must not evaluate an element that
can fail if an
+ // element written ahead of it matches.
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ withTable("t") {
+ sql(s"CREATE TABLE t(c CHAR(2), c2 CHAR(2), c5 CHAR(5), s STRING, arr
ARRAY<STRING>) " +
+ s"USING $format")
+ sql("INSERT INTO t VALUES ('a', 'a', 'b', 'x', array('y'))")
+ val cond = "c IN (s, c2, element_at(arr, 10), c5)"
Review Comment:
Added in acda41b8b0a. `c IN (s, c5a, element_at(arr, 10))`, where `c5a` is a
`CHAR(5)` holding `'a'`, and `c IN (s, 'a', c5, element_at(arr, 10))`, together
with their NOT IN forms and a NULL outcome. The written-order path already
padded these correctly, so they pass on the previous commit too; before this PR
they failed at runtime, since the unpadded match is missed and `element_at` is
reached.
The IN and NOT IN are checked in separate queries: with both in one SELECT
list, the shared `element_at(arr, 10)` is evaluated for both and fails, and the
plain OR form of the equalities does the same on master.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/PlanRewriter.scala:
##########
@@ -60,17 +63,65 @@ class PlanRewriter(
}
private def doRewriteWithSubqueries(plan: LogicalPlan): LogicalPlan = {
+ val subqueriesWithChangedSql = new mutable.HashSet[ExprId]
val planWithRewrittenSubqueries =
plan.transformAllExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
case subqueryExpression: SubqueryExpression =>
val rewrittenSubqueryPlan =
doRewriteWithSubqueries(subqueryExpression.plan)
- subqueryExpression.withNewPlan(rewrittenSubqueryPlan)
+ if (rewrittenSubqueryPlan.fastEquals(subqueryExpression.plan)) {
+ subqueryExpression
+ } else {
+ // A post-resolution rule can change the outer references of the
subquery plan, e.g.
+ // `ApplyCharTypePadding` can reference an outer attribute more
than once when it pads
+ // it. The fixed-point Analyzer collects the outer references
after running these
+ // rules on the subquery plan, so collect them again from the
rewritten plan.
+ val rewrittenSubqueryExpression = subqueryExpression
+ .withNewPlan(rewrittenSubqueryPlan)
+
.withNewOuterAttrs(SubExprUtils.getOuterReferences(rewrittenSubqueryPlan))
+ if (toPrettySQL(rewrittenSubqueryExpression) !=
toPrettySQL(subqueryExpression)) {
+ subqueriesWithChangedSql += subqueryExpression.exprId
+ }
+ rewrittenSubqueryExpression
+ }
}
+ if (subqueriesWithChangedSql.nonEmpty) {
+ checkNoImplicitNameOfChangedSubquery(planWithRewrittenSubqueries,
subqueriesWithChangedSql)
+ }
+
rewrite(planWithRewrittenSubqueries)
}
+ /**
+ * An unaliased expression in a select list is named after its SQL during
resolution, e.g. an
+ * EXISTS subquery with the outer reference `c` is named `exists(c)`. If the
post-resolution
+ * rules then change the outer references of the subquery, its SQL changes,
e.g. to
+ * `exists(c, c)`, but its name does not. The fixed-point Analyzer names it
after running these
+ * rules on the subquery plan, so it gives the column the new name. Renaming
the column here
+ * would also require renaming every reference to it, so fall back to the
fixed-point Analyzer
+ * instead. An explicit alias is kept as written by both analyzers.
+ */
+ private def checkNoImplicitNameOfChangedSubquery(
+ plan: LogicalPlan,
+ subqueriesWithChangedSql: mutable.Set[ExprId]): Unit = {
+ plan.foreach { operator =>
+ operator.expressions.foreach(_.foreach {
+ case alias: Alias
+ if alias.metadata.contains(AUTO_GENERATED_ALIAS) &&
alias.child.exists {
Review Comment:
Fixed in acda41b8b0a. I reproduced it: the unaliased DataFrame column failed
with `HYBRID_ANALYZER_EXCEPTION.OUTPUT_SCHEMA_COMPARISON_MISMATCH` under dual
run. Instead of a new resolver tag, the check now also treats an alias as
implicit if its name is the SQL of its expression, which covers both naming
paths, and it runs on the plan before the rewrite, whose aliases still have the
expressions they were named after. An explicit alias that happens to equal that
SQL falls back too, which is safe. The test checks the DataFrame column gets
`exists(c, c)` under dual run, and an explicit alias keeps its name.
##########
sql/core/src/test/scala/org/apache/spark/sql/analysis/resolver/ExplicitlyUnsupportedResolverFeatureSuite.scala:
##########
@@ -137,6 +138,38 @@ class ExplicitlyUnsupportedResolverFeatureSuite extends
SharedSparkSession {
)
}
+ test("Implicitly named subquery whose outer references the post-resolution
rules change") {
+ withTable("n1", "n2") {
+ spark.sql("CREATE TABLE n1(c CHAR(2)) USING PARQUET")
+ spark.sql("CREATE TABLE n2(c5 CHAR(5), s STRING) USING PARQUET")
+ spark.sql("INSERT INTO n1 VALUES ('a')")
+ spark.sql("INSERT INTO n2 VALUES ('a', 'a')")
+ // `ApplyCharTypePadding` splits the IN and references the outer `n1.c`
once per split IN,
+ // so the outer references of the subqueries change from (c) to (c, c).
+ val condition = "n1.c IN (n2.c5, n2.s)"
+ val exists = s"EXISTS (SELECT 1 FROM n2 WHERE $condition)"
+ val scalar = s"(SELECT count(*) FROM n2 WHERE $condition)"
+ val query = s"SELECT $exists, $scalar FROM n1"
+ checkResolution(
+ query,
+ shouldPass = false,
+ expectedMessage = Some("an implicitly named column whose subquery has
its outer references")
+ )
+ checkResolution(s"SELECT $exists AS e, $scalar AS `exists(c)` FROM n1",
shouldPass = true)
Review Comment:
Added both in acda41b8b0a: `SELECT EXISTS (SELECT 1 FROM n2 WHERE n1.c =
n2.c5) FROM n1` and `SELECT EXISTS (SELECT 1 FROM n2) FROM n1` resolve in
single pass.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -161,6 +182,74 @@ object ApplyCharTypePaddingHelper {
case other => other
}
+ // How an element of `value IN (list)` is padded in its comparison with the
value.
+ private sealed trait InElementPadding
+ private case object NotPadded extends InElementPadding
+ // A string literal compared with a CHAR value, padded like in an IN list of
literals.
+ private case object PaddedLiteral extends InElementPadding
+ // A column whose type has CHAR, padded together with the columns of the
same type, regardless
+ // of the CHAR and VARCHAR lengths.
+ private case class PaddedColumn(typeWithoutLengths: DataType) extends
InElementPadding
+
+ private def inElementPadding(valueIsChar: Boolean, element: Expression):
InElementPadding =
+ element match {
+ case e if e.foldable => if (valueIsChar) PaddedLiteral else NotPadded
+ case a: Attribute =>
+ CharVarcharUtils.getRawType(a.metadata)
+ .filter(_.existsRecursively(_.isInstanceOf[CharType]))
+ .map { rawType =>
+ PaddedColumn(rawType.transformRecursively {
+ case _: CharType => CharType(0)
+ case _: VarcharType => VarcharType(0)
+ })
+ }
+ .getOrElse(NotPadded)
+ // TODO: Pad outer references used as list elements the way their
equalities with the value
+ // pad them. They are compared unpadded for now. IN subqueries, and a
literal value with a
+ // list of CHAR columns, are not padded either.
+ case _ => NotPadded
+ }
+
+ /**
+ * Matches `value IN (list)` whose elements are padded in different ways in
their comparisons
+ * with the value, and returns the lists of the INs to split it into, such
that the elements of
+ * each list are padded the same way.
+ *
+ * The INs are combined with OR, which evaluates them in order, and each IN
evaluates its
+ * elements in order until one matches. If every element can be evaluated on
any row, the
+ * elements are grouped by how they are padded, so that e.g. all the string
literals stay in one
+ * IN. Otherwise grouping could evaluate an element that can fail, or is
non-deterministic,
+ * before an element written ahead of it that matches, so the list is split
into its runs of
+ * consecutive elements that are padded the same way, in the order written.
+ */
+ private object InWithMixedPadding {
+ def unapply(in: In): Option[Seq[Seq[Expression]]] = in.value match {
+ case AttrOrOuterRef(attr) if in.resolved =>
+ // Parse the raw type of the value once, not once per element.
+ CharVarcharUtils.getRawType(attr.metadata).flatMap { valueRawType =>
Review Comment:
Done in acda41b8b0a: `InWithMixedPadding` now returns before parsing any raw
type when every element is a constant, so a literal list like `i_category IN
('Books', 'Home', 'Sports')` is parsed only by the literal-IN padding, as
before. I left the few extra parses for a split IN, which only happen for the
lists this PR changes.
--
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]