linhongliu-db commented on code in PR #60582:
URL: https://github.com/apache/spark/pull/60582#discussion_r4594838140


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -714,6 +716,24 @@ object Cast extends QueryErrorsBase {
 
   def resolvableNullability(from: Boolean, to: Boolean): Boolean = !from || to
 
+  // A cast from VARIANT puts NULL in any nested slot whose JSON value is null 
or missing, so, as
+  // `resolvableNullability` does for a nullable source slot, reject a target 
with a non-nullable
+  // nested slot: the cast would otherwise hold NULLs its type says cannot 
occur.
+  private def variantCastTargetRejected(to: DataType): Boolean =
+    hasNonNullableNestedSlot(to) &&
+      
!SQLConf.get.getConf(SQLConf.LEGACY_VARIANT_CAST_ALLOW_NON_NULLABLE_TARGET)
+
+  // Whether the type has a non-nullable struct field, array element or map 
value at any depth.
+  private def hasNonNullableNestedSlot(dt: DataType): Boolean = dt match {
+    case StructType(fields) =>
+      fields.exists(f => !f.nullable || hasNonNullableNestedSlot(f.dataType))
+    case ArrayType(elementType, containsNull) =>
+      !containsNull || hasNonNullableNestedSlot(elementType)
+    case MapType(_, valueType, valueContainsNull) =>
+      !valueContainsNull || hasNonNullableNestedSlot(valueType)

Review Comment:
   Agreed, fixed in f20d51efa2d. A non-nullable array element or map value now 
counts only when its type is not VARIANT, since `VariantGet.cast` returns a 
`VariantVal` (a variant null for a JSON null) for a VARIANT target. A 
non-nullable VARIANT struct field is still rejected, because a missing key 
leaves it NULL. I updated the code comment, the conf doc, the migration note 
and the PR description to match. `VariantSuite` now covers 
`ArrayType(VariantType, false)`, `MapType(StringType, VariantType, false)`, a 
struct field holding such an array (all accepted, returning variant nulls), and 
`STRUCT<user_id: VARIANT NOT NULL>` and an array of non-nullable arrays of 
VARIANT (both rejected).
   



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