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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,20 +442,285 @@ 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]] = {

Review Comment:
   Thanks, fixed. When the positions that share a column can't get one raw 
type, `widerCharRawTypes` now gives each of them its own, as long as that 
doesn't pad the shared column. In your example, `t5.c` is already the widest at 
position 0, so `c3` is padded to CHAR(5) there, and position 1 stays as it was. 
Without read-side padding every column is padded, so there a shared column 
always counts as padded, and the positions keep one raw type or none. Your 
query is in the set-operations test: it returns the row, with position 0 as 
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