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


##########
connector/proto/src/main/scala/org/apache/spark/sql/proto/utils/DynamicSchema.scala:
##########
@@ -0,0 +1,172 @@
+/*
+ * 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.proto.utils
+
+import java.util
+
+import scala.collection.JavaConverters._
+import scala.util.control.Breaks.{break, breakable}
+
+import com.google.protobuf.DescriptorProtos.{FileDescriptorProto, 
FileDescriptorSet}
+import com.google.protobuf.Descriptors.{Descriptor, FileDescriptor}
+
+class DynamicSchema {

Review Comment:
   Yes



##########
connector/proto/src/main/scala/org/apache/spark/sql/proto/utils/DynamicSchema.scala:
##########
@@ -0,0 +1,172 @@
+/*
+ * 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.proto.utils
+
+import java.util
+
+import scala.collection.JavaConverters._
+import scala.util.control.Breaks.{break, breakable}
+
+import com.google.protobuf.DescriptorProtos.{FileDescriptorProto, 
FileDescriptorSet}
+import com.google.protobuf.Descriptors.{Descriptor, FileDescriptor}
+
+class DynamicSchema {
+  var fileDescSet: FileDescriptorSet = null

Review Comment:
   Agreed, we will make that change.



##########
connector/proto/src/main/scala/org/apache/spark/sql/proto/utils/MessageDefinition.scala:
##########
@@ -0,0 +1,99 @@
+/*
+ * 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.proto.utils
+
+import com.google.protobuf.DescriptorProtos.{DescriptorProto, 
FieldDescriptorProto}
+
+class MessageDefinition(val messageType: DescriptorProto = null) {

Review Comment:
   Yes.



##########
connector/proto/src/main/scala/org/apache/spark/sql/proto/utils/ProtoUtils.scala:
##########
@@ -0,0 +1,300 @@
+/*
+ * 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.proto.utils
+
+import java.io.{BufferedInputStream, FileInputStream, FileNotFoundException, 
IOException}
+import java.util.Locale
+
+import scala.collection.JavaConverters._
+
+import com.google.protobuf.{DescriptorProtos, Descriptors, 
InvalidProtocolBufferException}
+import com.google.protobuf.Descriptors.{Descriptor, FieldDescriptor}
+import org.apache.hadoop.fs.FileStatus
+
+import org.apache.spark.SparkException
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.FileSourceOptions
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.proto.utils.ProtoOptions.ignoreExtensionKey
+import 
org.apache.spark.sql.proto.utils.SchemaConverters.IncompatibleSchemaException
+import org.apache.spark.sql.types._
+import org.apache.spark.util.Utils
+
+private[sql] object ProtoUtils extends Logging {
+
+  def inferSchema(
+                   spark: SparkSession,
+                   options: Map[String, String],
+                   files: Seq[FileStatus]): Option[StructType] = {
+    val conf = spark.sessionState.newHadoopConfWithOptions(options)
+    val parsedOptions = new ProtoOptions(options, conf)
+
+    if (parsedOptions.parameters.contains(ignoreExtensionKey)) {
+      logWarning(s"Option $ignoreExtensionKey is deprecated. Please use the " +
+        "general data source option pathGlobFilter for filtering file names.")
+    }
+    // User can specify an optional proto json schema.
+    val protoSchema = parsedOptions.schema
+      .getOrElse {
+        inferProtoSchemaFromFiles(files,
+          new 
FileSourceOptions(CaseInsensitiveMap(options)).ignoreCorruptFiles)
+      }
+
+    SchemaConverters.toSqlType(protoSchema).dataType match {
+      case t: StructType => Some(t)
+      case _ => throw new RuntimeException(
+        s"""Proto schema cannot be converted to a Spark SQL StructType:
+           |
+           |${protoSchema.toString()}
+           |""".stripMargin)
+    }
+  }
+
+  private def inferProtoSchemaFromFiles(
+                                         files: Seq[FileStatus],
+                                         ignoreCorruptFiles: Boolean): 
Descriptor = {
+    // Schema evolution is not supported yet. Here we only pick first random 
readable sample file to
+    // figure out the schema of the whole dataset.
+    val protoReader = files.iterator.map { f =>
+      val path = f.getPath
+      if (!path.getName.endsWith(".pb")) {
+        None
+      } else {
+        Utils.tryWithResource {
+          new FileInputStream("saved_model.pb")
+        } { in =>
+          try {
+            
Some(DescriptorProtos.DescriptorProto.parseFrom(in).getDescriptorForType)
+          } catch {
+            case e: IOException =>
+              if (ignoreCorruptFiles) {
+                logWarning(s"Skipped the footer in the corrupted file: $path", 
e)
+                None
+              } else {
+                throw new SparkException(s"Could not read file: $path", e)
+              }
+          }
+        }
+      }
+    }.collectFirst {
+      case Some(reader) => reader
+    }
+
+    protoReader match {
+      case Some(reader) =>
+        reader.getContainingType
+      case None =>
+        throw new FileNotFoundException(
+          "No Proto files found. If files don't have .proto extension, set 
ignoreExtension to true")
+    }
+  }
+
+  def supportsDataType(dataType: DataType): Boolean = dataType match {
+    case _: AtomicType => true
+
+    case st: StructType => st.forall { f => supportsDataType(f.dataType) }
+
+    case ArrayType(elementType, _) => supportsDataType(elementType)
+
+    case MapType(keyType, valueType, _) =>

Review Comment:
   We do support maps both in serialization and deserialization.



##########
connector/proto/src/main/scala/org/apache/spark/sql/proto/utils/ProtoUtils.scala:
##########
@@ -0,0 +1,300 @@
+/*
+ * 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.proto.utils
+
+import java.io.{BufferedInputStream, FileInputStream, FileNotFoundException, 
IOException}
+import java.util.Locale
+
+import scala.collection.JavaConverters._
+
+import com.google.protobuf.{DescriptorProtos, Descriptors, 
InvalidProtocolBufferException}
+import com.google.protobuf.Descriptors.{Descriptor, FieldDescriptor}
+import org.apache.hadoop.fs.FileStatus
+
+import org.apache.spark.SparkException
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.FileSourceOptions
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.proto.utils.ProtoOptions.ignoreExtensionKey
+import 
org.apache.spark.sql.proto.utils.SchemaConverters.IncompatibleSchemaException
+import org.apache.spark.sql.types._
+import org.apache.spark.util.Utils
+
+private[sql] object ProtoUtils extends Logging {
+
+  def inferSchema(
+                   spark: SparkSession,
+                   options: Map[String, String],
+                   files: Seq[FileStatus]): Option[StructType] = {
+    val conf = spark.sessionState.newHadoopConfWithOptions(options)
+    val parsedOptions = new ProtoOptions(options, conf)
+
+    if (parsedOptions.parameters.contains(ignoreExtensionKey)) {
+      logWarning(s"Option $ignoreExtensionKey is deprecated. Please use the " +
+        "general data source option pathGlobFilter for filtering file names.")
+    }
+    // User can specify an optional proto json schema.
+    val protoSchema = parsedOptions.schema
+      .getOrElse {
+        inferProtoSchemaFromFiles(files,
+          new 
FileSourceOptions(CaseInsensitiveMap(options)).ignoreCorruptFiles)
+      }
+
+    SchemaConverters.toSqlType(protoSchema).dataType match {
+      case t: StructType => Some(t)
+      case _ => throw new RuntimeException(
+        s"""Proto schema cannot be converted to a Spark SQL StructType:
+           |
+           |${protoSchema.toString()}
+           |""".stripMargin)
+    }
+  }
+
+  private def inferProtoSchemaFromFiles(
+                                         files: Seq[FileStatus],
+                                         ignoreCorruptFiles: Boolean): 
Descriptor = {
+    // Schema evolution is not supported yet. Here we only pick first random 
readable sample file to
+    // figure out the schema of the whole dataset.
+    val protoReader = files.iterator.map { f =>
+      val path = f.getPath
+      if (!path.getName.endsWith(".pb")) {
+        None
+      } else {
+        Utils.tryWithResource {
+          new FileInputStream("saved_model.pb")

Review Comment:
   This was just an experiment.  We will remove it.



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