SandishKumarHN commented on code in PR #37972:
URL: https://github.com/apache/spark/pull/37972#discussion_r989452796


##########
connector/protobuf/src/main/scala/org/apache/spark/sql/protobuf/ProtobufDeserializer.scala:
##########
@@ -0,0 +1,373 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.protobuf
+
+import java.util
+
+import com.google.protobuf.{ByteString, DynamicMessage}
+import com.google.protobuf.Descriptors._
+import com.google.protobuf.Descriptors.FieldDescriptor.JavaType._
+
+import org.apache.spark.sql.catalyst.{InternalRow, NoopFilters, StructFilters}
+import org.apache.spark.sql.catalyst.expressions.{SpecificInternalRow, 
UnsafeArrayData}
+import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, ArrayData, 
GenericArrayData}
+import org.apache.spark.sql.protobuf.utils.ProtobufUtils
+import org.apache.spark.sql.protobuf.utils.ProtobufUtils.ProtoMatchedField
+import org.apache.spark.sql.protobuf.utils.ProtobufUtils.toFieldStr
+import 
org.apache.spark.sql.protobuf.utils.SchemaConverters.IncompatibleSchemaException
+import org.apache.spark.sql.types.{ArrayType, BinaryType, BooleanType, 
ByteType, DataType, Decimal, DoubleType, FloatType, IntegerType, LongType, 
MapType, NullType, ShortType, StringType, StructType}
+import org.apache.spark.unsafe.types.UTF8String
+
+private[sql] class ProtobufDeserializer(
+                                         rootDescriptor: Descriptor,
+                                      rootCatalystType: DataType,
+                                      positionalFieldMatch: Boolean,
+                                      filters: StructFilters) {
+
+  def this(
+            rootDescriptor: Descriptor,
+            rootCatalystType: DataType) = {
+    this(
+      rootDescriptor,
+      rootCatalystType,
+      positionalFieldMatch = false,
+      new NoopFilters)
+  }
+
+  private val converter: Any => Option[Any] = try {
+    rootCatalystType match {
+      // A shortcut for empty schema.
+      case st: StructType if st.isEmpty =>
+        (_: Any) => Some(InternalRow.empty)
+
+      case st: StructType =>
+        val resultRow = new SpecificInternalRow(st.map(_.dataType))
+        val fieldUpdater = new RowUpdater(resultRow)
+        val applyFilters = filters.skipRow(resultRow, _)
+        val writer = getRecordWriter(rootDescriptor, st, Nil, Nil, 
applyFilters)
+        (data: Any) => {
+          val record = data.asInstanceOf[DynamicMessage]
+          val skipRow = writer(fieldUpdater, record)
+          if (skipRow) None else Some(resultRow)
+        }
+    }
+  } catch {
+    case ise: IncompatibleSchemaException => throw new 
IncompatibleSchemaException(
+      s"Cannot convert Protobuf type ${rootDescriptor.getName} " +
+        s"to SQL type ${rootCatalystType.sql}.", ise)
+  }
+
+  def deserialize(data: Any): Option[Any] = converter(data)
+
+  private def newArrayWriter(
+                              protoField: FieldDescriptor,
+                              protoPath: Seq[String],
+                              catalystPath: Seq[String],
+                              elementType: DataType,
+                              containsNull: Boolean): (CatalystDataUpdater, 
Int, Any) => Unit = {
+
+
+    val protoElementPath = protoPath :+ "element"
+    val elementWriter = newWriter(protoField, elementType,
+      protoElementPath, catalystPath :+ "element")
+    (updater, ordinal, value) =>
+      val collection = value.asInstanceOf[java.util.Collection[Any]]
+      val result = createArrayData(elementType, collection.size())
+      val elementUpdater = new ArrayDataUpdater(result)
+
+      var i = 0
+      val iterator = collection.iterator()
+      while (iterator.hasNext) {
+        val element = iterator.next()
+        if (element == null) {
+          if (!containsNull) {
+            throw new RuntimeException(
+              s"Array value at path ${toFieldStr(protoElementPath)} is not 
allowed to be null")
+          } else {
+            elementUpdater.setNullAt(i)
+          }
+        } else {
+          elementWriter(elementUpdater, i, element)
+        }
+        i += 1
+      }
+
+      updater.set(ordinal, result)
+  }
+
+  private def newMapWriter(
+                            protoType: FieldDescriptor,
+                            protoPath: Seq[String],
+                            catalystPath: Seq[String],
+                            keyType: DataType,
+                            valueType: DataType,
+                            valueContainsNull: Boolean): (CatalystDataUpdater, 
Int, Any) => Unit = {
+
+    val keyWriter = newWriter(protoType.getMessageType.getFields.get(0), 
keyType,
+      protoPath :+ "key", catalystPath :+ "key")
+    val valueWriter = newWriter(protoType.getMessageType.getFields.get(1), 
valueType,
+      protoPath :+ "value", catalystPath :+ "value")
+    (updater, ordinal, value) =>
+      if (value != null) {
+        val messageList = 
value.asInstanceOf[java.util.List[com.google.protobuf.Message]]
+        val map = new util.HashMap[AnyRef, AnyRef]()
+        messageList.forEach {
+          field => {
+            var key: AnyRef = null
+            var value: AnyRef = null
+            field.getAllFields.forEach {
+              (k, v) => {
+                k.getName match {
+                  case "key" =>
+                    key = v
+                  case "value" =>
+                    value = v
+                }
+              }
+            }
+            map.put(key, value)
+          }
+        }
+        val keyArray = createArrayData(keyType, map.size())
+        val keyUpdater = new ArrayDataUpdater(keyArray)
+        val valueArray = createArrayData(valueType, map.size())
+        val valueUpdater = new ArrayDataUpdater(valueArray)
+        val iter = map.entrySet().iterator()
+        var i = 0
+        while (iter.hasNext) {
+          val entry = iter.next()
+          assert(entry.getKey != null)
+          keyWriter(keyUpdater, i, entry.getKey)
+          if (entry.getValue == null) {
+            if (!valueContainsNull) {
+              throw new RuntimeException(
+                s"Map value at path ${toFieldStr(protoPath :+ "value")} is not 
allowed to be null")
+            } else {
+              valueUpdater.setNullAt(i)
+            }
+          } else {
+            valueWriter(valueUpdater, i, entry.getValue)
+          }
+          i += 1
+        }
+        updater.set(ordinal, new ArrayBasedMapData(keyArray, valueArray))
+      }
+  }
+
+  /**
+   * Creates a writer to write Protobuf values to Catalyst values at the given 
ordinal with
+   * the given updater.
+   */
+  private def newWriter(
+                         protoType: FieldDescriptor,
+                         catalystType: DataType,
+                         protoPath: Seq[String],
+                         catalystPath: Seq[String]): (CatalystDataUpdater, 
Int, Any) => Unit = {
+    val errorPrefix = s"Cannot convert Protobuf ${toFieldStr(protoPath)} to " +
+      s"SQL ${toFieldStr(catalystPath)} because "
+    val incompatibleMsg = errorPrefix +
+      s"schema is incompatible (protoType = ${protoType} 
${protoType.toProto.getLabel} " +
+      s"${protoType.getJavaType} ${protoType.getType}, sqlType = 
${catalystType.sql})"
+
+    (protoType.getJavaType, catalystType) match {
+
+      case (null, NullType) => (updater, ordinal, _) =>
+        updater.setNullAt(ordinal)
+
+      // TODO: we can avoid boxing if future version of Protobuf provide 
primitive accessors.
+      case (BOOLEAN, BooleanType) => (updater, ordinal, value) =>
+        updater.setBoolean(ordinal, value.asInstanceOf[Boolean])
+
+      case (BOOLEAN, ArrayType(BooleanType, containsNull)) =>
+        newArrayWriter(protoType, protoPath,
+          catalystPath, BooleanType, containsNull)
+
+      case (INT, IntegerType) => (updater, ordinal, value) =>
+        updater.setInt(ordinal, value.asInstanceOf[Int])
+
+      case (INT, ArrayType(IntegerType, containsNull)) =>
+        newArrayWriter(protoType, protoPath,
+          catalystPath, IntegerType, containsNull)
+
+      case (LONG, LongType) => (updater, ordinal, value) =>
+        updater.setLong(ordinal, value.asInstanceOf[Long])
+
+      case (LONG, ArrayType(LongType, containsNull)) =>
+        newArrayWriter(protoType, protoPath,
+          catalystPath, LongType, containsNull)
+
+      case (FLOAT, FloatType) => (updater, ordinal, value) =>
+        updater.setFloat(ordinal, value.asInstanceOf[Float])
+
+      case (FLOAT, ArrayType(FloatType, containsNull)) =>
+        newArrayWriter(protoType, protoPath,
+          catalystPath, FloatType, containsNull)
+
+      case (DOUBLE, DoubleType) => (updater, ordinal, value) =>
+        updater.setDouble(ordinal, value.asInstanceOf[Double])
+
+      case (DOUBLE, ArrayType(DoubleType, containsNull)) =>
+        newArrayWriter(protoType, protoPath,
+          catalystPath, DoubleType, containsNull)
+
+      case (STRING, StringType) => (updater, ordinal, value) =>
+        val str = value match {
+          case s: String => UTF8String.fromString(s)
+        }
+        updater.set(ordinal, str)
+
+      case (STRING, ArrayType(StringType, containsNull)) =>
+        newArrayWriter(protoType, protoPath,
+          catalystPath, StringType, containsNull)
+
+      case (BYTE_STRING, BinaryType) => (updater, ordinal, value) =>
+        val byte_array = value match {
+          case s: ByteString => s.toByteArray
+          case _ => throw new Exception("Invalid ByteString format")
+        }
+        updater.set(ordinal, byte_array)
+
+      case (BYTE_STRING, ArrayType(BinaryType, containsNull)) =>
+        newArrayWriter(protoType, protoPath,
+          catalystPath, BinaryType, containsNull)
+
+      case (MESSAGE, MapType(keyType, valueType, valueContainsNull)) =>
+        newMapWriter(protoType, protoPath, catalystPath,
+          keyType, valueType, valueContainsNull)
+
+      case (MESSAGE, st: StructType) =>
+        val writeRecord = getRecordWriter(protoType.getMessageType, st, 
protoPath,
+          catalystPath, applyFilters = _ => false)
+        (updater, ordinal, value) =>
+          val row = new SpecificInternalRow(st)
+          writeRecord(new RowUpdater(row), value.asInstanceOf[DynamicMessage])
+          updater.set(ordinal, row)
+
+      case (MESSAGE, ArrayType(st: StructType, containsNull)) =>
+        newArrayWriter(protoType, protoPath,
+          catalystPath, st, containsNull)
+
+      case (ENUM, StringType) => (updater, ordinal, value) =>
+        updater.set(ordinal, UTF8String.fromString(value.toString))
+
+      case (ENUM, ArrayType(StringType, containsNull)) =>
+        newArrayWriter(protoType, protoPath,
+          catalystPath, StringType, containsNull)
+
+      case _ => throw new IncompatibleSchemaException(incompatibleMsg)
+    }
+  }
+
+
+  private def getRecordWriter(
+                               protoType: Descriptor,
+                               catalystType: StructType,
+                               protoPath: Seq[String],
+                               catalystPath: Seq[String],
+                               applyFilters: Int => Boolean):
+  (CatalystDataUpdater, DynamicMessage) => Boolean = {
+
+    val protoSchemaHelper = new ProtobufUtils.ProtoSchemaHelper(
+      protoType, catalystType, protoPath, catalystPath, positionalFieldMatch)
+
+   // protoSchemaHelper.validateNoExtraCatalystFields(ignoreNullable = true)
+   // no need to validateNoExtraProtoFields since extra Protobuf fields are 
ignored
+
+    val (validFieldIndexes, fieldWriters) = 
protoSchemaHelper.matchedFields.map {
+      case ProtoMatchedField(catalystField, ordinal, protoField) =>
+        val baseWriter = newWriter(protoField, catalystField.dataType,
+          protoPath :+ protoField.getName, catalystPath :+ catalystField.name)
+        val fieldWriter = (fieldUpdater: CatalystDataUpdater, value: Any) => {
+          if (value == null) {
+            fieldUpdater.setNullAt(ordinal)
+          } else {
+            baseWriter(fieldUpdater, ordinal, value)
+          }
+        }
+        (protoField, fieldWriter)
+    }.toArray.unzip
+
+    (fieldUpdater, record) => {
+      var i = 0
+      var skipRow = false
+      while (i < validFieldIndexes.length && !skipRow) {
+        fieldWriters(i)(fieldUpdater, record.getField(validFieldIndexes(i)))

Review Comment:
   makes sense, and added a unit test. 



##########
connector/protobuf/pom.xml:
##########
@@ -0,0 +1,119 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one or more
+  ~ contributor license agreements.  See the NOTICE file distributed with
+  ~ this work for additional information regarding copyright ownership.
+  ~ The ASF licenses this file to You under the Apache License, Version 2.0
+  ~ (the "License"); you may not use this file except in compliance with
+  ~ the License.  You may obtain a copy of the License at
+  ~
+  ~    http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.apache.spark</groupId>
+    <artifactId>spark-parent_2.12</artifactId>
+    <version>3.4.0-SNAPSHOT</version>
+    <relativePath>../../pom.xml</relativePath>
+  </parent>
+
+  <artifactId>spark-protobuf_2.12</artifactId>
+  <properties>
+    <sbt.project.name>protobuf</sbt.project.name>
+    <protobuf.version>3.21.1</protobuf.version>
+  </properties>
+  <packaging>jar</packaging>
+  <name>Spark Protobuf</name>
+  <url>https://spark.apache.org/</url>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.apache.spark</groupId>
+      <artifactId>spark-sql_${scala.binary.version}</artifactId>
+      <version>${project.version}</version>
+      <scope>provided</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.spark</groupId>
+      <artifactId>spark-core_${scala.binary.version}</artifactId>
+      <version>${project.version}</version>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.spark</groupId>
+      <artifactId>spark-catalyst_${scala.binary.version}</artifactId>
+      <version>${project.version}</version>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.spark</groupId>
+      <artifactId>spark-sql_${scala.binary.version}</artifactId>
+      <version>${project.version}</version>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.scalacheck</groupId>
+      <artifactId>scalacheck_${scala.binary.version}</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.spark</groupId>
+      <artifactId>spark-tags_${scala.binary.version}</artifactId>
+    </dependency>
+    <!-- #if scala-2.13 --><!--
+    <dependency>
+      <groupId>org.scala-lang.modules</groupId>
+      
<artifactId>scala-parallel-collections_${scala.binary.version}</artifactId>
+    </dependency>
+    --><!-- #endif scala-2.13 -->
+    <dependency>
+      <groupId>org.tukaani</groupId>

Review Comment:
   looks like not required. removed. 



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