dejankrak-db commented on code in PR #60741:
URL: https://github.com/apache/spark/pull/60741#discussion_r4644820746
##########
sql/core/src/main/java/org/apache/spark/sql/execution/vectorized/WritableColumnVector.java:
##########
@@ -802,7 +803,7 @@ public final int appendStruct(boolean isNull) {
putNull(elementsAppended);
elementsAppended++;
for (WritableColumnVector c: childColumns) {
- if (c.type instanceof StructType || c.type instanceof VariantType
+ if (isStruct(c.type) || c.type instanceof VariantType
Review Comment:
Done: the vector computes `isStruct` once in its constructor and the
null-struct append and the append assertions read the field, so appending makes
no Types Framework call.
##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/types/ops/FileTypeApiOps.scala:
##########
@@ -0,0 +1,107 @@
+/*
+ * 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.catalyst.types.ops
+
+import java.io.StringWriter
+
+import com.fasterxml.jackson.core.JsonFactory
+
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.FileRefEncoder
+import org.apache.spark.sql.types.{DataType, FileRef, FileRefInternals,
FileType}
+
+/**
+ * Client-side (spark-api) operations for FileType.
+ *
+ * This class implements TypeApiOps methods for the FILE data type:
+ * - String formatting: the canonical JSON of a value (see
[[FileTypeApiOps.formatJson]])
+ * - Row encoding: FileRefEncoder for [[FileRef]]
+ * - Hive and Row JSON formatting of a FileRef
+ *
+ * RELATIONSHIP TO FileTypeOps: FileTypeOps (in catalyst package) extends this
class to inherit
+ * client-side operations while adding server-side operations (physical type,
literals, etc.).
+ *
+ * @param ft
+ * The FileType with its mode
+ * @since 4.4.0
+ */
+class FileTypeApiOps(val ft: FileType) extends TypeApiOps {
+
+ override def dataType: DataType = ft
+
+ // ==================== String Formatting ====================
+
+ // FileTypeOps overrides this for the internal InternalRow value, as
InternalRow is not
+ // available in sql/api. A FileRef is formatted the same way.
+ override def format(v: Any): String = v match {
+ case f: FileRef => FileTypeApiOps.formatJson(f)
+ case _ => v.toString
+ }
+
+ // FILE has no literal syntax, so this is for display only, such as in
EXPLAIN output.
Review Comment:
Done: `Literal.toString` renders a FILE as its canonical JSON (EXPLAIN) and
`Literal.sql` as the `FILE {...}` form of `toSQLValue` (generated column names,
error messages). The previous fallback, the row's `toString`, did not parse
either, as FILE has no literal syntax. Tests in `FileTypeOpsSuite` and
`FileTypeDatasetSuite`.
##########
sql/api/src/main/java/org/apache/spark/sql/types/FileRef.java:
##########
@@ -0,0 +1,159 @@
+/*
+ * 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.types;
+
+import java.io.Serializable;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.StringJoiner;
+
+import javax.annotation.Nullable;
+
+import org.apache.spark.annotation.Unstable;
+
+/**
+ * The external value of the {@link FileType FILE} data type: a reference to a
file, with metadata
+ * describing it. This is what a FILE value is in a {@code Row}, in {@code
collect()} results and
+ * in the arguments and results of JVM UDFs.
+ *
+ * <p>Every field is nullable, as in the Parquet FILE logical type. A
reference names the bytes it
+ * refers to through {@link #uri}, and {@link #offset} and {@link #size}
select the byte range
+ * {@code [offset, offset + size)} of it. The Parquet FILE type also allows
the bytes to be stored
+ * inline in the value. Spark keeps those inline bytes internal: a FileRef
carries them, so that a
Review Comment:
Done: the FileRef Javadoc and the note on `FileType.FIELDS` now say that
FileRef has no constructor or getter for the inline bytes, and that the
canonical JSON form includes them.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/types/ops/FileTypeOpsSuite.scala:
##########
@@ -0,0 +1,310 @@
+/*
+ * 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.catalyst.types.ops
+
+import org.apache.spark.{SparkException, SparkFunSuite}
+import org.apache.spark.sql.{AnalysisException, Row}
+import org.apache.spark.sql.catalyst.{CatalystTypeConverters,
DeserializerBuildHelper, InternalRow, SerializerBuildHelper}
+import org.apache.spark.sql.catalyst.encoders.{ExpressionEncoder, RowEncoder}
+import
org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{FileRefEncoder,
OptionEncoder}
+import org.apache.spark.sql.catalyst.expressions._
+import
org.apache.spark.sql.catalyst.expressions.codegen.{GenerateSafeProjection,
GenerateUnsafeProjection}
+import org.apache.spark.sql.catalyst.plans.SQLHelper
+import org.apache.spark.sql.catalyst.types.{DataTypeUtils, PhysicalDataType,
PhysicalStructType}
+import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
+
+case class FileHolder(id: Int, file: FileRef, maybe: Option[FileRef], files:
Seq[FileRef])
+
+/**
+ * Tests for FileType in the Types Framework: its physical representation, the
conversions
+ * between [[FileRef]] and InternalRow, the row and code generation paths,
formatting and the
+ * FileRef encoder.
+ */
+class FileTypeOpsSuite extends SparkFunSuite with SQLHelper {
+
+ private val allFields = FileRefInternals.create(
+ "s3://bucket/dir/doc.pdf", 10L, 2048L, "application/pdf", "MD5:abc123",
Array[Byte](1, 2, 3))
+
+ private val uriOnly = new FileRef("/data/a.txt", null, null, null, null)
+
+ private def fileRow(
+ uri: String,
+ offset: java.lang.Long = null,
+ size: java.lang.Long = null,
+ contentType: String = null,
+ checksum: String = null,
+ inline: Array[Byte] = null): InternalRow = new
GenericInternalRow(Array[Any](
+ UTF8String.fromString(uri), offset, size,
UTF8String.fromString(contentType),
+ UTF8String.fromString(checksum), inline))
+
+ private def assertFileRow(row: InternalRow, expected: FileRef): Unit = {
+ assert(FileTypeOps.toFileRef(row) === expected)
+ }
+
+ // ==================== Physical Type Representation ====================
+
+ test("FileType has a struct physical type and row representation") {
+ Seq(FileType(), FileType.external).foreach { ft =>
+ val ops = TypeOps(ft).get
+ assert(ops.isInstanceOf[FileTypeOps])
+ assert(PhysicalDataType(ft) === PhysicalStructType(FileType.FIELDS))
+ assert(ops.rowRepresentationType === Some(FileType.asStruct))
+ assert(ops.getElementSize === 8)
+ assert(ops.getJavaClass === classOf[InternalRow])
+ assert(ops.getMutableValue.isInstanceOf[MutableAny])
+ assert(TypeApiOps(ft).get.isInstanceOf[FileTypeApiOps])
+ }
+ assert(TypeOps.rowRepresentationOrSelf(FileType()) === FileType.asStruct)
+ assert(TypeOps.rowRepresentationOrSelf(IntegerType) === IntegerType)
+ }
+
+ test("default literal") {
+ val lit = Literal.default(FileType.external)
+ assert(lit.dataType === FileType.external)
+ assertFileRow(lit.value.asInstanceOf[InternalRow], new FileRef("", null,
null, null, null))
+ }
+
+ test("there is no Java literal") {
+ val e = intercept[SparkException] {
+ FileTypeOps(FileType()).getJavaLiteral(fileRow("/a"))
+ }
+ assert(e.getCondition === "INTERNAL_ERROR")
+ }
+
+ test("literal validation") {
+ Literal.create(fileRow("/a"), FileType())
+ intercept[IllegalArgumentException](Literal.create("/a", FileType()))
+ }
+
+ // ==================== External Type Conversion ====================
+
+ test("FileRef to InternalRow and back keeps every field, including inline") {
+ val ops = FileTypeOps(FileType())
+ Seq(allFields, uriOnly, new FileRef(null, null, 3L, "image/png", null),
+ FileRefInternals.create(null, null, null, null, null,
Array[Byte](7))).foreach { f =>
+ val row = ops.toCatalystImpl(f).asInstanceOf[InternalRow]
+ assert(row.numFields === FileType.FIELDS.length)
+ assert(ops.toScala(row) === f)
+ }
+ val row = ops.toCatalystImpl(allFields).asInstanceOf[InternalRow]
+ assert(row.getUTF8String(FileType.URI_INDEX).toString ===
"s3://bucket/dir/doc.pdf")
+ assert(row.getLong(FileType.OFFSET_INDEX) === 10L)
+ assert(row.getLong(FileType.SIZE_INDEX) === 2048L)
+ assert(row.getUTF8String(FileType.CONTENT_TYPE_INDEX).toString ===
"application/pdf")
+ assert(row.getUTF8String(FileType.CHECKSUM_INDEX).toString ===
"MD5:abc123")
+ assert(row.getBinary(FileType.INLINE_INDEX).toSeq === Seq[Byte](1, 2, 3))
+ val nulls = ops.toCatalystImpl(uriOnly).asInstanceOf[InternalRow]
+ (1 until FileType.FIELDS.length).foreach(i => assert(nulls.isNullAt(i),
s"field $i"))
+ assert(ops.toScala(null) === null)
+ }
+
+ test("CatalystTypeConverters round-trip") {
+ val toCatalyst =
CatalystTypeConverters.createToCatalystConverter(FileType.external)
+ val toScala =
CatalystTypeConverters.createToScalaConverter(FileType.external)
+ assert(toScala(toCatalyst(allFields)) === allFields)
+ assert(toCatalyst(null) === null)
+ val structType = new StructType().add("f", FileType.external)
+ val rowToCatalyst =
CatalystTypeConverters.createToCatalystConverter(structType)
+ val rowToScala = CatalystTypeConverters.createToScalaConverter(structType)
+ assert(rowToScala(rowToCatalyst(Row(allFields))) === Row(allFields))
+ }
+
+ // ==================== Row Access and Code Generation ====================
+
+ test("read through SpecializedGettersReader") {
+ val row = new GenericInternalRow(Array[Any](fileRow("/r.txt", size =
100L)))
+ val value = SpecializedGettersReader.read(row, 0, FileType(), true, false)
+ assertFileRow(value.asInstanceOf[InternalRow], new FileRef("/r.txt", null,
100L, null, null))
+ }
+
+ private val values: Seq[FileRef] = Seq(allFields, uriOnly)
+
+ private def unsafeProjections(dt: DataType): Seq[(String, UnsafeProjection)]
= {
+ val exprs = Seq(BoundReference(0, dt, nullable = true))
+ Seq(
+ "interpreted" -> new InterpretedUnsafeProjection(exprs.toArray),
+ "codegen" -> GenerateUnsafeProjection.generate(exprs))
+ }
+
+ test("unsafe projection of a FILE column, a null value and null fields") {
+ val ops = FileTypeOps(FileType())
+ unsafeProjections(FileType()).foreach { case (mode, projection) =>
+ values.foreach { f =>
+ val out = projection(new
GenericInternalRow(Array[Any](ops.toCatalystImpl(f)))).copy()
+ assert(FileTypeOps.toFileRef(out.getStruct(0, FileType.FIELDS.length))
=== f, mode)
+ }
+ assert(projection(new GenericInternalRow(Array[Any](null))).isNullAt(0),
mode)
+ }
+ }
+
+ test("unsafe projection of an array of FILE, a map with FILE values and a
struct with FILE") {
+ val ops = FileTypeOps(FileType())
+ val elems = values.map(ops.toCatalystImpl) :+ null
+ val arrayType = ArrayType(FileType(), containsNull = true)
+ unsafeProjections(arrayType).foreach { case (mode, projection) =>
+ val out = projection(new GenericInternalRow(Array[Any](new
GenericArrayData(elems))))
+ val array = out.getArray(0)
+ assert(array.numElements() === 3, mode)
+ values.indices.foreach { i =>
+ assert(FileTypeOps.toFileRef(array.getStruct(i,
FileType.FIELDS.length)) === values(i))
+ }
+ assert(array.isNullAt(2), mode)
+ }
+ val mapType = MapType(StringType, FileType(), valueContainsNull = true)
+ unsafeProjections(mapType).foreach { case (mode, projection) =>
+ val map = ArrayBasedMapData(
+ Array[Any](UTF8String.fromString("k1"), UTF8String.fromString("k2")),
+ Array[Any](ops.toCatalystImpl(allFields), null))
+ val out = projection(new GenericInternalRow(Array[Any](map))).getMap(0)
+ assert(FileTypeOps.toFileRef(out.valueArray().getStruct(0,
FileType.FIELDS.length)) ===
+ allFields, mode)
+ assert(out.valueArray().isNullAt(1), mode)
+ }
+ val structType = new StructType().add("id", IntegerType).add("f",
FileType())
+ unsafeProjections(structType).foreach { case (mode, projection) =>
+ val inner = new GenericInternalRow(Array[Any](1,
ops.toCatalystImpl(uriOnly)))
+ val out = projection(new
GenericInternalRow(Array[Any](inner))).getStruct(0, 2)
+ assert(out.getInt(0) === 1, mode)
+ assert(FileTypeOps.toFileRef(out.getStruct(1, FileType.FIELDS.length))
=== uriOnly, mode)
+ }
+ }
+
+ test("safe projection copies a FILE value out of a reused UnsafeRow") {
+ val ops = FileTypeOps(FileType())
+ val producer = UnsafeProjection.create(Array[DataType](FileType()))
+ val input = producer(new
GenericInternalRow(Array[Any](ops.toCatalystImpl(allFields))))
+ val exprs = Seq(BoundReference(0, FileType(), nullable = true))
+ Seq(
+ "interpreted" -> InterpretedSafeProjection.createProjection(exprs),
+ "codegen" -> GenerateSafeProjection.generate(exprs)).foreach { case
(mode, projection) =>
+ val out = projection(input)
+ producer(new GenericInternalRow(Array[Any](ops.toCatalystImpl(uriOnly))))
+ assert(FileTypeOps.toFileRef(out.getStruct(0, FileType.FIELDS.length))
=== allFields, mode)
+ producer(new
GenericInternalRow(Array[Any](ops.toCatalystImpl(allFields))))
+ }
+ }
+
+ // ==================== Formatting ====================
+
+ test("format renders the canonical JSON and omits null fields") {
+ val ops = FileTypeOps(FileType())
+ assert(ops.format(ops.toCatalystImpl(allFields)) ===
+ """{"uri":"s3://bucket/dir/doc.pdf","offset":10,"size":2048,""" +
+
""""content_type":"application/pdf","checksum":"MD5:abc123","inline":"AQID"}""")
+ assert(ops.format(ops.toCatalystImpl(uriOnly)) ===
"""{"uri":"/data/a.txt"}""")
+ assert(ops.format(fileRow("""a "quoted"\path""")) === """{"uri":"a
\"quoted\"\\path"}""")
+ assert(ops.toSQLValue(ops.toCatalystImpl(uriOnly)) === """FILE
{"uri":"/data/a.txt"}""")
+ // The external value renders the same way.
+ assert(new FileTypeApiOps(FileType()).format(allFields) ===
+ ops.format(ops.toCatalystImpl(allFields)))
+ assert(ops.formatExternal(uriOnly) === Some("""{"uri":"/data/a.txt"}"""))
+ }
+
+ test("FileRef equality, hash code and string representation") {
+ val same = FileRefInternals.create(
+ "s3://bucket/dir/doc.pdf", 10L, 2048L, "application/pdf", "MD5:abc123",
Array[Byte](1, 2, 3))
+ assert(allFields === same)
+ assert(allFields.hashCode === same.hashCode)
+ assert(allFields !== FileRefInternals.create(
+ "s3://bucket/dir/doc.pdf", 10L, 2048L, "application/pdf", "MD5:abc123",
Array[Byte](1, 2)))
+ assert(uriOnly !== new FileRef("/data/a.txt", 0L, null, null, null))
Review Comment:
Done: one inequality case per field.
##########
sql/api/src/main/scala/org/apache/spark/sql/types/FileType.scala:
##########
@@ -31,8 +31,8 @@ import org.apache.spark.annotation.Unstable
* `"file unknown"` for `FileType()`, except that an external file in a struct
field is the plain
* `"file"`. A bare `"file"` is read as external inside a struct field and as
unknown elsewhere.
*
- * FileType is planned to be physically stored as a struct with the following
fields (see
- * `FileType.FIELDS`), but it deliberately does not extend [[StructType]]:
+ * FileType is physically stored as a struct with the following fields (see
`FileType.FIELDS`),
+ * but it deliberately does not extend [[StructType]]. Its external value is
[[FileRef]]:
Review Comment:
Done: the field list follows the sentence about the physical struct, and
FileRef is named after it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ToStringBase.scala:
##########
@@ -86,10 +86,16 @@ trait ToStringBase { self: UnaryExpression with
TimeZoneAwareExpression =>
// nanos renders in it; zone-independent types (TimeType, TIMESTAMP_NTZ
nanos) ignore it
// (SPARK-57285).
private def castToString(from: DataType): Any => UTF8String =
- TypeApiOps(from, zoneId)
+ frameworkOps(from)
.map(ops => acceptAny[Any](ops.formatUTF8))
.getOrElse(castToStringDefault(from))
+ // The internal value of a type stored as a struct, such as FileType, is an
InternalRow, which
+ // only its catalyst-side ops can format. Other framework types use their
client-side ops, which
+ // carry the cast's zone.
+ private def frameworkOps(from: DataType): Option[TypeApiOps] =
+
TypeOps(from).filter(_.rowRepresentationType.isDefined).orElse(TypeApiOps(from,
zoneId))
Review Comment:
I'd keep this as is. The base branch already resolves the nested formatter
inside the per-value lambdas (one `TypeApiOps` lookup per nested value); this
adds a `TypeOps` lookup next to it, which is a few class checks and no
allocation for most types. Building the nested formatters outside the lambdas
is a reasonable refactoring of `castToStringDefault`, but it is independent of
FILE and would touch every type's interpreted cast path, so it fits better in a
separate change.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]