Github user cloud-fan commented on a diff in the pull request:
https://github.com/apache/spark/pull/9937#discussion_r46114267
--- Diff:
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/JavaTypeInference.scala
---
@@ -87,31 +96,293 @@ object JavaTypeInference {
(ArrayType(dataType, nullable), true)
case _ if mapType.isAssignableFrom(typeToken) =>
- val typeToken2 = typeToken.asInstanceOf[TypeToken[_ <: JMap[_, _]]]
- val mapSupertype = typeToken2.getSupertype(classOf[JMap[_, _]])
- val keyType =
elementType(mapSupertype.resolveType(keySetReturnType))
- val valueType =
elementType(mapSupertype.resolveType(valuesReturnType))
+ val (keyType, valueType) = mapKeyValueType(typeToken)
val (keyDataType, _) = inferDataType(keyType)
val (valueDataType, nullable) = inferDataType(valueType)
(MapType(keyDataType, valueDataType, nullable), true)
- case _ =>
- val beanInfo = Introspector.getBeanInfo(typeToken.getRawType)
- val properties =
beanInfo.getPropertyDescriptors.filterNot(_.getName == "class")
- val fields = properties.map { property =>
- val returnType =
typeToken.method(property.getReadMethod).getReturnType
- val (dataType, nullable) = inferDataType(returnType)
- new StructField(property.getName, dataType, nullable)
+ case other =>
+ val properties = getJavaBeanProperties(other)
+ if (properties.length > 0) {
+ val fields = properties.map { property =>
+ val returnType =
typeToken.method(property.getReadMethod).getReturnType
+ val (dataType, nullable) = inferDataType(returnType)
+ new StructField(property.getName, dataType, nullable)
+ }
+ (new StructType(fields), true)
+ } else {
+ throw new UnsupportedOperationException(s"Cannot infer data type
for ${other.getName}")
}
- (new StructType(fields), true)
}
}
+ private def getJavaBeanProperties(beanClass: Class[_]):
Array[PropertyDescriptor] = {
+ val beanInfo = Introspector.getBeanInfo(beanClass)
+ beanInfo.getPropertyDescriptors
+ .filter(p => p.getReadMethod != null && p.getWriteMethod != null)
+ }
+
private def elementType(typeToken: TypeToken[_]): TypeToken[_] = {
val typeToken2 = typeToken.asInstanceOf[TypeToken[_ <: JIterable[_]]]
- val iterableSupertype = typeToken2.getSupertype(classOf[JIterable[_]])
- val iteratorType = iterableSupertype.resolveType(iteratorReturnType)
- val itemType = iteratorType.resolveType(nextReturnType)
- itemType
+ val iterableSuperType = typeToken2.getSupertype(classOf[JIterable[_]])
+ val iteratorType = iterableSuperType.resolveType(iteratorReturnType)
+ iteratorType.resolveType(nextReturnType)
+ }
+
+ private def mapKeyValueType(typeToken: TypeToken[_]): (TypeToken[_],
TypeToken[_]) = {
+ val typeToken2 = typeToken.asInstanceOf[TypeToken[_ <: JMap[_, _]]]
+ val mapSuperType = typeToken2.getSupertype(classOf[JMap[_, _]])
+ val keyType = elementType(mapSuperType.resolveType(keySetReturnType))
+ val valueType = elementType(mapSuperType.resolveType(valuesReturnType))
+ keyType -> valueType
+ }
+
+ private def inferExternalType(cls: Class[_]): DataType = cls match {
+ case c if c == java.lang.Boolean.TYPE => BooleanType
+ case c if c == java.lang.Byte.TYPE => ByteType
+ case c if c == java.lang.Short.TYPE => ShortType
+ case c if c == java.lang.Integer.TYPE => IntegerType
+ case c if c == java.lang.Long.TYPE => LongType
+ case c if c == java.lang.Float.TYPE => FloatType
+ case c if c == java.lang.Double.TYPE => DoubleType
+ case c if c == classOf[Array[Byte]] => BinaryType
+ case _ => ObjectType(cls)
+ }
+
+ def constructorFor(beanClass: Class[_]): Expression = {
+ constructorFor(TypeToken.of(beanClass), None)
+ }
+
+ private def constructorFor(typeToken: TypeToken[_], path:
Option[Expression]): Expression = {
+ /** Returns the current path with a sub-field extracted. */
+ def addToPath(part: String): Expression = path
+ .map(p => UnresolvedExtractValue(p, expressions.Literal(part)))
+ .getOrElse(UnresolvedAttribute(part))
+
+ /** Returns the current path or `BoundReference`. */
+ def getPath: Expression = path.getOrElse(BoundReference(0,
inferDataType(typeToken)._1, true))
+
+ typeToken.getRawType match {
+ case c if !inferExternalType(c).isInstanceOf[ObjectType] => getPath
+
+ case c if c == classOf[java.lang.Short] =>
+ NewInstance(c, getPath :: Nil, propagateNull = true, ObjectType(c))
+ case c if c == classOf[java.lang.Integer] =>
+ NewInstance(c, getPath :: Nil, propagateNull = true, ObjectType(c))
+ case c if c == classOf[java.lang.Long] =>
+ NewInstance(c, getPath :: Nil, propagateNull = true, ObjectType(c))
+ case c if c == classOf[java.lang.Double] =>
+ NewInstance(c, getPath :: Nil, propagateNull = true, ObjectType(c))
+ case c if c == classOf[java.lang.Byte] =>
+ NewInstance(c, getPath :: Nil, propagateNull = true, ObjectType(c))
+ case c if c == classOf[java.lang.Float] =>
+ NewInstance(c, getPath :: Nil, propagateNull = true, ObjectType(c))
+ case c if c == classOf[java.lang.Boolean] =>
+ NewInstance(c, getPath :: Nil, propagateNull = true, ObjectType(c))
+
+ case c if c == classOf[java.sql.Date] =>
+ StaticInvoke(
+ DateTimeUtils,
+ ObjectType(c),
+ "toJavaDate",
+ getPath :: Nil,
+ propagateNull = true)
+
+ case c if c == classOf[java.sql.Timestamp] =>
+ StaticInvoke(
+ DateTimeUtils,
+ ObjectType(c),
+ "toJavaTimestamp",
+ getPath :: Nil,
+ propagateNull = true)
+
+ case c if c == classOf[java.lang.String] =>
+ Invoke(getPath, "toString", ObjectType(classOf[String]))
+
+ case c if c == classOf[java.math.BigDecimal] =>
+ Invoke(getPath, "toJavaBigDecimal",
ObjectType(classOf[java.math.BigDecimal]))
+
+ case c if c.isArray =>
+ val elementType = c.getComponentType
+ val primitiveMethod = elementType match {
+ case c if c == java.lang.Boolean.TYPE => Some("toBooleanArray")
+ case c if c == java.lang.Byte.TYPE => Some("toByteArray")
+ case c if c == java.lang.Short.TYPE => Some("toShortArray")
+ case c if c == java.lang.Integer.TYPE => Some("toIntArray")
+ case c if c == java.lang.Long.TYPE => Some("toLongArray")
+ case c if c == java.lang.Float.TYPE => Some("toFloatArray")
+ case c if c == java.lang.Double.TYPE => Some("toDoubleArray")
+ case _ => None
+ }
+
+ primitiveMethod.map { method =>
+ Invoke(getPath, method, ObjectType(c))
+ }.getOrElse {
+ Invoke(
+ MapObjects(
+ p => constructorFor(typeToken.getComponentType, Some(p)),
+ getPath,
+ inferDataType(elementType)._1),
+ "array",
+ ObjectType(c))
+ }
+
+ case c if listType.isAssignableFrom(typeToken) =>
+ val et = elementType(typeToken)
+ val array =
+ Invoke(
+ MapObjects(
+ p => constructorFor(et, Some(p)),
+ getPath,
+ inferDataType(et)._1),
+ "array",
+ ObjectType(classOf[Array[Any]]))
+
+ StaticInvoke(classOf[java.util.Arrays], ObjectType(c), "asList",
array :: Nil)
+
+ case _ if mapType.isAssignableFrom(typeToken) =>
+ val (keyType, valueType) = mapKeyValueType(typeToken)
+ val keyDataType = inferDataType(keyType)._1
+ val valueDataType = inferDataType(valueType)._1
+
+ val keyData =
+ Invoke(
+ MapObjects(
+ p => constructorFor(keyType, Some(p)),
+ Invoke(getPath, "keyArray", ArrayType(keyDataType)),
+ keyDataType),
+ "array",
+ ObjectType(classOf[Array[Any]]))
+
+ val valueData =
+ Invoke(
+ MapObjects(
+ p => constructorFor(valueType, Some(p)),
+ Invoke(getPath, "valueArray", ArrayType(valueDataType)),
+ valueDataType),
+ "array",
+ ObjectType(classOf[Array[Any]]))
+
+ StaticInvoke(
+ ArrayBasedMapData,
+ ObjectType(classOf[JMap[_, _]]),
+ "toJavaMap",
+ keyData :: valueData :: Nil)
+
+ case other =>
+ val properties = getJavaBeanProperties(other)
+ assert(properties.length > 0)
+
+ val setters = properties.map { p =>
+ val fieldName = p.getName
+ val fieldType = typeToken.method(p.getReadMethod).getReturnType
+ p.getWriteMethod.getName -> constructorFor(fieldType,
Some(addToPath(fieldName)))
+ }.toMap
+
+ val newInstance = NewInstance(other, Nil, propagateNull = false,
ObjectType(other))
+ val result = InitializeJavaBean(newInstance, setters)
+
+ if (path.nonEmpty) {
+ expressions.If(
+ IsNull(getPath),
+ expressions.Literal.create(null, ObjectType(other)),
+ result
+ )
+ } else {
+ result
+ }
+ }
+ }
+
+ def extractorsFor(inputObject: Expression, beanClass: Class[_]):
CreateNamedStruct = {
+ extractorFor(inputObject,
TypeToken.of(beanClass)).asInstanceOf[CreateNamedStruct]
+ }
+
+ private def extractorFor(inputObject: Expression, typeToken:
TypeToken[_]): Expression = {
+
+ def toCatalystArray(input: Expression, elementType: TypeToken[_]):
Expression = {
+ val externalType = inferExternalType(elementType.getRawType)
+ val (dataType, nullable) = inferDataType(elementType)
+ if (ScalaReflection.isNativeType(dataType)) {
+ NewInstance(
+ classOf[GenericArrayData],
+ input :: Nil,
+ dataType = ArrayType(dataType, nullable))
+ } else {
+ MapObjects(extractorFor(_, elementType), input, externalType)
+ }
+ }
+
+ if (!inputObject.dataType.isInstanceOf[ObjectType]) {
+ inputObject
+ } else {
+ typeToken.getRawType match {
+ case c if c == classOf[String] =>
+ StaticInvoke(
+ classOf[UTF8String],
+ StringType,
+ "fromString",
+ inputObject :: Nil)
+
+ case c if c == classOf[java.sql.Timestamp] =>
+ StaticInvoke(
+ DateTimeUtils,
+ TimestampType,
+ "fromJavaTimestamp",
+ inputObject :: Nil)
+
+ case c if c == classOf[java.sql.Date] =>
+ StaticInvoke(
+ DateTimeUtils,
+ DateType,
+ "fromJavaDate",
+ inputObject :: Nil)
+
+ case c if c == classOf[java.math.BigDecimal] =>
+ StaticInvoke(
+ Decimal,
+ DecimalType.SYSTEM_DEFAULT,
+ "apply",
+ inputObject :: Nil)
+
+ case c if c == classOf[java.lang.Boolean] =>
+ Invoke(inputObject, "booleanValue", BooleanType)
+ case c if c == classOf[java.lang.Byte] =>
+ Invoke(inputObject, "byteValue", ByteType)
+ case c if c == classOf[java.lang.Short] =>
+ Invoke(inputObject, "shortValue", ShortType)
+ case c if c == classOf[java.lang.Integer] =>
+ Invoke(inputObject, "intValue", IntegerType)
+ case c if c == classOf[java.lang.Long] =>
+ Invoke(inputObject, "longValue", LongType)
+ case c if c == classOf[java.lang.Float] =>
+ Invoke(inputObject, "floatValue", FloatType)
+ case c if c == classOf[java.lang.Double] =>
+ Invoke(inputObject, "doubleValue", DoubleType)
+
+ case _ if typeToken.isArray =>
+ toCatalystArray(inputObject, typeToken.getComponentType)
+
+ case _ if listType.isAssignableFrom(typeToken) =>
+ toCatalystArray(inputObject, elementType(typeToken))
+
+ case _ if mapType.isAssignableFrom(typeToken) =>
+ throw new UnsupportedOperationException("map type is not
supported currently")
--- End diff --
The problem is that, for java map, if we get the keys and values by
`keySet` and `values`, we can not guarantee they have same iteration
order(which is different from scala map). A possible solution is creating a new
`MapObjects` that can iterate a map directly.
cc @marmbrus
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]