shivadarshan-devadiga commented on code in PR #60756:
URL: https://github.com/apache/spark/pull/60756#discussion_r4653379112


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +437,251 @@ object CharVarcharUtils extends Logging with 
SparkCharVarcharUtils {
    * attributes. When comparing two char type columns/fields, we need to pad 
the shorter one to
    * the longer length.
    */
-  def addPaddingInStringComparison(attrs: Seq[Attribute], alwaysPad: Boolean): 
Seq[Expression] = {
-    val rawTypes = attrs.map(attr => getRawType(attr.metadata))
+  def addPaddingInStringComparison(attrs: Seq[Attribute], alwaysPad: Boolean): 
Seq[Expression] =
+    addPaddingInStringComparison(attrs, attrs.map(attr => 
getRawType(attr.metadata)), alwaysPad)
+
+  /**
+   * Like the method above, for expressions with the given raw types, such as 
a scalar subquery or
+   * a column of an IN subquery, whose raw type is the one of their column. 
With `truncate = false`,
+   * it pads like read-side padding, which keeps longer values instead of 
truncating them.
+   */
+  def addPaddingInStringComparison(
+      exprs: Seq[Expression],
+      rawTypes: Seq[Option[DataType]],
+      alwaysPad: Boolean,
+      truncate: Boolean = true): Seq[Expression] = {
     if (rawTypes.exists(_.isEmpty)) {
-      attrs
-    } else if (attrs.exists(attr => !RowOrdering.isOrderable(attr.dataType))) {
+      exprs
+    } else if (exprs.exists(expr => !RowOrdering.isOrderable(expr.dataType))) {
       // Comparing a non-orderable type, such as a struct holding a MAP, is 
rejected later by
       // CheckAnalysis. Leave it alone so the error names the attribute the 
user wrote rather
       // than the rewritten struct.
-      attrs
+      exprs
     } else {
       val typeWithTargetCharLength = 
rawTypes.map(_.get).reduce(typeWithWiderCharLength)
-      attrs.zip(rawTypes.map(_.get)).map { case (attr, rawType) =>
-        padCharToTargetLength(attr, rawType, typeWithTargetCharLength, 
alwaysPad).getOrElse(attr)
+      exprs.zip(rawTypes.map(_.get)).map { case (expr, rawType) =>
+        padCharToTargetLength(expr, rawType, typeWithTargetCharLength, 
alwaysPad, truncate)
+          .getOrElse(expr)
+      }
+    }
+  }
+
+  /**
+   * The raw type of the output of a UNION at one position, given the outputs 
of its children
+   * there, if they are CHAR types, or structs and arrays of them, with 
different lengths at the
+   * same places: the widest lengths, as the SQL standard gives the union of 
CHAR(n) and CHAR(m)
+   * the length max(n, m). Keeps the names of the first attribute's fields. 
Returns None if the
+   * raw types are the same, or not all CHAR types of the same shape.
+   */
+  def widerCharRawType(attrs: Seq[Attribute]): Option[DataType] = {
+    val rawTypeStrings = attrs.map(attr => getRawTypeString(attr.metadata))
+    if (rawTypeStrings.exists(_.isEmpty) || rawTypeStrings.distinct.length == 
1) {
+      None
+    } else {
+      val rawTypes = rawTypeStrings.map(s => 
CatalystSqlParser.parseDataType(s.get))
+      // Raw types can differ only in how they print, such as with the default 
collation given
+      // explicitly or with other names of struct fields. They have the same 
lengths already.
+      if (rawTypes.map(normalizeCharType).distinct.length == 1) {
+        None
+      } else {
+        rawTypes.map(Option(_)).reduce {
+          (left, right) => for (l <- left; r <- right; wider <- 
widerCharType(l, r)) yield wider
+        }
+      }
+    }
+  }
+
+  // The type with the collation of each CHAR type given explicitly, and 
without field names.
+  private def normalizeCharType(dt: DataType): DataType = dt match {
+    case c: CharType => CharType(c.length, Some(c.collationId))
+    case StructType(fields) =>
+      StructType(fields.map(f => StructField("", 
normalizeCharType(f.dataType))))
+    case ArrayType(et, _) => ArrayType(normalizeCharType(et))
+    case other => other
+  }
+
+  /**
+   * Pads the CHAR columns and fields of the given attribute that are shorter 
than those at the
+   * same places of the given raw type, see [[widerCharRawType]]. Like 
read-side padding, it does
+   * not truncate longer values. Returns the padded value and its raw type, 
which keeps the names
+   * of the attribute's fields, or None if the attribute is already as long, 
unless `alwaysPad`,
+   * for values that the scan does not pad.
+   */
+  def padCharToWiderLength(
+      attr: Attribute,
+      rawType: DataType,
+      alwaysPad: Boolean = false): Option[(Expression, DataType)] = {
+    getRawType(attr.metadata).flatMap { attrRawType =>
+      widerCharType(attrRawType, rawType).filter(alwaysPad || _ != 
attrRawType).map { wider =>
+        val padded = processStringForCharVarchar(attr, wider,
+          charFuncName = Some(READ_SIDE_PADDING), varcharFuncName = None,
+          keepFieldNullability = true)
+        (padded, wider)
       }
     }
   }
 
+
+  /**
+   * The raw type of a value with the given metadata and data type. The raw 
type of a column is in
+   * its metadata, and the raw types of fields of a struct built from columns, 
such as by
+   * `named_struct`, are in the metadata of the fields. None if neither has a 
CHAR or VARCHAR type.
+   */
+  def getRawType(metadata: Metadata, dataType: DataType): Option[DataType] = {
+    def nested(dt: DataType): Option[DataType] = dt match {
+      case StructType(fields) =>
+        val rawFields = fields.map(f => 
getRawType(f.metadata).orElse(nested(f.dataType)))
+        if (rawFields.forall(_.isEmpty)) {
+          None
+        } else {
+          Some(StructType(fields.zip(rawFields).map { case (f, raw) =>
+            f.copy(dataType = raw.getOrElse(f.dataType), metadata = 
cleanMetadata(f.metadata))
+          }))
+        }
+      case ArrayType(et, containsNull) => nested(et).map(ArrayType(_, 
containsNull))
+      case _ => None
+    }
+    getRawType(metadata).orElse(nested(dataType))
+  }
+
+  /**
+   * [[widerCharRawType]] for each position of the outputs of the children of 
a set operation. A
+   * child can output a column at more than one position, and a reference to 
the column can't tell
+   * them apart, so the positions that share a column in any child get one raw 
type: the widest of
+   * all of them. Returns None for every position if the outputs have 
different lengths.
+   */
+  def widerCharRawTypes(childOutputs: Seq[Seq[Attribute]]): 
Seq[Option[DataType]] = {
+    val width = childOutputs.head.length
+    if (childOutputs.exists(_.length != width)) {
+      Seq.fill(width)(None)
+    } else {
+      val columns = childOutputs.transpose
+      // The first position of each group of positions that share a column.
+      val group = Array.tabulate(width)(identity)
+      def find(i: Int): Int = if (group(i) == i) i else find(group(i))
+      childOutputs.foreach { output =>
+        output.indices.groupBy(i => output(i).exprId).values.foreach { 
positions =>
+          positions.tail.foreach(i => group(find(i)) = find(positions.head))
+        }
+      }
+      val rawTypes = columns.indices.groupBy(find).map { case (first, 
positions) =>
+        first -> widerCharRawType(positions.flatMap(columns))
+      }
+      columns.indices.map(i => rawTypes(find(i)))
+    }
+  }
+
+  /**
+   * Narrows the CHAR columns and fields of the given expression, whose raw 
type is `fromType`, that
+   * are longer than those at the same places of `toType`, by removing the 
trailing spaces past the
+   * length of `toType`. Values with other characters past that length are 
kept, as read-side
+   * padding keeps them. A view stores the CHAR type of its columns, which can 
be shorter than the
+   * CHAR type of the same column of its query, such as for a view of a UNION 
created before the
+   * union had the widest length of its children. Returns None if no column or 
field is longer.
+   */
+  def narrowCharToLength(
+      expr: Expression,
+      fromType: DataType,
+      toType: DataType): Option[Expression] = {
+    narrowerCharType(fromType, toType).map { narrower =>
+      processStringForCharVarchar(expr, narrower,
+        charFuncName = Some(CHAR_TYPE_NARROWING), varcharFuncName = None,
+        keepFieldNullability = true)
+    }.filterNot(_.fastEquals(expr))
+  }
+
+  // The CHAR types of toType where fromType is longer, and STRING elsewhere, 
with the field names
+  // of toType. None if they are not both CHAR types, or structs and arrays of 
them, of one shape.
+  // Fields of other types must be the same.
+  private def narrowerCharType(fromType: DataType, toType: DataType): 
Option[DataType] = {
+    (fromType, toType) match {
+      case (c1: CharType, c2: CharType) if c1.collationId == c2.collationId =>
+        Some(if (c1.length > c2.length) c2 else c2.toStringType)
+      case (StructType(fields1), StructType(fields2)) if fields1.length == 
fields2.length =>
+        val narrowerFields = fields1.zip(fields2).map { case (from, to) =>
+          narrowerCharType(from.dataType, to.dataType).map(dt => 
to.copy(dataType = dt))
+        }
+        if (narrowerFields.forall(_.isDefined)) {
+          Some(StructType(narrowerFields.map(_.get)))
+        } else {
+          None
+        }
+      case (ArrayType(et1, _), ArrayType(et2, containsNull)) =>
+        narrowerCharType(et1, et2).map(ArrayType(_, containsNull))
+      // other fields of a struct, such as an INT next to a CHAR
+      case _ if fromType == toType && !hasChar(toType) => Some(toType)
+      case _ => None
+    }
+  }
+
+  /**
+   * The raw type of a value of the given raw type cast to `dataType`: the 
CHAR and VARCHAR types
+   * of the raw type where the cast keeps a string of the same collation, and 
the types of
+   * `dataType` elsewhere, with its field names. None if the types don't have 
the same shape.
+   */
+  def rawTypeOfCast(rawType: DataType, dataType: DataType): Option[DataType] = 
{
+    (rawType, dataType) match {
+      case (c: CharType, s: StringType) if c.collationId == s.collationId => 
Some(c)
+      case (v: VarcharType, s: StringType) if v.collationId == s.collationId 
=> Some(v)

Review Comment:
   Thanks, fixed. `rawTypeOfCast` now takes the target type when it is itself a 
CHAR or VARCHAR type, as under first-class types, so a cast to VARCHAR(5) keeps 
VARCHAR(5). Widening casts also keep raw types only where the children can be 
padded to the same lengths, which VARCHAR(3) and VARCHAR(10) can't, as written 
above. `SPARK-61972: a view of a union of VARCHAR columns under standard 
semantics` has your example: the view stores VARCHAR(5) and returns 'abcde'.



-- 
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]

Reply via email to