You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by rx...@apache.org on 2016/05/26 06:54:28 UTC
[1/4] spark git commit: [SPARK-15543][SQL] Rename DefaultSources to
make them more self-describing
Repository: spark
Updated Branches:
refs/heads/master dfc9fc02c -> 361ebc282
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/hive/src/main/scala/org/apache/spark/sql/hive/orc/OrcRelation.scala
----------------------------------------------------------------------
diff --git a/sql/hive/src/main/scala/org/apache/spark/sql/hive/orc/OrcRelation.scala b/sql/hive/src/main/scala/org/apache/spark/sql/hive/orc/OrcRelation.scala
deleted file mode 100644
index 38f50c1..0000000
--- a/sql/hive/src/main/scala/org/apache/spark/sql/hive/orc/OrcRelation.scala
+++ /dev/null
@@ -1,371 +0,0 @@
-/*
- * 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.hive.orc
-
-import java.net.URI
-import java.util.Properties
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.{FileStatus, Path}
-import org.apache.hadoop.hive.conf.HiveConf.ConfVars
-import org.apache.hadoop.hive.ql.io.orc._
-import org.apache.hadoop.hive.serde2.objectinspector.{SettableStructObjectInspector, StructObjectInspector}
-import org.apache.hadoop.hive.serde2.typeinfo.{StructTypeInfo, TypeInfoUtils}
-import org.apache.hadoop.io.{NullWritable, Writable}
-import org.apache.hadoop.mapred.{InputFormat => MapRedInputFormat, JobConf, OutputFormat => MapRedOutputFormat, RecordWriter, Reporter}
-import org.apache.hadoop.mapreduce._
-import org.apache.hadoop.mapreduce.lib.input.{FileInputFormat, FileSplit}
-
-import org.apache.spark.internal.Logging
-import org.apache.spark.rdd.{HadoopRDD, RDD}
-import org.apache.spark.sql.{Row, SparkSession}
-import org.apache.spark.sql.catalyst.InternalRow
-import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.execution.datasources._
-import org.apache.spark.sql.hive.{HiveInspectors, HiveShim}
-import org.apache.spark.sql.sources.{Filter, _}
-import org.apache.spark.sql.types.StructType
-import org.apache.spark.util.SerializableConfiguration
-
-private[sql] class DefaultSource
- extends FileFormat with DataSourceRegister with Serializable {
-
- override def shortName(): String = "orc"
-
- override def toString: String = "ORC"
-
- override def inferSchema(
- sparkSession: SparkSession,
- options: Map[String, String],
- files: Seq[FileStatus]): Option[StructType] = {
- OrcFileOperator.readSchema(
- files.map(_.getPath.toUri.toString),
- Some(sparkSession.sessionState.newHadoopConf())
- )
- }
-
- override def prepareWrite(
- sparkSession: SparkSession,
- job: Job,
- options: Map[String, String],
- dataSchema: StructType): OutputWriterFactory = {
- val orcOptions = new OrcOptions(options)
-
- val configuration = job.getConfiguration
-
- configuration.set(OrcRelation.ORC_COMPRESSION, orcOptions.compressionCodec)
- configuration match {
- case conf: JobConf =>
- conf.setOutputFormat(classOf[OrcOutputFormat])
- case conf =>
- conf.setClass(
- "mapred.output.format.class",
- classOf[OrcOutputFormat],
- classOf[MapRedOutputFormat[_, _]])
- }
-
- new OutputWriterFactory {
- override def newInstance(
- path: String,
- bucketId: Option[Int],
- dataSchema: StructType,
- context: TaskAttemptContext): OutputWriter = {
- new OrcOutputWriter(path, bucketId, dataSchema, context)
- }
- }
- }
-
- override def buildReader(
- sparkSession: SparkSession,
- dataSchema: StructType,
- partitionSchema: StructType,
- requiredSchema: StructType,
- filters: Seq[Filter],
- options: Map[String, String],
- hadoopConf: Configuration): (PartitionedFile) => Iterator[InternalRow] = {
- if (sparkSession.sessionState.conf.orcFilterPushDown) {
- // Sets pushed predicates
- OrcFilters.createFilter(requiredSchema, filters.toArray).foreach { f =>
- hadoopConf.set(OrcTableScan.SARG_PUSHDOWN, f.toKryo)
- hadoopConf.setBoolean(ConfVars.HIVEOPTINDEXFILTER.varname, true)
- }
- }
-
- val broadcastedHadoopConf =
- sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf))
-
- (file: PartitionedFile) => {
- val conf = broadcastedHadoopConf.value.value
-
- // SPARK-8501: Empty ORC files always have an empty schema stored in their footer. In this
- // case, `OrcFileOperator.readSchema` returns `None`, and we can't read the underlying file
- // using the given physical schema. Instead, we simply return an empty iterator.
- val maybePhysicalSchema = OrcFileOperator.readSchema(Seq(file.filePath), Some(conf))
- if (maybePhysicalSchema.isEmpty) {
- Iterator.empty
- } else {
- val physicalSchema = maybePhysicalSchema.get
- OrcRelation.setRequiredColumns(conf, physicalSchema, requiredSchema)
-
- val orcRecordReader = {
- val job = Job.getInstance(conf)
- FileInputFormat.setInputPaths(job, file.filePath)
-
- val fileSplit = new FileSplit(
- new Path(new URI(file.filePath)), file.start, file.length, Array.empty
- )
- // Custom OrcRecordReader is used to get
- // ObjectInspector during recordReader creation itself and can
- // avoid NameNode call in unwrapOrcStructs per file.
- // Specifically would be helpful for partitioned datasets.
- val orcReader = OrcFile.createReader(
- new Path(new URI(file.filePath)), OrcFile.readerOptions(conf))
- new SparkOrcNewRecordReader(orcReader, conf, fileSplit.getStart, fileSplit.getLength)
- }
-
- // Unwraps `OrcStruct`s to `UnsafeRow`s
- OrcRelation.unwrapOrcStructs(
- conf,
- requiredSchema,
- Some(orcRecordReader.getObjectInspector.asInstanceOf[StructObjectInspector]),
- new RecordReaderIterator[OrcStruct](orcRecordReader))
- }
- }
- }
-}
-
-private[orc] class OrcSerializer(dataSchema: StructType, conf: Configuration)
- extends HiveInspectors {
-
- def serialize(row: InternalRow): Writable = {
- wrapOrcStruct(cachedOrcStruct, structOI, row)
- serializer.serialize(cachedOrcStruct, structOI)
- }
-
- private[this] val serializer = {
- val table = new Properties()
- table.setProperty("columns", dataSchema.fieldNames.mkString(","))
- table.setProperty("columns.types", dataSchema.map(_.dataType.catalogString).mkString(":"))
-
- val serde = new OrcSerde
- serde.initialize(conf, table)
- serde
- }
-
- // Object inspector converted from the schema of the relation to be serialized.
- private[this] val structOI = {
- val typeInfo = TypeInfoUtils.getTypeInfoFromTypeString(dataSchema.catalogString)
- OrcStruct.createObjectInspector(typeInfo.asInstanceOf[StructTypeInfo])
- .asInstanceOf[SettableStructObjectInspector]
- }
-
- private[this] val cachedOrcStruct = structOI.create().asInstanceOf[OrcStruct]
-
- private[this] def wrapOrcStruct(
- struct: OrcStruct,
- oi: SettableStructObjectInspector,
- row: InternalRow): Unit = {
- val fieldRefs = oi.getAllStructFieldRefs
- var i = 0
- while (i < fieldRefs.size) {
-
- oi.setStructFieldData(
- struct,
- fieldRefs.get(i),
- wrap(
- row.get(i, dataSchema(i).dataType),
- fieldRefs.get(i).getFieldObjectInspector,
- dataSchema(i).dataType))
- i += 1
- }
- }
-}
-
-private[orc] class OrcOutputWriter(
- path: String,
- bucketId: Option[Int],
- dataSchema: StructType,
- context: TaskAttemptContext)
- extends OutputWriter {
-
- private[this] val conf = context.getConfiguration
-
- private[this] val serializer = new OrcSerializer(dataSchema, conf)
-
- // `OrcRecordWriter.close()` creates an empty file if no rows are written at all. We use this
- // flag to decide whether `OrcRecordWriter.close()` needs to be called.
- private var recordWriterInstantiated = false
-
- private lazy val recordWriter: RecordWriter[NullWritable, Writable] = {
- recordWriterInstantiated = true
- val uniqueWriteJobId = conf.get("spark.sql.sources.writeJobUUID")
- val taskAttemptId = context.getTaskAttemptID
- val partition = taskAttemptId.getTaskID.getId
- val bucketString = bucketId.map(BucketingUtils.bucketIdToString).getOrElse("")
- val compressionExtension = {
- val name = conf.get(OrcRelation.ORC_COMPRESSION)
- OrcRelation.extensionsForCompressionCodecNames.getOrElse(name, "")
- }
- // It has the `.orc` extension at the end because (de)compression tools
- // such as gunzip would not be able to decompress this as the compression
- // is not applied on this whole file but on each "stream" in ORC format.
- val filename = f"part-r-$partition%05d-$uniqueWriteJobId$bucketString$compressionExtension.orc"
-
- new OrcOutputFormat().getRecordWriter(
- new Path(path, filename).getFileSystem(conf),
- conf.asInstanceOf[JobConf],
- new Path(path, filename).toString,
- Reporter.NULL
- ).asInstanceOf[RecordWriter[NullWritable, Writable]]
- }
-
- override def write(row: Row): Unit =
- throw new UnsupportedOperationException("call writeInternal")
-
- override protected[sql] def writeInternal(row: InternalRow): Unit = {
- recordWriter.write(NullWritable.get(), serializer.serialize(row))
- }
-
- override def close(): Unit = {
- if (recordWriterInstantiated) {
- recordWriter.close(Reporter.NULL)
- }
- }
-}
-
-private[orc] case class OrcTableScan(
- @transient sparkSession: SparkSession,
- attributes: Seq[Attribute],
- filters: Array[Filter],
- @transient inputPaths: Seq[FileStatus])
- extends Logging
- with HiveInspectors {
-
- def execute(): RDD[InternalRow] = {
- val job = Job.getInstance(sparkSession.sessionState.newHadoopConf())
- val conf = job.getConfiguration
-
- // Figure out the actual schema from the ORC source (without partition columns) so that we
- // can pick the correct ordinals. Note that this assumes that all files have the same schema.
- val orcFormat = new DefaultSource
- val dataSchema =
- orcFormat
- .inferSchema(sparkSession, Map.empty, inputPaths)
- .getOrElse(sys.error("Failed to read schema from target ORC files."))
-
- // Tries to push down filters if ORC filter push-down is enabled
- if (sparkSession.sessionState.conf.orcFilterPushDown) {
- OrcFilters.createFilter(dataSchema, filters).foreach { f =>
- conf.set(OrcTableScan.SARG_PUSHDOWN, f.toKryo)
- conf.setBoolean(ConfVars.HIVEOPTINDEXFILTER.varname, true)
- }
- }
-
- // Sets requested columns
- OrcRelation.setRequiredColumns(conf, dataSchema, StructType.fromAttributes(attributes))
-
- if (inputPaths.isEmpty) {
- // the input path probably be pruned, return an empty RDD.
- return sparkSession.sparkContext.emptyRDD[InternalRow]
- }
- FileInputFormat.setInputPaths(job, inputPaths.map(_.getPath): _*)
-
- val inputFormatClass =
- classOf[OrcInputFormat]
- .asInstanceOf[Class[_ <: MapRedInputFormat[NullWritable, Writable]]]
-
- val rdd = sparkSession.sparkContext.hadoopRDD(
- conf.asInstanceOf[JobConf],
- inputFormatClass,
- classOf[NullWritable],
- classOf[Writable]
- ).asInstanceOf[HadoopRDD[NullWritable, Writable]]
-
- val wrappedConf = new SerializableConfiguration(conf)
-
- rdd.mapPartitionsWithInputSplit { case (split: OrcSplit, iterator) =>
- val writableIterator = iterator.map(_._2)
- val maybeStructOI = OrcFileOperator.getObjectInspector(split.getPath.toString, Some(conf))
- OrcRelation.unwrapOrcStructs(
- wrappedConf.value,
- StructType.fromAttributes(attributes),
- maybeStructOI,
- writableIterator
- )
- }
- }
-}
-
-private[orc] object OrcTableScan {
- // This constant duplicates `OrcInputFormat.SARG_PUSHDOWN`, which is unfortunately not public.
- private[orc] val SARG_PUSHDOWN = "sarg.pushdown"
-}
-
-private[orc] object OrcRelation extends HiveInspectors {
- // The references of Hive's classes will be minimized.
- val ORC_COMPRESSION = "orc.compress"
-
- // The extensions for ORC compression codecs
- val extensionsForCompressionCodecNames = Map(
- "NONE" -> "",
- "SNAPPY" -> ".snappy",
- "ZLIB" -> ".zlib",
- "LZO" -> ".lzo")
-
- def unwrapOrcStructs(
- conf: Configuration,
- dataSchema: StructType,
- maybeStructOI: Option[StructObjectInspector],
- iterator: Iterator[Writable]): Iterator[InternalRow] = {
- val deserializer = new OrcSerde
- val mutableRow = new SpecificMutableRow(dataSchema.map(_.dataType))
- val unsafeProjection = UnsafeProjection.create(dataSchema)
-
- def unwrap(oi: StructObjectInspector): Iterator[InternalRow] = {
- val (fieldRefs, fieldOrdinals) = dataSchema.zipWithIndex.map {
- case (field, ordinal) => oi.getStructFieldRef(field.name) -> ordinal
- }.unzip
-
- val unwrappers = fieldRefs.map(unwrapperFor)
-
- iterator.map { value =>
- val raw = deserializer.deserialize(value)
- var i = 0
- while (i < fieldRefs.length) {
- val fieldValue = oi.getStructFieldData(raw, fieldRefs(i))
- if (fieldValue == null) {
- mutableRow.setNullAt(fieldOrdinals(i))
- } else {
- unwrappers(i)(fieldValue, mutableRow, fieldOrdinals(i))
- }
- i += 1
- }
- unsafeProjection(mutableRow)
- }
- }
-
- maybeStructOI.map(unwrap).getOrElse(Iterator.empty)
- }
-
- def setRequiredColumns(
- conf: Configuration, physicalSchema: StructType, requestedSchema: StructType): Unit = {
- val ids = requestedSchema.map(a => physicalSchema.fieldIndex(a.name): Integer)
- val (sortedIDs, sortedNames) = ids.zip(requestedSchema.fieldNames).sorted.unzip
- HiveShim.appendReadColumns(conf, sortedIDs, sortedNames)
- }
-}
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/hive/src/test/scala/org/apache/spark/sql/hive/orc/OrcHadoopFsRelationSuite.scala
----------------------------------------------------------------------
diff --git a/sql/hive/src/test/scala/org/apache/spark/sql/hive/orc/OrcHadoopFsRelationSuite.scala b/sql/hive/src/test/scala/org/apache/spark/sql/hive/orc/OrcHadoopFsRelationSuite.scala
index 0207b4e..5dfa58f 100644
--- a/sql/hive/src/test/scala/org/apache/spark/sql/hive/orc/OrcHadoopFsRelationSuite.scala
+++ b/sql/hive/src/test/scala/org/apache/spark/sql/hive/orc/OrcHadoopFsRelationSuite.scala
@@ -30,7 +30,7 @@ import org.apache.spark.sql.types._
class OrcHadoopFsRelationSuite extends HadoopFsRelationTest {
import testImplicits._
- override val dataSourceName: String = classOf[DefaultSource].getCanonicalName
+ override val dataSourceName: String = classOf[OrcFileFormat].getCanonicalName
// ORC does not play well with NullType and UDT.
override protected def supportsDataType(dataType: DataType): Boolean = dataType match {
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org
[2/4] spark git commit: [SPARK-15543][SQL] Rename DefaultSources to
make them more self-describing
Posted by rx...@apache.org.
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/text/DefaultSource.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/text/DefaultSource.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/text/DefaultSource.scala
deleted file mode 100644
index f091615..0000000
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/text/DefaultSource.scala
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * 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.execution.datasources.text
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.{FileStatus, Path}
-import org.apache.hadoop.io.{NullWritable, Text}
-import org.apache.hadoop.mapreduce.{Job, RecordWriter, TaskAttemptContext}
-import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat
-
-import org.apache.spark.sql.{AnalysisException, Row, SparkSession}
-import org.apache.spark.sql.catalyst.InternalRow
-import org.apache.spark.sql.catalyst.expressions.UnsafeRow
-import org.apache.spark.sql.catalyst.expressions.codegen.{BufferHolder, UnsafeRowWriter}
-import org.apache.spark.sql.execution.datasources._
-import org.apache.spark.sql.sources._
-import org.apache.spark.sql.types.{StringType, StructType}
-import org.apache.spark.util.SerializableConfiguration
-
-/**
- * A data source for reading text files.
- */
-class DefaultSource extends FileFormat with DataSourceRegister {
-
- override def shortName(): String = "text"
-
- private def verifySchema(schema: StructType): Unit = {
- if (schema.size != 1) {
- throw new AnalysisException(
- s"Text data source supports only a single column, and you have ${schema.size} columns.")
- }
- val tpe = schema(0).dataType
- if (tpe != StringType) {
- throw new AnalysisException(
- s"Text data source supports only a string column, but you have ${tpe.simpleString}.")
- }
- }
-
- override def inferSchema(
- sparkSession: SparkSession,
- options: Map[String, String],
- files: Seq[FileStatus]): Option[StructType] = Some(new StructType().add("value", StringType))
-
- override def prepareWrite(
- sparkSession: SparkSession,
- job: Job,
- options: Map[String, String],
- dataSchema: StructType): OutputWriterFactory = {
- verifySchema(dataSchema)
-
- val conf = job.getConfiguration
- val compressionCodec = options.get("compression").map(CompressionCodecs.getCodecClassName)
- compressionCodec.foreach { codec =>
- CompressionCodecs.setCodecConfiguration(conf, codec)
- }
-
- new OutputWriterFactory {
- override def newInstance(
- path: String,
- bucketId: Option[Int],
- dataSchema: StructType,
- context: TaskAttemptContext): OutputWriter = {
- if (bucketId.isDefined) {
- throw new AnalysisException("Text doesn't support bucketing")
- }
- new TextOutputWriter(path, dataSchema, context)
- }
- }
- }
-
- override def buildReader(
- sparkSession: SparkSession,
- dataSchema: StructType,
- partitionSchema: StructType,
- requiredSchema: StructType,
- filters: Seq[Filter],
- options: Map[String, String],
- hadoopConf: Configuration): PartitionedFile => Iterator[InternalRow] = {
- val broadcastedHadoopConf =
- sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf))
-
- (file: PartitionedFile) => {
- val unsafeRow = new UnsafeRow(1)
- val bufferHolder = new BufferHolder(unsafeRow)
- val unsafeRowWriter = new UnsafeRowWriter(bufferHolder, 1)
-
- new HadoopFileLinesReader(file, broadcastedHadoopConf.value.value).map { line =>
- // Writes to an UnsafeRow directly
- bufferHolder.reset()
- unsafeRowWriter.write(0, line.getBytes, 0, line.getLength)
- unsafeRow.setTotalSize(bufferHolder.totalSize())
- unsafeRow
- }
- }
- }
-}
-
-class TextOutputWriter(path: String, dataSchema: StructType, context: TaskAttemptContext)
- extends OutputWriter {
-
- private[this] val buffer = new Text()
-
- private val recordWriter: RecordWriter[NullWritable, Text] = {
- new TextOutputFormat[NullWritable, Text]() {
- override def getDefaultWorkFile(context: TaskAttemptContext, extension: String): Path = {
- val configuration = context.getConfiguration
- val uniqueWriteJobId = configuration.get("spark.sql.sources.writeJobUUID")
- val taskAttemptId = context.getTaskAttemptID
- val split = taskAttemptId.getTaskID.getId
- new Path(path, f"part-r-$split%05d-$uniqueWriteJobId.txt$extension")
- }
- }.getRecordWriter(context)
- }
-
- override def write(row: Row): Unit = throw new UnsupportedOperationException("call writeInternal")
-
- override protected[sql] def writeInternal(row: InternalRow): Unit = {
- val utf8string = row.getUTF8String(0)
- buffer.set(utf8string.getBytes)
- recordWriter.write(NullWritable.get(), buffer)
- }
-
- override def close(): Unit = {
- recordWriter.close(context)
- }
-}
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/text/TextFileFormat.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/text/TextFileFormat.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/text/TextFileFormat.scala
new file mode 100644
index 0000000..d9525ef
--- /dev/null
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/text/TextFileFormat.scala
@@ -0,0 +1,141 @@
+/*
+ * 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.execution.datasources.text
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{FileStatus, Path}
+import org.apache.hadoop.io.{NullWritable, Text}
+import org.apache.hadoop.mapreduce.{Job, RecordWriter, TaskAttemptContext}
+import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat
+
+import org.apache.spark.sql.{AnalysisException, Row, SparkSession}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.UnsafeRow
+import org.apache.spark.sql.catalyst.expressions.codegen.{BufferHolder, UnsafeRowWriter}
+import org.apache.spark.sql.execution.datasources._
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types.{StringType, StructType}
+import org.apache.spark.util.SerializableConfiguration
+
+/**
+ * A data source for reading text files.
+ */
+class TextFileFormat extends FileFormat with DataSourceRegister {
+
+ override def shortName(): String = "text"
+
+ private def verifySchema(schema: StructType): Unit = {
+ if (schema.size != 1) {
+ throw new AnalysisException(
+ s"Text data source supports only a single column, and you have ${schema.size} columns.")
+ }
+ val tpe = schema(0).dataType
+ if (tpe != StringType) {
+ throw new AnalysisException(
+ s"Text data source supports only a string column, but you have ${tpe.simpleString}.")
+ }
+ }
+
+ override def inferSchema(
+ sparkSession: SparkSession,
+ options: Map[String, String],
+ files: Seq[FileStatus]): Option[StructType] = Some(new StructType().add("value", StringType))
+
+ override def prepareWrite(
+ sparkSession: SparkSession,
+ job: Job,
+ options: Map[String, String],
+ dataSchema: StructType): OutputWriterFactory = {
+ verifySchema(dataSchema)
+
+ val conf = job.getConfiguration
+ val compressionCodec = options.get("compression").map(CompressionCodecs.getCodecClassName)
+ compressionCodec.foreach { codec =>
+ CompressionCodecs.setCodecConfiguration(conf, codec)
+ }
+
+ new OutputWriterFactory {
+ override def newInstance(
+ path: String,
+ bucketId: Option[Int],
+ dataSchema: StructType,
+ context: TaskAttemptContext): OutputWriter = {
+ if (bucketId.isDefined) {
+ throw new AnalysisException("Text doesn't support bucketing")
+ }
+ new TextOutputWriter(path, dataSchema, context)
+ }
+ }
+ }
+
+ override def buildReader(
+ sparkSession: SparkSession,
+ dataSchema: StructType,
+ partitionSchema: StructType,
+ requiredSchema: StructType,
+ filters: Seq[Filter],
+ options: Map[String, String],
+ hadoopConf: Configuration): PartitionedFile => Iterator[InternalRow] = {
+ val broadcastedHadoopConf =
+ sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf))
+
+ (file: PartitionedFile) => {
+ val unsafeRow = new UnsafeRow(1)
+ val bufferHolder = new BufferHolder(unsafeRow)
+ val unsafeRowWriter = new UnsafeRowWriter(bufferHolder, 1)
+
+ new HadoopFileLinesReader(file, broadcastedHadoopConf.value.value).map { line =>
+ // Writes to an UnsafeRow directly
+ bufferHolder.reset()
+ unsafeRowWriter.write(0, line.getBytes, 0, line.getLength)
+ unsafeRow.setTotalSize(bufferHolder.totalSize())
+ unsafeRow
+ }
+ }
+ }
+}
+
+class TextOutputWriter(path: String, dataSchema: StructType, context: TaskAttemptContext)
+ extends OutputWriter {
+
+ private[this] val buffer = new Text()
+
+ private val recordWriter: RecordWriter[NullWritable, Text] = {
+ new TextOutputFormat[NullWritable, Text]() {
+ override def getDefaultWorkFile(context: TaskAttemptContext, extension: String): Path = {
+ val configuration = context.getConfiguration
+ val uniqueWriteJobId = configuration.get("spark.sql.sources.writeJobUUID")
+ val taskAttemptId = context.getTaskAttemptID
+ val split = taskAttemptId.getTaskID.getId
+ new Path(path, f"part-r-$split%05d-$uniqueWriteJobId.txt$extension")
+ }
+ }.getRecordWriter(context)
+ }
+
+ override def write(row: Row): Unit = throw new UnsupportedOperationException("call writeInternal")
+
+ override protected[sql] def writeInternal(row: InternalRow): Unit = {
+ val utf8string = row.getUTF8String(0)
+ buffer.set(utf8string.getBytes)
+ recordWriter.write(NullWritable.get(), buffer)
+ }
+
+ override def close(): Unit = {
+ recordWriter.close(context)
+ }
+}
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/json/JsonSuite.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/json/JsonSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/json/JsonSuite.scala
index 46213a2..500d8ff 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/json/JsonSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/json/JsonSuite.scala
@@ -1320,7 +1320,7 @@ class JsonSuite extends QueryTest with SharedSQLContext with TestJsonData {
userSpecifiedSchema = None,
partitionColumns = Array.empty[String],
bucketSpec = None,
- className = classOf[DefaultSource].getCanonicalName,
+ className = classOf[JsonFileFormat].getCanonicalName,
options = Map("path" -> path)).resolveRelation()
val d2 = DataSource(
@@ -1328,7 +1328,7 @@ class JsonSuite extends QueryTest with SharedSQLContext with TestJsonData {
userSpecifiedSchema = None,
partitionColumns = Array.empty[String],
bucketSpec = None,
- className = classOf[DefaultSource].getCanonicalName,
+ className = classOf[JsonFileFormat].getCanonicalName,
options = Map("path" -> path)).resolveRelation()
assert(d1 === d2)
})
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetSchemaSuite.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetSchemaSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetSchemaSuite.scala
index c43b142..6db6492 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetSchemaSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetSchemaSuite.scala
@@ -375,7 +375,7 @@ class ParquetSchemaSuite extends ParquetSchemaTest {
StructField("lowerCase", StringType),
StructField("UPPERCase", DoubleType, nullable = false)))) {
- ParquetRelation.mergeMetastoreParquetSchema(
+ ParquetFileFormat.mergeMetastoreParquetSchema(
StructType(Seq(
StructField("lowercase", StringType),
StructField("uppercase", DoubleType, nullable = false))),
@@ -390,7 +390,7 @@ class ParquetSchemaSuite extends ParquetSchemaTest {
StructType(Seq(
StructField("UPPERCase", DoubleType, nullable = false)))) {
- ParquetRelation.mergeMetastoreParquetSchema(
+ ParquetFileFormat.mergeMetastoreParquetSchema(
StructType(Seq(
StructField("uppercase", DoubleType, nullable = false))),
@@ -401,7 +401,7 @@ class ParquetSchemaSuite extends ParquetSchemaTest {
// Metastore schema contains additional non-nullable fields.
assert(intercept[Throwable] {
- ParquetRelation.mergeMetastoreParquetSchema(
+ ParquetFileFormat.mergeMetastoreParquetSchema(
StructType(Seq(
StructField("uppercase", DoubleType, nullable = false),
StructField("lowerCase", BinaryType, nullable = false))),
@@ -412,7 +412,7 @@ class ParquetSchemaSuite extends ParquetSchemaTest {
// Conflicting non-nullable field names
intercept[Throwable] {
- ParquetRelation.mergeMetastoreParquetSchema(
+ ParquetFileFormat.mergeMetastoreParquetSchema(
StructType(Seq(StructField("lower", StringType, nullable = false))),
StructType(Seq(StructField("lowerCase", BinaryType))))
}
@@ -426,7 +426,7 @@ class ParquetSchemaSuite extends ParquetSchemaTest {
StructField("firstField", StringType, nullable = true),
StructField("secondField", StringType, nullable = true),
StructField("thirdfield", StringType, nullable = true)))) {
- ParquetRelation.mergeMetastoreParquetSchema(
+ ParquetFileFormat.mergeMetastoreParquetSchema(
StructType(Seq(
StructField("firstfield", StringType, nullable = true),
StructField("secondfield", StringType, nullable = true),
@@ -439,7 +439,7 @@ class ParquetSchemaSuite extends ParquetSchemaTest {
// Merge should fail if the Metastore contains any additional fields that are not
// nullable.
assert(intercept[Throwable] {
- ParquetRelation.mergeMetastoreParquetSchema(
+ ParquetFileFormat.mergeMetastoreParquetSchema(
StructType(Seq(
StructField("firstfield", StringType, nullable = true),
StructField("secondfield", StringType, nullable = true),
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/test/scala/org/apache/spark/sql/sources/ResolvedDataSourceSuite.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/sources/ResolvedDataSourceSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/sources/ResolvedDataSourceSuite.scala
index 4f6df54..320aaea 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/sources/ResolvedDataSourceSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/sources/ResolvedDataSourceSuite.scala
@@ -27,37 +27,37 @@ class ResolvedDataSourceSuite extends SparkFunSuite {
test("jdbc") {
assert(
getProvidingClass("jdbc") ===
- classOf[org.apache.spark.sql.execution.datasources.jdbc.DefaultSource])
+ classOf[org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider])
assert(
getProvidingClass("org.apache.spark.sql.execution.datasources.jdbc") ===
- classOf[org.apache.spark.sql.execution.datasources.jdbc.DefaultSource])
+ classOf[org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider])
assert(
getProvidingClass("org.apache.spark.sql.jdbc") ===
- classOf[org.apache.spark.sql.execution.datasources.jdbc.DefaultSource])
+ classOf[org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider])
}
test("json") {
assert(
getProvidingClass("json") ===
- classOf[org.apache.spark.sql.execution.datasources.json.DefaultSource])
+ classOf[org.apache.spark.sql.execution.datasources.json.JsonFileFormat])
assert(
getProvidingClass("org.apache.spark.sql.execution.datasources.json") ===
- classOf[org.apache.spark.sql.execution.datasources.json.DefaultSource])
+ classOf[org.apache.spark.sql.execution.datasources.json.JsonFileFormat])
assert(
getProvidingClass("org.apache.spark.sql.json") ===
- classOf[org.apache.spark.sql.execution.datasources.json.DefaultSource])
+ classOf[org.apache.spark.sql.execution.datasources.json.JsonFileFormat])
}
test("parquet") {
assert(
getProvidingClass("parquet") ===
- classOf[org.apache.spark.sql.execution.datasources.parquet.DefaultSource])
+ classOf[org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat])
assert(
getProvidingClass("org.apache.spark.sql.execution.datasources.parquet") ===
- classOf[org.apache.spark.sql.execution.datasources.parquet.DefaultSource])
+ classOf[org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat])
assert(
getProvidingClass("org.apache.spark.sql.parquet") ===
- classOf[org.apache.spark.sql.execution.datasources.parquet.DefaultSource])
+ classOf[org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat])
}
test("error message for unknown data sources") {
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/test/scala/org/apache/spark/sql/streaming/DataFrameReaderWriterSuite.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/streaming/DataFrameReaderWriterSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/streaming/DataFrameReaderWriterSuite.scala
deleted file mode 100644
index e6c0ce9..0000000
--- a/sql/core/src/test/scala/org/apache/spark/sql/streaming/DataFrameReaderWriterSuite.scala
+++ /dev/null
@@ -1,542 +0,0 @@
-/*
- * 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.streaming.test
-
-import java.util.concurrent.TimeUnit
-
-import scala.concurrent.duration._
-
-import org.mockito.Mockito._
-import org.scalatest.BeforeAndAfter
-
-import org.apache.spark.sql._
-import org.apache.spark.sql.execution.streaming._
-import org.apache.spark.sql.sources.{StreamSinkProvider, StreamSourceProvider}
-import org.apache.spark.sql.test.SharedSQLContext
-import org.apache.spark.sql.types.{IntegerType, StructField, StructType}
-import org.apache.spark.util.Utils
-
-object LastOptions {
-
- var mockStreamSourceProvider = mock(classOf[StreamSourceProvider])
- var mockStreamSinkProvider = mock(classOf[StreamSinkProvider])
- var parameters: Map[String, String] = null
- var schema: Option[StructType] = null
- var partitionColumns: Seq[String] = Nil
-
- def clear(): Unit = {
- parameters = null
- schema = null
- partitionColumns = null
- reset(mockStreamSourceProvider)
- reset(mockStreamSinkProvider)
- }
-}
-
-/** Dummy provider: returns no-op source/sink and records options in [[LastOptions]]. */
-class DefaultSource extends StreamSourceProvider with StreamSinkProvider {
-
- private val fakeSchema = StructType(StructField("a", IntegerType) :: Nil)
-
- override def sourceSchema(
- spark: SQLContext,
- schema: Option[StructType],
- providerName: String,
- parameters: Map[String, String]): (String, StructType) = {
- LastOptions.parameters = parameters
- LastOptions.schema = schema
- LastOptions.mockStreamSourceProvider.sourceSchema(spark, schema, providerName, parameters)
- ("dummySource", fakeSchema)
- }
-
- override def createSource(
- spark: SQLContext,
- metadataPath: String,
- schema: Option[StructType],
- providerName: String,
- parameters: Map[String, String]): Source = {
- LastOptions.parameters = parameters
- LastOptions.schema = schema
- LastOptions.mockStreamSourceProvider.createSource(
- spark, metadataPath, schema, providerName, parameters)
- new Source {
- override def schema: StructType = fakeSchema
-
- override def getOffset: Option[Offset] = Some(new LongOffset(0))
-
- override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
- import spark.implicits._
-
- Seq[Int]().toDS().toDF()
- }
- }
- }
-
- override def createSink(
- spark: SQLContext,
- parameters: Map[String, String],
- partitionColumns: Seq[String]): Sink = {
- LastOptions.parameters = parameters
- LastOptions.partitionColumns = partitionColumns
- LastOptions.mockStreamSinkProvider.createSink(spark, parameters, partitionColumns)
- new Sink {
- override def addBatch(batchId: Long, data: DataFrame): Unit = {}
- }
- }
-}
-
-class DataFrameReaderWriterSuite extends StreamTest with SharedSQLContext with BeforeAndAfter {
- import testImplicits._
-
- private def newMetadataDir =
- Utils.createTempDir(namePrefix = "streaming.metadata").getCanonicalPath
-
- after {
- spark.streams.active.foreach(_.stop())
- }
-
- test("resolve default source") {
- spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- .write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .startStream()
- .stop()
- }
-
- test("resolve full class") {
- spark.read
- .format("org.apache.spark.sql.streaming.test.DefaultSource")
- .stream()
- .write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .startStream()
- .stop()
- }
-
- test("options") {
- val map = new java.util.HashMap[String, String]
- map.put("opt3", "3")
-
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .option("opt1", "1")
- .options(Map("opt2" -> "2"))
- .options(map)
- .stream()
-
- assert(LastOptions.parameters("opt1") == "1")
- assert(LastOptions.parameters("opt2") == "2")
- assert(LastOptions.parameters("opt3") == "3")
-
- LastOptions.clear()
-
- df.write
- .format("org.apache.spark.sql.streaming.test")
- .option("opt1", "1")
- .options(Map("opt2" -> "2"))
- .options(map)
- .option("checkpointLocation", newMetadataDir)
- .startStream()
- .stop()
-
- assert(LastOptions.parameters("opt1") == "1")
- assert(LastOptions.parameters("opt2") == "2")
- assert(LastOptions.parameters("opt3") == "3")
- }
-
- test("partitioning") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
-
- df.write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .startStream()
- .stop()
- assert(LastOptions.partitionColumns == Nil)
-
- df.write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .partitionBy("a")
- .startStream()
- .stop()
- assert(LastOptions.partitionColumns == Seq("a"))
-
- withSQLConf("spark.sql.caseSensitive" -> "false") {
- df.write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .partitionBy("A")
- .startStream()
- .stop()
- assert(LastOptions.partitionColumns == Seq("a"))
- }
-
- intercept[AnalysisException] {
- df.write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .partitionBy("b")
- .startStream()
- .stop()
- }
- }
-
- test("stream paths") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .stream("/test")
-
- assert(LastOptions.parameters("path") == "/test")
-
- LastOptions.clear()
-
- df.write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .startStream("/test")
- .stop()
-
- assert(LastOptions.parameters("path") == "/test")
- }
-
- test("test different data types for options") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .option("intOpt", 56)
- .option("boolOpt", false)
- .option("doubleOpt", 6.7)
- .stream("/test")
-
- assert(LastOptions.parameters("intOpt") == "56")
- assert(LastOptions.parameters("boolOpt") == "false")
- assert(LastOptions.parameters("doubleOpt") == "6.7")
-
- LastOptions.clear()
- df.write
- .format("org.apache.spark.sql.streaming.test")
- .option("intOpt", 56)
- .option("boolOpt", false)
- .option("doubleOpt", 6.7)
- .option("checkpointLocation", newMetadataDir)
- .startStream("/test")
- .stop()
-
- assert(LastOptions.parameters("intOpt") == "56")
- assert(LastOptions.parameters("boolOpt") == "false")
- assert(LastOptions.parameters("doubleOpt") == "6.7")
- }
-
- test("unique query names") {
-
- /** Start a query with a specific name */
- def startQueryWithName(name: String = ""): ContinuousQuery = {
- spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream("/test")
- .write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .queryName(name)
- .startStream()
- }
-
- /** Start a query without specifying a name */
- def startQueryWithoutName(): ContinuousQuery = {
- spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream("/test")
- .write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .startStream()
- }
-
- /** Get the names of active streams */
- def activeStreamNames: Set[String] = {
- val streams = spark.streams.active
- val names = streams.map(_.name).toSet
- assert(streams.length === names.size, s"names of active queries are not unique: $names")
- names
- }
-
- val q1 = startQueryWithName("name")
-
- // Should not be able to start another query with the same name
- intercept[IllegalArgumentException] {
- startQueryWithName("name")
- }
- assert(activeStreamNames === Set("name"))
-
- // Should be able to start queries with other names
- val q3 = startQueryWithName("another-name")
- assert(activeStreamNames === Set("name", "another-name"))
-
- // Should be able to start queries with auto-generated names
- val q4 = startQueryWithoutName()
- assert(activeStreamNames.contains(q4.name))
-
- // Should not be able to start a query with same auto-generated name
- intercept[IllegalArgumentException] {
- startQueryWithName(q4.name)
- }
-
- // Should be able to start query with that name after stopping the previous query
- q1.stop()
- val q5 = startQueryWithName("name")
- assert(activeStreamNames.contains("name"))
- spark.streams.active.foreach(_.stop())
- }
-
- test("trigger") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream("/test")
-
- var q = df.write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .trigger(ProcessingTime(10.seconds))
- .startStream()
- q.stop()
-
- assert(q.asInstanceOf[StreamExecution].trigger == ProcessingTime(10000))
-
- q = df.write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", newMetadataDir)
- .trigger(ProcessingTime.create(100, TimeUnit.SECONDS))
- .startStream()
- q.stop()
-
- assert(q.asInstanceOf[StreamExecution].trigger == ProcessingTime(100000))
- }
-
- test("source metadataPath") {
- LastOptions.clear()
-
- val checkpointLocation = newMetadataDir
-
- val df1 = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
-
- val df2 = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
-
- val q = df1.union(df2).write
- .format("org.apache.spark.sql.streaming.test")
- .option("checkpointLocation", checkpointLocation)
- .trigger(ProcessingTime(10.seconds))
- .startStream()
- q.stop()
-
- verify(LastOptions.mockStreamSourceProvider).createSource(
- spark.sqlContext,
- checkpointLocation + "/sources/0",
- None,
- "org.apache.spark.sql.streaming.test",
- Map.empty)
-
- verify(LastOptions.mockStreamSourceProvider).createSource(
- spark.sqlContext,
- checkpointLocation + "/sources/1",
- None,
- "org.apache.spark.sql.streaming.test",
- Map.empty)
- }
-
- private def newTextInput = Utils.createTempDir(namePrefix = "text").getCanonicalPath
-
- test("check trigger() can only be called on continuous queries") {
- val df = spark.read.text(newTextInput)
- val w = df.write.option("checkpointLocation", newMetadataDir)
- val e = intercept[AnalysisException](w.trigger(ProcessingTime("10 seconds")))
- assert(e.getMessage == "trigger() can only be called on continuous queries;")
- }
-
- test("check queryName() can only be called on continuous queries") {
- val df = spark.read.text(newTextInput)
- val w = df.write.option("checkpointLocation", newMetadataDir)
- val e = intercept[AnalysisException](w.queryName("queryName"))
- assert(e.getMessage == "queryName() can only be called on continuous queries;")
- }
-
- test("check startStream() can only be called on continuous queries") {
- val df = spark.read.text(newTextInput)
- val w = df.write.option("checkpointLocation", newMetadataDir)
- val e = intercept[AnalysisException](w.startStream())
- assert(e.getMessage == "startStream() can only be called on continuous queries;")
- }
-
- test("check startStream(path) can only be called on continuous queries") {
- val df = spark.read.text(newTextInput)
- val w = df.write.option("checkpointLocation", newMetadataDir)
- val e = intercept[AnalysisException](w.startStream("non_exist_path"))
- assert(e.getMessage == "startStream() can only be called on continuous queries;")
- }
-
- test("check mode(SaveMode) can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.mode(SaveMode.Append))
- assert(e.getMessage == "mode() can only be called on non-continuous queries;")
- }
-
- test("check mode(string) can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.mode("append"))
- assert(e.getMessage == "mode() can only be called on non-continuous queries;")
- }
-
- test("check bucketBy() can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[IllegalArgumentException](w.bucketBy(1, "text").startStream())
- assert(e.getMessage == "Currently we don't support writing bucketed data to this data source.")
- }
-
- test("check sortBy() can only be called on non-continuous queries;") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[IllegalArgumentException](w.sortBy("text").startStream())
- assert(e.getMessage == "Currently we don't support writing bucketed data to this data source.")
- }
-
- test("check save(path) can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.save("non_exist_path"))
- assert(e.getMessage == "save() can only be called on non-continuous queries;")
- }
-
- test("check save() can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.save())
- assert(e.getMessage == "save() can only be called on non-continuous queries;")
- }
-
- test("check insertInto() can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.insertInto("non_exsit_table"))
- assert(e.getMessage == "insertInto() can only be called on non-continuous queries;")
- }
-
- test("check saveAsTable() can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.saveAsTable("non_exsit_table"))
- assert(e.getMessage == "saveAsTable() can only be called on non-continuous queries;")
- }
-
- test("check jdbc() can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.jdbc(null, null, null))
- assert(e.getMessage == "jdbc() can only be called on non-continuous queries;")
- }
-
- test("check json() can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.json("non_exist_path"))
- assert(e.getMessage == "json() can only be called on non-continuous queries;")
- }
-
- test("check parquet() can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.parquet("non_exist_path"))
- assert(e.getMessage == "parquet() can only be called on non-continuous queries;")
- }
-
- test("check orc() can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.orc("non_exist_path"))
- assert(e.getMessage == "orc() can only be called on non-continuous queries;")
- }
-
- test("check text() can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.text("non_exist_path"))
- assert(e.getMessage == "text() can only be called on non-continuous queries;")
- }
-
- test("check csv() can only be called on non-continuous queries") {
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
- val w = df.write
- val e = intercept[AnalysisException](w.csv("non_exist_path"))
- assert(e.getMessage == "csv() can only be called on non-continuous queries;")
- }
-
- test("ConsoleSink can be correctly loaded") {
- LastOptions.clear()
- val df = spark.read
- .format("org.apache.spark.sql.streaming.test")
- .stream()
-
- val cq = df.write
- .format("console")
- .option("checkpointLocation", newMetadataDir)
- .trigger(ProcessingTime(2.seconds))
- .startStream()
-
- cq.awaitTermination(2000L)
- }
-}
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSinkSuite.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSinkSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSinkSuite.scala
index 6238b74..f3262f7 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSinkSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSinkSuite.scala
@@ -41,7 +41,7 @@ class FileStreamSinkSuite extends StreamTest with SharedSQLContext {
path.delete()
val hadoopConf = spark.sparkContext.hadoopConfiguration
- val fileFormat = new parquet.DefaultSource()
+ val fileFormat = new parquet.ParquetFileFormat()
def writeRange(start: Int, end: Int, numPartitions: Int): Seq[String] = {
val df = spark
@@ -73,7 +73,7 @@ class FileStreamSinkSuite extends StreamTest with SharedSQLContext {
path.delete()
val hadoopConf = spark.sparkContext.hadoopConfiguration
- val fileFormat = new parquet.DefaultSource()
+ val fileFormat = new parquet.ParquetFileFormat()
def writeRange(start: Int, end: Int, numPartitions: Int): Seq[String] = {
val df = spark
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/test/scala/org/apache/spark/sql/streaming/test/DataFrameReaderWriterSuite.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/streaming/test/DataFrameReaderWriterSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/streaming/test/DataFrameReaderWriterSuite.scala
new file mode 100644
index 0000000..288f6dc
--- /dev/null
+++ b/sql/core/src/test/scala/org/apache/spark/sql/streaming/test/DataFrameReaderWriterSuite.scala
@@ -0,0 +1,541 @@
+/*
+ * 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.streaming.test
+
+import java.util.concurrent.TimeUnit
+
+import scala.concurrent.duration._
+
+import org.mockito.Mockito._
+import org.scalatest.BeforeAndAfter
+
+import org.apache.spark.sql._
+import org.apache.spark.sql.execution.streaming._
+import org.apache.spark.sql.sources.{StreamSinkProvider, StreamSourceProvider}
+import org.apache.spark.sql.test.SharedSQLContext
+import org.apache.spark.sql.types.{IntegerType, StructField, StructType}
+import org.apache.spark.util.Utils
+
+object LastOptions {
+
+ var mockStreamSourceProvider = mock(classOf[StreamSourceProvider])
+ var mockStreamSinkProvider = mock(classOf[StreamSinkProvider])
+ var parameters: Map[String, String] = null
+ var schema: Option[StructType] = null
+ var partitionColumns: Seq[String] = Nil
+
+ def clear(): Unit = {
+ parameters = null
+ schema = null
+ partitionColumns = null
+ reset(mockStreamSourceProvider)
+ reset(mockStreamSinkProvider)
+ }
+}
+
+/** Dummy provider: returns no-op source/sink and records options in [[LastOptions]]. */
+class DefaultSource extends StreamSourceProvider with StreamSinkProvider {
+
+ private val fakeSchema = StructType(StructField("a", IntegerType) :: Nil)
+
+ override def sourceSchema(
+ spark: SQLContext,
+ schema: Option[StructType],
+ providerName: String,
+ parameters: Map[String, String]): (String, StructType) = {
+ LastOptions.parameters = parameters
+ LastOptions.schema = schema
+ LastOptions.mockStreamSourceProvider.sourceSchema(spark, schema, providerName, parameters)
+ ("dummySource", fakeSchema)
+ }
+
+ override def createSource(
+ spark: SQLContext,
+ metadataPath: String,
+ schema: Option[StructType],
+ providerName: String,
+ parameters: Map[String, String]): Source = {
+ LastOptions.parameters = parameters
+ LastOptions.schema = schema
+ LastOptions.mockStreamSourceProvider.createSource(
+ spark, metadataPath, schema, providerName, parameters)
+ new Source {
+ override def schema: StructType = fakeSchema
+
+ override def getOffset: Option[Offset] = Some(new LongOffset(0))
+
+ override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
+ import spark.implicits._
+
+ Seq[Int]().toDS().toDF()
+ }
+ }
+ }
+
+ override def createSink(
+ spark: SQLContext,
+ parameters: Map[String, String],
+ partitionColumns: Seq[String]): Sink = {
+ LastOptions.parameters = parameters
+ LastOptions.partitionColumns = partitionColumns
+ LastOptions.mockStreamSinkProvider.createSink(spark, parameters, partitionColumns)
+ new Sink {
+ override def addBatch(batchId: Long, data: DataFrame): Unit = {}
+ }
+ }
+}
+
+class DataFrameReaderWriterSuite extends StreamTest with SharedSQLContext with BeforeAndAfter {
+
+ private def newMetadataDir =
+ Utils.createTempDir(namePrefix = "streaming.metadata").getCanonicalPath
+
+ after {
+ spark.streams.active.foreach(_.stop())
+ }
+
+ test("resolve default source") {
+ spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ .write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .startStream()
+ .stop()
+ }
+
+ test("resolve full class") {
+ spark.read
+ .format("org.apache.spark.sql.streaming.test.DefaultSource")
+ .stream()
+ .write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .startStream()
+ .stop()
+ }
+
+ test("options") {
+ val map = new java.util.HashMap[String, String]
+ map.put("opt3", "3")
+
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .option("opt1", "1")
+ .options(Map("opt2" -> "2"))
+ .options(map)
+ .stream()
+
+ assert(LastOptions.parameters("opt1") == "1")
+ assert(LastOptions.parameters("opt2") == "2")
+ assert(LastOptions.parameters("opt3") == "3")
+
+ LastOptions.clear()
+
+ df.write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("opt1", "1")
+ .options(Map("opt2" -> "2"))
+ .options(map)
+ .option("checkpointLocation", newMetadataDir)
+ .startStream()
+ .stop()
+
+ assert(LastOptions.parameters("opt1") == "1")
+ assert(LastOptions.parameters("opt2") == "2")
+ assert(LastOptions.parameters("opt3") == "3")
+ }
+
+ test("partitioning") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+
+ df.write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .startStream()
+ .stop()
+ assert(LastOptions.partitionColumns == Nil)
+
+ df.write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .partitionBy("a")
+ .startStream()
+ .stop()
+ assert(LastOptions.partitionColumns == Seq("a"))
+
+ withSQLConf("spark.sql.caseSensitive" -> "false") {
+ df.write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .partitionBy("A")
+ .startStream()
+ .stop()
+ assert(LastOptions.partitionColumns == Seq("a"))
+ }
+
+ intercept[AnalysisException] {
+ df.write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .partitionBy("b")
+ .startStream()
+ .stop()
+ }
+ }
+
+ test("stream paths") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .stream("/test")
+
+ assert(LastOptions.parameters("path") == "/test")
+
+ LastOptions.clear()
+
+ df.write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .startStream("/test")
+ .stop()
+
+ assert(LastOptions.parameters("path") == "/test")
+ }
+
+ test("test different data types for options") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .option("intOpt", 56)
+ .option("boolOpt", false)
+ .option("doubleOpt", 6.7)
+ .stream("/test")
+
+ assert(LastOptions.parameters("intOpt") == "56")
+ assert(LastOptions.parameters("boolOpt") == "false")
+ assert(LastOptions.parameters("doubleOpt") == "6.7")
+
+ LastOptions.clear()
+ df.write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("intOpt", 56)
+ .option("boolOpt", false)
+ .option("doubleOpt", 6.7)
+ .option("checkpointLocation", newMetadataDir)
+ .startStream("/test")
+ .stop()
+
+ assert(LastOptions.parameters("intOpt") == "56")
+ assert(LastOptions.parameters("boolOpt") == "false")
+ assert(LastOptions.parameters("doubleOpt") == "6.7")
+ }
+
+ test("unique query names") {
+
+ /** Start a query with a specific name */
+ def startQueryWithName(name: String = ""): ContinuousQuery = {
+ spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream("/test")
+ .write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .queryName(name)
+ .startStream()
+ }
+
+ /** Start a query without specifying a name */
+ def startQueryWithoutName(): ContinuousQuery = {
+ spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream("/test")
+ .write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .startStream()
+ }
+
+ /** Get the names of active streams */
+ def activeStreamNames: Set[String] = {
+ val streams = spark.streams.active
+ val names = streams.map(_.name).toSet
+ assert(streams.length === names.size, s"names of active queries are not unique: $names")
+ names
+ }
+
+ val q1 = startQueryWithName("name")
+
+ // Should not be able to start another query with the same name
+ intercept[IllegalArgumentException] {
+ startQueryWithName("name")
+ }
+ assert(activeStreamNames === Set("name"))
+
+ // Should be able to start queries with other names
+ val q3 = startQueryWithName("another-name")
+ assert(activeStreamNames === Set("name", "another-name"))
+
+ // Should be able to start queries with auto-generated names
+ val q4 = startQueryWithoutName()
+ assert(activeStreamNames.contains(q4.name))
+
+ // Should not be able to start a query with same auto-generated name
+ intercept[IllegalArgumentException] {
+ startQueryWithName(q4.name)
+ }
+
+ // Should be able to start query with that name after stopping the previous query
+ q1.stop()
+ val q5 = startQueryWithName("name")
+ assert(activeStreamNames.contains("name"))
+ spark.streams.active.foreach(_.stop())
+ }
+
+ test("trigger") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream("/test")
+
+ var q = df.write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .trigger(ProcessingTime(10.seconds))
+ .startStream()
+ q.stop()
+
+ assert(q.asInstanceOf[StreamExecution].trigger == ProcessingTime(10000))
+
+ q = df.write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", newMetadataDir)
+ .trigger(ProcessingTime.create(100, TimeUnit.SECONDS))
+ .startStream()
+ q.stop()
+
+ assert(q.asInstanceOf[StreamExecution].trigger == ProcessingTime(100000))
+ }
+
+ test("source metadataPath") {
+ LastOptions.clear()
+
+ val checkpointLocation = newMetadataDir
+
+ val df1 = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+
+ val df2 = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+
+ val q = df1.union(df2).write
+ .format("org.apache.spark.sql.streaming.test")
+ .option("checkpointLocation", checkpointLocation)
+ .trigger(ProcessingTime(10.seconds))
+ .startStream()
+ q.stop()
+
+ verify(LastOptions.mockStreamSourceProvider).createSource(
+ spark.sqlContext,
+ checkpointLocation + "/sources/0",
+ None,
+ "org.apache.spark.sql.streaming.test",
+ Map.empty)
+
+ verify(LastOptions.mockStreamSourceProvider).createSource(
+ spark.sqlContext,
+ checkpointLocation + "/sources/1",
+ None,
+ "org.apache.spark.sql.streaming.test",
+ Map.empty)
+ }
+
+ private def newTextInput = Utils.createTempDir(namePrefix = "text").getCanonicalPath
+
+ test("check trigger() can only be called on continuous queries") {
+ val df = spark.read.text(newTextInput)
+ val w = df.write.option("checkpointLocation", newMetadataDir)
+ val e = intercept[AnalysisException](w.trigger(ProcessingTime("10 seconds")))
+ assert(e.getMessage == "trigger() can only be called on continuous queries;")
+ }
+
+ test("check queryName() can only be called on continuous queries") {
+ val df = spark.read.text(newTextInput)
+ val w = df.write.option("checkpointLocation", newMetadataDir)
+ val e = intercept[AnalysisException](w.queryName("queryName"))
+ assert(e.getMessage == "queryName() can only be called on continuous queries;")
+ }
+
+ test("check startStream() can only be called on continuous queries") {
+ val df = spark.read.text(newTextInput)
+ val w = df.write.option("checkpointLocation", newMetadataDir)
+ val e = intercept[AnalysisException](w.startStream())
+ assert(e.getMessage == "startStream() can only be called on continuous queries;")
+ }
+
+ test("check startStream(path) can only be called on continuous queries") {
+ val df = spark.read.text(newTextInput)
+ val w = df.write.option("checkpointLocation", newMetadataDir)
+ val e = intercept[AnalysisException](w.startStream("non_exist_path"))
+ assert(e.getMessage == "startStream() can only be called on continuous queries;")
+ }
+
+ test("check mode(SaveMode) can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.mode(SaveMode.Append))
+ assert(e.getMessage == "mode() can only be called on non-continuous queries;")
+ }
+
+ test("check mode(string) can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.mode("append"))
+ assert(e.getMessage == "mode() can only be called on non-continuous queries;")
+ }
+
+ test("check bucketBy() can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[IllegalArgumentException](w.bucketBy(1, "text").startStream())
+ assert(e.getMessage == "Currently we don't support writing bucketed data to this data source.")
+ }
+
+ test("check sortBy() can only be called on non-continuous queries;") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[IllegalArgumentException](w.sortBy("text").startStream())
+ assert(e.getMessage == "Currently we don't support writing bucketed data to this data source.")
+ }
+
+ test("check save(path) can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.save("non_exist_path"))
+ assert(e.getMessage == "save() can only be called on non-continuous queries;")
+ }
+
+ test("check save() can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.save())
+ assert(e.getMessage == "save() can only be called on non-continuous queries;")
+ }
+
+ test("check insertInto() can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.insertInto("non_exsit_table"))
+ assert(e.getMessage == "insertInto() can only be called on non-continuous queries;")
+ }
+
+ test("check saveAsTable() can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.saveAsTable("non_exsit_table"))
+ assert(e.getMessage == "saveAsTable() can only be called on non-continuous queries;")
+ }
+
+ test("check jdbc() can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.jdbc(null, null, null))
+ assert(e.getMessage == "jdbc() can only be called on non-continuous queries;")
+ }
+
+ test("check json() can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.json("non_exist_path"))
+ assert(e.getMessage == "json() can only be called on non-continuous queries;")
+ }
+
+ test("check parquet() can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.parquet("non_exist_path"))
+ assert(e.getMessage == "parquet() can only be called on non-continuous queries;")
+ }
+
+ test("check orc() can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.orc("non_exist_path"))
+ assert(e.getMessage == "orc() can only be called on non-continuous queries;")
+ }
+
+ test("check text() can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.text("non_exist_path"))
+ assert(e.getMessage == "text() can only be called on non-continuous queries;")
+ }
+
+ test("check csv() can only be called on non-continuous queries") {
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+ val w = df.write
+ val e = intercept[AnalysisException](w.csv("non_exist_path"))
+ assert(e.getMessage == "csv() can only be called on non-continuous queries;")
+ }
+
+ test("ConsoleSink can be correctly loaded") {
+ LastOptions.clear()
+ val df = spark.read
+ .format("org.apache.spark.sql.streaming.test")
+ .stream()
+
+ val cq = df.write
+ .format("console")
+ .option("checkpointLocation", newMetadataDir)
+ .trigger(ProcessingTime(2.seconds))
+ .startStream()
+
+ cq.awaitTermination(2000L)
+ }
+}
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/hive/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
----------------------------------------------------------------------
diff --git a/sql/hive/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister b/sql/hive/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
index 4a774fb..32aa13f 100644
--- a/sql/hive/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
+++ b/sql/hive/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
@@ -1 +1 @@
-org.apache.spark.sql.hive.orc.DefaultSource
+org.apache.spark.sql.hive.orc.OrcFileFormat
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveMetastoreCatalog.scala
----------------------------------------------------------------------
diff --git a/sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveMetastoreCatalog.scala b/sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveMetastoreCatalog.scala
index 86ab152..b377a20 100644
--- a/sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveMetastoreCatalog.scala
+++ b/sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveMetastoreCatalog.scala
@@ -32,8 +32,8 @@ import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.rules._
import org.apache.spark.sql.execution.command.CreateTableAsSelectLogicalPlan
import org.apache.spark.sql.execution.datasources.{Partition => _, _}
-import org.apache.spark.sql.execution.datasources.parquet.{DefaultSource => ParquetDefaultSource, ParquetRelation}
-import org.apache.spark.sql.hive.orc.{DefaultSource => OrcDefaultSource}
+import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
+import org.apache.spark.sql.hive.orc.OrcFileFormat
import org.apache.spark.sql.types._
@@ -281,7 +281,7 @@ private[hive] class HiveMetastoreCatalog(sparkSession: SparkSession) extends Log
val inferredSchema =
defaultSource.inferSchema(sparkSession, options, fileCatalog.allFiles())
inferredSchema.map { inferred =>
- ParquetRelation.mergeMetastoreParquetSchema(metastoreSchema, inferred)
+ ParquetFileFormat.mergeMetastoreParquetSchema(metastoreSchema, inferred)
}.getOrElse(metastoreSchema)
} else {
defaultSource.inferSchema(sparkSession, options, fileCatalog.allFiles()).get
@@ -348,13 +348,13 @@ private[hive] class HiveMetastoreCatalog(sparkSession: SparkSession) extends Log
}
private def convertToParquetRelation(relation: MetastoreRelation): LogicalRelation = {
- val defaultSource = new ParquetDefaultSource()
- val fileFormatClass = classOf[ParquetDefaultSource]
+ val defaultSource = new ParquetFileFormat()
+ val fileFormatClass = classOf[ParquetFileFormat]
val mergeSchema = sessionState.convertMetastoreParquetWithSchemaMerging
val options = Map(
- ParquetRelation.MERGE_SCHEMA -> mergeSchema.toString,
- ParquetRelation.METASTORE_TABLE_NAME -> TableIdentifier(
+ ParquetFileFormat.MERGE_SCHEMA -> mergeSchema.toString,
+ ParquetFileFormat.METASTORE_TABLE_NAME -> TableIdentifier(
relation.tableName,
Some(relation.databaseName)
).unquotedString
@@ -400,8 +400,8 @@ private[hive] class HiveMetastoreCatalog(sparkSession: SparkSession) extends Log
}
private def convertToOrcRelation(relation: MetastoreRelation): LogicalRelation = {
- val defaultSource = new OrcDefaultSource()
- val fileFormatClass = classOf[OrcDefaultSource]
+ val defaultSource = new OrcFileFormat()
+ val fileFormatClass = classOf[OrcFileFormat]
val options = Map[String, String]()
convertToLogicalRelation(relation, options, defaultSource, fileFormatClass, "orc")
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/hive/src/main/scala/org/apache/spark/sql/hive/orc/OrcFileFormat.scala
----------------------------------------------------------------------
diff --git a/sql/hive/src/main/scala/org/apache/spark/sql/hive/orc/OrcFileFormat.scala b/sql/hive/src/main/scala/org/apache/spark/sql/hive/orc/OrcFileFormat.scala
new file mode 100644
index 0000000..f119817
--- /dev/null
+++ b/sql/hive/src/main/scala/org/apache/spark/sql/hive/orc/OrcFileFormat.scala
@@ -0,0 +1,375 @@
+/*
+ * 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.hive.orc
+
+import java.net.URI
+import java.util.Properties
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{FileStatus, Path}
+import org.apache.hadoop.hive.conf.HiveConf.ConfVars
+import org.apache.hadoop.hive.ql.io.orc._
+import org.apache.hadoop.hive.serde2.objectinspector.{SettableStructObjectInspector, StructObjectInspector}
+import org.apache.hadoop.hive.serde2.typeinfo.{StructTypeInfo, TypeInfoUtils}
+import org.apache.hadoop.io.{NullWritable, Writable}
+import org.apache.hadoop.mapred.{InputFormat => MapRedInputFormat, JobConf, OutputFormat => MapRedOutputFormat, RecordWriter, Reporter}
+import org.apache.hadoop.mapreduce._
+import org.apache.hadoop.mapreduce.lib.input.{FileInputFormat, FileSplit}
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.rdd.{HadoopRDD, RDD}
+import org.apache.spark.sql.{Row, SparkSession}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.execution.datasources._
+import org.apache.spark.sql.hive.{HiveInspectors, HiveShim}
+import org.apache.spark.sql.sources.{Filter, _}
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.util.SerializableConfiguration
+
+/**
+ * [[FileFormat]] for reading ORC files. If this is moved or renamed, please update
+ * [[DataSource]]'s backwardCompatibilityMap.
+ */
+private[sql] class OrcFileFormat
+ extends FileFormat with DataSourceRegister with Serializable {
+
+ override def shortName(): String = "orc"
+
+ override def toString: String = "ORC"
+
+ override def inferSchema(
+ sparkSession: SparkSession,
+ options: Map[String, String],
+ files: Seq[FileStatus]): Option[StructType] = {
+ OrcFileOperator.readSchema(
+ files.map(_.getPath.toUri.toString),
+ Some(sparkSession.sessionState.newHadoopConf())
+ )
+ }
+
+ override def prepareWrite(
+ sparkSession: SparkSession,
+ job: Job,
+ options: Map[String, String],
+ dataSchema: StructType): OutputWriterFactory = {
+ val orcOptions = new OrcOptions(options)
+
+ val configuration = job.getConfiguration
+
+ configuration.set(OrcRelation.ORC_COMPRESSION, orcOptions.compressionCodec)
+ configuration match {
+ case conf: JobConf =>
+ conf.setOutputFormat(classOf[OrcOutputFormat])
+ case conf =>
+ conf.setClass(
+ "mapred.output.format.class",
+ classOf[OrcOutputFormat],
+ classOf[MapRedOutputFormat[_, _]])
+ }
+
+ new OutputWriterFactory {
+ override def newInstance(
+ path: String,
+ bucketId: Option[Int],
+ dataSchema: StructType,
+ context: TaskAttemptContext): OutputWriter = {
+ new OrcOutputWriter(path, bucketId, dataSchema, context)
+ }
+ }
+ }
+
+ override def buildReader(
+ sparkSession: SparkSession,
+ dataSchema: StructType,
+ partitionSchema: StructType,
+ requiredSchema: StructType,
+ filters: Seq[Filter],
+ options: Map[String, String],
+ hadoopConf: Configuration): (PartitionedFile) => Iterator[InternalRow] = {
+ if (sparkSession.sessionState.conf.orcFilterPushDown) {
+ // Sets pushed predicates
+ OrcFilters.createFilter(requiredSchema, filters.toArray).foreach { f =>
+ hadoopConf.set(OrcTableScan.SARG_PUSHDOWN, f.toKryo)
+ hadoopConf.setBoolean(ConfVars.HIVEOPTINDEXFILTER.varname, true)
+ }
+ }
+
+ val broadcastedHadoopConf =
+ sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf))
+
+ (file: PartitionedFile) => {
+ val conf = broadcastedHadoopConf.value.value
+
+ // SPARK-8501: Empty ORC files always have an empty schema stored in their footer. In this
+ // case, `OrcFileOperator.readSchema` returns `None`, and we can't read the underlying file
+ // using the given physical schema. Instead, we simply return an empty iterator.
+ val maybePhysicalSchema = OrcFileOperator.readSchema(Seq(file.filePath), Some(conf))
+ if (maybePhysicalSchema.isEmpty) {
+ Iterator.empty
+ } else {
+ val physicalSchema = maybePhysicalSchema.get
+ OrcRelation.setRequiredColumns(conf, physicalSchema, requiredSchema)
+
+ val orcRecordReader = {
+ val job = Job.getInstance(conf)
+ FileInputFormat.setInputPaths(job, file.filePath)
+
+ val fileSplit = new FileSplit(
+ new Path(new URI(file.filePath)), file.start, file.length, Array.empty
+ )
+ // Custom OrcRecordReader is used to get
+ // ObjectInspector during recordReader creation itself and can
+ // avoid NameNode call in unwrapOrcStructs per file.
+ // Specifically would be helpful for partitioned datasets.
+ val orcReader = OrcFile.createReader(
+ new Path(new URI(file.filePath)), OrcFile.readerOptions(conf))
+ new SparkOrcNewRecordReader(orcReader, conf, fileSplit.getStart, fileSplit.getLength)
+ }
+
+ // Unwraps `OrcStruct`s to `UnsafeRow`s
+ OrcRelation.unwrapOrcStructs(
+ conf,
+ requiredSchema,
+ Some(orcRecordReader.getObjectInspector.asInstanceOf[StructObjectInspector]),
+ new RecordReaderIterator[OrcStruct](orcRecordReader))
+ }
+ }
+ }
+}
+
+private[orc] class OrcSerializer(dataSchema: StructType, conf: Configuration)
+ extends HiveInspectors {
+
+ def serialize(row: InternalRow): Writable = {
+ wrapOrcStruct(cachedOrcStruct, structOI, row)
+ serializer.serialize(cachedOrcStruct, structOI)
+ }
+
+ private[this] val serializer = {
+ val table = new Properties()
+ table.setProperty("columns", dataSchema.fieldNames.mkString(","))
+ table.setProperty("columns.types", dataSchema.map(_.dataType.catalogString).mkString(":"))
+
+ val serde = new OrcSerde
+ serde.initialize(conf, table)
+ serde
+ }
+
+ // Object inspector converted from the schema of the relation to be serialized.
+ private[this] val structOI = {
+ val typeInfo = TypeInfoUtils.getTypeInfoFromTypeString(dataSchema.catalogString)
+ OrcStruct.createObjectInspector(typeInfo.asInstanceOf[StructTypeInfo])
+ .asInstanceOf[SettableStructObjectInspector]
+ }
+
+ private[this] val cachedOrcStruct = structOI.create().asInstanceOf[OrcStruct]
+
+ private[this] def wrapOrcStruct(
+ struct: OrcStruct,
+ oi: SettableStructObjectInspector,
+ row: InternalRow): Unit = {
+ val fieldRefs = oi.getAllStructFieldRefs
+ var i = 0
+ while (i < fieldRefs.size) {
+
+ oi.setStructFieldData(
+ struct,
+ fieldRefs.get(i),
+ wrap(
+ row.get(i, dataSchema(i).dataType),
+ fieldRefs.get(i).getFieldObjectInspector,
+ dataSchema(i).dataType))
+ i += 1
+ }
+ }
+}
+
+private[orc] class OrcOutputWriter(
+ path: String,
+ bucketId: Option[Int],
+ dataSchema: StructType,
+ context: TaskAttemptContext)
+ extends OutputWriter {
+
+ private[this] val conf = context.getConfiguration
+
+ private[this] val serializer = new OrcSerializer(dataSchema, conf)
+
+ // `OrcRecordWriter.close()` creates an empty file if no rows are written at all. We use this
+ // flag to decide whether `OrcRecordWriter.close()` needs to be called.
+ private var recordWriterInstantiated = false
+
+ private lazy val recordWriter: RecordWriter[NullWritable, Writable] = {
+ recordWriterInstantiated = true
+ val uniqueWriteJobId = conf.get("spark.sql.sources.writeJobUUID")
+ val taskAttemptId = context.getTaskAttemptID
+ val partition = taskAttemptId.getTaskID.getId
+ val bucketString = bucketId.map(BucketingUtils.bucketIdToString).getOrElse("")
+ val compressionExtension = {
+ val name = conf.get(OrcRelation.ORC_COMPRESSION)
+ OrcRelation.extensionsForCompressionCodecNames.getOrElse(name, "")
+ }
+ // It has the `.orc` extension at the end because (de)compression tools
+ // such as gunzip would not be able to decompress this as the compression
+ // is not applied on this whole file but on each "stream" in ORC format.
+ val filename = f"part-r-$partition%05d-$uniqueWriteJobId$bucketString$compressionExtension.orc"
+
+ new OrcOutputFormat().getRecordWriter(
+ new Path(path, filename).getFileSystem(conf),
+ conf.asInstanceOf[JobConf],
+ new Path(path, filename).toString,
+ Reporter.NULL
+ ).asInstanceOf[RecordWriter[NullWritable, Writable]]
+ }
+
+ override def write(row: Row): Unit =
+ throw new UnsupportedOperationException("call writeInternal")
+
+ override protected[sql] def writeInternal(row: InternalRow): Unit = {
+ recordWriter.write(NullWritable.get(), serializer.serialize(row))
+ }
+
+ override def close(): Unit = {
+ if (recordWriterInstantiated) {
+ recordWriter.close(Reporter.NULL)
+ }
+ }
+}
+
+private[orc] case class OrcTableScan(
+ @transient sparkSession: SparkSession,
+ attributes: Seq[Attribute],
+ filters: Array[Filter],
+ @transient inputPaths: Seq[FileStatus])
+ extends Logging
+ with HiveInspectors {
+
+ def execute(): RDD[InternalRow] = {
+ val job = Job.getInstance(sparkSession.sessionState.newHadoopConf())
+ val conf = job.getConfiguration
+
+ // Figure out the actual schema from the ORC source (without partition columns) so that we
+ // can pick the correct ordinals. Note that this assumes that all files have the same schema.
+ val orcFormat = new OrcFileFormat
+ val dataSchema =
+ orcFormat
+ .inferSchema(sparkSession, Map.empty, inputPaths)
+ .getOrElse(sys.error("Failed to read schema from target ORC files."))
+
+ // Tries to push down filters if ORC filter push-down is enabled
+ if (sparkSession.sessionState.conf.orcFilterPushDown) {
+ OrcFilters.createFilter(dataSchema, filters).foreach { f =>
+ conf.set(OrcTableScan.SARG_PUSHDOWN, f.toKryo)
+ conf.setBoolean(ConfVars.HIVEOPTINDEXFILTER.varname, true)
+ }
+ }
+
+ // Sets requested columns
+ OrcRelation.setRequiredColumns(conf, dataSchema, StructType.fromAttributes(attributes))
+
+ if (inputPaths.isEmpty) {
+ // the input path probably be pruned, return an empty RDD.
+ return sparkSession.sparkContext.emptyRDD[InternalRow]
+ }
+ FileInputFormat.setInputPaths(job, inputPaths.map(_.getPath): _*)
+
+ val inputFormatClass =
+ classOf[OrcInputFormat]
+ .asInstanceOf[Class[_ <: MapRedInputFormat[NullWritable, Writable]]]
+
+ val rdd = sparkSession.sparkContext.hadoopRDD(
+ conf.asInstanceOf[JobConf],
+ inputFormatClass,
+ classOf[NullWritable],
+ classOf[Writable]
+ ).asInstanceOf[HadoopRDD[NullWritable, Writable]]
+
+ val wrappedConf = new SerializableConfiguration(conf)
+
+ rdd.mapPartitionsWithInputSplit { case (split: OrcSplit, iterator) =>
+ val writableIterator = iterator.map(_._2)
+ val maybeStructOI = OrcFileOperator.getObjectInspector(split.getPath.toString, Some(conf))
+ OrcRelation.unwrapOrcStructs(
+ wrappedConf.value,
+ StructType.fromAttributes(attributes),
+ maybeStructOI,
+ writableIterator
+ )
+ }
+ }
+}
+
+private[orc] object OrcTableScan {
+ // This constant duplicates `OrcInputFormat.SARG_PUSHDOWN`, which is unfortunately not public.
+ private[orc] val SARG_PUSHDOWN = "sarg.pushdown"
+}
+
+private[orc] object OrcRelation extends HiveInspectors {
+ // The references of Hive's classes will be minimized.
+ val ORC_COMPRESSION = "orc.compress"
+
+ // The extensions for ORC compression codecs
+ val extensionsForCompressionCodecNames = Map(
+ "NONE" -> "",
+ "SNAPPY" -> ".snappy",
+ "ZLIB" -> ".zlib",
+ "LZO" -> ".lzo")
+
+ def unwrapOrcStructs(
+ conf: Configuration,
+ dataSchema: StructType,
+ maybeStructOI: Option[StructObjectInspector],
+ iterator: Iterator[Writable]): Iterator[InternalRow] = {
+ val deserializer = new OrcSerde
+ val mutableRow = new SpecificMutableRow(dataSchema.map(_.dataType))
+ val unsafeProjection = UnsafeProjection.create(dataSchema)
+
+ def unwrap(oi: StructObjectInspector): Iterator[InternalRow] = {
+ val (fieldRefs, fieldOrdinals) = dataSchema.zipWithIndex.map {
+ case (field, ordinal) => oi.getStructFieldRef(field.name) -> ordinal
+ }.unzip
+
+ val unwrappers = fieldRefs.map(unwrapperFor)
+
+ iterator.map { value =>
+ val raw = deserializer.deserialize(value)
+ var i = 0
+ while (i < fieldRefs.length) {
+ val fieldValue = oi.getStructFieldData(raw, fieldRefs(i))
+ if (fieldValue == null) {
+ mutableRow.setNullAt(fieldOrdinals(i))
+ } else {
+ unwrappers(i)(fieldValue, mutableRow, fieldOrdinals(i))
+ }
+ i += 1
+ }
+ unsafeProjection(mutableRow)
+ }
+ }
+
+ maybeStructOI.map(unwrap).getOrElse(Iterator.empty)
+ }
+
+ def setRequiredColumns(
+ conf: Configuration, physicalSchema: StructType, requestedSchema: StructType): Unit = {
+ val ids = requestedSchema.map(a => physicalSchema.fieldIndex(a.name): Integer)
+ val (sortedIDs, sortedNames) = ids.zip(requestedSchema.fieldNames).sorted.unzip
+ HiveShim.appendReadColumns(conf, sortedIDs, sortedNames)
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org
[3/4] spark git commit: [SPARK-15543][SQL] Rename DefaultSources to
make them more self-describing
Posted by rx...@apache.org.
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetFileFormat.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetFileFormat.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetFileFormat.scala
new file mode 100644
index 0000000..b47d41e
--- /dev/null
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetFileFormat.scala
@@ -0,0 +1,923 @@
+/*
+ * 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.execution.datasources.parquet
+
+import java.net.URI
+import java.util.logging.{Logger => JLogger}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.util.{Failure, Try}
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{FileStatus, Path}
+import org.apache.hadoop.mapreduce._
+import org.apache.hadoop.mapreduce.lib.input.{FileInputFormat, FileSplit}
+import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl
+import org.apache.parquet.{Log => ApacheParquetLog}
+import org.apache.parquet.filter2.compat.FilterCompat
+import org.apache.parquet.filter2.predicate.FilterApi
+import org.apache.parquet.hadoop._
+import org.apache.parquet.hadoop.util.ContextUtil
+import org.apache.parquet.schema.MessageType
+import org.slf4j.bridge.SLF4JBridgeHandler
+
+import org.apache.spark.SparkException
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql._
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.catalyst.parser.LegacyTypeStringParser
+import org.apache.spark.sql.execution.datasources._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types._
+import org.apache.spark.util.SerializableConfiguration
+
+private[sql] class ParquetFileFormat
+ extends FileFormat
+ with DataSourceRegister
+ with Logging
+ with Serializable {
+
+ override def shortName(): String = "parquet"
+
+ override def toString: String = "ParquetFormat"
+
+ override def hashCode(): Int = getClass.hashCode()
+
+ override def equals(other: Any): Boolean = other.isInstanceOf[ParquetFileFormat]
+
+ override def prepareWrite(
+ sparkSession: SparkSession,
+ job: Job,
+ options: Map[String, String],
+ dataSchema: StructType): OutputWriterFactory = {
+
+ val parquetOptions = new ParquetOptions(options, sparkSession.sessionState.conf)
+
+ val conf = ContextUtil.getConfiguration(job)
+
+ val committerClass =
+ conf.getClass(
+ SQLConf.PARQUET_OUTPUT_COMMITTER_CLASS.key,
+ classOf[ParquetOutputCommitter],
+ classOf[ParquetOutputCommitter])
+
+ if (conf.get(SQLConf.PARQUET_OUTPUT_COMMITTER_CLASS.key) == null) {
+ logInfo("Using default output committer for Parquet: " +
+ classOf[ParquetOutputCommitter].getCanonicalName)
+ } else {
+ logInfo("Using user defined output committer for Parquet: " + committerClass.getCanonicalName)
+ }
+
+ conf.setClass(
+ SQLConf.OUTPUT_COMMITTER_CLASS.key,
+ committerClass,
+ classOf[ParquetOutputCommitter])
+
+ // We're not really using `ParquetOutputFormat[Row]` for writing data here, because we override
+ // it in `ParquetOutputWriter` to support appending and dynamic partitioning. The reason why
+ // we set it here is to setup the output committer class to `ParquetOutputCommitter`, which is
+ // bundled with `ParquetOutputFormat[Row]`.
+ job.setOutputFormatClass(classOf[ParquetOutputFormat[Row]])
+
+ ParquetOutputFormat.setWriteSupportClass(job, classOf[CatalystWriteSupport])
+
+ // We want to clear this temporary metadata from saving into Parquet file.
+ // This metadata is only useful for detecting optional columns when pushdowning filters.
+ val dataSchemaToWrite = StructType.removeMetadata(StructType.metadataKeyForOptionalField,
+ dataSchema).asInstanceOf[StructType]
+ CatalystWriteSupport.setSchema(dataSchemaToWrite, conf)
+
+ // Sets flags for `CatalystSchemaConverter` (which converts Catalyst schema to Parquet schema)
+ // and `CatalystWriteSupport` (writing actual rows to Parquet files).
+ conf.set(
+ SQLConf.PARQUET_BINARY_AS_STRING.key,
+ sparkSession.sessionState.conf.isParquetBinaryAsString.toString)
+
+ conf.set(
+ SQLConf.PARQUET_INT96_AS_TIMESTAMP.key,
+ sparkSession.sessionState.conf.isParquetINT96AsTimestamp.toString)
+
+ conf.set(
+ SQLConf.PARQUET_WRITE_LEGACY_FORMAT.key,
+ sparkSession.sessionState.conf.writeLegacyParquetFormat.toString)
+
+ // Sets compression scheme
+ conf.set(ParquetOutputFormat.COMPRESSION, parquetOptions.compressionCodec)
+
+ new OutputWriterFactory {
+ override def newInstance(
+ path: String,
+ bucketId: Option[Int],
+ dataSchema: StructType,
+ context: TaskAttemptContext): OutputWriter = {
+ new ParquetOutputWriter(path, bucketId, context)
+ }
+ }
+ }
+
+ def inferSchema(
+ sparkSession: SparkSession,
+ parameters: Map[String, String],
+ files: Seq[FileStatus]): Option[StructType] = {
+ // Should we merge schemas from all Parquet part-files?
+ val shouldMergeSchemas =
+ parameters
+ .get(ParquetFileFormat.MERGE_SCHEMA)
+ .map(_.toBoolean)
+ .getOrElse(sparkSession.conf.get(SQLConf.PARQUET_SCHEMA_MERGING_ENABLED))
+
+ val mergeRespectSummaries = sparkSession.conf.get(SQLConf.PARQUET_SCHEMA_RESPECT_SUMMARIES)
+
+ val filesByType = splitFiles(files)
+
+ // Sees which file(s) we need to touch in order to figure out the schema.
+ //
+ // Always tries the summary files first if users don't require a merged schema. In this case,
+ // "_common_metadata" is more preferable than "_metadata" because it doesn't contain row
+ // groups information, and could be much smaller for large Parquet files with lots of row
+ // groups. If no summary file is available, falls back to some random part-file.
+ //
+ // NOTE: Metadata stored in the summary files are merged from all part-files. However, for
+ // user defined key-value metadata (in which we store Spark SQL schema), Parquet doesn't know
+ // how to merge them correctly if some key is associated with different values in different
+ // part-files. When this happens, Parquet simply gives up generating the summary file. This
+ // implies that if a summary file presents, then:
+ //
+ // 1. Either all part-files have exactly the same Spark SQL schema, or
+ // 2. Some part-files don't contain Spark SQL schema in the key-value metadata at all (thus
+ // their schemas may differ from each other).
+ //
+ // Here we tend to be pessimistic and take the second case into account. Basically this means
+ // we can't trust the summary files if users require a merged schema, and must touch all part-
+ // files to do the merge.
+ val filesToTouch =
+ if (shouldMergeSchemas) {
+ // Also includes summary files, 'cause there might be empty partition directories.
+
+ // If mergeRespectSummaries config is true, we assume that all part-files are the same for
+ // their schema with summary files, so we ignore them when merging schema.
+ // If the config is disabled, which is the default setting, we merge all part-files.
+ // In this mode, we only need to merge schemas contained in all those summary files.
+ // You should enable this configuration only if you are very sure that for the parquet
+ // part-files to read there are corresponding summary files containing correct schema.
+
+ // As filed in SPARK-11500, the order of files to touch is a matter, which might affect
+ // the ordering of the output columns. There are several things to mention here.
+ //
+ // 1. If mergeRespectSummaries config is false, then it merges schemas by reducing from
+ // the first part-file so that the columns of the lexicographically first file show
+ // first.
+ //
+ // 2. If mergeRespectSummaries config is true, then there should be, at least,
+ // "_metadata"s for all given files, so that we can ensure the columns of
+ // the lexicographically first file show first.
+ //
+ // 3. If shouldMergeSchemas is false, but when multiple files are given, there is
+ // no guarantee of the output order, since there might not be a summary file for the
+ // lexicographically first file, which ends up putting ahead the columns of
+ // the other files. However, this should be okay since not enabling
+ // shouldMergeSchemas means (assumes) all the files have the same schemas.
+
+ val needMerged: Seq[FileStatus] =
+ if (mergeRespectSummaries) {
+ Seq()
+ } else {
+ filesByType.data
+ }
+ needMerged ++ filesByType.metadata ++ filesByType.commonMetadata
+ } else {
+ // Tries any "_common_metadata" first. Parquet files written by old versions or Parquet
+ // don't have this.
+ filesByType.commonMetadata.headOption
+ // Falls back to "_metadata"
+ .orElse(filesByType.metadata.headOption)
+ // Summary file(s) not found, the Parquet file is either corrupted, or different part-
+ // files contain conflicting user defined metadata (two or more values are associated
+ // with a same key in different files). In either case, we fall back to any of the
+ // first part-file, and just assume all schemas are consistent.
+ .orElse(filesByType.data.headOption)
+ .toSeq
+ }
+ ParquetFileFormat.mergeSchemasInParallel(filesToTouch, sparkSession)
+ }
+
+ case class FileTypes(
+ data: Seq[FileStatus],
+ metadata: Seq[FileStatus],
+ commonMetadata: Seq[FileStatus])
+
+ private def splitFiles(allFiles: Seq[FileStatus]): FileTypes = {
+ // Lists `FileStatus`es of all leaf nodes (files) under all base directories.
+ val leaves = allFiles.filter { f =>
+ isSummaryFile(f.getPath) ||
+ !(f.getPath.getName.startsWith("_") || f.getPath.getName.startsWith("."))
+ }.toArray.sortBy(_.getPath.toString)
+
+ FileTypes(
+ data = leaves.filterNot(f => isSummaryFile(f.getPath)),
+ metadata =
+ leaves.filter(_.getPath.getName == ParquetFileWriter.PARQUET_METADATA_FILE),
+ commonMetadata =
+ leaves.filter(_.getPath.getName == ParquetFileWriter.PARQUET_COMMON_METADATA_FILE))
+ }
+
+ private def isSummaryFile(file: Path): Boolean = {
+ file.getName == ParquetFileWriter.PARQUET_COMMON_METADATA_FILE ||
+ file.getName == ParquetFileWriter.PARQUET_METADATA_FILE
+ }
+
+ /**
+ * Returns whether the reader will return the rows as batch or not.
+ */
+ override def supportBatch(sparkSession: SparkSession, schema: StructType): Boolean = {
+ val conf = sparkSession.sessionState.conf
+ conf.parquetVectorizedReaderEnabled && conf.wholeStageEnabled &&
+ schema.length <= conf.wholeStageMaxNumFields &&
+ schema.forall(_.dataType.isInstanceOf[AtomicType])
+ }
+
+ override private[sql] def buildReaderWithPartitionValues(
+ sparkSession: SparkSession,
+ dataSchema: StructType,
+ partitionSchema: StructType,
+ requiredSchema: StructType,
+ filters: Seq[Filter],
+ options: Map[String, String],
+ hadoopConf: Configuration): (PartitionedFile) => Iterator[InternalRow] = {
+ // For Parquet data source, `buildReader` already handles partition values appending. Here we
+ // simply delegate to `buildReader`.
+ buildReader(
+ sparkSession, dataSchema, partitionSchema, requiredSchema, filters, options, hadoopConf)
+ }
+
+ override def buildReader(
+ sparkSession: SparkSession,
+ dataSchema: StructType,
+ partitionSchema: StructType,
+ requiredSchema: StructType,
+ filters: Seq[Filter],
+ options: Map[String, String],
+ hadoopConf: Configuration): PartitionedFile => Iterator[InternalRow] = {
+ hadoopConf.set(ParquetInputFormat.READ_SUPPORT_CLASS, classOf[CatalystReadSupport].getName)
+ hadoopConf.set(
+ CatalystReadSupport.SPARK_ROW_REQUESTED_SCHEMA,
+ CatalystSchemaConverter.checkFieldNames(requiredSchema).json)
+ hadoopConf.set(
+ CatalystWriteSupport.SPARK_ROW_SCHEMA,
+ CatalystSchemaConverter.checkFieldNames(requiredSchema).json)
+
+ // We want to clear this temporary metadata from saving into Parquet file.
+ // This metadata is only useful for detecting optional columns when pushdowning filters.
+ val dataSchemaToWrite = StructType.removeMetadata(StructType.metadataKeyForOptionalField,
+ requiredSchema).asInstanceOf[StructType]
+ CatalystWriteSupport.setSchema(dataSchemaToWrite, hadoopConf)
+
+ // Sets flags for `CatalystSchemaConverter`
+ hadoopConf.setBoolean(
+ SQLConf.PARQUET_BINARY_AS_STRING.key,
+ sparkSession.conf.get(SQLConf.PARQUET_BINARY_AS_STRING))
+ hadoopConf.setBoolean(
+ SQLConf.PARQUET_INT96_AS_TIMESTAMP.key,
+ sparkSession.conf.get(SQLConf.PARQUET_INT96_AS_TIMESTAMP))
+
+ // Try to push down filters when filter push-down is enabled.
+ val pushed =
+ if (sparkSession.conf.get(SQLConf.PARQUET_FILTER_PUSHDOWN_ENABLED.key).toBoolean) {
+ filters
+ // Collects all converted Parquet filter predicates. Notice that not all predicates can be
+ // converted (`ParquetFilters.createFilter` returns an `Option`). That's why a `flatMap`
+ // is used here.
+ .flatMap(ParquetFilters.createFilter(requiredSchema, _))
+ .reduceOption(FilterApi.and)
+ } else {
+ None
+ }
+
+ val broadcastedHadoopConf =
+ sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf))
+
+ // TODO: if you move this into the closure it reverts to the default values.
+ // If true, enable using the custom RecordReader for parquet. This only works for
+ // a subset of the types (no complex types).
+ val resultSchema = StructType(partitionSchema.fields ++ requiredSchema.fields)
+ val enableVectorizedReader: Boolean =
+ sparkSession.sessionState.conf.parquetVectorizedReaderEnabled &&
+ resultSchema.forall(_.dataType.isInstanceOf[AtomicType])
+ // Whole stage codegen (PhysicalRDD) is able to deal with batches directly
+ val returningBatch = supportBatch(sparkSession, resultSchema)
+
+ (file: PartitionedFile) => {
+ assert(file.partitionValues.numFields == partitionSchema.size)
+
+ val fileSplit =
+ new FileSplit(new Path(new URI(file.filePath)), file.start, file.length, Array.empty)
+
+ val split =
+ new org.apache.parquet.hadoop.ParquetInputSplit(
+ fileSplit.getPath,
+ fileSplit.getStart,
+ fileSplit.getStart + fileSplit.getLength,
+ fileSplit.getLength,
+ fileSplit.getLocations,
+ null)
+
+ val attemptId = new TaskAttemptID(new TaskID(new JobID(), TaskType.MAP, 0), 0)
+ val hadoopAttemptContext =
+ new TaskAttemptContextImpl(broadcastedHadoopConf.value.value, attemptId)
+
+ val parquetReader = if (enableVectorizedReader) {
+ val vectorizedReader = new VectorizedParquetRecordReader()
+ vectorizedReader.initialize(split, hadoopAttemptContext)
+ logDebug(s"Appending $partitionSchema ${file.partitionValues}")
+ vectorizedReader.initBatch(partitionSchema, file.partitionValues)
+ if (returningBatch) {
+ vectorizedReader.enableReturningBatches()
+ }
+ vectorizedReader
+ } else {
+ logDebug(s"Falling back to parquet-mr")
+ val reader = pushed match {
+ case Some(filter) =>
+ new ParquetRecordReader[InternalRow](
+ new CatalystReadSupport,
+ FilterCompat.get(filter, null))
+ case _ =>
+ new ParquetRecordReader[InternalRow](new CatalystReadSupport)
+ }
+ reader.initialize(split, hadoopAttemptContext)
+ reader
+ }
+
+ val iter = new RecordReaderIterator(parquetReader)
+
+ // UnsafeRowParquetRecordReader appends the columns internally to avoid another copy.
+ if (parquetReader.isInstanceOf[VectorizedParquetRecordReader] &&
+ enableVectorizedReader) {
+ iter.asInstanceOf[Iterator[InternalRow]]
+ } else {
+ val fullSchema = requiredSchema.toAttributes ++ partitionSchema.toAttributes
+ val joinedRow = new JoinedRow()
+ val appendPartitionColumns = GenerateUnsafeProjection.generate(fullSchema, fullSchema)
+
+ // This is a horrible erasure hack... if we type the iterator above, then it actually check
+ // the type in next() and we get a class cast exception. If we make that function return
+ // Object, then we can defer the cast until later!
+ iter.asInstanceOf[Iterator[InternalRow]]
+ .map(d => appendPartitionColumns(joinedRow(d, file.partitionValues)))
+ }
+ }
+ }
+
+ override def buildWriter(
+ sqlContext: SQLContext,
+ dataSchema: StructType,
+ options: Map[String, String]): OutputWriterFactory = {
+ new ParquetOutputWriterFactory(
+ sqlContext.conf,
+ dataSchema,
+ sqlContext.sparkContext.hadoopConfiguration,
+ options)
+ }
+}
+
+/**
+ * A factory for generating OutputWriters for writing parquet files. This implemented is different
+ * from the [[ParquetOutputWriter]] as this does not use any [[OutputCommitter]]. It simply
+ * writes the data to the path used to generate the output writer. Callers of this factory
+ * has to ensure which files are to be considered as committed.
+ */
+private[sql] class ParquetOutputWriterFactory(
+ sqlConf: SQLConf,
+ dataSchema: StructType,
+ hadoopConf: Configuration,
+ options: Map[String, String]) extends OutputWriterFactory {
+
+ private val serializableConf: SerializableConfiguration = {
+ val job = Job.getInstance(hadoopConf)
+ val conf = ContextUtil.getConfiguration(job)
+ val parquetOptions = new ParquetOptions(options, sqlConf)
+
+ // We're not really using `ParquetOutputFormat[Row]` for writing data here, because we override
+ // it in `ParquetOutputWriter` to support appending and dynamic partitioning. The reason why
+ // we set it here is to setup the output committer class to `ParquetOutputCommitter`, which is
+ // bundled with `ParquetOutputFormat[Row]`.
+ job.setOutputFormatClass(classOf[ParquetOutputFormat[Row]])
+
+ ParquetOutputFormat.setWriteSupportClass(job, classOf[CatalystWriteSupport])
+
+ // We want to clear this temporary metadata from saving into Parquet file.
+ // This metadata is only useful for detecting optional columns when pushdowning filters.
+ val dataSchemaToWrite = StructType.removeMetadata(
+ StructType.metadataKeyForOptionalField,
+ dataSchema).asInstanceOf[StructType]
+ CatalystWriteSupport.setSchema(dataSchemaToWrite, conf)
+
+ // Sets flags for `CatalystSchemaConverter` (which converts Catalyst schema to Parquet schema)
+ // and `CatalystWriteSupport` (writing actual rows to Parquet files).
+ conf.set(
+ SQLConf.PARQUET_BINARY_AS_STRING.key,
+ sqlConf.isParquetBinaryAsString.toString)
+
+ conf.set(
+ SQLConf.PARQUET_INT96_AS_TIMESTAMP.key,
+ sqlConf.isParquetINT96AsTimestamp.toString)
+
+ conf.set(
+ SQLConf.PARQUET_WRITE_LEGACY_FORMAT.key,
+ sqlConf.writeLegacyParquetFormat.toString)
+
+ // Sets compression scheme
+ conf.set(ParquetOutputFormat.COMPRESSION, parquetOptions.compressionCodec)
+ new SerializableConfiguration(conf)
+ }
+
+ /**
+ * Returns a [[OutputWriter]] that writes data to the give path without using
+ * [[OutputCommitter]].
+ */
+ override private[sql] def newWriter(path: String): OutputWriter = new OutputWriter {
+
+ // Create TaskAttemptContext that is used to pass on Configuration to the ParquetRecordWriter
+ private val hadoopTaskAttempId = new TaskAttemptID(new TaskID(new JobID, TaskType.MAP, 0), 0)
+ private val hadoopAttemptContext = new TaskAttemptContextImpl(
+ serializableConf.value, hadoopTaskAttempId)
+
+ // Instance of ParquetRecordWriter that does not use OutputCommitter
+ private val recordWriter = createNoCommitterRecordWriter(path, hadoopAttemptContext)
+
+ override def write(row: Row): Unit = {
+ throw new UnsupportedOperationException("call writeInternal")
+ }
+
+ protected[sql] override def writeInternal(row: InternalRow): Unit = {
+ recordWriter.write(null, row)
+ }
+
+ override def close(): Unit = recordWriter.close(hadoopAttemptContext)
+ }
+
+ /** Create a [[ParquetRecordWriter]] that writes the given path without using OutputCommitter */
+ private def createNoCommitterRecordWriter(
+ path: String,
+ hadoopAttemptContext: TaskAttemptContext): RecordWriter[Void, InternalRow] = {
+ // Custom ParquetOutputFormat that disable use of committer and writes to the given path
+ val outputFormat = new ParquetOutputFormat[InternalRow]() {
+ override def getOutputCommitter(c: TaskAttemptContext): OutputCommitter = { null }
+ override def getDefaultWorkFile(c: TaskAttemptContext, ext: String): Path = { new Path(path) }
+ }
+ outputFormat.getRecordWriter(hadoopAttemptContext)
+ }
+
+ /** Disable the use of the older API. */
+ def newInstance(
+ path: String,
+ bucketId: Option[Int],
+ dataSchema: StructType,
+ context: TaskAttemptContext): OutputWriter = {
+ throw new UnsupportedOperationException(
+ "this verison of newInstance not supported for " +
+ "ParquetOutputWriterFactory")
+ }
+}
+
+
+// NOTE: This class is instantiated and used on executor side only, no need to be serializable.
+private[sql] class ParquetOutputWriter(
+ path: String,
+ bucketId: Option[Int],
+ context: TaskAttemptContext)
+ extends OutputWriter {
+
+ private val recordWriter: RecordWriter[Void, InternalRow] = {
+ val outputFormat = {
+ new ParquetOutputFormat[InternalRow]() {
+ // Here we override `getDefaultWorkFile` for two reasons:
+ //
+ // 1. To allow appending. We need to generate unique output file names to avoid
+ // overwriting existing files (either exist before the write job, or are just written
+ // by other tasks within the same write job).
+ //
+ // 2. To allow dynamic partitioning. Default `getDefaultWorkFile` uses
+ // `FileOutputCommitter.getWorkPath()`, which points to the base directory of all
+ // partitions in the case of dynamic partitioning.
+ override def getDefaultWorkFile(context: TaskAttemptContext, extension: String): Path = {
+ val configuration = context.getConfiguration
+ val uniqueWriteJobId = configuration.get("spark.sql.sources.writeJobUUID")
+ val taskAttemptId = context.getTaskAttemptID
+ val split = taskAttemptId.getTaskID.getId
+ val bucketString = bucketId.map(BucketingUtils.bucketIdToString).getOrElse("")
+ // It has the `.parquet` extension at the end because (de)compression tools
+ // such as gunzip would not be able to decompress this as the compression
+ // is not applied on this whole file but on each "page" in Parquet format.
+ new Path(path, f"part-r-$split%05d-$uniqueWriteJobId$bucketString$extension")
+ }
+ }
+ }
+
+ outputFormat.getRecordWriter(context)
+ }
+
+ override def write(row: Row): Unit = throw new UnsupportedOperationException("call writeInternal")
+
+ override protected[sql] def writeInternal(row: InternalRow): Unit = recordWriter.write(null, row)
+
+ override def close(): Unit = recordWriter.close(context)
+}
+
+private[sql] object ParquetFileFormat extends Logging {
+ // Whether we should merge schemas collected from all Parquet part-files.
+ private[sql] val MERGE_SCHEMA = "mergeSchema"
+
+ // Hive Metastore schema, used when converting Metastore Parquet tables. This option is only used
+ // internally.
+ private[sql] val METASTORE_SCHEMA = "metastoreSchema"
+
+ // If a ParquetRelation is converted from a Hive metastore table, this option is set to the
+ // original Hive table name.
+ private[sql] val METASTORE_TABLE_NAME = "metastoreTableName"
+
+ /**
+ * If parquet's block size (row group size) setting is larger than the min split size,
+ * we use parquet's block size setting as the min split size. Otherwise, we will create
+ * tasks processing nothing (because a split does not cover the starting point of a
+ * parquet block). See https://issues.apache.org/jira/browse/SPARK-10143 for more information.
+ */
+ private def overrideMinSplitSize(parquetBlockSize: Long, conf: Configuration): Unit = {
+ val minSplitSize =
+ math.max(
+ conf.getLong("mapred.min.split.size", 0L),
+ conf.getLong("mapreduce.input.fileinputformat.split.minsize", 0L))
+ if (parquetBlockSize > minSplitSize) {
+ val message =
+ s"Parquet's block size (row group size) is larger than " +
+ s"mapred.min.split.size/mapreduce.input.fileinputformat.split.minsize. Setting " +
+ s"mapred.min.split.size and mapreduce.input.fileinputformat.split.minsize to " +
+ s"$parquetBlockSize."
+ logDebug(message)
+ conf.set("mapred.min.split.size", parquetBlockSize.toString)
+ conf.set("mapreduce.input.fileinputformat.split.minsize", parquetBlockSize.toString)
+ }
+ }
+
+ /** This closure sets various Parquet configurations at both driver side and executor side. */
+ private[parquet] def initializeLocalJobFunc(
+ requiredColumns: Array[String],
+ filters: Array[Filter],
+ dataSchema: StructType,
+ parquetBlockSize: Long,
+ useMetadataCache: Boolean,
+ parquetFilterPushDown: Boolean,
+ assumeBinaryIsString: Boolean,
+ assumeInt96IsTimestamp: Boolean)(job: Job): Unit = {
+ val conf = job.getConfiguration
+ conf.set(ParquetInputFormat.READ_SUPPORT_CLASS, classOf[CatalystReadSupport].getName)
+
+ // Try to push down filters when filter push-down is enabled.
+ if (parquetFilterPushDown) {
+ filters
+ // Collects all converted Parquet filter predicates. Notice that not all predicates can be
+ // converted (`ParquetFilters.createFilter` returns an `Option`). That's why a `flatMap`
+ // is used here.
+ .flatMap(ParquetFilters.createFilter(dataSchema, _))
+ .reduceOption(FilterApi.and)
+ .foreach(ParquetInputFormat.setFilterPredicate(conf, _))
+ }
+
+ conf.set(CatalystReadSupport.SPARK_ROW_REQUESTED_SCHEMA, {
+ val requestedSchema = StructType(requiredColumns.map(dataSchema(_)))
+ CatalystSchemaConverter.checkFieldNames(requestedSchema).json
+ })
+
+ conf.set(
+ CatalystWriteSupport.SPARK_ROW_SCHEMA,
+ CatalystSchemaConverter.checkFieldNames(dataSchema).json)
+
+ // Tell FilteringParquetRowInputFormat whether it's okay to cache Parquet and FS metadata
+ conf.setBoolean(SQLConf.PARQUET_CACHE_METADATA.key, useMetadataCache)
+
+ // Sets flags for `CatalystSchemaConverter`
+ conf.setBoolean(SQLConf.PARQUET_BINARY_AS_STRING.key, assumeBinaryIsString)
+ conf.setBoolean(SQLConf.PARQUET_INT96_AS_TIMESTAMP.key, assumeInt96IsTimestamp)
+
+ overrideMinSplitSize(parquetBlockSize, conf)
+ }
+
+ /** This closure sets input paths at the driver side. */
+ private[parquet] def initializeDriverSideJobFunc(
+ inputFiles: Array[FileStatus],
+ parquetBlockSize: Long)(job: Job): Unit = {
+ // We side the input paths at the driver side.
+ logInfo(s"Reading Parquet file(s) from ${inputFiles.map(_.getPath).mkString(", ")}")
+ if (inputFiles.nonEmpty) {
+ FileInputFormat.setInputPaths(job, inputFiles.map(_.getPath): _*)
+ }
+
+ overrideMinSplitSize(parquetBlockSize, job.getConfiguration)
+ }
+
+ private[parquet] def readSchema(
+ footers: Seq[Footer], sparkSession: SparkSession): Option[StructType] = {
+
+ def parseParquetSchema(schema: MessageType): StructType = {
+ val converter = new CatalystSchemaConverter(
+ sparkSession.sessionState.conf.isParquetBinaryAsString,
+ sparkSession.sessionState.conf.isParquetBinaryAsString,
+ sparkSession.sessionState.conf.writeLegacyParquetFormat)
+
+ converter.convert(schema)
+ }
+
+ val seen = mutable.HashSet[String]()
+ val finalSchemas: Seq[StructType] = footers.flatMap { footer =>
+ val metadata = footer.getParquetMetadata.getFileMetaData
+ val serializedSchema = metadata
+ .getKeyValueMetaData
+ .asScala.toMap
+ .get(CatalystReadSupport.SPARK_METADATA_KEY)
+ if (serializedSchema.isEmpty) {
+ // Falls back to Parquet schema if no Spark SQL schema found.
+ Some(parseParquetSchema(metadata.getSchema))
+ } else if (!seen.contains(serializedSchema.get)) {
+ seen += serializedSchema.get
+
+ // Don't throw even if we failed to parse the serialized Spark schema. Just fallback to
+ // whatever is available.
+ Some(Try(DataType.fromJson(serializedSchema.get))
+ .recover { case _: Throwable =>
+ logInfo(
+ s"Serialized Spark schema in Parquet key-value metadata is not in JSON format, " +
+ "falling back to the deprecated DataType.fromCaseClassString parser.")
+ LegacyTypeStringParser.parse(serializedSchema.get)
+ }
+ .recover { case cause: Throwable =>
+ logWarning(
+ s"""Failed to parse serialized Spark schema in Parquet key-value metadata:
+ |\t$serializedSchema
+ """.stripMargin,
+ cause)
+ }
+ .map(_.asInstanceOf[StructType])
+ .getOrElse {
+ // Falls back to Parquet schema if Spark SQL schema can't be parsed.
+ parseParquetSchema(metadata.getSchema)
+ })
+ } else {
+ None
+ }
+ }
+
+ finalSchemas.reduceOption { (left, right) =>
+ try left.merge(right) catch { case e: Throwable =>
+ throw new SparkException(s"Failed to merge incompatible schemas $left and $right", e)
+ }
+ }
+ }
+
+ /**
+ * Reconciles Hive Metastore case insensitivity issue and data type conflicts between Metastore
+ * schema and Parquet schema.
+ *
+ * Hive doesn't retain case information, while Parquet is case sensitive. On the other hand, the
+ * schema read from Parquet files may be incomplete (e.g. older versions of Parquet doesn't
+ * distinguish binary and string). This method generates a correct schema by merging Metastore
+ * schema data types and Parquet schema field names.
+ */
+ private[sql] def mergeMetastoreParquetSchema(
+ metastoreSchema: StructType,
+ parquetSchema: StructType): StructType = {
+ def schemaConflictMessage: String =
+ s"""Converting Hive Metastore Parquet, but detected conflicting schemas. Metastore schema:
+ |${metastoreSchema.prettyJson}
+ |
+ |Parquet schema:
+ |${parquetSchema.prettyJson}
+ """.stripMargin
+
+ val mergedParquetSchema = mergeMissingNullableFields(metastoreSchema, parquetSchema)
+
+ assert(metastoreSchema.size <= mergedParquetSchema.size, schemaConflictMessage)
+
+ val ordinalMap = metastoreSchema.zipWithIndex.map {
+ case (field, index) => field.name.toLowerCase -> index
+ }.toMap
+
+ val reorderedParquetSchema = mergedParquetSchema.sortBy(f =>
+ ordinalMap.getOrElse(f.name.toLowerCase, metastoreSchema.size + 1))
+
+ StructType(metastoreSchema.zip(reorderedParquetSchema).map {
+ // Uses Parquet field names but retains Metastore data types.
+ case (mSchema, pSchema) if mSchema.name.toLowerCase == pSchema.name.toLowerCase =>
+ mSchema.copy(name = pSchema.name)
+ case _ =>
+ throw new SparkException(schemaConflictMessage)
+ })
+ }
+
+ /**
+ * Returns the original schema from the Parquet file with any missing nullable fields from the
+ * Hive Metastore schema merged in.
+ *
+ * When constructing a DataFrame from a collection of structured data, the resulting object has
+ * a schema corresponding to the union of the fields present in each element of the collection.
+ * Spark SQL simply assigns a null value to any field that isn't present for a particular row.
+ * In some cases, it is possible that a given table partition stored as a Parquet file doesn't
+ * contain a particular nullable field in its schema despite that field being present in the
+ * table schema obtained from the Hive Metastore. This method returns a schema representing the
+ * Parquet file schema along with any additional nullable fields from the Metastore schema
+ * merged in.
+ */
+ private[parquet] def mergeMissingNullableFields(
+ metastoreSchema: StructType,
+ parquetSchema: StructType): StructType = {
+ val fieldMap = metastoreSchema.map(f => f.name.toLowerCase -> f).toMap
+ val missingFields = metastoreSchema
+ .map(_.name.toLowerCase)
+ .diff(parquetSchema.map(_.name.toLowerCase))
+ .map(fieldMap(_))
+ .filter(_.nullable)
+ StructType(parquetSchema ++ missingFields)
+ }
+
+ /**
+ * Figures out a merged Parquet schema with a distributed Spark job.
+ *
+ * Note that locality is not taken into consideration here because:
+ *
+ * 1. For a single Parquet part-file, in most cases the footer only resides in the last block of
+ * that file. Thus we only need to retrieve the location of the last block. However, Hadoop
+ * `FileSystem` only provides API to retrieve locations of all blocks, which can be
+ * potentially expensive.
+ *
+ * 2. This optimization is mainly useful for S3, where file metadata operations can be pretty
+ * slow. And basically locality is not available when using S3 (you can't run computation on
+ * S3 nodes).
+ */
+ def mergeSchemasInParallel(
+ filesToTouch: Seq[FileStatus],
+ sparkSession: SparkSession): Option[StructType] = {
+ val assumeBinaryIsString = sparkSession.sessionState.conf.isParquetBinaryAsString
+ val assumeInt96IsTimestamp = sparkSession.sessionState.conf.isParquetINT96AsTimestamp
+ val writeLegacyParquetFormat = sparkSession.sessionState.conf.writeLegacyParquetFormat
+ val serializedConf =
+ new SerializableConfiguration(sparkSession.sessionState.newHadoopConf())
+
+ // !! HACK ALERT !!
+ //
+ // Parquet requires `FileStatus`es to read footers. Here we try to send cached `FileStatus`es
+ // to executor side to avoid fetching them again. However, `FileStatus` is not `Serializable`
+ // but only `Writable`. What makes it worth, for some reason, `FileStatus` doesn't play well
+ // with `SerializableWritable[T]` and always causes a weird `IllegalStateException`. These
+ // facts virtually prevents us to serialize `FileStatus`es.
+ //
+ // Since Parquet only relies on path and length information of those `FileStatus`es to read
+ // footers, here we just extract them (which can be easily serialized), send them to executor
+ // side, and resemble fake `FileStatus`es there.
+ val partialFileStatusInfo = filesToTouch.map(f => (f.getPath.toString, f.getLen))
+
+ // Issues a Spark job to read Parquet schema in parallel.
+ val partiallyMergedSchemas =
+ sparkSession
+ .sparkContext
+ .parallelize(partialFileStatusInfo)
+ .mapPartitions { iterator =>
+ // Resembles fake `FileStatus`es with serialized path and length information.
+ val fakeFileStatuses = iterator.map { case (path, length) =>
+ new FileStatus(length, false, 0, 0, 0, 0, null, null, null, new Path(path))
+ }.toSeq
+
+ // Skips row group information since we only need the schema
+ val skipRowGroups = true
+
+ // Reads footers in multi-threaded manner within each task
+ val footers =
+ ParquetFileReader.readAllFootersInParallel(
+ serializedConf.value, fakeFileStatuses.asJava, skipRowGroups).asScala
+
+ // Converter used to convert Parquet `MessageType` to Spark SQL `StructType`
+ val converter =
+ new CatalystSchemaConverter(
+ assumeBinaryIsString = assumeBinaryIsString,
+ assumeInt96IsTimestamp = assumeInt96IsTimestamp,
+ writeLegacyParquetFormat = writeLegacyParquetFormat)
+
+ if (footers.isEmpty) {
+ Iterator.empty
+ } else {
+ var mergedSchema = ParquetFileFormat.readSchemaFromFooter(footers.head, converter)
+ footers.tail.foreach { footer =>
+ val schema = ParquetFileFormat.readSchemaFromFooter(footer, converter)
+ try {
+ mergedSchema = mergedSchema.merge(schema)
+ } catch { case cause: SparkException =>
+ throw new SparkException(
+ s"Failed merging schema of file ${footer.getFile}:\n${schema.treeString}", cause)
+ }
+ }
+ Iterator.single(mergedSchema)
+ }
+ }.collect()
+
+ if (partiallyMergedSchemas.isEmpty) {
+ None
+ } else {
+ var finalSchema = partiallyMergedSchemas.head
+ partiallyMergedSchemas.tail.foreach { schema =>
+ try {
+ finalSchema = finalSchema.merge(schema)
+ } catch { case cause: SparkException =>
+ throw new SparkException(
+ s"Failed merging schema:\n${schema.treeString}", cause)
+ }
+ }
+ Some(finalSchema)
+ }
+ }
+
+ /**
+ * Reads Spark SQL schema from a Parquet footer. If a valid serialized Spark SQL schema string
+ * can be found in the file metadata, returns the deserialized [[StructType]], otherwise, returns
+ * a [[StructType]] converted from the [[MessageType]] stored in this footer.
+ */
+ def readSchemaFromFooter(
+ footer: Footer, converter: CatalystSchemaConverter): StructType = {
+ val fileMetaData = footer.getParquetMetadata.getFileMetaData
+ fileMetaData
+ .getKeyValueMetaData
+ .asScala.toMap
+ .get(CatalystReadSupport.SPARK_METADATA_KEY)
+ .flatMap(deserializeSchemaString)
+ .getOrElse(converter.convert(fileMetaData.getSchema))
+ }
+
+ private def deserializeSchemaString(schemaString: String): Option[StructType] = {
+ // Tries to deserialize the schema string as JSON first, then falls back to the case class
+ // string parser (data generated by older versions of Spark SQL uses this format).
+ Try(DataType.fromJson(schemaString).asInstanceOf[StructType]).recover {
+ case _: Throwable =>
+ logInfo(
+ s"Serialized Spark schema in Parquet key-value metadata is not in JSON format, " +
+ "falling back to the deprecated DataType.fromCaseClassString parser.")
+ LegacyTypeStringParser.parse(schemaString).asInstanceOf[StructType]
+ }.recoverWith {
+ case cause: Throwable =>
+ logWarning(
+ "Failed to parse and ignored serialized Spark schema in " +
+ s"Parquet key-value metadata:\n\t$schemaString", cause)
+ Failure(cause)
+ }.toOption
+ }
+
+ // JUL loggers must be held by a strong reference, otherwise they may get destroyed by GC.
+ // However, the root JUL logger used by Parquet isn't properly referenced. Here we keep
+ // references to loggers in both parquet-mr <= 1.6 and >= 1.7
+ val apacheParquetLogger: JLogger = JLogger.getLogger(classOf[ApacheParquetLog].getPackage.getName)
+ val parquetLogger: JLogger = JLogger.getLogger("parquet")
+
+ // Parquet initializes its own JUL logger in a static block which always prints to stdout. Here
+ // we redirect the JUL logger via SLF4J JUL bridge handler.
+ val redirectParquetLogsViaSLF4J: Unit = {
+ def redirect(logger: JLogger): Unit = {
+ logger.getHandlers.foreach(logger.removeHandler)
+ logger.setUseParentHandlers(false)
+ logger.addHandler(new SLF4JBridgeHandler)
+ }
+
+ // For parquet-mr 1.7.0 and above versions, which are under `org.apache.parquet` namespace.
+ // scalastyle:off classforname
+ Class.forName(classOf[ApacheParquetLog].getName)
+ // scalastyle:on classforname
+ redirect(JLogger.getLogger(classOf[ApacheParquetLog].getPackage.getName))
+
+ // For parquet-mr 1.6.0 and lower versions bundled with Hive, which are under `parquet`
+ // namespace.
+ try {
+ // scalastyle:off classforname
+ Class.forName("parquet.Log")
+ // scalastyle:on classforname
+ redirect(JLogger.getLogger("parquet"))
+ } catch { case _: Throwable =>
+ // SPARK-9974: com.twitter:parquet-hadoop-bundle:1.6.0 is not packaged into the assembly
+ // when Spark is built with SBT. So `parquet.Log` may not be found. This try/catch block
+ // should be removed after this issue is fixed.
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetRelation.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetRelation.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetRelation.scala
deleted file mode 100644
index cf5c8e9..0000000
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetRelation.scala
+++ /dev/null
@@ -1,923 +0,0 @@
-/*
- * 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.execution.datasources.parquet
-
-import java.net.URI
-import java.util.logging.{Logger => JLogger}
-
-import scala.collection.JavaConverters._
-import scala.collection.mutable
-import scala.util.{Failure, Try}
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.{FileStatus, Path}
-import org.apache.hadoop.mapreduce._
-import org.apache.hadoop.mapreduce.lib.input.{FileInputFormat, FileSplit}
-import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl
-import org.apache.parquet.{Log => ApacheParquetLog}
-import org.apache.parquet.filter2.compat.FilterCompat
-import org.apache.parquet.filter2.predicate.FilterApi
-import org.apache.parquet.hadoop._
-import org.apache.parquet.hadoop.util.ContextUtil
-import org.apache.parquet.schema.MessageType
-import org.slf4j.bridge.SLF4JBridgeHandler
-
-import org.apache.spark.SparkException
-import org.apache.spark.internal.Logging
-import org.apache.spark.sql._
-import org.apache.spark.sql.catalyst.InternalRow
-import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
-import org.apache.spark.sql.catalyst.parser.LegacyTypeStringParser
-import org.apache.spark.sql.execution.datasources._
-import org.apache.spark.sql.internal.SQLConf
-import org.apache.spark.sql.sources._
-import org.apache.spark.sql.types._
-import org.apache.spark.util.SerializableConfiguration
-
-private[sql] class DefaultSource
- extends FileFormat
- with DataSourceRegister
- with Logging
- with Serializable {
-
- override def shortName(): String = "parquet"
-
- override def toString: String = "ParquetFormat"
-
- override def hashCode(): Int = getClass.hashCode()
-
- override def equals(other: Any): Boolean = other.isInstanceOf[DefaultSource]
-
- override def prepareWrite(
- sparkSession: SparkSession,
- job: Job,
- options: Map[String, String],
- dataSchema: StructType): OutputWriterFactory = {
-
- val parquetOptions = new ParquetOptions(options, sparkSession.sessionState.conf)
-
- val conf = ContextUtil.getConfiguration(job)
-
- val committerClass =
- conf.getClass(
- SQLConf.PARQUET_OUTPUT_COMMITTER_CLASS.key,
- classOf[ParquetOutputCommitter],
- classOf[ParquetOutputCommitter])
-
- if (conf.get(SQLConf.PARQUET_OUTPUT_COMMITTER_CLASS.key) == null) {
- logInfo("Using default output committer for Parquet: " +
- classOf[ParquetOutputCommitter].getCanonicalName)
- } else {
- logInfo("Using user defined output committer for Parquet: " + committerClass.getCanonicalName)
- }
-
- conf.setClass(
- SQLConf.OUTPUT_COMMITTER_CLASS.key,
- committerClass,
- classOf[ParquetOutputCommitter])
-
- // We're not really using `ParquetOutputFormat[Row]` for writing data here, because we override
- // it in `ParquetOutputWriter` to support appending and dynamic partitioning. The reason why
- // we set it here is to setup the output committer class to `ParquetOutputCommitter`, which is
- // bundled with `ParquetOutputFormat[Row]`.
- job.setOutputFormatClass(classOf[ParquetOutputFormat[Row]])
-
- ParquetOutputFormat.setWriteSupportClass(job, classOf[CatalystWriteSupport])
-
- // We want to clear this temporary metadata from saving into Parquet file.
- // This metadata is only useful for detecting optional columns when pushdowning filters.
- val dataSchemaToWrite = StructType.removeMetadata(StructType.metadataKeyForOptionalField,
- dataSchema).asInstanceOf[StructType]
- CatalystWriteSupport.setSchema(dataSchemaToWrite, conf)
-
- // Sets flags for `CatalystSchemaConverter` (which converts Catalyst schema to Parquet schema)
- // and `CatalystWriteSupport` (writing actual rows to Parquet files).
- conf.set(
- SQLConf.PARQUET_BINARY_AS_STRING.key,
- sparkSession.sessionState.conf.isParquetBinaryAsString.toString)
-
- conf.set(
- SQLConf.PARQUET_INT96_AS_TIMESTAMP.key,
- sparkSession.sessionState.conf.isParquetINT96AsTimestamp.toString)
-
- conf.set(
- SQLConf.PARQUET_WRITE_LEGACY_FORMAT.key,
- sparkSession.sessionState.conf.writeLegacyParquetFormat.toString)
-
- // Sets compression scheme
- conf.set(ParquetOutputFormat.COMPRESSION, parquetOptions.compressionCodec)
-
- new OutputWriterFactory {
- override def newInstance(
- path: String,
- bucketId: Option[Int],
- dataSchema: StructType,
- context: TaskAttemptContext): OutputWriter = {
- new ParquetOutputWriter(path, bucketId, context)
- }
- }
- }
-
- def inferSchema(
- sparkSession: SparkSession,
- parameters: Map[String, String],
- files: Seq[FileStatus]): Option[StructType] = {
- // Should we merge schemas from all Parquet part-files?
- val shouldMergeSchemas =
- parameters
- .get(ParquetRelation.MERGE_SCHEMA)
- .map(_.toBoolean)
- .getOrElse(sparkSession.conf.get(SQLConf.PARQUET_SCHEMA_MERGING_ENABLED))
-
- val mergeRespectSummaries = sparkSession.conf.get(SQLConf.PARQUET_SCHEMA_RESPECT_SUMMARIES)
-
- val filesByType = splitFiles(files)
-
- // Sees which file(s) we need to touch in order to figure out the schema.
- //
- // Always tries the summary files first if users don't require a merged schema. In this case,
- // "_common_metadata" is more preferable than "_metadata" because it doesn't contain row
- // groups information, and could be much smaller for large Parquet files with lots of row
- // groups. If no summary file is available, falls back to some random part-file.
- //
- // NOTE: Metadata stored in the summary files are merged from all part-files. However, for
- // user defined key-value metadata (in which we store Spark SQL schema), Parquet doesn't know
- // how to merge them correctly if some key is associated with different values in different
- // part-files. When this happens, Parquet simply gives up generating the summary file. This
- // implies that if a summary file presents, then:
- //
- // 1. Either all part-files have exactly the same Spark SQL schema, or
- // 2. Some part-files don't contain Spark SQL schema in the key-value metadata at all (thus
- // their schemas may differ from each other).
- //
- // Here we tend to be pessimistic and take the second case into account. Basically this means
- // we can't trust the summary files if users require a merged schema, and must touch all part-
- // files to do the merge.
- val filesToTouch =
- if (shouldMergeSchemas) {
- // Also includes summary files, 'cause there might be empty partition directories.
-
- // If mergeRespectSummaries config is true, we assume that all part-files are the same for
- // their schema with summary files, so we ignore them when merging schema.
- // If the config is disabled, which is the default setting, we merge all part-files.
- // In this mode, we only need to merge schemas contained in all those summary files.
- // You should enable this configuration only if you are very sure that for the parquet
- // part-files to read there are corresponding summary files containing correct schema.
-
- // As filed in SPARK-11500, the order of files to touch is a matter, which might affect
- // the ordering of the output columns. There are several things to mention here.
- //
- // 1. If mergeRespectSummaries config is false, then it merges schemas by reducing from
- // the first part-file so that the columns of the lexicographically first file show
- // first.
- //
- // 2. If mergeRespectSummaries config is true, then there should be, at least,
- // "_metadata"s for all given files, so that we can ensure the columns of
- // the lexicographically first file show first.
- //
- // 3. If shouldMergeSchemas is false, but when multiple files are given, there is
- // no guarantee of the output order, since there might not be a summary file for the
- // lexicographically first file, which ends up putting ahead the columns of
- // the other files. However, this should be okay since not enabling
- // shouldMergeSchemas means (assumes) all the files have the same schemas.
-
- val needMerged: Seq[FileStatus] =
- if (mergeRespectSummaries) {
- Seq()
- } else {
- filesByType.data
- }
- needMerged ++ filesByType.metadata ++ filesByType.commonMetadata
- } else {
- // Tries any "_common_metadata" first. Parquet files written by old versions or Parquet
- // don't have this.
- filesByType.commonMetadata.headOption
- // Falls back to "_metadata"
- .orElse(filesByType.metadata.headOption)
- // Summary file(s) not found, the Parquet file is either corrupted, or different part-
- // files contain conflicting user defined metadata (two or more values are associated
- // with a same key in different files). In either case, we fall back to any of the
- // first part-file, and just assume all schemas are consistent.
- .orElse(filesByType.data.headOption)
- .toSeq
- }
- ParquetRelation.mergeSchemasInParallel(filesToTouch, sparkSession)
- }
-
- case class FileTypes(
- data: Seq[FileStatus],
- metadata: Seq[FileStatus],
- commonMetadata: Seq[FileStatus])
-
- private def splitFiles(allFiles: Seq[FileStatus]): FileTypes = {
- // Lists `FileStatus`es of all leaf nodes (files) under all base directories.
- val leaves = allFiles.filter { f =>
- isSummaryFile(f.getPath) ||
- !(f.getPath.getName.startsWith("_") || f.getPath.getName.startsWith("."))
- }.toArray.sortBy(_.getPath.toString)
-
- FileTypes(
- data = leaves.filterNot(f => isSummaryFile(f.getPath)),
- metadata =
- leaves.filter(_.getPath.getName == ParquetFileWriter.PARQUET_METADATA_FILE),
- commonMetadata =
- leaves.filter(_.getPath.getName == ParquetFileWriter.PARQUET_COMMON_METADATA_FILE))
- }
-
- private def isSummaryFile(file: Path): Boolean = {
- file.getName == ParquetFileWriter.PARQUET_COMMON_METADATA_FILE ||
- file.getName == ParquetFileWriter.PARQUET_METADATA_FILE
- }
-
- /**
- * Returns whether the reader will return the rows as batch or not.
- */
- override def supportBatch(sparkSession: SparkSession, schema: StructType): Boolean = {
- val conf = sparkSession.sessionState.conf
- conf.parquetVectorizedReaderEnabled && conf.wholeStageEnabled &&
- schema.length <= conf.wholeStageMaxNumFields &&
- schema.forall(_.dataType.isInstanceOf[AtomicType])
- }
-
- override private[sql] def buildReaderWithPartitionValues(
- sparkSession: SparkSession,
- dataSchema: StructType,
- partitionSchema: StructType,
- requiredSchema: StructType,
- filters: Seq[Filter],
- options: Map[String, String],
- hadoopConf: Configuration): (PartitionedFile) => Iterator[InternalRow] = {
- // For Parquet data source, `buildReader` already handles partition values appending. Here we
- // simply delegate to `buildReader`.
- buildReader(
- sparkSession, dataSchema, partitionSchema, requiredSchema, filters, options, hadoopConf)
- }
-
- override def buildReader(
- sparkSession: SparkSession,
- dataSchema: StructType,
- partitionSchema: StructType,
- requiredSchema: StructType,
- filters: Seq[Filter],
- options: Map[String, String],
- hadoopConf: Configuration): PartitionedFile => Iterator[InternalRow] = {
- hadoopConf.set(ParquetInputFormat.READ_SUPPORT_CLASS, classOf[CatalystReadSupport].getName)
- hadoopConf.set(
- CatalystReadSupport.SPARK_ROW_REQUESTED_SCHEMA,
- CatalystSchemaConverter.checkFieldNames(requiredSchema).json)
- hadoopConf.set(
- CatalystWriteSupport.SPARK_ROW_SCHEMA,
- CatalystSchemaConverter.checkFieldNames(requiredSchema).json)
-
- // We want to clear this temporary metadata from saving into Parquet file.
- // This metadata is only useful for detecting optional columns when pushdowning filters.
- val dataSchemaToWrite = StructType.removeMetadata(StructType.metadataKeyForOptionalField,
- requiredSchema).asInstanceOf[StructType]
- CatalystWriteSupport.setSchema(dataSchemaToWrite, hadoopConf)
-
- // Sets flags for `CatalystSchemaConverter`
- hadoopConf.setBoolean(
- SQLConf.PARQUET_BINARY_AS_STRING.key,
- sparkSession.conf.get(SQLConf.PARQUET_BINARY_AS_STRING))
- hadoopConf.setBoolean(
- SQLConf.PARQUET_INT96_AS_TIMESTAMP.key,
- sparkSession.conf.get(SQLConf.PARQUET_INT96_AS_TIMESTAMP))
-
- // Try to push down filters when filter push-down is enabled.
- val pushed =
- if (sparkSession.conf.get(SQLConf.PARQUET_FILTER_PUSHDOWN_ENABLED.key).toBoolean) {
- filters
- // Collects all converted Parquet filter predicates. Notice that not all predicates can be
- // converted (`ParquetFilters.createFilter` returns an `Option`). That's why a `flatMap`
- // is used here.
- .flatMap(ParquetFilters.createFilter(requiredSchema, _))
- .reduceOption(FilterApi.and)
- } else {
- None
- }
-
- val broadcastedHadoopConf =
- sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf))
-
- // TODO: if you move this into the closure it reverts to the default values.
- // If true, enable using the custom RecordReader for parquet. This only works for
- // a subset of the types (no complex types).
- val resultSchema = StructType(partitionSchema.fields ++ requiredSchema.fields)
- val enableVectorizedReader: Boolean =
- sparkSession.sessionState.conf.parquetVectorizedReaderEnabled &&
- resultSchema.forall(_.dataType.isInstanceOf[AtomicType])
- // Whole stage codegen (PhysicalRDD) is able to deal with batches directly
- val returningBatch = supportBatch(sparkSession, resultSchema)
-
- (file: PartitionedFile) => {
- assert(file.partitionValues.numFields == partitionSchema.size)
-
- val fileSplit =
- new FileSplit(new Path(new URI(file.filePath)), file.start, file.length, Array.empty)
-
- val split =
- new org.apache.parquet.hadoop.ParquetInputSplit(
- fileSplit.getPath,
- fileSplit.getStart,
- fileSplit.getStart + fileSplit.getLength,
- fileSplit.getLength,
- fileSplit.getLocations,
- null)
-
- val attemptId = new TaskAttemptID(new TaskID(new JobID(), TaskType.MAP, 0), 0)
- val hadoopAttemptContext =
- new TaskAttemptContextImpl(broadcastedHadoopConf.value.value, attemptId)
-
- val parquetReader = if (enableVectorizedReader) {
- val vectorizedReader = new VectorizedParquetRecordReader()
- vectorizedReader.initialize(split, hadoopAttemptContext)
- logDebug(s"Appending $partitionSchema ${file.partitionValues}")
- vectorizedReader.initBatch(partitionSchema, file.partitionValues)
- if (returningBatch) {
- vectorizedReader.enableReturningBatches()
- }
- vectorizedReader
- } else {
- logDebug(s"Falling back to parquet-mr")
- val reader = pushed match {
- case Some(filter) =>
- new ParquetRecordReader[InternalRow](
- new CatalystReadSupport,
- FilterCompat.get(filter, null))
- case _ =>
- new ParquetRecordReader[InternalRow](new CatalystReadSupport)
- }
- reader.initialize(split, hadoopAttemptContext)
- reader
- }
-
- val iter = new RecordReaderIterator(parquetReader)
-
- // UnsafeRowParquetRecordReader appends the columns internally to avoid another copy.
- if (parquetReader.isInstanceOf[VectorizedParquetRecordReader] &&
- enableVectorizedReader) {
- iter.asInstanceOf[Iterator[InternalRow]]
- } else {
- val fullSchema = requiredSchema.toAttributes ++ partitionSchema.toAttributes
- val joinedRow = new JoinedRow()
- val appendPartitionColumns = GenerateUnsafeProjection.generate(fullSchema, fullSchema)
-
- // This is a horrible erasure hack... if we type the iterator above, then it actually check
- // the type in next() and we get a class cast exception. If we make that function return
- // Object, then we can defer the cast until later!
- iter.asInstanceOf[Iterator[InternalRow]]
- .map(d => appendPartitionColumns(joinedRow(d, file.partitionValues)))
- }
- }
- }
-
- override def buildWriter(
- sqlContext: SQLContext,
- dataSchema: StructType,
- options: Map[String, String]): OutputWriterFactory = {
- new ParquetOutputWriterFactory(
- sqlContext.conf,
- dataSchema,
- sqlContext.sparkContext.hadoopConfiguration,
- options)
- }
-}
-
-/**
- * A factory for generating OutputWriters for writing parquet files. This implemented is different
- * from the [[ParquetOutputWriter]] as this does not use any [[OutputCommitter]]. It simply
- * writes the data to the path used to generate the output writer. Callers of this factory
- * has to ensure which files are to be considered as committed.
- */
-private[sql] class ParquetOutputWriterFactory(
- sqlConf: SQLConf,
- dataSchema: StructType,
- hadoopConf: Configuration,
- options: Map[String, String]) extends OutputWriterFactory {
-
- private val serializableConf: SerializableConfiguration = {
- val job = Job.getInstance(hadoopConf)
- val conf = ContextUtil.getConfiguration(job)
- val parquetOptions = new ParquetOptions(options, sqlConf)
-
- // We're not really using `ParquetOutputFormat[Row]` for writing data here, because we override
- // it in `ParquetOutputWriter` to support appending and dynamic partitioning. The reason why
- // we set it here is to setup the output committer class to `ParquetOutputCommitter`, which is
- // bundled with `ParquetOutputFormat[Row]`.
- job.setOutputFormatClass(classOf[ParquetOutputFormat[Row]])
-
- ParquetOutputFormat.setWriteSupportClass(job, classOf[CatalystWriteSupport])
-
- // We want to clear this temporary metadata from saving into Parquet file.
- // This metadata is only useful for detecting optional columns when pushdowning filters.
- val dataSchemaToWrite = StructType.removeMetadata(
- StructType.metadataKeyForOptionalField,
- dataSchema).asInstanceOf[StructType]
- CatalystWriteSupport.setSchema(dataSchemaToWrite, conf)
-
- // Sets flags for `CatalystSchemaConverter` (which converts Catalyst schema to Parquet schema)
- // and `CatalystWriteSupport` (writing actual rows to Parquet files).
- conf.set(
- SQLConf.PARQUET_BINARY_AS_STRING.key,
- sqlConf.isParquetBinaryAsString.toString)
-
- conf.set(
- SQLConf.PARQUET_INT96_AS_TIMESTAMP.key,
- sqlConf.isParquetINT96AsTimestamp.toString)
-
- conf.set(
- SQLConf.PARQUET_WRITE_LEGACY_FORMAT.key,
- sqlConf.writeLegacyParquetFormat.toString)
-
- // Sets compression scheme
- conf.set(ParquetOutputFormat.COMPRESSION, parquetOptions.compressionCodec)
- new SerializableConfiguration(conf)
- }
-
- /**
- * Returns a [[OutputWriter]] that writes data to the give path without using
- * [[OutputCommitter]].
- */
- override private[sql] def newWriter(path: String): OutputWriter = new OutputWriter {
-
- // Create TaskAttemptContext that is used to pass on Configuration to the ParquetRecordWriter
- private val hadoopTaskAttempId = new TaskAttemptID(new TaskID(new JobID, TaskType.MAP, 0), 0)
- private val hadoopAttemptContext = new TaskAttemptContextImpl(
- serializableConf.value, hadoopTaskAttempId)
-
- // Instance of ParquetRecordWriter that does not use OutputCommitter
- private val recordWriter = createNoCommitterRecordWriter(path, hadoopAttemptContext)
-
- override def write(row: Row): Unit = {
- throw new UnsupportedOperationException("call writeInternal")
- }
-
- protected[sql] override def writeInternal(row: InternalRow): Unit = {
- recordWriter.write(null, row)
- }
-
- override def close(): Unit = recordWriter.close(hadoopAttemptContext)
- }
-
- /** Create a [[ParquetRecordWriter]] that writes the given path without using OutputCommitter */
- private def createNoCommitterRecordWriter(
- path: String,
- hadoopAttemptContext: TaskAttemptContext): RecordWriter[Void, InternalRow] = {
- // Custom ParquetOutputFormat that disable use of committer and writes to the given path
- val outputFormat = new ParquetOutputFormat[InternalRow]() {
- override def getOutputCommitter(c: TaskAttemptContext): OutputCommitter = { null }
- override def getDefaultWorkFile(c: TaskAttemptContext, ext: String): Path = { new Path(path) }
- }
- outputFormat.getRecordWriter(hadoopAttemptContext)
- }
-
- /** Disable the use of the older API. */
- def newInstance(
- path: String,
- bucketId: Option[Int],
- dataSchema: StructType,
- context: TaskAttemptContext): OutputWriter = {
- throw new UnsupportedOperationException(
- "this verison of newInstance not supported for " +
- "ParquetOutputWriterFactory")
- }
-}
-
-
-// NOTE: This class is instantiated and used on executor side only, no need to be serializable.
-private[sql] class ParquetOutputWriter(
- path: String,
- bucketId: Option[Int],
- context: TaskAttemptContext)
- extends OutputWriter {
-
- private val recordWriter: RecordWriter[Void, InternalRow] = {
- val outputFormat = {
- new ParquetOutputFormat[InternalRow]() {
- // Here we override `getDefaultWorkFile` for two reasons:
- //
- // 1. To allow appending. We need to generate unique output file names to avoid
- // overwriting existing files (either exist before the write job, or are just written
- // by other tasks within the same write job).
- //
- // 2. To allow dynamic partitioning. Default `getDefaultWorkFile` uses
- // `FileOutputCommitter.getWorkPath()`, which points to the base directory of all
- // partitions in the case of dynamic partitioning.
- override def getDefaultWorkFile(context: TaskAttemptContext, extension: String): Path = {
- val configuration = context.getConfiguration
- val uniqueWriteJobId = configuration.get("spark.sql.sources.writeJobUUID")
- val taskAttemptId = context.getTaskAttemptID
- val split = taskAttemptId.getTaskID.getId
- val bucketString = bucketId.map(BucketingUtils.bucketIdToString).getOrElse("")
- // It has the `.parquet` extension at the end because (de)compression tools
- // such as gunzip would not be able to decompress this as the compression
- // is not applied on this whole file but on each "page" in Parquet format.
- new Path(path, f"part-r-$split%05d-$uniqueWriteJobId$bucketString$extension")
- }
- }
- }
-
- outputFormat.getRecordWriter(context)
- }
-
- override def write(row: Row): Unit = throw new UnsupportedOperationException("call writeInternal")
-
- override protected[sql] def writeInternal(row: InternalRow): Unit = recordWriter.write(null, row)
-
- override def close(): Unit = recordWriter.close(context)
-}
-
-private[sql] object ParquetRelation extends Logging {
- // Whether we should merge schemas collected from all Parquet part-files.
- private[sql] val MERGE_SCHEMA = "mergeSchema"
-
- // Hive Metastore schema, used when converting Metastore Parquet tables. This option is only used
- // internally.
- private[sql] val METASTORE_SCHEMA = "metastoreSchema"
-
- // If a ParquetRelation is converted from a Hive metastore table, this option is set to the
- // original Hive table name.
- private[sql] val METASTORE_TABLE_NAME = "metastoreTableName"
-
- /**
- * If parquet's block size (row group size) setting is larger than the min split size,
- * we use parquet's block size setting as the min split size. Otherwise, we will create
- * tasks processing nothing (because a split does not cover the starting point of a
- * parquet block). See https://issues.apache.org/jira/browse/SPARK-10143 for more information.
- */
- private def overrideMinSplitSize(parquetBlockSize: Long, conf: Configuration): Unit = {
- val minSplitSize =
- math.max(
- conf.getLong("mapred.min.split.size", 0L),
- conf.getLong("mapreduce.input.fileinputformat.split.minsize", 0L))
- if (parquetBlockSize > minSplitSize) {
- val message =
- s"Parquet's block size (row group size) is larger than " +
- s"mapred.min.split.size/mapreduce.input.fileinputformat.split.minsize. Setting " +
- s"mapred.min.split.size and mapreduce.input.fileinputformat.split.minsize to " +
- s"$parquetBlockSize."
- logDebug(message)
- conf.set("mapred.min.split.size", parquetBlockSize.toString)
- conf.set("mapreduce.input.fileinputformat.split.minsize", parquetBlockSize.toString)
- }
- }
-
- /** This closure sets various Parquet configurations at both driver side and executor side. */
- private[parquet] def initializeLocalJobFunc(
- requiredColumns: Array[String],
- filters: Array[Filter],
- dataSchema: StructType,
- parquetBlockSize: Long,
- useMetadataCache: Boolean,
- parquetFilterPushDown: Boolean,
- assumeBinaryIsString: Boolean,
- assumeInt96IsTimestamp: Boolean)(job: Job): Unit = {
- val conf = job.getConfiguration
- conf.set(ParquetInputFormat.READ_SUPPORT_CLASS, classOf[CatalystReadSupport].getName)
-
- // Try to push down filters when filter push-down is enabled.
- if (parquetFilterPushDown) {
- filters
- // Collects all converted Parquet filter predicates. Notice that not all predicates can be
- // converted (`ParquetFilters.createFilter` returns an `Option`). That's why a `flatMap`
- // is used here.
- .flatMap(ParquetFilters.createFilter(dataSchema, _))
- .reduceOption(FilterApi.and)
- .foreach(ParquetInputFormat.setFilterPredicate(conf, _))
- }
-
- conf.set(CatalystReadSupport.SPARK_ROW_REQUESTED_SCHEMA, {
- val requestedSchema = StructType(requiredColumns.map(dataSchema(_)))
- CatalystSchemaConverter.checkFieldNames(requestedSchema).json
- })
-
- conf.set(
- CatalystWriteSupport.SPARK_ROW_SCHEMA,
- CatalystSchemaConverter.checkFieldNames(dataSchema).json)
-
- // Tell FilteringParquetRowInputFormat whether it's okay to cache Parquet and FS metadata
- conf.setBoolean(SQLConf.PARQUET_CACHE_METADATA.key, useMetadataCache)
-
- // Sets flags for `CatalystSchemaConverter`
- conf.setBoolean(SQLConf.PARQUET_BINARY_AS_STRING.key, assumeBinaryIsString)
- conf.setBoolean(SQLConf.PARQUET_INT96_AS_TIMESTAMP.key, assumeInt96IsTimestamp)
-
- overrideMinSplitSize(parquetBlockSize, conf)
- }
-
- /** This closure sets input paths at the driver side. */
- private[parquet] def initializeDriverSideJobFunc(
- inputFiles: Array[FileStatus],
- parquetBlockSize: Long)(job: Job): Unit = {
- // We side the input paths at the driver side.
- logInfo(s"Reading Parquet file(s) from ${inputFiles.map(_.getPath).mkString(", ")}")
- if (inputFiles.nonEmpty) {
- FileInputFormat.setInputPaths(job, inputFiles.map(_.getPath): _*)
- }
-
- overrideMinSplitSize(parquetBlockSize, job.getConfiguration)
- }
-
- private[parquet] def readSchema(
- footers: Seq[Footer], sparkSession: SparkSession): Option[StructType] = {
-
- def parseParquetSchema(schema: MessageType): StructType = {
- val converter = new CatalystSchemaConverter(
- sparkSession.sessionState.conf.isParquetBinaryAsString,
- sparkSession.sessionState.conf.isParquetBinaryAsString,
- sparkSession.sessionState.conf.writeLegacyParquetFormat)
-
- converter.convert(schema)
- }
-
- val seen = mutable.HashSet[String]()
- val finalSchemas: Seq[StructType] = footers.flatMap { footer =>
- val metadata = footer.getParquetMetadata.getFileMetaData
- val serializedSchema = metadata
- .getKeyValueMetaData
- .asScala.toMap
- .get(CatalystReadSupport.SPARK_METADATA_KEY)
- if (serializedSchema.isEmpty) {
- // Falls back to Parquet schema if no Spark SQL schema found.
- Some(parseParquetSchema(metadata.getSchema))
- } else if (!seen.contains(serializedSchema.get)) {
- seen += serializedSchema.get
-
- // Don't throw even if we failed to parse the serialized Spark schema. Just fallback to
- // whatever is available.
- Some(Try(DataType.fromJson(serializedSchema.get))
- .recover { case _: Throwable =>
- logInfo(
- s"Serialized Spark schema in Parquet key-value metadata is not in JSON format, " +
- "falling back to the deprecated DataType.fromCaseClassString parser.")
- LegacyTypeStringParser.parse(serializedSchema.get)
- }
- .recover { case cause: Throwable =>
- logWarning(
- s"""Failed to parse serialized Spark schema in Parquet key-value metadata:
- |\t$serializedSchema
- """.stripMargin,
- cause)
- }
- .map(_.asInstanceOf[StructType])
- .getOrElse {
- // Falls back to Parquet schema if Spark SQL schema can't be parsed.
- parseParquetSchema(metadata.getSchema)
- })
- } else {
- None
- }
- }
-
- finalSchemas.reduceOption { (left, right) =>
- try left.merge(right) catch { case e: Throwable =>
- throw new SparkException(s"Failed to merge incompatible schemas $left and $right", e)
- }
- }
- }
-
- /**
- * Reconciles Hive Metastore case insensitivity issue and data type conflicts between Metastore
- * schema and Parquet schema.
- *
- * Hive doesn't retain case information, while Parquet is case sensitive. On the other hand, the
- * schema read from Parquet files may be incomplete (e.g. older versions of Parquet doesn't
- * distinguish binary and string). This method generates a correct schema by merging Metastore
- * schema data types and Parquet schema field names.
- */
- private[sql] def mergeMetastoreParquetSchema(
- metastoreSchema: StructType,
- parquetSchema: StructType): StructType = {
- def schemaConflictMessage: String =
- s"""Converting Hive Metastore Parquet, but detected conflicting schemas. Metastore schema:
- |${metastoreSchema.prettyJson}
- |
- |Parquet schema:
- |${parquetSchema.prettyJson}
- """.stripMargin
-
- val mergedParquetSchema = mergeMissingNullableFields(metastoreSchema, parquetSchema)
-
- assert(metastoreSchema.size <= mergedParquetSchema.size, schemaConflictMessage)
-
- val ordinalMap = metastoreSchema.zipWithIndex.map {
- case (field, index) => field.name.toLowerCase -> index
- }.toMap
-
- val reorderedParquetSchema = mergedParquetSchema.sortBy(f =>
- ordinalMap.getOrElse(f.name.toLowerCase, metastoreSchema.size + 1))
-
- StructType(metastoreSchema.zip(reorderedParquetSchema).map {
- // Uses Parquet field names but retains Metastore data types.
- case (mSchema, pSchema) if mSchema.name.toLowerCase == pSchema.name.toLowerCase =>
- mSchema.copy(name = pSchema.name)
- case _ =>
- throw new SparkException(schemaConflictMessage)
- })
- }
-
- /**
- * Returns the original schema from the Parquet file with any missing nullable fields from the
- * Hive Metastore schema merged in.
- *
- * When constructing a DataFrame from a collection of structured data, the resulting object has
- * a schema corresponding to the union of the fields present in each element of the collection.
- * Spark SQL simply assigns a null value to any field that isn't present for a particular row.
- * In some cases, it is possible that a given table partition stored as a Parquet file doesn't
- * contain a particular nullable field in its schema despite that field being present in the
- * table schema obtained from the Hive Metastore. This method returns a schema representing the
- * Parquet file schema along with any additional nullable fields from the Metastore schema
- * merged in.
- */
- private[parquet] def mergeMissingNullableFields(
- metastoreSchema: StructType,
- parquetSchema: StructType): StructType = {
- val fieldMap = metastoreSchema.map(f => f.name.toLowerCase -> f).toMap
- val missingFields = metastoreSchema
- .map(_.name.toLowerCase)
- .diff(parquetSchema.map(_.name.toLowerCase))
- .map(fieldMap(_))
- .filter(_.nullable)
- StructType(parquetSchema ++ missingFields)
- }
-
- /**
- * Figures out a merged Parquet schema with a distributed Spark job.
- *
- * Note that locality is not taken into consideration here because:
- *
- * 1. For a single Parquet part-file, in most cases the footer only resides in the last block of
- * that file. Thus we only need to retrieve the location of the last block. However, Hadoop
- * `FileSystem` only provides API to retrieve locations of all blocks, which can be
- * potentially expensive.
- *
- * 2. This optimization is mainly useful for S3, where file metadata operations can be pretty
- * slow. And basically locality is not available when using S3 (you can't run computation on
- * S3 nodes).
- */
- def mergeSchemasInParallel(
- filesToTouch: Seq[FileStatus],
- sparkSession: SparkSession): Option[StructType] = {
- val assumeBinaryIsString = sparkSession.sessionState.conf.isParquetBinaryAsString
- val assumeInt96IsTimestamp = sparkSession.sessionState.conf.isParquetINT96AsTimestamp
- val writeLegacyParquetFormat = sparkSession.sessionState.conf.writeLegacyParquetFormat
- val serializedConf =
- new SerializableConfiguration(sparkSession.sessionState.newHadoopConf())
-
- // !! HACK ALERT !!
- //
- // Parquet requires `FileStatus`es to read footers. Here we try to send cached `FileStatus`es
- // to executor side to avoid fetching them again. However, `FileStatus` is not `Serializable`
- // but only `Writable`. What makes it worth, for some reason, `FileStatus` doesn't play well
- // with `SerializableWritable[T]` and always causes a weird `IllegalStateException`. These
- // facts virtually prevents us to serialize `FileStatus`es.
- //
- // Since Parquet only relies on path and length information of those `FileStatus`es to read
- // footers, here we just extract them (which can be easily serialized), send them to executor
- // side, and resemble fake `FileStatus`es there.
- val partialFileStatusInfo = filesToTouch.map(f => (f.getPath.toString, f.getLen))
-
- // Issues a Spark job to read Parquet schema in parallel.
- val partiallyMergedSchemas =
- sparkSession
- .sparkContext
- .parallelize(partialFileStatusInfo)
- .mapPartitions { iterator =>
- // Resembles fake `FileStatus`es with serialized path and length information.
- val fakeFileStatuses = iterator.map { case (path, length) =>
- new FileStatus(length, false, 0, 0, 0, 0, null, null, null, new Path(path))
- }.toSeq
-
- // Skips row group information since we only need the schema
- val skipRowGroups = true
-
- // Reads footers in multi-threaded manner within each task
- val footers =
- ParquetFileReader.readAllFootersInParallel(
- serializedConf.value, fakeFileStatuses.asJava, skipRowGroups).asScala
-
- // Converter used to convert Parquet `MessageType` to Spark SQL `StructType`
- val converter =
- new CatalystSchemaConverter(
- assumeBinaryIsString = assumeBinaryIsString,
- assumeInt96IsTimestamp = assumeInt96IsTimestamp,
- writeLegacyParquetFormat = writeLegacyParquetFormat)
-
- if (footers.isEmpty) {
- Iterator.empty
- } else {
- var mergedSchema = ParquetRelation.readSchemaFromFooter(footers.head, converter)
- footers.tail.foreach { footer =>
- val schema = ParquetRelation.readSchemaFromFooter(footer, converter)
- try {
- mergedSchema = mergedSchema.merge(schema)
- } catch { case cause: SparkException =>
- throw new SparkException(
- s"Failed merging schema of file ${footer.getFile}:\n${schema.treeString}", cause)
- }
- }
- Iterator.single(mergedSchema)
- }
- }.collect()
-
- if (partiallyMergedSchemas.isEmpty) {
- None
- } else {
- var finalSchema = partiallyMergedSchemas.head
- partiallyMergedSchemas.tail.foreach { schema =>
- try {
- finalSchema = finalSchema.merge(schema)
- } catch { case cause: SparkException =>
- throw new SparkException(
- s"Failed merging schema:\n${schema.treeString}", cause)
- }
- }
- Some(finalSchema)
- }
- }
-
- /**
- * Reads Spark SQL schema from a Parquet footer. If a valid serialized Spark SQL schema string
- * can be found in the file metadata, returns the deserialized [[StructType]], otherwise, returns
- * a [[StructType]] converted from the [[MessageType]] stored in this footer.
- */
- def readSchemaFromFooter(
- footer: Footer, converter: CatalystSchemaConverter): StructType = {
- val fileMetaData = footer.getParquetMetadata.getFileMetaData
- fileMetaData
- .getKeyValueMetaData
- .asScala.toMap
- .get(CatalystReadSupport.SPARK_METADATA_KEY)
- .flatMap(deserializeSchemaString)
- .getOrElse(converter.convert(fileMetaData.getSchema))
- }
-
- private def deserializeSchemaString(schemaString: String): Option[StructType] = {
- // Tries to deserialize the schema string as JSON first, then falls back to the case class
- // string parser (data generated by older versions of Spark SQL uses this format).
- Try(DataType.fromJson(schemaString).asInstanceOf[StructType]).recover {
- case _: Throwable =>
- logInfo(
- s"Serialized Spark schema in Parquet key-value metadata is not in JSON format, " +
- "falling back to the deprecated DataType.fromCaseClassString parser.")
- LegacyTypeStringParser.parse(schemaString).asInstanceOf[StructType]
- }.recoverWith {
- case cause: Throwable =>
- logWarning(
- "Failed to parse and ignored serialized Spark schema in " +
- s"Parquet key-value metadata:\n\t$schemaString", cause)
- Failure(cause)
- }.toOption
- }
-
- // JUL loggers must be held by a strong reference, otherwise they may get destroyed by GC.
- // However, the root JUL logger used by Parquet isn't properly referenced. Here we keep
- // references to loggers in both parquet-mr <= 1.6 and >= 1.7
- val apacheParquetLogger: JLogger = JLogger.getLogger(classOf[ApacheParquetLog].getPackage.getName)
- val parquetLogger: JLogger = JLogger.getLogger("parquet")
-
- // Parquet initializes its own JUL logger in a static block which always prints to stdout. Here
- // we redirect the JUL logger via SLF4J JUL bridge handler.
- val redirectParquetLogsViaSLF4J: Unit = {
- def redirect(logger: JLogger): Unit = {
- logger.getHandlers.foreach(logger.removeHandler)
- logger.setUseParentHandlers(false)
- logger.addHandler(new SLF4JBridgeHandler)
- }
-
- // For parquet-mr 1.7.0 and above versions, which are under `org.apache.parquet` namespace.
- // scalastyle:off classforname
- Class.forName(classOf[ApacheParquetLog].getName)
- // scalastyle:on classforname
- redirect(JLogger.getLogger(classOf[ApacheParquetLog].getPackage.getName))
-
- // For parquet-mr 1.6.0 and lower versions bundled with Hive, which are under `parquet`
- // namespace.
- try {
- // scalastyle:off classforname
- Class.forName("parquet.Log")
- // scalastyle:on classforname
- redirect(JLogger.getLogger("parquet"))
- } catch { case _: Throwable =>
- // SPARK-9974: com.twitter:parquet-hadoop-bundle:1.6.0 is not packaged into the assembly
- // when Spark is built with SBT. So `parquet.Log` may not be found. This try/catch block
- // should be removed after this issue is fixed.
- }
- }
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org
[4/4] spark git commit: [SPARK-15543][SQL] Rename DefaultSources to
make them more self-describing
Posted by rx...@apache.org.
[SPARK-15543][SQL] Rename DefaultSources to make them more self-describing
## What changes were proposed in this pull request?
This patch renames various DefaultSources to make their names more self-describing. The choice of "DefaultSource" was from the days when we did not have a good way to specify short names.
They are now named:
- LibSVMFileFormat
- CSVFileFormat
- JdbcRelationProvider
- JsonFileFormat
- ParquetFileFormat
- TextFileFormat
Backward compatibility is maintained through aliasing.
## How was this patch tested?
Updated relevant test cases too.
Author: Reynold Xin <rx...@databricks.com>
Closes #13311 from rxin/SPARK-15543.
Project: http://git-wip-us.apache.org/repos/asf/spark/repo
Commit: http://git-wip-us.apache.org/repos/asf/spark/commit/361ebc28
Tree: http://git-wip-us.apache.org/repos/asf/spark/tree/361ebc28
Diff: http://git-wip-us.apache.org/repos/asf/spark/diff/361ebc28
Branch: refs/heads/master
Commit: 361ebc282b2d09dc6dcf21419a53c5c617b1b6bd
Parents: dfc9fc0
Author: Reynold Xin <rx...@databricks.com>
Authored: Wed May 25 23:54:24 2016 -0700
Committer: Reynold Xin <rx...@databricks.com>
Committed: Wed May 25 23:54:24 2016 -0700
----------------------------------------------------------------------
....apache.spark.sql.sources.DataSourceRegister | 2 +-
.../spark/ml/source/libsvm/LibSVMRelation.scala | 8 +-
project/MimaExcludes.scala | 4 +-
....apache.spark.sql.sources.DataSourceRegister | 10 +-
.../spark/sql/execution/ExistingRDD.scala | 2 +-
.../sql/execution/datasources/DataSource.scala | 45 +-
.../datasources/csv/CSVFileFormat.scala | 185 ++++
.../datasources/csv/DefaultSource.scala | 187 ----
.../datasources/jdbc/DefaultSource.scala | 55 --
.../datasources/jdbc/JdbcRelationProvider.scala | 55 ++
.../datasources/json/JSONRelation.scala | 198 ----
.../datasources/json/JsonFileFormat.scala | 198 ++++
.../datasources/parquet/ParquetFileFormat.scala | 923 +++++++++++++++++++
.../datasources/parquet/ParquetRelation.scala | 923 -------------------
.../datasources/text/DefaultSource.scala | 141 ---
.../datasources/text/TextFileFormat.scala | 141 +++
.../execution/datasources/json/JsonSuite.scala | 4 +-
.../parquet/ParquetSchemaSuite.scala | 12 +-
.../sql/sources/ResolvedDataSourceSuite.scala | 18 +-
.../streaming/DataFrameReaderWriterSuite.scala | 542 -----------
.../sql/streaming/FileStreamSinkSuite.scala | 4 +-
.../test/DataFrameReaderWriterSuite.scala | 541 +++++++++++
....apache.spark.sql.sources.DataSourceRegister | 2 +-
.../spark/sql/hive/HiveMetastoreCatalog.scala | 18 +-
.../spark/sql/hive/orc/OrcFileFormat.scala | 375 ++++++++
.../apache/spark/sql/hive/orc/OrcRelation.scala | 371 --------
.../sql/hive/orc/OrcHadoopFsRelationSuite.scala | 2 +-
27 files changed, 2498 insertions(+), 2468 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/mllib/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
----------------------------------------------------------------------
diff --git a/mllib/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister b/mllib/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
index f632dd6..a865cbe 100644
--- a/mllib/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
+++ b/mllib/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
@@ -1 +1 @@
-org.apache.spark.ml.source.libsvm.DefaultSource
+org.apache.spark.ml.source.libsvm.LibSVMFileFormat
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/mllib/src/main/scala/org/apache/spark/ml/source/libsvm/LibSVMRelation.scala
----------------------------------------------------------------------
diff --git a/mllib/src/main/scala/org/apache/spark/ml/source/libsvm/LibSVMRelation.scala b/mllib/src/main/scala/org/apache/spark/ml/source/libsvm/LibSVMRelation.scala
index 5ba768d..64ebf0c 100644
--- a/mllib/src/main/scala/org/apache/spark/ml/source/libsvm/LibSVMRelation.scala
+++ b/mllib/src/main/scala/org/apache/spark/ml/source/libsvm/LibSVMRelation.scala
@@ -90,7 +90,7 @@ private[libsvm] class LibSVMOutputWriter(
* .load("data/mllib/sample_libsvm_data.txt")
*
* // Java
- * DataFrame df = spark.read().format("libsvm")
+ * Dataset<Row> df = spark.read().format("libsvm")
* .option("numFeatures, "780")
* .load("data/mllib/sample_libsvm_data.txt");
* }}}
@@ -105,9 +105,13 @@ private[libsvm] class LibSVMOutputWriter(
* - "vectorType": feature vector type, "sparse" (default) or "dense".
*
* @see [[https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/ LIBSVM datasets]]
+ *
+ * Note that this class is public for documentation purpose. Please don't use this class directly.
+ * Rather, use the data source API as illustrated above.
*/
+// If this is moved or renamed, please update DataSource's backwardCompatibilityMap.
@Since("1.6.0")
-class DefaultSource extends FileFormat with DataSourceRegister {
+class LibSVMFileFormat extends FileFormat with DataSourceRegister {
@Since("1.6.0")
override def shortName(): String = "libsvm"
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/project/MimaExcludes.scala
----------------------------------------------------------------------
diff --git a/project/MimaExcludes.scala b/project/MimaExcludes.scala
index 4e99a09..08c575a 100644
--- a/project/MimaExcludes.scala
+++ b/project/MimaExcludes.scala
@@ -68,7 +68,9 @@ object MimaExcludes {
// SPARK-13664 Replace HadoopFsRelation with FileFormat
ProblemFilters.exclude[MissingClassProblem]("org.apache.spark.ml.source.libsvm.LibSVMRelation"),
ProblemFilters.exclude[MissingClassProblem]("org.apache.spark.sql.sources.HadoopFsRelationProvider"),
- ProblemFilters.exclude[MissingClassProblem]("org.apache.spark.sql.sources.HadoopFsRelation$FileStatusCache")
+ ProblemFilters.exclude[MissingClassProblem]("org.apache.spark.sql.sources.HadoopFsRelation$FileStatusCache"),
+ // SPARK-15543 Rename DefaultSources to make them more self-describing
+ ProblemFilters.exclude[MissingClassProblem]("org.apache.spark.ml.source.libsvm.DefaultSource")
) ++ Seq(
ProblemFilters.exclude[IncompatibleResultTypeProblem]("org.apache.spark.SparkContext.emptyRDD"),
ProblemFilters.exclude[MissingClassProblem]("org.apache.spark.broadcast.HttpBroadcastFactory"),
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
----------------------------------------------------------------------
diff --git a/sql/core/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister b/sql/core/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
index ef92557..9f8bb5d 100644
--- a/sql/core/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
+++ b/sql/core/src/main/resources/META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
@@ -1,6 +1,6 @@
-org.apache.spark.sql.execution.datasources.csv.DefaultSource
-org.apache.spark.sql.execution.datasources.jdbc.DefaultSource
-org.apache.spark.sql.execution.datasources.json.DefaultSource
-org.apache.spark.sql.execution.datasources.parquet.DefaultSource
-org.apache.spark.sql.execution.datasources.text.DefaultSource
+org.apache.spark.sql.execution.datasources.csv.CSVFileFormat
+org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider
+org.apache.spark.sql.execution.datasources.json.JsonFileFormat
+org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
+org.apache.spark.sql.execution.datasources.text.TextFileFormat
org.apache.spark.sql.execution.streaming.ConsoleSinkProvider
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala
index ec23a9c..412f5fa 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala
@@ -28,7 +28,7 @@ import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext, ExprCo
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Statistics}
import org.apache.spark.sql.catalyst.plans.physical.{HashPartitioning, Partitioning, UnknownPartitioning}
import org.apache.spark.sql.execution.datasources.HadoopFsRelation
-import org.apache.spark.sql.execution.datasources.parquet.{DefaultSource => ParquetSource}
+import org.apache.spark.sql.execution.datasources.parquet.{ParquetFileFormat => ParquetSource}
import org.apache.spark.sql.execution.metric.SQLMetrics
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.sources.BaseRelation
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/DataSource.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/DataSource.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/DataSource.scala
index d0853f6..dfe0647 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/DataSource.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/DataSource.scala
@@ -30,6 +30,10 @@ import org.apache.spark.deploy.SparkHadoopUtil
import org.apache.spark.internal.Logging
import org.apache.spark.sql._
import org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute
+import org.apache.spark.sql.execution.datasources.csv.CSVFileFormat
+import org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider
+import org.apache.spark.sql.execution.datasources.json.JsonFileFormat
+import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
import org.apache.spark.sql.execution.streaming._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.sources._
@@ -74,15 +78,34 @@ case class DataSource(
lazy val sourceInfo = sourceSchema()
/** A map to maintain backward compatibility in case we move data sources around. */
- private val backwardCompatibilityMap = Map(
- "org.apache.spark.sql.jdbc" -> classOf[jdbc.DefaultSource].getCanonicalName,
- "org.apache.spark.sql.jdbc.DefaultSource" -> classOf[jdbc.DefaultSource].getCanonicalName,
- "org.apache.spark.sql.json" -> classOf[json.DefaultSource].getCanonicalName,
- "org.apache.spark.sql.json.DefaultSource" -> classOf[json.DefaultSource].getCanonicalName,
- "org.apache.spark.sql.parquet" -> classOf[parquet.DefaultSource].getCanonicalName,
- "org.apache.spark.sql.parquet.DefaultSource" -> classOf[parquet.DefaultSource].getCanonicalName,
- "com.databricks.spark.csv" -> classOf[csv.DefaultSource].getCanonicalName
- )
+ private val backwardCompatibilityMap: Map[String, String] = {
+ val jdbc = classOf[JdbcRelationProvider].getCanonicalName
+ val json = classOf[JsonFileFormat].getCanonicalName
+ val parquet = classOf[ParquetFileFormat].getCanonicalName
+ val csv = classOf[CSVFileFormat].getCanonicalName
+ val libsvm = "org.apache.spark.ml.source.libsvm.LibSVMFileFormat"
+ val orc = "org.apache.spark.sql.hive.orc.OrcFileFormat"
+
+ Map(
+ "org.apache.spark.sql.jdbc" -> jdbc,
+ "org.apache.spark.sql.jdbc.DefaultSource" -> jdbc,
+ "org.apache.spark.sql.execution.datasources.jdbc.DefaultSource" -> jdbc,
+ "org.apache.spark.sql.execution.datasources.jdbc" -> jdbc,
+ "org.apache.spark.sql.json" -> json,
+ "org.apache.spark.sql.json.DefaultSource" -> json,
+ "org.apache.spark.sql.execution.datasources.json" -> json,
+ "org.apache.spark.sql.execution.datasources.json.DefaultSource" -> json,
+ "org.apache.spark.sql.parquet" -> parquet,
+ "org.apache.spark.sql.parquet.DefaultSource" -> parquet,
+ "org.apache.spark.sql.execution.datasources.parquet" -> parquet,
+ "org.apache.spark.sql.execution.datasources.parquet.DefaultSource" -> parquet,
+ "org.apache.spark.sql.hive.orc.DefaultSource" -> orc,
+ "org.apache.spark.sql.hive.orc" -> orc,
+ "org.apache.spark.ml.source.libsvm.DefaultSource" -> libsvm,
+ "org.apache.spark.ml.source.libsvm" -> libsvm,
+ "com.databricks.spark.csv" -> csv
+ )
+ }
/**
* Class that were removed in Spark 2.0. Used to detect incompatibility libraries for Spark 2.0.
@@ -188,7 +211,7 @@ case class DataSource(
throw new IllegalArgumentException("'path' is not specified")
})
val isSchemaInferenceEnabled = sparkSession.conf.get(SQLConf.STREAMING_SCHEMA_INFERENCE)
- val isTextSource = providingClass == classOf[text.DefaultSource]
+ val isTextSource = providingClass == classOf[text.TextFileFormat]
// If the schema inference is disabled, only text sources require schema to be specified
if (!isSchemaInferenceEnabled && !isTextSource && userSpecifiedSchema.isEmpty) {
throw new IllegalArgumentException(
@@ -229,7 +252,7 @@ case class DataSource(
providingClass.newInstance() match {
case s: StreamSinkProvider => s.createSink(sparkSession.sqlContext, options, partitionColumns)
- case parquet: parquet.DefaultSource =>
+ case parquet: parquet.ParquetFileFormat =>
val caseInsensitiveOptions = new CaseInsensitiveMap(options)
val path = caseInsensitiveOptions.getOrElse("path", {
throw new IllegalArgumentException("'path' is not specified")
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/csv/CSVFileFormat.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/csv/CSVFileFormat.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/csv/CSVFileFormat.scala
new file mode 100644
index 0000000..4d36b76
--- /dev/null
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/csv/CSVFileFormat.scala
@@ -0,0 +1,185 @@
+/*
+ * 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.execution.datasources.csv
+
+import java.nio.charset.{Charset, StandardCharsets}
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.FileStatus
+import org.apache.hadoop.io.{LongWritable, Text}
+import org.apache.hadoop.mapred.TextInputFormat
+import org.apache.hadoop.mapreduce._
+
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.execution.datasources._
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types._
+import org.apache.spark.util.SerializableConfiguration
+
+/**
+ * Provides access to CSV data from pure SQL statements.
+ */
+class CSVFileFormat extends FileFormat with DataSourceRegister {
+
+ override def shortName(): String = "csv"
+
+ override def toString: String = "CSV"
+
+ override def hashCode(): Int = getClass.hashCode()
+
+ override def equals(other: Any): Boolean = other.isInstanceOf[CSVFileFormat]
+
+ override def inferSchema(
+ sparkSession: SparkSession,
+ options: Map[String, String],
+ files: Seq[FileStatus]): Option[StructType] = {
+ val csvOptions = new CSVOptions(options)
+
+ // TODO: Move filtering.
+ val paths = files.filterNot(_.getPath.getName startsWith "_").map(_.getPath.toString)
+ val rdd = baseRdd(sparkSession, csvOptions, paths)
+ val firstLine = findFirstLine(csvOptions, rdd)
+ val firstRow = new LineCsvReader(csvOptions).parseLine(firstLine)
+
+ val header = if (csvOptions.headerFlag) {
+ firstRow.zipWithIndex.map { case (value, index) =>
+ if (value == null || value.isEmpty || value == csvOptions.nullValue) s"_c$index" else value
+ }
+ } else {
+ firstRow.zipWithIndex.map { case (value, index) => s"_c$index" }
+ }
+
+ val parsedRdd = tokenRdd(sparkSession, csvOptions, header, paths)
+ val schema = if (csvOptions.inferSchemaFlag) {
+ CSVInferSchema.infer(parsedRdd, header, csvOptions)
+ } else {
+ // By default fields are assumed to be StringType
+ val schemaFields = header.map { fieldName =>
+ StructField(fieldName.toString, StringType, nullable = true)
+ }
+ StructType(schemaFields)
+ }
+ Some(schema)
+ }
+
+ override def prepareWrite(
+ sparkSession: SparkSession,
+ job: Job,
+ options: Map[String, String],
+ dataSchema: StructType): OutputWriterFactory = {
+ verifySchema(dataSchema)
+ val conf = job.getConfiguration
+ val csvOptions = new CSVOptions(options)
+ csvOptions.compressionCodec.foreach { codec =>
+ CompressionCodecs.setCodecConfiguration(conf, codec)
+ }
+
+ new CSVOutputWriterFactory(csvOptions)
+ }
+
+ override def buildReader(
+ sparkSession: SparkSession,
+ dataSchema: StructType,
+ partitionSchema: StructType,
+ requiredSchema: StructType,
+ filters: Seq[Filter],
+ options: Map[String, String],
+ hadoopConf: Configuration): (PartitionedFile) => Iterator[InternalRow] = {
+ val csvOptions = new CSVOptions(options)
+ val headers = requiredSchema.fields.map(_.name)
+
+ val broadcastedHadoopConf =
+ sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf))
+
+ (file: PartitionedFile) => {
+ val lineIterator = {
+ val conf = broadcastedHadoopConf.value.value
+ new HadoopFileLinesReader(file, conf).map { line =>
+ new String(line.getBytes, 0, line.getLength, csvOptions.charset)
+ }
+ }
+
+ CSVRelation.dropHeaderLine(file, lineIterator, csvOptions)
+
+ val tokenizedIterator = new BulkCsvReader(lineIterator, csvOptions, headers)
+ val parser = CSVRelation.csvParser(dataSchema, requiredSchema.fieldNames, csvOptions)
+ tokenizedIterator.flatMap(parser(_).toSeq)
+ }
+ }
+
+ private def baseRdd(
+ sparkSession: SparkSession,
+ options: CSVOptions,
+ inputPaths: Seq[String]): RDD[String] = {
+ readText(sparkSession, options, inputPaths.mkString(","))
+ }
+
+ private def tokenRdd(
+ sparkSession: SparkSession,
+ options: CSVOptions,
+ header: Array[String],
+ inputPaths: Seq[String]): RDD[Array[String]] = {
+ val rdd = baseRdd(sparkSession, options, inputPaths)
+ // Make sure firstLine is materialized before sending to executors
+ val firstLine = if (options.headerFlag) findFirstLine(options, rdd) else null
+ CSVRelation.univocityTokenizer(rdd, header, firstLine, options)
+ }
+
+ /**
+ * Returns the first line of the first non-empty file in path
+ */
+ private def findFirstLine(options: CSVOptions, rdd: RDD[String]): String = {
+ if (options.isCommentSet) {
+ val comment = options.comment.toString
+ rdd.filter { line =>
+ line.trim.nonEmpty && !line.startsWith(comment)
+ }.first()
+ } else {
+ rdd.filter { line =>
+ line.trim.nonEmpty
+ }.first()
+ }
+ }
+
+ private def readText(
+ sparkSession: SparkSession,
+ options: CSVOptions,
+ location: String): RDD[String] = {
+ if (Charset.forName(options.charset) == StandardCharsets.UTF_8) {
+ sparkSession.sparkContext.textFile(location)
+ } else {
+ val charset = options.charset
+ sparkSession.sparkContext
+ .hadoopFile[LongWritable, Text, TextInputFormat](location)
+ .mapPartitions(_.map(pair => new String(pair._2.getBytes, 0, pair._2.getLength, charset)))
+ }
+ }
+
+ private def verifySchema(schema: StructType): Unit = {
+ schema.foreach { field =>
+ field.dataType match {
+ case _: ArrayType | _: MapType | _: StructType =>
+ throw new UnsupportedOperationException(
+ s"CSV data source does not support ${field.dataType.simpleString} data type.")
+ case _ =>
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/csv/DefaultSource.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/csv/DefaultSource.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/csv/DefaultSource.scala
deleted file mode 100644
index 057bde1..0000000
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/csv/DefaultSource.scala
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * 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.execution.datasources.csv
-
-import java.nio.charset.{Charset, StandardCharsets}
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.FileStatus
-import org.apache.hadoop.io.{LongWritable, Text}
-import org.apache.hadoop.mapred.TextInputFormat
-import org.apache.hadoop.mapreduce._
-
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.SparkSession
-import org.apache.spark.sql.catalyst.InternalRow
-import org.apache.spark.sql.catalyst.expressions.JoinedRow
-import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
-import org.apache.spark.sql.execution.datasources._
-import org.apache.spark.sql.sources._
-import org.apache.spark.sql.types._
-import org.apache.spark.util.SerializableConfiguration
-
-/**
- * Provides access to CSV data from pure SQL statements.
- */
-class DefaultSource extends FileFormat with DataSourceRegister {
-
- override def shortName(): String = "csv"
-
- override def toString: String = "CSV"
-
- override def hashCode(): Int = getClass.hashCode()
-
- override def equals(other: Any): Boolean = other.isInstanceOf[DefaultSource]
-
- override def inferSchema(
- sparkSession: SparkSession,
- options: Map[String, String],
- files: Seq[FileStatus]): Option[StructType] = {
- val csvOptions = new CSVOptions(options)
-
- // TODO: Move filtering.
- val paths = files.filterNot(_.getPath.getName startsWith "_").map(_.getPath.toString)
- val rdd = baseRdd(sparkSession, csvOptions, paths)
- val firstLine = findFirstLine(csvOptions, rdd)
- val firstRow = new LineCsvReader(csvOptions).parseLine(firstLine)
-
- val header = if (csvOptions.headerFlag) {
- firstRow.zipWithIndex.map { case (value, index) =>
- if (value == null || value.isEmpty || value == csvOptions.nullValue) s"_c$index" else value
- }
- } else {
- firstRow.zipWithIndex.map { case (value, index) => s"_c$index" }
- }
-
- val parsedRdd = tokenRdd(sparkSession, csvOptions, header, paths)
- val schema = if (csvOptions.inferSchemaFlag) {
- CSVInferSchema.infer(parsedRdd, header, csvOptions)
- } else {
- // By default fields are assumed to be StringType
- val schemaFields = header.map { fieldName =>
- StructField(fieldName.toString, StringType, nullable = true)
- }
- StructType(schemaFields)
- }
- Some(schema)
- }
-
- override def prepareWrite(
- sparkSession: SparkSession,
- job: Job,
- options: Map[String, String],
- dataSchema: StructType): OutputWriterFactory = {
- verifySchema(dataSchema)
- val conf = job.getConfiguration
- val csvOptions = new CSVOptions(options)
- csvOptions.compressionCodec.foreach { codec =>
- CompressionCodecs.setCodecConfiguration(conf, codec)
- }
-
- new CSVOutputWriterFactory(csvOptions)
- }
-
- override def buildReader(
- sparkSession: SparkSession,
- dataSchema: StructType,
- partitionSchema: StructType,
- requiredSchema: StructType,
- filters: Seq[Filter],
- options: Map[String, String],
- hadoopConf: Configuration): (PartitionedFile) => Iterator[InternalRow] = {
- val csvOptions = new CSVOptions(options)
- val headers = requiredSchema.fields.map(_.name)
-
- val broadcastedHadoopConf =
- sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf))
-
- (file: PartitionedFile) => {
- val lineIterator = {
- val conf = broadcastedHadoopConf.value.value
- new HadoopFileLinesReader(file, conf).map { line =>
- new String(line.getBytes, 0, line.getLength, csvOptions.charset)
- }
- }
-
- CSVRelation.dropHeaderLine(file, lineIterator, csvOptions)
-
- val tokenizedIterator = new BulkCsvReader(lineIterator, csvOptions, headers)
- val parser = CSVRelation.csvParser(dataSchema, requiredSchema.fieldNames, csvOptions)
- tokenizedIterator.flatMap(parser(_).toSeq)
- }
- }
-
- private def baseRdd(
- sparkSession: SparkSession,
- options: CSVOptions,
- inputPaths: Seq[String]): RDD[String] = {
- readText(sparkSession, options, inputPaths.mkString(","))
- }
-
- private def tokenRdd(
- sparkSession: SparkSession,
- options: CSVOptions,
- header: Array[String],
- inputPaths: Seq[String]): RDD[Array[String]] = {
- val rdd = baseRdd(sparkSession, options, inputPaths)
- // Make sure firstLine is materialized before sending to executors
- val firstLine = if (options.headerFlag) findFirstLine(options, rdd) else null
- CSVRelation.univocityTokenizer(rdd, header, firstLine, options)
- }
-
- /**
- * Returns the first line of the first non-empty file in path
- */
- private def findFirstLine(options: CSVOptions, rdd: RDD[String]): String = {
- if (options.isCommentSet) {
- val comment = options.comment.toString
- rdd.filter { line =>
- line.trim.nonEmpty && !line.startsWith(comment)
- }.first()
- } else {
- rdd.filter { line =>
- line.trim.nonEmpty
- }.first()
- }
- }
-
- private def readText(
- sparkSession: SparkSession,
- options: CSVOptions,
- location: String): RDD[String] = {
- if (Charset.forName(options.charset) == StandardCharsets.UTF_8) {
- sparkSession.sparkContext.textFile(location)
- } else {
- val charset = options.charset
- sparkSession.sparkContext
- .hadoopFile[LongWritable, Text, TextInputFormat](location)
- .mapPartitions(_.map(pair => new String(pair._2.getBytes, 0, pair._2.getLength, charset)))
- }
- }
-
- private def verifySchema(schema: StructType): Unit = {
- schema.foreach { field =>
- field.dataType match {
- case _: ArrayType | _: MapType | _: StructType =>
- throw new UnsupportedOperationException(
- s"CSV data source does not support ${field.dataType.simpleString} data type.")
- case _ =>
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/DefaultSource.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/DefaultSource.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/DefaultSource.scala
deleted file mode 100644
index 6609e5d..0000000
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/DefaultSource.scala
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.execution.datasources.jdbc
-
-import java.util.Properties
-
-import org.apache.spark.sql.SQLContext
-import org.apache.spark.sql.sources.{BaseRelation, DataSourceRegister, RelationProvider}
-
-class DefaultSource extends RelationProvider with DataSourceRegister {
-
- override def shortName(): String = "jdbc"
-
- /** Returns a new base relation with the given parameters. */
- override def createRelation(
- sqlContext: SQLContext,
- parameters: Map[String, String]): BaseRelation = {
- val jdbcOptions = new JDBCOptions(parameters)
- if (jdbcOptions.partitionColumn != null
- && (jdbcOptions.lowerBound == null
- || jdbcOptions.upperBound == null
- || jdbcOptions.numPartitions == null)) {
- sys.error("Partitioning incompletely specified")
- }
-
- val partitionInfo = if (jdbcOptions.partitionColumn == null) {
- null
- } else {
- JDBCPartitioningInfo(
- jdbcOptions.partitionColumn,
- jdbcOptions.lowerBound.toLong,
- jdbcOptions.upperBound.toLong,
- jdbcOptions.numPartitions.toInt)
- }
- val parts = JDBCRelation.columnPartition(partitionInfo)
- val properties = new Properties() // Additional properties that we will pass to getConnection
- parameters.foreach(kv => properties.setProperty(kv._1, kv._2))
- JDBCRelation(jdbcOptions.url, jdbcOptions.table, parts, properties)(sqlContext.sparkSession)
- }
-}
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcRelationProvider.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcRelationProvider.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcRelationProvider.scala
new file mode 100644
index 0000000..106ed1d
--- /dev/null
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcRelationProvider.scala
@@ -0,0 +1,55 @@
+/*
+ * 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.execution.datasources.jdbc
+
+import java.util.Properties
+
+import org.apache.spark.sql.SQLContext
+import org.apache.spark.sql.sources.{BaseRelation, DataSourceRegister, RelationProvider}
+
+class JdbcRelationProvider extends RelationProvider with DataSourceRegister {
+
+ override def shortName(): String = "jdbc"
+
+ /** Returns a new base relation with the given parameters. */
+ override def createRelation(
+ sqlContext: SQLContext,
+ parameters: Map[String, String]): BaseRelation = {
+ val jdbcOptions = new JDBCOptions(parameters)
+ if (jdbcOptions.partitionColumn != null
+ && (jdbcOptions.lowerBound == null
+ || jdbcOptions.upperBound == null
+ || jdbcOptions.numPartitions == null)) {
+ sys.error("Partitioning incompletely specified")
+ }
+
+ val partitionInfo = if (jdbcOptions.partitionColumn == null) {
+ null
+ } else {
+ JDBCPartitioningInfo(
+ jdbcOptions.partitionColumn,
+ jdbcOptions.lowerBound.toLong,
+ jdbcOptions.upperBound.toLong,
+ jdbcOptions.numPartitions.toInt)
+ }
+ val parts = JDBCRelation.columnPartition(partitionInfo)
+ val properties = new Properties() // Additional properties that we will pass to getConnection
+ parameters.foreach(kv => properties.setProperty(kv._1, kv._2))
+ JDBCRelation(jdbcOptions.url, jdbcOptions.table, parts, properties)(sqlContext.sparkSession)
+ }
+}
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/json/JSONRelation.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/json/JSONRelation.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/json/JSONRelation.scala
deleted file mode 100644
index 4c97abe..0000000
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/json/JSONRelation.scala
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * 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.execution.datasources.json
-
-import java.io.CharArrayWriter
-
-import com.fasterxml.jackson.core.JsonFactory
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.{FileStatus, Path}
-import org.apache.hadoop.io.{LongWritable, NullWritable, Text}
-import org.apache.hadoop.mapred.{JobConf, TextInputFormat}
-import org.apache.hadoop.mapreduce.{Job, RecordWriter, TaskAttemptContext}
-import org.apache.hadoop.mapreduce.lib.input.FileInputFormat
-import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat
-
-import org.apache.spark.internal.Logging
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.{AnalysisException, Row, SparkSession}
-import org.apache.spark.sql.catalyst.InternalRow
-import org.apache.spark.sql.catalyst.expressions.JoinedRow
-import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
-import org.apache.spark.sql.execution.datasources._
-import org.apache.spark.sql.sources._
-import org.apache.spark.sql.types.StructType
-import org.apache.spark.util.SerializableConfiguration
-
-class DefaultSource extends FileFormat with DataSourceRegister {
-
- override def shortName(): String = "json"
-
- override def inferSchema(
- sparkSession: SparkSession,
- options: Map[String, String],
- files: Seq[FileStatus]): Option[StructType] = {
- if (files.isEmpty) {
- None
- } else {
- val parsedOptions: JSONOptions = new JSONOptions(options)
- val columnNameOfCorruptRecord =
- parsedOptions.columnNameOfCorruptRecord
- .getOrElse(sparkSession.sessionState.conf.columnNameOfCorruptRecord)
- val jsonFiles = files.filterNot { status =>
- val name = status.getPath.getName
- name.startsWith("_") || name.startsWith(".")
- }.toArray
-
- val jsonSchema = InferSchema.infer(
- createBaseRdd(sparkSession, jsonFiles),
- columnNameOfCorruptRecord,
- parsedOptions)
- checkConstraints(jsonSchema)
-
- Some(jsonSchema)
- }
- }
-
- override def prepareWrite(
- sparkSession: SparkSession,
- job: Job,
- options: Map[String, String],
- dataSchema: StructType): OutputWriterFactory = {
- val conf = job.getConfiguration
- val parsedOptions: JSONOptions = new JSONOptions(options)
- parsedOptions.compressionCodec.foreach { codec =>
- CompressionCodecs.setCodecConfiguration(conf, codec)
- }
-
- new OutputWriterFactory {
- override def newInstance(
- path: String,
- bucketId: Option[Int],
- dataSchema: StructType,
- context: TaskAttemptContext): OutputWriter = {
- new JsonOutputWriter(path, bucketId, dataSchema, context)
- }
- }
- }
-
- override def buildReader(
- sparkSession: SparkSession,
- dataSchema: StructType,
- partitionSchema: StructType,
- requiredSchema: StructType,
- filters: Seq[Filter],
- options: Map[String, String],
- hadoopConf: Configuration): PartitionedFile => Iterator[InternalRow] = {
- val broadcastedHadoopConf =
- sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf))
-
- val parsedOptions: JSONOptions = new JSONOptions(options)
- val columnNameOfCorruptRecord = parsedOptions.columnNameOfCorruptRecord
- .getOrElse(sparkSession.sessionState.conf.columnNameOfCorruptRecord)
-
- (file: PartitionedFile) => {
- val lines = new HadoopFileLinesReader(file, broadcastedHadoopConf.value.value).map(_.toString)
-
- JacksonParser.parseJson(
- lines,
- requiredSchema,
- columnNameOfCorruptRecord,
- parsedOptions)
- }
- }
-
- private def createBaseRdd(
- sparkSession: SparkSession,
- inputPaths: Seq[FileStatus]): RDD[String] = {
- val job = Job.getInstance(sparkSession.sessionState.newHadoopConf())
- val conf = job.getConfiguration
-
- val paths = inputPaths.map(_.getPath)
-
- if (paths.nonEmpty) {
- FileInputFormat.setInputPaths(job, paths: _*)
- }
-
- sparkSession.sparkContext.hadoopRDD(
- conf.asInstanceOf[JobConf],
- classOf[TextInputFormat],
- classOf[LongWritable],
- classOf[Text]).map(_._2.toString) // get the text line
- }
-
- /** Constraints to be imposed on schema to be stored. */
- private def checkConstraints(schema: StructType): Unit = {
- if (schema.fieldNames.length != schema.fieldNames.distinct.length) {
- val duplicateColumns = schema.fieldNames.groupBy(identity).collect {
- case (x, ys) if ys.length > 1 => "\"" + x + "\""
- }.mkString(", ")
- throw new AnalysisException(s"Duplicate column(s) : $duplicateColumns found, " +
- s"cannot save to JSON format")
- }
- }
-
- override def toString: String = "JSON"
-
- override def hashCode(): Int = getClass.hashCode()
-
- override def equals(other: Any): Boolean = other.isInstanceOf[DefaultSource]
-}
-
-private[json] class JsonOutputWriter(
- path: String,
- bucketId: Option[Int],
- dataSchema: StructType,
- context: TaskAttemptContext)
- extends OutputWriter with Logging {
-
- private[this] val writer = new CharArrayWriter()
- // create the Generator without separator inserted between 2 records
- private[this] val gen = new JsonFactory().createGenerator(writer).setRootValueSeparator(null)
- private[this] val result = new Text()
-
- private val recordWriter: RecordWriter[NullWritable, Text] = {
- new TextOutputFormat[NullWritable, Text]() {
- override def getDefaultWorkFile(context: TaskAttemptContext, extension: String): Path = {
- val configuration = context.getConfiguration
- val uniqueWriteJobId = configuration.get("spark.sql.sources.writeJobUUID")
- val taskAttemptId = context.getTaskAttemptID
- val split = taskAttemptId.getTaskID.getId
- val bucketString = bucketId.map(BucketingUtils.bucketIdToString).getOrElse("")
- new Path(path, f"part-r-$split%05d-$uniqueWriteJobId$bucketString.json$extension")
- }
- }.getRecordWriter(context)
- }
-
- override def write(row: Row): Unit = throw new UnsupportedOperationException("call writeInternal")
-
- override protected[sql] def writeInternal(row: InternalRow): Unit = {
- JacksonGenerator(dataSchema, gen)(row)
- gen.flush()
-
- result.set(writer.toString)
- writer.reset()
-
- recordWriter.write(NullWritable.get(), result)
- }
-
- override def close(): Unit = {
- gen.close()
- recordWriter.close(context)
- }
-}
http://git-wip-us.apache.org/repos/asf/spark/blob/361ebc28/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/json/JsonFileFormat.scala
----------------------------------------------------------------------
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/json/JsonFileFormat.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/json/JsonFileFormat.scala
new file mode 100644
index 0000000..35f2476
--- /dev/null
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/json/JsonFileFormat.scala
@@ -0,0 +1,198 @@
+/*
+ * 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.execution.datasources.json
+
+import java.io.CharArrayWriter
+
+import com.fasterxml.jackson.core.JsonFactory
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{FileStatus, Path}
+import org.apache.hadoop.io.{LongWritable, NullWritable, Text}
+import org.apache.hadoop.mapred.{JobConf, TextInputFormat}
+import org.apache.hadoop.mapreduce.{Job, RecordWriter, TaskAttemptContext}
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat
+import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{AnalysisException, Row, SparkSession}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.JoinedRow
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.datasources._
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.util.SerializableConfiguration
+
+class JsonFileFormat extends FileFormat with DataSourceRegister {
+
+ override def shortName(): String = "json"
+
+ override def inferSchema(
+ sparkSession: SparkSession,
+ options: Map[String, String],
+ files: Seq[FileStatus]): Option[StructType] = {
+ if (files.isEmpty) {
+ None
+ } else {
+ val parsedOptions: JSONOptions = new JSONOptions(options)
+ val columnNameOfCorruptRecord =
+ parsedOptions.columnNameOfCorruptRecord
+ .getOrElse(sparkSession.sessionState.conf.columnNameOfCorruptRecord)
+ val jsonFiles = files.filterNot { status =>
+ val name = status.getPath.getName
+ name.startsWith("_") || name.startsWith(".")
+ }.toArray
+
+ val jsonSchema = InferSchema.infer(
+ createBaseRdd(sparkSession, jsonFiles),
+ columnNameOfCorruptRecord,
+ parsedOptions)
+ checkConstraints(jsonSchema)
+
+ Some(jsonSchema)
+ }
+ }
+
+ override def prepareWrite(
+ sparkSession: SparkSession,
+ job: Job,
+ options: Map[String, String],
+ dataSchema: StructType): OutputWriterFactory = {
+ val conf = job.getConfiguration
+ val parsedOptions: JSONOptions = new JSONOptions(options)
+ parsedOptions.compressionCodec.foreach { codec =>
+ CompressionCodecs.setCodecConfiguration(conf, codec)
+ }
+
+ new OutputWriterFactory {
+ override def newInstance(
+ path: String,
+ bucketId: Option[Int],
+ dataSchema: StructType,
+ context: TaskAttemptContext): OutputWriter = {
+ new JsonOutputWriter(path, bucketId, dataSchema, context)
+ }
+ }
+ }
+
+ override def buildReader(
+ sparkSession: SparkSession,
+ dataSchema: StructType,
+ partitionSchema: StructType,
+ requiredSchema: StructType,
+ filters: Seq[Filter],
+ options: Map[String, String],
+ hadoopConf: Configuration): PartitionedFile => Iterator[InternalRow] = {
+ val broadcastedHadoopConf =
+ sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf))
+
+ val parsedOptions: JSONOptions = new JSONOptions(options)
+ val columnNameOfCorruptRecord = parsedOptions.columnNameOfCorruptRecord
+ .getOrElse(sparkSession.sessionState.conf.columnNameOfCorruptRecord)
+
+ (file: PartitionedFile) => {
+ val lines = new HadoopFileLinesReader(file, broadcastedHadoopConf.value.value).map(_.toString)
+
+ JacksonParser.parseJson(
+ lines,
+ requiredSchema,
+ columnNameOfCorruptRecord,
+ parsedOptions)
+ }
+ }
+
+ private def createBaseRdd(
+ sparkSession: SparkSession,
+ inputPaths: Seq[FileStatus]): RDD[String] = {
+ val job = Job.getInstance(sparkSession.sessionState.newHadoopConf())
+ val conf = job.getConfiguration
+
+ val paths = inputPaths.map(_.getPath)
+
+ if (paths.nonEmpty) {
+ FileInputFormat.setInputPaths(job, paths: _*)
+ }
+
+ sparkSession.sparkContext.hadoopRDD(
+ conf.asInstanceOf[JobConf],
+ classOf[TextInputFormat],
+ classOf[LongWritable],
+ classOf[Text]).map(_._2.toString) // get the text line
+ }
+
+ /** Constraints to be imposed on schema to be stored. */
+ private def checkConstraints(schema: StructType): Unit = {
+ if (schema.fieldNames.length != schema.fieldNames.distinct.length) {
+ val duplicateColumns = schema.fieldNames.groupBy(identity).collect {
+ case (x, ys) if ys.length > 1 => "\"" + x + "\""
+ }.mkString(", ")
+ throw new AnalysisException(s"Duplicate column(s) : $duplicateColumns found, " +
+ s"cannot save to JSON format")
+ }
+ }
+
+ override def toString: String = "JSON"
+
+ override def hashCode(): Int = getClass.hashCode()
+
+ override def equals(other: Any): Boolean = other.isInstanceOf[JsonFileFormat]
+}
+
+private[json] class JsonOutputWriter(
+ path: String,
+ bucketId: Option[Int],
+ dataSchema: StructType,
+ context: TaskAttemptContext)
+ extends OutputWriter with Logging {
+
+ private[this] val writer = new CharArrayWriter()
+ // create the Generator without separator inserted between 2 records
+ private[this] val gen = new JsonFactory().createGenerator(writer).setRootValueSeparator(null)
+ private[this] val result = new Text()
+
+ private val recordWriter: RecordWriter[NullWritable, Text] = {
+ new TextOutputFormat[NullWritable, Text]() {
+ override def getDefaultWorkFile(context: TaskAttemptContext, extension: String): Path = {
+ val configuration = context.getConfiguration
+ val uniqueWriteJobId = configuration.get("spark.sql.sources.writeJobUUID")
+ val taskAttemptId = context.getTaskAttemptID
+ val split = taskAttemptId.getTaskID.getId
+ val bucketString = bucketId.map(BucketingUtils.bucketIdToString).getOrElse("")
+ new Path(path, f"part-r-$split%05d-$uniqueWriteJobId$bucketString.json$extension")
+ }
+ }.getRecordWriter(context)
+ }
+
+ override def write(row: Row): Unit = throw new UnsupportedOperationException("call writeInternal")
+
+ override protected[sql] def writeInternal(row: InternalRow): Unit = {
+ JacksonGenerator(dataSchema, gen)(row)
+ gen.flush()
+
+ result.set(writer.toString)
+ writer.reset()
+
+ recordWriter.write(NullWritable.get(), result)
+ }
+
+ override def close(): Unit = {
+ gen.close()
+ recordWriter.close(context)
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org