You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2022/12/22 19:03:37 UTC

[GitHub] [spark] hvanhovell opened a new pull request, #39186: [SPARK-41690][SQL][CONNECT] Agnostic Encoders

hvanhovell opened a new pull request, #39186:
URL: https://github.com/apache/spark/pull/39186

   ### What changes were proposed in this pull request?
   This PR introduces so AgnosticEncoders. AgnosticEncoders describe how an external type maps to a Spark data type. They are agnostic in the sense that they do not prescribe which internal format is to be used.
   
   For example the following class:
   ```
   case class Person(id: Long, name: String, hobbies: Seq[String])
   ```
   
   Translates into the following agnostic encoder:
   ```
   ProductEncoder(Person,List(
     (id, PrimitiveLongEncoder),
     (name, StringEncoder),
     (hobbies, IterableEncoder(scala.collection.Seq,StringEncoder))))
   ```
   
   This PR integrates `AgnosticEncoders` in `ScalaReflection`, and so it is used for all `Dataset` operations. In a follow-up we will address `RowEncoder` and `JavaReflection`. In the old situation we would traverse the type hierarchy for each options (`serializedForType`, `deserializerForType` & `schemaFor`). In the new situation we will create an AgnosticEncoder first and then generate a serializer, deserializer, and/or `schema`. This saves significantly in time, especially for `ExpressionEncoder` where we only need one pass through the type hierarchy instead 2 or 3.
   
   ### Why are the changes needed?
   For the Spark Connect Scala Client we need encoders. We want to stay as close to the current Dataset APIs and encoders are part of this. Additionally we would like retain the rich type support.
   
   Encoders are currently tied to ExpressionEncoders, we cannot use for a couple of reasons:
   1. Mid-term we don't want to have a dependency on Catalyst. Splitting of the public API that will be shared between Catalyst and the client is tracked in SPARK-41400.
   2. ExpressionEncoders only support the internal row format. The client will use Arrow instead.
   3. We are nog particularly keen on sending the expressions needed by ExpressionEncoders over the wire. They are overpowered.
   
   So we need an alternative to the current ExpressionEncoders. This class need to be serializable.
   
   ### Does this PR introduce _any_ user-facing change?
   No
   
   ### How was this patch tested?
   Existing tests.


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] cloud-fan closed pull request #39186: [SPARK-41690][SQL][CONNECT] Agnostic Encoders

Posted by GitBox <gi...@apache.org>.
cloud-fan closed pull request #39186: [SPARK-41690][SQL][CONNECT] Agnostic Encoders
URL: https://github.com/apache/spark/pull/39186


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] cloud-fan commented on a diff in pull request #39186: [SPARK-41690][SQL][CONNECT] Agnostic Encoders

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on code in PR #39186:
URL: https://github.com/apache/spark/pull/39186#discussion_r1056264625


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/ScalaReflection.scala:
##########
@@ -186,237 +167,129 @@ object ScalaReflection extends ScalaReflection {
    * @param walkedTypePath The paths from top to bottom to access current field when deserializing.
    */
   private def deserializerFor(
-      tpe: `Type`,
-      walkedTypePath: WalkedTypePath): Expression => Expression = cleanUpReflectionObjects {
-    baseType(tpe) match {
-      case t if !dataTypeFor(t).isInstanceOf[ObjectType] => identity
-
-      case t if isSubtype(t, localTypeOf[Option[_]]) =>
-        val TypeRef(_, _, Seq(optType)) = t
-        val className = getClassNameFromType(optType)
-        val newTypePath = walkedTypePath.recordOption(className)
-        val dataType = dataTypeFor(optType)
-        val deserializerFunc = deserializerFor(optType, newTypePath)
-        path => WrapOption(deserializerFunc(path), dataType)
-
-      case t if isSubtype(t, localTypeOf[java.lang.Integer]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Integer])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Long]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Long])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Double]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Double])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Float]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Float])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Short]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Short])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Byte]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Byte])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Boolean]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Boolean])
-
-      case t if isSubtype(t, localTypeOf[java.time.LocalDate]) =>
-        createDeserializerForLocalDate
-
-      case t if isSubtype(t, localTypeOf[java.sql.Date]) =>
-        createDeserializerForSqlDate
-
-      case t if isSubtype(t, localTypeOf[java.time.Instant]) =>
-        createDeserializerForInstant
-
-      case t if isSubtype(t, localTypeOf[java.lang.Enum[_]]) =>
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val cls = getClassFromType(t)
-        path => createDeserializerForTypesSupportValueOf(
-          Invoke(path, "toString", ObjectType(classOf[String]), returnNullable = false), cls)
-
-      case t if isSubtype(t, localTypeOf[java.sql.Timestamp]) =>
-        createDeserializerForSqlTimestamp
-
-      case t if isSubtype(t, localTypeOf[java.time.LocalDateTime]) =>
-        createDeserializerForLocalDateTime
-
-      case t if isSubtype(t, localTypeOf[java.time.Duration]) =>
-        createDeserializerForDuration
-
-      case t if isSubtype(t, localTypeOf[java.time.Period]) =>
-        createDeserializerForPeriod
-
-      case t if isSubtype(t, localTypeOf[java.lang.String]) =>
-        createDeserializerForString(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[java.math.BigDecimal]) =>
-        createDeserializerForJavaBigDecimal(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[BigDecimal]) =>
-        createDeserializerForScalaBigDecimal(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[java.math.BigInteger]) =>
-        createDeserializerForJavaBigInteger(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[scala.math.BigInt]) =>
-        createDeserializerForScalaBigInt
-
-      case t if isSubtype(t, localTypeOf[Array[_]]) =>
-        val TypeRef(_, _, Seq(elementType)) = t
-        val Schema(dataType, elementNullable) = schemaFor(elementType)
-        val className = getClassNameFromType(elementType)
-        val newTypePath = walkedTypePath.recordArray(className)
-        val deserializerFunc = deserializerFor(elementType, newTypePath)
-        val mapFunction: Expression => Expression = element => {
-          // upcast the array element to the data type the encoder expected.
-          deserializerForWithNullSafetyAndUpcast(
-            element,
-            dataType,
-            nullable = elementNullable,
-            newTypePath,
-            deserializerFunc)
-        }
-
-        val arrayCls = arrayClassFor(elementType)
-
-        val methodName = elementType match {
-          case t if isSubtype(t, definitions.IntTpe) => "toIntArray"
-          case t if isSubtype(t, definitions.LongTpe) => "toLongArray"
-          case t if isSubtype(t, definitions.DoubleTpe) => "toDoubleArray"
-          case t if isSubtype(t, definitions.FloatTpe) => "toFloatArray"
-          case t if isSubtype(t, definitions.ShortTpe) => "toShortArray"
-          case t if isSubtype(t, definitions.ByteTpe) => "toByteArray"
-          case t if isSubtype(t, definitions.BooleanTpe) => "toBooleanArray"
-          // non-primitive
-          case _ => "array"
-        }
-        path => {
-          val arrayData = UnresolvedMapObjects(mapFunction, path)
-          Invoke(arrayData, methodName, arrayCls, returnNullable = false)
-        }
-
-      // We serialize a `Set` to Catalyst array. When we deserialize a Catalyst array
-      // to a `Set`, if there are duplicated elements, the elements will be de-duplicated.
-      case t if isSubtype(t, localTypeOf[scala.collection.Seq[_]]) ||
-          isSubtype(t, localTypeOf[scala.collection.Set[_]]) =>
-        val TypeRef(_, _, Seq(elementType)) = t
-        val Schema(dataType, elementNullable) = schemaFor(elementType)
-        val className = getClassNameFromType(elementType)
-        val newTypePath = walkedTypePath.recordArray(className)
-        val deserializerFunc = deserializerFor(elementType, newTypePath)
-        val mapFunction: Expression => Expression = element => {
-          deserializerForWithNullSafetyAndUpcast(
-            element,
-            dataType,
-            nullable = elementNullable,
-            newTypePath,
-            deserializerFunc)
-        }
-
-        val companion = t.dealias.typeSymbol.companion.typeSignature
-        val cls = companion.member(TermName("newBuilder")) match {
-          case NoSymbol if isSubtype(t, localTypeOf[Seq[_]]) => classOf[Seq[_]]
-          case NoSymbol if isSubtype(t, localTypeOf[scala.collection.Set[_]]) =>
-            classOf[scala.collection.Set[_]]
-          case _ => mirror.runtimeClass(t.typeSymbol.asClass)
-        }
-        UnresolvedMapObjects(mapFunction, _, Some(cls))
-
-      case t if isSubtype(t, localTypeOf[Map[_, _]]) =>
-        val TypeRef(_, _, Seq(keyType, valueType)) = t
-
-        val classNameForKey = getClassNameFromType(keyType)
-        val classNameForValue = getClassNameFromType(valueType)
-
-        val newTypePath = walkedTypePath.recordMap(classNameForKey, classNameForValue)
-
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val keyDeserializerFunc = deserializerFor(keyType, newTypePath)
-        val valueDeserializerFunc = deserializerFor(valueType, newTypePath)
-        val cls = mirror.runtimeClass(t.typeSymbol.asClass)
-        UnresolvedCatalystToExternalMap(_, keyDeserializerFunc, valueDeserializerFunc, cls)
-
-      case t if t.typeSymbol.annotations.exists(_.tree.tpe =:= typeOf[SQLUserDefinedType]) =>
-        val udt = getClassFromType(t).getAnnotation(classOf[SQLUserDefinedType]).udt().
-          getConstructor().newInstance()
-        val obj = NewInstance(
-          udt.userClass.getAnnotation(classOf[SQLUserDefinedType]).udt(),
-          Nil,
-          dataType = ObjectType(udt.userClass.getAnnotation(classOf[SQLUserDefinedType]).udt()))
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val cls = udt.userClass
-        path => Invoke(obj, "deserialize", ObjectType(cls), Seq(path))
-
-      case t if UDTRegistration.exists(getClassNameFromType(t)) =>
-        val udt = UDTRegistration.getUDTFor(getClassNameFromType(t)).get.getConstructor().
-          newInstance().asInstanceOf[UserDefinedType[_]]
-        val obj = NewInstance(
-          udt.getClass,
-          Nil,
-          dataType = ObjectType(udt.getClass))
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val cls = udt.userClass
-        path => Invoke(obj, "deserialize", ObjectType(cls), Seq(path))
-
-      case t if definedByConstructorParams(t) =>
-        val params = getConstructorParameters(t)
-
-        val cls = getClassFromType(tpe)
-
-        val arguDeserializerFuncs = params.zipWithIndex.map { case ((fieldName, fieldType), i) =>
-          val Schema(dataType, nullable) = schemaFor(fieldType)
-          val clsName = getClassNameFromType(fieldType)
-          val newTypePath = walkedTypePath.recordField(clsName, fieldName)
-
-          // For tuples, we based grab the inner fields by ordinal instead of name.
-          val newPathFunc = if (cls.getName startsWith "scala.Tuple") {
-            addToPathOrdinal(_, i, dataType, newTypePath)
+      enc: AgnosticEncoder[_],
+      input: Expression,
+      typePath: WalkedTypePath): Expression = enc match {
+    case _ if isNativeEncoder(enc) =>
+      input
+    case BooleanEncoder =>

Review Comment:
   nvm, we have `PrimitiveBooleanEncoder` and `BooleanEncoder`



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/ScalaReflection.scala:
##########
@@ -186,237 +167,129 @@ object ScalaReflection extends ScalaReflection {
    * @param walkedTypePath The paths from top to bottom to access current field when deserializing.
    */
   private def deserializerFor(
-      tpe: `Type`,
-      walkedTypePath: WalkedTypePath): Expression => Expression = cleanUpReflectionObjects {
-    baseType(tpe) match {
-      case t if !dataTypeFor(t).isInstanceOf[ObjectType] => identity
-
-      case t if isSubtype(t, localTypeOf[Option[_]]) =>
-        val TypeRef(_, _, Seq(optType)) = t
-        val className = getClassNameFromType(optType)
-        val newTypePath = walkedTypePath.recordOption(className)
-        val dataType = dataTypeFor(optType)
-        val deserializerFunc = deserializerFor(optType, newTypePath)
-        path => WrapOption(deserializerFunc(path), dataType)
-
-      case t if isSubtype(t, localTypeOf[java.lang.Integer]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Integer])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Long]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Long])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Double]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Double])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Float]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Float])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Short]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Short])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Byte]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Byte])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Boolean]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Boolean])
-
-      case t if isSubtype(t, localTypeOf[java.time.LocalDate]) =>
-        createDeserializerForLocalDate
-
-      case t if isSubtype(t, localTypeOf[java.sql.Date]) =>
-        createDeserializerForSqlDate
-
-      case t if isSubtype(t, localTypeOf[java.time.Instant]) =>
-        createDeserializerForInstant
-
-      case t if isSubtype(t, localTypeOf[java.lang.Enum[_]]) =>
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val cls = getClassFromType(t)
-        path => createDeserializerForTypesSupportValueOf(
-          Invoke(path, "toString", ObjectType(classOf[String]), returnNullable = false), cls)
-
-      case t if isSubtype(t, localTypeOf[java.sql.Timestamp]) =>
-        createDeserializerForSqlTimestamp
-
-      case t if isSubtype(t, localTypeOf[java.time.LocalDateTime]) =>
-        createDeserializerForLocalDateTime
-
-      case t if isSubtype(t, localTypeOf[java.time.Duration]) =>
-        createDeserializerForDuration
-
-      case t if isSubtype(t, localTypeOf[java.time.Period]) =>
-        createDeserializerForPeriod
-
-      case t if isSubtype(t, localTypeOf[java.lang.String]) =>
-        createDeserializerForString(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[java.math.BigDecimal]) =>
-        createDeserializerForJavaBigDecimal(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[BigDecimal]) =>
-        createDeserializerForScalaBigDecimal(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[java.math.BigInteger]) =>
-        createDeserializerForJavaBigInteger(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[scala.math.BigInt]) =>
-        createDeserializerForScalaBigInt
-
-      case t if isSubtype(t, localTypeOf[Array[_]]) =>
-        val TypeRef(_, _, Seq(elementType)) = t
-        val Schema(dataType, elementNullable) = schemaFor(elementType)
-        val className = getClassNameFromType(elementType)
-        val newTypePath = walkedTypePath.recordArray(className)
-        val deserializerFunc = deserializerFor(elementType, newTypePath)
-        val mapFunction: Expression => Expression = element => {
-          // upcast the array element to the data type the encoder expected.
-          deserializerForWithNullSafetyAndUpcast(
-            element,
-            dataType,
-            nullable = elementNullable,
-            newTypePath,
-            deserializerFunc)
-        }
-
-        val arrayCls = arrayClassFor(elementType)
-
-        val methodName = elementType match {
-          case t if isSubtype(t, definitions.IntTpe) => "toIntArray"
-          case t if isSubtype(t, definitions.LongTpe) => "toLongArray"
-          case t if isSubtype(t, definitions.DoubleTpe) => "toDoubleArray"
-          case t if isSubtype(t, definitions.FloatTpe) => "toFloatArray"
-          case t if isSubtype(t, definitions.ShortTpe) => "toShortArray"
-          case t if isSubtype(t, definitions.ByteTpe) => "toByteArray"
-          case t if isSubtype(t, definitions.BooleanTpe) => "toBooleanArray"
-          // non-primitive
-          case _ => "array"
-        }
-        path => {
-          val arrayData = UnresolvedMapObjects(mapFunction, path)
-          Invoke(arrayData, methodName, arrayCls, returnNullable = false)
-        }
-
-      // We serialize a `Set` to Catalyst array. When we deserialize a Catalyst array
-      // to a `Set`, if there are duplicated elements, the elements will be de-duplicated.
-      case t if isSubtype(t, localTypeOf[scala.collection.Seq[_]]) ||
-          isSubtype(t, localTypeOf[scala.collection.Set[_]]) =>
-        val TypeRef(_, _, Seq(elementType)) = t
-        val Schema(dataType, elementNullable) = schemaFor(elementType)
-        val className = getClassNameFromType(elementType)
-        val newTypePath = walkedTypePath.recordArray(className)
-        val deserializerFunc = deserializerFor(elementType, newTypePath)
-        val mapFunction: Expression => Expression = element => {
-          deserializerForWithNullSafetyAndUpcast(
-            element,
-            dataType,
-            nullable = elementNullable,
-            newTypePath,
-            deserializerFunc)
-        }
-
-        val companion = t.dealias.typeSymbol.companion.typeSignature
-        val cls = companion.member(TermName("newBuilder")) match {
-          case NoSymbol if isSubtype(t, localTypeOf[Seq[_]]) => classOf[Seq[_]]
-          case NoSymbol if isSubtype(t, localTypeOf[scala.collection.Set[_]]) =>
-            classOf[scala.collection.Set[_]]
-          case _ => mirror.runtimeClass(t.typeSymbol.asClass)
-        }
-        UnresolvedMapObjects(mapFunction, _, Some(cls))
-
-      case t if isSubtype(t, localTypeOf[Map[_, _]]) =>
-        val TypeRef(_, _, Seq(keyType, valueType)) = t
-
-        val classNameForKey = getClassNameFromType(keyType)
-        val classNameForValue = getClassNameFromType(valueType)
-
-        val newTypePath = walkedTypePath.recordMap(classNameForKey, classNameForValue)
-
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val keyDeserializerFunc = deserializerFor(keyType, newTypePath)
-        val valueDeserializerFunc = deserializerFor(valueType, newTypePath)
-        val cls = mirror.runtimeClass(t.typeSymbol.asClass)
-        UnresolvedCatalystToExternalMap(_, keyDeserializerFunc, valueDeserializerFunc, cls)
-
-      case t if t.typeSymbol.annotations.exists(_.tree.tpe =:= typeOf[SQLUserDefinedType]) =>
-        val udt = getClassFromType(t).getAnnotation(classOf[SQLUserDefinedType]).udt().
-          getConstructor().newInstance()
-        val obj = NewInstance(
-          udt.userClass.getAnnotation(classOf[SQLUserDefinedType]).udt(),
-          Nil,
-          dataType = ObjectType(udt.userClass.getAnnotation(classOf[SQLUserDefinedType]).udt()))
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val cls = udt.userClass
-        path => Invoke(obj, "deserialize", ObjectType(cls), Seq(path))
-
-      case t if UDTRegistration.exists(getClassNameFromType(t)) =>
-        val udt = UDTRegistration.getUDTFor(getClassNameFromType(t)).get.getConstructor().
-          newInstance().asInstanceOf[UserDefinedType[_]]
-        val obj = NewInstance(
-          udt.getClass,
-          Nil,
-          dataType = ObjectType(udt.getClass))
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val cls = udt.userClass
-        path => Invoke(obj, "deserialize", ObjectType(cls), Seq(path))
-
-      case t if definedByConstructorParams(t) =>
-        val params = getConstructorParameters(t)
-
-        val cls = getClassFromType(tpe)
-
-        val arguDeserializerFuncs = params.zipWithIndex.map { case ((fieldName, fieldType), i) =>
-          val Schema(dataType, nullable) = schemaFor(fieldType)
-          val clsName = getClassNameFromType(fieldType)
-          val newTypePath = walkedTypePath.recordField(clsName, fieldName)
-
-          // For tuples, we based grab the inner fields by ordinal instead of name.
-          val newPathFunc = if (cls.getName startsWith "scala.Tuple") {
-            addToPathOrdinal(_, i, dataType, newTypePath)
+      enc: AgnosticEncoder[_],
+      input: Expression,
+      typePath: WalkedTypePath): Expression = enc match {
+    case _ if isNativeEncoder(enc) =>
+      input
+    case BooleanEncoder =>

Review Comment:
   maybe `BoxedBooleanEncoder` is a better name



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] cloud-fan commented on a diff in pull request #39186: [SPARK-41690][SQL][CONNECT] Agnostic Encoders

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on code in PR #39186:
URL: https://github.com/apache/spark/pull/39186#discussion_r1056263221


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/ScalaReflection.scala:
##########
@@ -186,237 +167,129 @@ object ScalaReflection extends ScalaReflection {
    * @param walkedTypePath The paths from top to bottom to access current field when deserializing.
    */
   private def deserializerFor(
-      tpe: `Type`,
-      walkedTypePath: WalkedTypePath): Expression => Expression = cleanUpReflectionObjects {
-    baseType(tpe) match {
-      case t if !dataTypeFor(t).isInstanceOf[ObjectType] => identity
-
-      case t if isSubtype(t, localTypeOf[Option[_]]) =>
-        val TypeRef(_, _, Seq(optType)) = t
-        val className = getClassNameFromType(optType)
-        val newTypePath = walkedTypePath.recordOption(className)
-        val dataType = dataTypeFor(optType)
-        val deserializerFunc = deserializerFor(optType, newTypePath)
-        path => WrapOption(deserializerFunc(path), dataType)
-
-      case t if isSubtype(t, localTypeOf[java.lang.Integer]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Integer])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Long]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Long])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Double]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Double])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Float]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Float])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Short]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Short])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Byte]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Byte])
-
-      case t if isSubtype(t, localTypeOf[java.lang.Boolean]) =>
-        createDeserializerForTypesSupportValueOf(_, classOf[java.lang.Boolean])
-
-      case t if isSubtype(t, localTypeOf[java.time.LocalDate]) =>
-        createDeserializerForLocalDate
-
-      case t if isSubtype(t, localTypeOf[java.sql.Date]) =>
-        createDeserializerForSqlDate
-
-      case t if isSubtype(t, localTypeOf[java.time.Instant]) =>
-        createDeserializerForInstant
-
-      case t if isSubtype(t, localTypeOf[java.lang.Enum[_]]) =>
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val cls = getClassFromType(t)
-        path => createDeserializerForTypesSupportValueOf(
-          Invoke(path, "toString", ObjectType(classOf[String]), returnNullable = false), cls)
-
-      case t if isSubtype(t, localTypeOf[java.sql.Timestamp]) =>
-        createDeserializerForSqlTimestamp
-
-      case t if isSubtype(t, localTypeOf[java.time.LocalDateTime]) =>
-        createDeserializerForLocalDateTime
-
-      case t if isSubtype(t, localTypeOf[java.time.Duration]) =>
-        createDeserializerForDuration
-
-      case t if isSubtype(t, localTypeOf[java.time.Period]) =>
-        createDeserializerForPeriod
-
-      case t if isSubtype(t, localTypeOf[java.lang.String]) =>
-        createDeserializerForString(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[java.math.BigDecimal]) =>
-        createDeserializerForJavaBigDecimal(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[BigDecimal]) =>
-        createDeserializerForScalaBigDecimal(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[java.math.BigInteger]) =>
-        createDeserializerForJavaBigInteger(_, returnNullable = false)
-
-      case t if isSubtype(t, localTypeOf[scala.math.BigInt]) =>
-        createDeserializerForScalaBigInt
-
-      case t if isSubtype(t, localTypeOf[Array[_]]) =>
-        val TypeRef(_, _, Seq(elementType)) = t
-        val Schema(dataType, elementNullable) = schemaFor(elementType)
-        val className = getClassNameFromType(elementType)
-        val newTypePath = walkedTypePath.recordArray(className)
-        val deserializerFunc = deserializerFor(elementType, newTypePath)
-        val mapFunction: Expression => Expression = element => {
-          // upcast the array element to the data type the encoder expected.
-          deserializerForWithNullSafetyAndUpcast(
-            element,
-            dataType,
-            nullable = elementNullable,
-            newTypePath,
-            deserializerFunc)
-        }
-
-        val arrayCls = arrayClassFor(elementType)
-
-        val methodName = elementType match {
-          case t if isSubtype(t, definitions.IntTpe) => "toIntArray"
-          case t if isSubtype(t, definitions.LongTpe) => "toLongArray"
-          case t if isSubtype(t, definitions.DoubleTpe) => "toDoubleArray"
-          case t if isSubtype(t, definitions.FloatTpe) => "toFloatArray"
-          case t if isSubtype(t, definitions.ShortTpe) => "toShortArray"
-          case t if isSubtype(t, definitions.ByteTpe) => "toByteArray"
-          case t if isSubtype(t, definitions.BooleanTpe) => "toBooleanArray"
-          // non-primitive
-          case _ => "array"
-        }
-        path => {
-          val arrayData = UnresolvedMapObjects(mapFunction, path)
-          Invoke(arrayData, methodName, arrayCls, returnNullable = false)
-        }
-
-      // We serialize a `Set` to Catalyst array. When we deserialize a Catalyst array
-      // to a `Set`, if there are duplicated elements, the elements will be de-duplicated.
-      case t if isSubtype(t, localTypeOf[scala.collection.Seq[_]]) ||
-          isSubtype(t, localTypeOf[scala.collection.Set[_]]) =>
-        val TypeRef(_, _, Seq(elementType)) = t
-        val Schema(dataType, elementNullable) = schemaFor(elementType)
-        val className = getClassNameFromType(elementType)
-        val newTypePath = walkedTypePath.recordArray(className)
-        val deserializerFunc = deserializerFor(elementType, newTypePath)
-        val mapFunction: Expression => Expression = element => {
-          deserializerForWithNullSafetyAndUpcast(
-            element,
-            dataType,
-            nullable = elementNullable,
-            newTypePath,
-            deserializerFunc)
-        }
-
-        val companion = t.dealias.typeSymbol.companion.typeSignature
-        val cls = companion.member(TermName("newBuilder")) match {
-          case NoSymbol if isSubtype(t, localTypeOf[Seq[_]]) => classOf[Seq[_]]
-          case NoSymbol if isSubtype(t, localTypeOf[scala.collection.Set[_]]) =>
-            classOf[scala.collection.Set[_]]
-          case _ => mirror.runtimeClass(t.typeSymbol.asClass)
-        }
-        UnresolvedMapObjects(mapFunction, _, Some(cls))
-
-      case t if isSubtype(t, localTypeOf[Map[_, _]]) =>
-        val TypeRef(_, _, Seq(keyType, valueType)) = t
-
-        val classNameForKey = getClassNameFromType(keyType)
-        val classNameForValue = getClassNameFromType(valueType)
-
-        val newTypePath = walkedTypePath.recordMap(classNameForKey, classNameForValue)
-
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val keyDeserializerFunc = deserializerFor(keyType, newTypePath)
-        val valueDeserializerFunc = deserializerFor(valueType, newTypePath)
-        val cls = mirror.runtimeClass(t.typeSymbol.asClass)
-        UnresolvedCatalystToExternalMap(_, keyDeserializerFunc, valueDeserializerFunc, cls)
-
-      case t if t.typeSymbol.annotations.exists(_.tree.tpe =:= typeOf[SQLUserDefinedType]) =>
-        val udt = getClassFromType(t).getAnnotation(classOf[SQLUserDefinedType]).udt().
-          getConstructor().newInstance()
-        val obj = NewInstance(
-          udt.userClass.getAnnotation(classOf[SQLUserDefinedType]).udt(),
-          Nil,
-          dataType = ObjectType(udt.userClass.getAnnotation(classOf[SQLUserDefinedType]).udt()))
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val cls = udt.userClass
-        path => Invoke(obj, "deserialize", ObjectType(cls), Seq(path))
-
-      case t if UDTRegistration.exists(getClassNameFromType(t)) =>
-        val udt = UDTRegistration.getUDTFor(getClassNameFromType(t)).get.getConstructor().
-          newInstance().asInstanceOf[UserDefinedType[_]]
-        val obj = NewInstance(
-          udt.getClass,
-          Nil,
-          dataType = ObjectType(udt.getClass))
-        // Code touching Scala Reflection should be called outside the returned function to allow
-        // caching the Scala Reflection result
-        val cls = udt.userClass
-        path => Invoke(obj, "deserialize", ObjectType(cls), Seq(path))
-
-      case t if definedByConstructorParams(t) =>
-        val params = getConstructorParameters(t)
-
-        val cls = getClassFromType(tpe)
-
-        val arguDeserializerFuncs = params.zipWithIndex.map { case ((fieldName, fieldType), i) =>
-          val Schema(dataType, nullable) = schemaFor(fieldType)
-          val clsName = getClassNameFromType(fieldType)
-          val newTypePath = walkedTypePath.recordField(clsName, fieldName)
-
-          // For tuples, we based grab the inner fields by ordinal instead of name.
-          val newPathFunc = if (cls.getName startsWith "scala.Tuple") {
-            addToPathOrdinal(_, i, dataType, newTypePath)
+      enc: AgnosticEncoder[_],
+      input: Expression,
+      typePath: WalkedTypePath): Expression = enc match {
+    case _ if isNativeEncoder(enc) =>
+      input
+    case BooleanEncoder =>

Review Comment:
   aren't these handled by `case _ if isNativeEncoder(enc) =>` already?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] cloud-fan commented on a diff in pull request #39186: [SPARK-41690][SQL][CONNECT] Agnostic Encoders

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on code in PR #39186:
URL: https://github.com/apache/spark/pull/39186#discussion_r1056263501


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/ScalaReflection.scala:
##########
@@ -432,224 +305,96 @@ object ScalaReflection extends ScalaReflection {
    *  * the element type of [[Array]] or [[Seq]]: `array element class: "abc.xyz.MyClass"`
    *  * the field of [[Product]]: `field (class: "abc.xyz.MyClass", name: "myField")`
    */
-  def serializerForType(tpe: `Type`): Expression = ScalaReflection.cleanUpReflectionObjects {
-    val clsName = getClassNameFromType(tpe)
-    val walkedTypePath = new WalkedTypePath().recordRoot(clsName)
-
-    // The input object to `ExpressionEncoder` is located at first column of an row.
-    val isPrimitive = tpe.typeSymbol.asClass.isPrimitive
-    val inputObject = BoundReference(0, dataTypeFor(tpe), nullable = !isPrimitive)
-
-    serializerFor(inputObject, tpe, walkedTypePath)
-  }
-
-  /**
-   * Returns an expression for serializing the value of an input expression into Spark SQL
-   * internal representation.
-   */
-  private def serializerFor(
-      inputObject: Expression,
-      tpe: `Type`,
-      walkedTypePath: WalkedTypePath,
-      seenTypeSet: Set[`Type`] = Set.empty): Expression = cleanUpReflectionObjects {
-
-    def toCatalystArray(input: Expression, elementType: `Type`): Expression = {
-      dataTypeFor(elementType) match {
-        case dt: ObjectType =>
-          val clsName = getClassNameFromType(elementType)
-          val newPath = walkedTypePath.recordArray(clsName)
-          createSerializerForMapObjects(input, dt,
-            serializerFor(_, elementType, newPath, seenTypeSet))
-
-        case dt @ (BooleanType | ByteType | ShortType | IntegerType | LongType |
-                   FloatType | DoubleType) =>
-          val cls = input.dataType.asInstanceOf[ObjectType].cls
-          if (cls.isArray && cls.getComponentType.isPrimitive) {
-            createSerializerForPrimitiveArray(input, dt)
-          } else {
-            createSerializerForGenericArray(input, dt, nullable = schemaFor(elementType).nullable)
-          }
-
-        case dt =>
-          createSerializerForGenericArray(input, dt, nullable = schemaFor(elementType).nullable)
-      }
-    }
-    baseType(tpe) match {
-      case _ if !inputObject.dataType.isInstanceOf[ObjectType] => inputObject
-
-      case t if isSubtype(t, localTypeOf[Option[_]]) =>
-        val TypeRef(_, _, Seq(optType)) = t
-        val className = getClassNameFromType(optType)
-        val newPath = walkedTypePath.recordOption(className)
-        val unwrapped = UnwrapOption(dataTypeFor(optType), inputObject)
-        serializerFor(unwrapped, optType, newPath, seenTypeSet)
-
-      // Since List[_] also belongs to localTypeOf[Product], we put this case before
-      // "case t if definedByConstructorParams(t)" to make sure it will match to the
-      // case "localTypeOf[Seq[_]]"
-      case t if isSubtype(t, localTypeOf[scala.collection.Seq[_]]) =>
-        val TypeRef(_, _, Seq(elementType)) = t
-        toCatalystArray(inputObject, elementType)
-      case t if isSubtype(t, localTypeOf[Array[_]]) =>
-        val TypeRef(_, _, Seq(elementType)) = t
-        toCatalystArray(inputObject, elementType)
-
-      case t if isSubtype(t, localTypeOf[Map[_, _]]) =>
-        val TypeRef(_, _, Seq(keyType, valueType)) = t
-        val keyClsName = getClassNameFromType(keyType)
-        val valueClsName = getClassNameFromType(valueType)
-        val keyPath = walkedTypePath.recordKeyForMap(keyClsName)
-        val valuePath = walkedTypePath.recordValueForMap(valueClsName)
-
-        createSerializerForMap(
-          inputObject,
-          MapElementInformation(
-            dataTypeFor(keyType),
-            nullable = !keyType.typeSymbol.asClass.isPrimitive,
-            serializerFor(_, keyType, keyPath, seenTypeSet)),
-          MapElementInformation(
-            dataTypeFor(valueType),
-            nullable = !valueType.typeSymbol.asClass.isPrimitive,
-            serializerFor(_, valueType, valuePath, seenTypeSet))
-        )
-
-      case t if isSubtype(t, localTypeOf[scala.collection.Set[_]]) =>
-        val TypeRef(_, _, Seq(elementType)) = t
-
+  // TODO doc
+  def serializerFor(enc: AgnosticEncoder[_]): Expression = {
+    val input = BoundReference(0, dataTypeFor(enc), nullable = enc.nullable)
+    serializerFor(enc, input)
+  }
+
+  private def serializerFor(enc: AgnosticEncoder[_], input: Expression): Expression = enc match {
+    case _ if isNativeEncoder(enc) => input
+    case BooleanEncoder => createSerializerForBoolean(input)

Review Comment:
   ditto



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] cloud-fan commented on pull request #39186: [SPARK-41690][SQL][CONNECT] Agnostic Encoders

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on PR #39186:
URL: https://github.com/apache/spark/pull/39186#issuecomment-1365585284

   thanks, merging to master!


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] hvanhovell commented on a diff in pull request #39186: [SPARK-41690][SQL][CONNECT] Agnostic Encoders

Posted by GitBox <gi...@apache.org>.
hvanhovell commented on code in PR #39186:
URL: https://github.com/apache/spark/pull/39186#discussion_r1055772805


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/encoders/EncoderResolutionSuite.scala:
##########
@@ -94,8 +94,8 @@ class EncoderResolutionSuite extends PlanTest {
         "details" -> (
           s"""
           |The type path of the target object is:
-          |- array element class: "scala.Long"
-          |- field (class: "scala.Array", name: "arr")
+          |- array element class: "long"

Review Comment:
   This is a side effect of not having the same type information when creating the deserializer. 



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org