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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +412,158 @@ 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.
+   */
+  def addPaddingInStringComparison(
+      exprs: Seq[Expression],
+      rawTypes: Seq[Option[DataType]],
+      alwaysPad: Boolean): 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).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 {
+      rawTypeStrings.map(s => 
Option(CatalystSqlParser.parseDataType(s.get))).reduce {
+        (left, right) => for (l <- left; r <- right; wider <- widerCharType(l, 
r)) yield wider
       }
     }
   }
 
+  /**
+   * 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.
+   */
+  def padCharToWiderLength(attr: Attribute, rawType: DataType): 
Option[(Expression, DataType)] = {
+    getRawType(attr.metadata).flatMap { attrRawType =>
+      widerCharType(attrRawType, rawType).filter(_ != attrRawType).map { wider 
=>
+        val padded = processStringForCharVarchar(
+          attr, wider, charFuncName = Some(READ_SIDE_PADDING), varcharFuncName 
= None)
+        (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))
+  }
+
+  /** The metadata of the first attribute, with the raw type of 
[[widerCharRawType]] if any. */
+  def widerCharMetadata(attrs: Seq[Attribute]): Metadata = {
+    widerCharRawType(attrs).map(withRawType(attrs.head.metadata, 
_)).getOrElse(attrs.head.metadata)
+  }
+
+  /**
+   * 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)
+    }.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.
+  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)) {

Review Comment:
   Fixed, in the narrowing and in the widening, which had the same check: 
fields of other types now match when they are the same type, so an INT next to 
a CHAR no longer stops either. The view test's `named_struct` now has an `id` 
INT field next to `c`, and the union test has a union of `STRUCT<id: INT, c: 
CHAR(3)>` and `STRUCT<id: INT, c: CHAR(5)>` columns, which is now `STRUCT<id: 
INT, c: CHAR(5)>`.



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