dejankrak-db commented on code in PR #60531: URL: https://github.com/apache/spark/pull/60531#discussion_r4620584897
########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/types/ops/StructBackedFrameworkTypeSuite.scala: ########## @@ -0,0 +1,603 @@ +/* + * 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.SparkFunSuite +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext, CodeGenerator, GenerateMutableProjection, GenerateOrdering, GeneratePredicate, GenerateSafeProjection, GenerateUnsafeProjection} +import org.apache.spark.sql.catalyst.expressions.objects.{CatalystToExternalMap, MapObjects, UnresolvedCatalystToExternalMap} +import org.apache.spark.sql.catalyst.types.{PhysicalDataType, PhysicalStructType} +import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData} +import org.apache.spark.sql.types._ +import org.apache.spark.unsafe.types.UTF8String + +/** + * Test-only DataType backed by a struct: its physical type is a PhysicalStructType and its row + * representation is the matching StructType. + * + * This type has 2 fields: name (String, nullable) and value (Long, non-null). + * The internal representation is InternalRow (same as StructType). + */ +case class TestStructBackedType() extends TestableFrameworkType { + override def defaultSize: Int = 20 + override def asNullable: TestStructBackedType = this + override def typeName: String = "test_struct_backed" + override def createTypeOps(): TypeOps = TestStructBackedTypeOps(this) +} + +object TestStructBackedType { + val FIELDS: Array[StructField] = Array( + StructField("name", StringType, nullable = true), + StructField("value", LongType, nullable = false) + ) +} + +/** + * Test-only TypeOps for TestStructBackedType. + * + * The sites that dispatch on the physical type (SpecializedGettersReader, + * InternalRow.getAccessor, InterpretedUnsafeProjection's field writers) handle the type through + * PhysicalStructType(fields). The sites that dispatch on the logical type (the code generation + * helpers, InternalRow.getWriter and InterpretedSafeProjection) handle it through its row + * representation, StructType(fields). + */ +case class TestStructBackedTypeOps(override val dataType: TestStructBackedType) + extends TypeOps { + + override def getPhysicalType: PhysicalDataType = + PhysicalStructType(TestStructBackedType.FIELDS) + + override def getJavaClass: Class[_] = classOf[InternalRow] + + override def getMutableValue: MutableValue = new MutableAny + + override def getRowWriter(ordinal: Int): (InternalRow, Any) => Unit = + (row, v) => row.update(ordinal, v) + + override def getDefaultLiteral: Literal = + Literal.create( + new GenericInternalRow(Array[Any](UTF8String.fromString(""), 0L)), + new TestStructBackedType()) + + override def getJavaLiteral(v: Any): String = v.toString + + override def toCatalystImpl(scalaValue: Any): Any = scalaValue + + override def toScala(catalystValue: Any): Any = catalystValue + + override def toScalaImpl(row: InternalRow, column: Int): Any = + row.getStruct(column, 2) + + // Test type does not exercise client-side ops; stub TypeApiOps members so the trait contract + // is satisfied without pulling in encoder / SQL-literal infrastructure. + override def format(v: Any): String = v.toString + override def toSQLValue(v: Any): String = v.toString + override def getEncoder: AgnosticEncoder[_] = + throw new UnsupportedOperationException("Test type does not provide an encoder") +} + +/** + * A user-defined type stored as TestStructBackedType, to check that the dispatch sites look a + * framework type up again after unwrapping a UDT. + */ +class TestStructBackedUDT extends UserDefinedType[InternalRow] { + override def sqlType: DataType = TestStructBackedType() + override def serialize(obj: InternalRow): Any = obj + override def deserialize(datum: Any): InternalRow = datum.asInstanceOf[InternalRow] + override def userClass: Class[InternalRow] = classOf[InternalRow] +} + +/** + * Suite for a framework type with a struct-backed physical representation, on the interpreted + * and the code generation paths. + * + * The readers and the interpreted unsafe writer reach the type through its physical type + * (PhysicalStructType). The code generation helpers, InternalRow.getWriter and + * InterpretedSafeProjection reach it through its row representation (StructType). + */ +class StructBackedFrameworkTypeSuite extends SparkFunSuite { + + private val testType = TestStructBackedType() + + private def makeStructRow(name: String, value: Long): GenericInternalRow = { + new GenericInternalRow(Array[Any]( + if (name != null) UTF8String.fromString(name) else null, + value + )) + } + + // ==================== Physical Type Resolution ==================== + + test("PhysicalDataType resolves to PhysicalStructType for struct-backed framework type") { + val physType = PhysicalDataType(testType) + assert(physType.isInstanceOf[PhysicalStructType]) + val st = physType.asInstanceOf[PhysicalStructType] + assert(st.fields.length === 2) + assert(st.fields(0).dataType === StringType) + assert(st.fields(1).dataType === LongType) + } + + // ==================== Interpreted Path ==================== + + test("interpreted read: SpecializedGettersReader reads struct for framework type") { + val struct = makeStructRow("hello", 42L) + val row: SpecializedGetters = new GenericInternalRow(Array[Any](struct)) + + val handleNull = true + val handleUserDefinedType = false + val result = SpecializedGettersReader.read(row, 0, testType, handleNull, handleUserDefinedType) + assert(result.isInstanceOf[InternalRow]) + val resultRow = result.asInstanceOf[InternalRow] + assert(resultRow.getUTF8String(0).toString === "hello") + assert(resultRow.getLong(1) === 42L) + } + + test("interpreted read: SpecializedGettersReader returns null for null column") { + val row: SpecializedGetters = new GenericInternalRow(Array[Any](null)) + + val handleNull = true + val handleUserDefinedType = false + val result = SpecializedGettersReader.read(row, 0, testType, handleNull, handleUserDefinedType) + assert(result === null) + } + + test("interpreted read: InternalRow.getAccessor dispatches through PhysicalStructType") { + val struct = makeStructRow("accessor", 7L) + val row = new GenericInternalRow(Array[Any](struct)) + + val accessor = InternalRow.getAccessor(testType) + val result = accessor(row, 0) + assert(result.isInstanceOf[InternalRow]) + val resultRow = result.asInstanceOf[InternalRow] + assert(resultRow.getUTF8String(0).toString === "accessor") + assert(resultRow.getLong(1) === 7L) + } + + test("interpreted write: InterpretedUnsafeProjection round-trips struct") { + val struct = makeStructRow("test", 123L) + val inputRow = new GenericInternalRow(Array[Any](struct)) + + val exprs: Array[Expression] = Array( + BoundReference(0, testType, nullable = true): Expression) + val projection = new InterpretedUnsafeProjection(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val result = unsafeRow.getStruct(0, 2) + assert(result.getUTF8String(0).toString === "test") + assert(result.getLong(1) === 123L) + } + + test("interpreted write: InterpretedUnsafeProjection handles null column") { + val inputRow = new GenericInternalRow(Array[Any](null)) + + val exprs: Array[Expression] = Array( + BoundReference(0, testType, nullable = true): Expression) + val projection = new InterpretedUnsafeProjection(exprs) + val unsafeRow = projection.apply(inputRow) + + assert(unsafeRow.isNullAt(0)) + } + + // ==================== Codegen Path ==================== + + test("codegen write: GenerateUnsafeProjection round-trips struct") { + val struct = makeStructRow("codegen", 456L) + val inputRow = new GenericInternalRow(Array[Any](struct)) + + val exprs = Seq(BoundReference(0, testType, nullable = true)) + val projection = GenerateUnsafeProjection.generate(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val result = unsafeRow.getStruct(0, 2) + assert(result.getUTF8String(0).toString === "codegen") + assert(result.getLong(1) === 456L) + } + + test("codegen write: GenerateUnsafeProjection handles null column") { + val inputRow = new GenericInternalRow(Array[Any](null)) + + val exprs = Seq(BoundReference(0, testType, nullable = true)) + val projection = GenerateUnsafeProjection.generate(exprs) + val unsafeRow = projection.apply(inputRow) + + assert(unsafeRow.isNullAt(0)) + } + + test("codegen write: GenerateUnsafeProjection round-trips null struct field") { + val struct = makeStructRow(null, 789L) + val inputRow = new GenericInternalRow(Array[Any](struct)) + + val exprs = Seq(BoundReference(0, testType, nullable = true)) + val projection = GenerateUnsafeProjection.generate(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val result = unsafeRow.getStruct(0, 2) + assert(result.isNullAt(0)) + assert(result.getLong(1) === 789L) + } + + // ==================== Literal Validation ==================== + + test("literal validation accepts InternalRow for struct-backed framework type") { + val struct = makeStructRow("lit", 10L) + // Should not throw - PhysicalStructType validation checks InternalRow + fields + Literal.create(struct, testType) + } + + test("literal validation rejects non-InternalRow for struct-backed framework type") { + intercept[IllegalArgumentException] { + Literal.create("not a row", testType) + } + } + + // ==================== Array Containing Framework Type ==================== + + test("interpreted write: array of framework type round-trips") { + val elem1 = makeStructRow("a", 1L) + val elem2 = makeStructRow("b", 2L) + val arrayData = new GenericArrayData(Array[Any](elem1, elem2)) + val inputRow = new GenericInternalRow(Array[Any](arrayData)) + + val arrayType = ArrayType(testType, containsNull = false) + val exprs: Array[Expression] = Array( + BoundReference(0, arrayType, nullable = false): Expression) + val projection = new InterpretedUnsafeProjection(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val resultArray = unsafeRow.getArray(0) + assert(resultArray.numElements() === 2) + val s0 = resultArray.getStruct(0, 2) + assert(s0.getUTF8String(0).toString === "a") + assert(s0.getLong(1) === 1L) + val s1 = resultArray.getStruct(1, 2) + assert(s1.getUTF8String(0).toString === "b") + assert(s1.getLong(1) === 2L) + } + + test("codegen write: array of framework type round-trips") { + val elem1 = makeStructRow("x", 10L) + val elem2 = makeStructRow("y", 20L) + val arrayData = new GenericArrayData(Array[Any](elem1, elem2)) + val inputRow = new GenericInternalRow(Array[Any](arrayData)) + + val arrayType = ArrayType(testType, containsNull = false) + val exprs = Seq(BoundReference(0, arrayType, nullable = false)) + val projection = GenerateUnsafeProjection.generate(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val resultArray = unsafeRow.getArray(0) + assert(resultArray.numElements() === 2) + val s0 = resultArray.getStruct(0, 2) + assert(s0.getUTF8String(0).toString === "x") + assert(s0.getLong(1) === 10L) + val s1 = resultArray.getStruct(1, 2) + assert(s1.getUTF8String(0).toString === "y") + assert(s1.getLong(1) === 20L) + } + + // ==================== Map Containing Framework Type ==================== + + test("interpreted write: map with framework type values round-trips") { + val key1 = UTF8String.fromString("k1") + val key2 = UTF8String.fromString("k2") + val val1 = makeStructRow("m1", 100L) + val val2 = makeStructRow("m2", 200L) + val mapData = new ArrayBasedMapData( + new GenericArrayData(Array[Any](key1, key2)), + new GenericArrayData(Array[Any](val1, val2))) + val inputRow = new GenericInternalRow(Array[Any](mapData)) + + val mapType = MapType(StringType, testType, valueContainsNull = false) + val exprs: Array[Expression] = Array( + BoundReference(0, mapType, nullable = false): Expression) + val projection = new InterpretedUnsafeProjection(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val resultMap = unsafeRow.getMap(0) + assert(resultMap.numElements() === 2) + val keys = resultMap.keyArray() + val values = resultMap.valueArray() + assert(keys.getUTF8String(0).toString === "k1") + assert(keys.getUTF8String(1).toString === "k2") + val v0 = values.getStruct(0, 2) + assert(v0.getUTF8String(0).toString === "m1") + assert(v0.getLong(1) === 100L) + val v1 = values.getStruct(1, 2) + assert(v1.getUTF8String(0).toString === "m2") + assert(v1.getLong(1) === 200L) + } + + test("codegen write: map with framework type values round-trips") { + val key1 = UTF8String.fromString("k1") + val key2 = UTF8String.fromString("k2") + val val1 = makeStructRow("m1", 100L) + val val2 = makeStructRow("m2", 200L) + val mapData = new ArrayBasedMapData( + new GenericArrayData(Array[Any](key1, key2)), + new GenericArrayData(Array[Any](val1, val2))) + val inputRow = new GenericInternalRow(Array[Any](mapData)) + + val mapType = MapType(StringType, testType, valueContainsNull = false) + val exprs = Seq(BoundReference(0, mapType, nullable = false)) + val projection = GenerateUnsafeProjection.generate(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val resultMap = unsafeRow.getMap(0) + assert(resultMap.numElements() === 2) + val keys = resultMap.keyArray() + val values = resultMap.valueArray() + assert(keys.getUTF8String(0).toString === "k1") + assert(keys.getUTF8String(1).toString === "k2") + val v0 = values.getStruct(0, 2) + assert(v0.getUTF8String(0).toString === "m1") + assert(v0.getLong(1) === 100L) + val v1 = values.getStruct(1, 2) + assert(v1.getUTF8String(0).toString === "m2") + assert(v1.getLong(1) === 200L) + } + + // ==================== Safe Projection ==================== + + test("codegen: GenerateSafeProjection round-trips framework type") { + val struct = makeStructRow("safe", 42L) + val inputRow = new GenericInternalRow(Array[Any](struct)) + + // Create an UnsafeRow first via GenerateUnsafeProjection + val unsafeExprs = Seq(BoundReference(0, testType, nullable = true)) + val unsafeProjection = GenerateUnsafeProjection.generate(unsafeExprs) + val unsafeRow = unsafeProjection.apply(inputRow) + + // Now convert back to safe via GenerateSafeProjection + val safeExprs = Seq(BoundReference(0, testType, nullable = true)) + val safeProjection = GenerateSafeProjection.generate(safeExprs) + val safeRow = safeProjection.apply(unsafeRow) + + // The result should be a safe (non-unsafe) InternalRow with correct values + val result = safeRow.getStruct(0, 2) + assert(!result.isInstanceOf[UnsafeRow]) + assert(result.getUTF8String(0).toString === "safe") + assert(result.getLong(1) === 42L) + } + + test("codegen: GenerateOrdering compares framework type values like structs") { + val ordering = GenerateOrdering.generate( + Seq(SortOrder(BoundReference(0, testType, nullable = true), Ascending))) + def row(name: String, value: Long): InternalRow = + new GenericInternalRow(Array[Any](makeStructRow(name, value))) + assert(ordering.compare(row("a", 1L), row("a", 1L)) === 0) + assert(ordering.compare(row("a", 1L), row("b", 1L)) < 0) + assert(ordering.compare(row("a", 2L), row("a", 1L)) > 0) + } + + test("codegen: GenerateMutableProjection sets framework type values") { + val projection = GenerateMutableProjection.generate( + Seq(BoundReference(0, testType, nullable = true))) + val target = new GenericInternalRow(1) + projection.target(target) + projection(new GenericInternalRow(Array[Any](makeStructRow("mutable", 7L)))) + val result = target.getStruct(0, 2) + assert(result.getUTF8String(0).toString === "mutable") + assert(result.getLong(1) === 7L) + } + + // ==================== Derived Layout ==================== + + test("the row representation and the element size are derived from the physical type") { + assert(TypeOps(testType).get.rowRepresentationType === + Some(StructType(TestStructBackedType.FIELDS))) + assert(TypeOps(TimeType(6)).get.rowRepresentationType.isEmpty) + val types = Seq(TimeType(6), TimestampNTZNanosType(9), TimestampLTZNanosType(9), testType) Review Comment: Done in 804c8d0a456: added array- and map-backed test types, whose nullability flag is a parameter (the map has different key and value types). The suite checks their derived row representations for both flag values, and runs them through the reused-input safe and mutable projections and the unsafe round trip, in both modes. ########## sql/catalyst/src/main/java/org/apache/spark/sql/vectorized/ColumnarRow.java: ########## @@ -40,10 +43,18 @@ public final class ColumnarRow extends InternalRow { private final int numFields; public ColumnarRow(ColumnVector data, int rowId) { - assert (data.dataType() instanceof StructType); this.data = data; this.rowId = rowId; - this.numFields = ((StructType) data.dataType()).size(); + DataType dt = data.dataType(); + if (dt instanceof StructType) { + this.numFields = ((StructType) dt).size(); + } else { + // Struct-backed framework types map to PhysicalStructType but are not StructType. + PhysicalDataType pdt = PhysicalDataType.apply(dt); Review Comment: Done in 804c8d0a456: a test-only column vector that only returns given children holds the struct-backed type over string and long vectors. `ColumnarBatchSuite` reads it through `ColumnVector.getStruct`, `ColumnarBatchRow.get`, and `ColumnarRow.get` as the field of an enclosing struct vector. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala: ########## @@ -3011,9 +3027,11 @@ object CodeGenerator extends Logging { case _ => dataType } - if (sqlDataType.isInstanceOf[StructType]) { - // `ColumnVector.getStruct` is different from `InternalRow.getStruct`, it only takes an - // `ordinal` parameter. + // ColumnVector.getStruct takes a single arg (rowId), unlike InternalRow.getStruct which + // takes two args (ordinal, numFields). Resolve framework types so struct-backed types + // hit the StructType path. + val resolved = TypeOps(sqlDataType).flatMap(_.rowRepresentationType).getOrElse(sqlDataType) Review Comment: Done in 804c8d0a456: a string check that `getValueFromVector` returns the one-argument `getStruct` call for the type and a UDT over it. It fails without the lookup. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/InterpretedSafeProjection.scala: ########## @@ -56,9 +57,21 @@ class InterpretedSafeProjection(expressions: Seq[Expression]) extends Projection (exprs(i), f) } - private def generateSafeValueConverter(dt: DataType): Any => Any = dt match { + // A framework type with a row representation is converted as that representation. + private def generateSafeValueConverter(dt: DataType): Any => Any = + TypeOps(dt).flatMap(_.rowRepresentationType).map(generateSafeValueConverter) + .getOrElse(generateSafeValueConverterDefault(dt)) + + // A nested value (an array element, a struct field, a map key or value) may be null, which the + // array, struct and map converters cannot convert. + private def generateNullSafeValueConverter(dt: DataType): Any => Any = { + val converter = generateSafeValueConverter(dt) + v => if (v == null) null else converter(v) Review Comment: Done in 804c8d0a456: the default arm returns one shared identity converter from the companion object, and the nested-null wrapper leaves it unwrapped, so only the struct, array, map and representation converters get the null check. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/TypeOps.scala: ########## @@ -108,13 +134,69 @@ trait TypeOps extends TypeApiOps { /** * Returns a writer function for setting values in an InternalRow. * + * Not used by InternalRow.getWriter for a type with a [[rowRepresentationType]], which is + * written as that representation. + * * @param ordinal * the column index to write to * @return * writer function (InternalRow, Any) => Unit */ def getRowWriter(ordinal: Int): (InternalRow, Any) => Unit + /** + * Returns the number of bytes this type occupies in the fixed-size region of an + * [[org.apache.spark.sql.catalyst.expressions.UnsafeArrayData UnsafeArrayData]]. + * + * Variable-length types (struct, array, map, binary, string) use 8 bytes because + * the fixed region stores an offset+size pointer into the variable-length region. + * Fixed-size primitive types use their natural size (1 for byte/boolean, 2 for short, + * 4 for int/float, 8 for long/double). + * + * Consumed by [[org.apache.spark.sql.catalyst.expressions.InterpretedUnsafeProjection]] + * when writing arrays or maps that contain framework type elements. Derived from + * [[getPhysicalType]], matching the slot size that code generation uses. + * + * @return + * element size in bytes + */ + def getElementSize: Int = getPhysicalType match { + case PhysicalBooleanType | PhysicalByteType => 1 + case PhysicalShortType => 2 + case PhysicalIntegerType | PhysicalFloatType => 4 + case _ => 8 + } + + /** + * Returns an equivalent built-in DataType for infrastructure dispatch. + * + * Framework types backed by complex physical storage (struct, array, map) return + * the corresponding built-in DataType so that row infrastructure code (codegen, + * projection, comparison, etc.) can handle them through existing code paths via + * self-recursion - no per-physical-type matching needed at call sites. + * + * Primitive-backed types (e.g., TimeType backed by Long) return None because + * existing infrastructure default paths already handle primitives correctly. + * + * This is NOT a type alias - the framework type retains its identity in schemas, + * expressions, proto serialization, and error messages. This is solely a dispatch + * hint for row infrastructure internals. + * + * Derived from [[getPhysicalType]]: PhysicalStructType(fields) is StructType(fields), and + * PhysicalArrayType and PhysicalMapType are the matching ArrayType and MapType. The result is + * always a built-in DataType, never another framework type, as some sites look the + * representation up only once. + * + * @return Some(DataType) for complex-backed types, None for primitive-backed types Review Comment: Done in 804c8d0a456: the doc and `@return` now say that every type other than a struct-, array- or map-backed one returns None and that the logical-type sites then see the type itself, so a primitive-backed type such as TIME uses their primitive handling and any other type, such as the nanosecond timestamp types, needs handling of its own there. ########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/types/ops/StructBackedFrameworkTypeSuite.scala: ########## @@ -0,0 +1,603 @@ +/* + * 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.SparkFunSuite +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext, CodeGenerator, GenerateMutableProjection, GenerateOrdering, GeneratePredicate, GenerateSafeProjection, GenerateUnsafeProjection} +import org.apache.spark.sql.catalyst.expressions.objects.{CatalystToExternalMap, MapObjects, UnresolvedCatalystToExternalMap} +import org.apache.spark.sql.catalyst.types.{PhysicalDataType, PhysicalStructType} +import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData} +import org.apache.spark.sql.types._ +import org.apache.spark.unsafe.types.UTF8String + +/** + * Test-only DataType backed by a struct: its physical type is a PhysicalStructType and its row + * representation is the matching StructType. + * + * This type has 2 fields: name (String, nullable) and value (Long, non-null). + * The internal representation is InternalRow (same as StructType). + */ +case class TestStructBackedType() extends TestableFrameworkType { + override def defaultSize: Int = 20 + override def asNullable: TestStructBackedType = this + override def typeName: String = "test_struct_backed" + override def createTypeOps(): TypeOps = TestStructBackedTypeOps(this) +} + +object TestStructBackedType { + val FIELDS: Array[StructField] = Array( + StructField("name", StringType, nullable = true), + StructField("value", LongType, nullable = false) + ) +} + +/** + * Test-only TypeOps for TestStructBackedType. + * + * The sites that dispatch on the physical type (SpecializedGettersReader, + * InternalRow.getAccessor, InterpretedUnsafeProjection's field writers) handle the type through + * PhysicalStructType(fields). The sites that dispatch on the logical type (the code generation + * helpers, InternalRow.getWriter and InterpretedSafeProjection) handle it through its row + * representation, StructType(fields). + */ +case class TestStructBackedTypeOps(override val dataType: TestStructBackedType) + extends TypeOps { + + override def getPhysicalType: PhysicalDataType = + PhysicalStructType(TestStructBackedType.FIELDS) + + override def getJavaClass: Class[_] = classOf[InternalRow] + + override def getMutableValue: MutableValue = new MutableAny + + override def getRowWriter(ordinal: Int): (InternalRow, Any) => Unit = + (row, v) => row.update(ordinal, v) + + override def getDefaultLiteral: Literal = + Literal.create( + new GenericInternalRow(Array[Any](UTF8String.fromString(""), 0L)), + new TestStructBackedType()) + + override def getJavaLiteral(v: Any): String = v.toString + + override def toCatalystImpl(scalaValue: Any): Any = scalaValue + + override def toScala(catalystValue: Any): Any = catalystValue + + override def toScalaImpl(row: InternalRow, column: Int): Any = + row.getStruct(column, 2) + + // Test type does not exercise client-side ops; stub TypeApiOps members so the trait contract + // is satisfied without pulling in encoder / SQL-literal infrastructure. + override def format(v: Any): String = v.toString + override def toSQLValue(v: Any): String = v.toString + override def getEncoder: AgnosticEncoder[_] = + throw new UnsupportedOperationException("Test type does not provide an encoder") +} + +/** + * A user-defined type stored as TestStructBackedType, to check that the dispatch sites look a + * framework type up again after unwrapping a UDT. + */ +class TestStructBackedUDT extends UserDefinedType[InternalRow] { + override def sqlType: DataType = TestStructBackedType() + override def serialize(obj: InternalRow): Any = obj + override def deserialize(datum: Any): InternalRow = datum.asInstanceOf[InternalRow] + override def userClass: Class[InternalRow] = classOf[InternalRow] +} + +/** + * Suite for a framework type with a struct-backed physical representation, on the interpreted + * and the code generation paths. + * + * The readers and the interpreted unsafe writer reach the type through its physical type + * (PhysicalStructType). The code generation helpers, InternalRow.getWriter and + * InterpretedSafeProjection reach it through its row representation (StructType). + */ +class StructBackedFrameworkTypeSuite extends SparkFunSuite { + + private val testType = TestStructBackedType() + + private def makeStructRow(name: String, value: Long): GenericInternalRow = { + new GenericInternalRow(Array[Any]( + if (name != null) UTF8String.fromString(name) else null, + value + )) + } + + // ==================== Physical Type Resolution ==================== + + test("PhysicalDataType resolves to PhysicalStructType for struct-backed framework type") { + val physType = PhysicalDataType(testType) + assert(physType.isInstanceOf[PhysicalStructType]) + val st = physType.asInstanceOf[PhysicalStructType] + assert(st.fields.length === 2) + assert(st.fields(0).dataType === StringType) + assert(st.fields(1).dataType === LongType) + } + + // ==================== Interpreted Path ==================== + + test("interpreted read: SpecializedGettersReader reads struct for framework type") { + val struct = makeStructRow("hello", 42L) + val row: SpecializedGetters = new GenericInternalRow(Array[Any](struct)) + + val handleNull = true + val handleUserDefinedType = false + val result = SpecializedGettersReader.read(row, 0, testType, handleNull, handleUserDefinedType) + assert(result.isInstanceOf[InternalRow]) + val resultRow = result.asInstanceOf[InternalRow] + assert(resultRow.getUTF8String(0).toString === "hello") + assert(resultRow.getLong(1) === 42L) + } + + test("interpreted read: SpecializedGettersReader returns null for null column") { + val row: SpecializedGetters = new GenericInternalRow(Array[Any](null)) + + val handleNull = true + val handleUserDefinedType = false + val result = SpecializedGettersReader.read(row, 0, testType, handleNull, handleUserDefinedType) + assert(result === null) + } + + test("interpreted read: InternalRow.getAccessor dispatches through PhysicalStructType") { + val struct = makeStructRow("accessor", 7L) + val row = new GenericInternalRow(Array[Any](struct)) + + val accessor = InternalRow.getAccessor(testType) + val result = accessor(row, 0) + assert(result.isInstanceOf[InternalRow]) + val resultRow = result.asInstanceOf[InternalRow] + assert(resultRow.getUTF8String(0).toString === "accessor") + assert(resultRow.getLong(1) === 7L) + } + + test("interpreted write: InterpretedUnsafeProjection round-trips struct") { + val struct = makeStructRow("test", 123L) + val inputRow = new GenericInternalRow(Array[Any](struct)) + + val exprs: Array[Expression] = Array( + BoundReference(0, testType, nullable = true): Expression) + val projection = new InterpretedUnsafeProjection(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val result = unsafeRow.getStruct(0, 2) + assert(result.getUTF8String(0).toString === "test") + assert(result.getLong(1) === 123L) + } + + test("interpreted write: InterpretedUnsafeProjection handles null column") { + val inputRow = new GenericInternalRow(Array[Any](null)) + + val exprs: Array[Expression] = Array( + BoundReference(0, testType, nullable = true): Expression) + val projection = new InterpretedUnsafeProjection(exprs) + val unsafeRow = projection.apply(inputRow) + + assert(unsafeRow.isNullAt(0)) + } + + // ==================== Codegen Path ==================== + + test("codegen write: GenerateUnsafeProjection round-trips struct") { + val struct = makeStructRow("codegen", 456L) + val inputRow = new GenericInternalRow(Array[Any](struct)) + + val exprs = Seq(BoundReference(0, testType, nullable = true)) + val projection = GenerateUnsafeProjection.generate(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val result = unsafeRow.getStruct(0, 2) + assert(result.getUTF8String(0).toString === "codegen") + assert(result.getLong(1) === 456L) + } + + test("codegen write: GenerateUnsafeProjection handles null column") { + val inputRow = new GenericInternalRow(Array[Any](null)) + + val exprs = Seq(BoundReference(0, testType, nullable = true)) + val projection = GenerateUnsafeProjection.generate(exprs) + val unsafeRow = projection.apply(inputRow) + + assert(unsafeRow.isNullAt(0)) + } + + test("codegen write: GenerateUnsafeProjection round-trips null struct field") { + val struct = makeStructRow(null, 789L) + val inputRow = new GenericInternalRow(Array[Any](struct)) + + val exprs = Seq(BoundReference(0, testType, nullable = true)) + val projection = GenerateUnsafeProjection.generate(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val result = unsafeRow.getStruct(0, 2) + assert(result.isNullAt(0)) + assert(result.getLong(1) === 789L) + } + + // ==================== Literal Validation ==================== + + test("literal validation accepts InternalRow for struct-backed framework type") { + val struct = makeStructRow("lit", 10L) + // Should not throw - PhysicalStructType validation checks InternalRow + fields + Literal.create(struct, testType) + } + + test("literal validation rejects non-InternalRow for struct-backed framework type") { + intercept[IllegalArgumentException] { + Literal.create("not a row", testType) + } + } + + // ==================== Array Containing Framework Type ==================== + + test("interpreted write: array of framework type round-trips") { + val elem1 = makeStructRow("a", 1L) + val elem2 = makeStructRow("b", 2L) + val arrayData = new GenericArrayData(Array[Any](elem1, elem2)) + val inputRow = new GenericInternalRow(Array[Any](arrayData)) + + val arrayType = ArrayType(testType, containsNull = false) + val exprs: Array[Expression] = Array( + BoundReference(0, arrayType, nullable = false): Expression) + val projection = new InterpretedUnsafeProjection(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val resultArray = unsafeRow.getArray(0) + assert(resultArray.numElements() === 2) + val s0 = resultArray.getStruct(0, 2) + assert(s0.getUTF8String(0).toString === "a") + assert(s0.getLong(1) === 1L) + val s1 = resultArray.getStruct(1, 2) + assert(s1.getUTF8String(0).toString === "b") + assert(s1.getLong(1) === 2L) + } + + test("codegen write: array of framework type round-trips") { + val elem1 = makeStructRow("x", 10L) + val elem2 = makeStructRow("y", 20L) + val arrayData = new GenericArrayData(Array[Any](elem1, elem2)) + val inputRow = new GenericInternalRow(Array[Any](arrayData)) + + val arrayType = ArrayType(testType, containsNull = false) + val exprs = Seq(BoundReference(0, arrayType, nullable = false)) + val projection = GenerateUnsafeProjection.generate(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val resultArray = unsafeRow.getArray(0) + assert(resultArray.numElements() === 2) + val s0 = resultArray.getStruct(0, 2) + assert(s0.getUTF8String(0).toString === "x") + assert(s0.getLong(1) === 10L) + val s1 = resultArray.getStruct(1, 2) + assert(s1.getUTF8String(0).toString === "y") + assert(s1.getLong(1) === 20L) + } + + // ==================== Map Containing Framework Type ==================== + + test("interpreted write: map with framework type values round-trips") { + val key1 = UTF8String.fromString("k1") + val key2 = UTF8String.fromString("k2") + val val1 = makeStructRow("m1", 100L) + val val2 = makeStructRow("m2", 200L) + val mapData = new ArrayBasedMapData( + new GenericArrayData(Array[Any](key1, key2)), + new GenericArrayData(Array[Any](val1, val2))) + val inputRow = new GenericInternalRow(Array[Any](mapData)) + + val mapType = MapType(StringType, testType, valueContainsNull = false) + val exprs: Array[Expression] = Array( + BoundReference(0, mapType, nullable = false): Expression) + val projection = new InterpretedUnsafeProjection(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val resultMap = unsafeRow.getMap(0) + assert(resultMap.numElements() === 2) + val keys = resultMap.keyArray() + val values = resultMap.valueArray() + assert(keys.getUTF8String(0).toString === "k1") + assert(keys.getUTF8String(1).toString === "k2") + val v0 = values.getStruct(0, 2) + assert(v0.getUTF8String(0).toString === "m1") + assert(v0.getLong(1) === 100L) + val v1 = values.getStruct(1, 2) + assert(v1.getUTF8String(0).toString === "m2") + assert(v1.getLong(1) === 200L) + } + + test("codegen write: map with framework type values round-trips") { + val key1 = UTF8String.fromString("k1") + val key2 = UTF8String.fromString("k2") + val val1 = makeStructRow("m1", 100L) + val val2 = makeStructRow("m2", 200L) + val mapData = new ArrayBasedMapData( + new GenericArrayData(Array[Any](key1, key2)), + new GenericArrayData(Array[Any](val1, val2))) + val inputRow = new GenericInternalRow(Array[Any](mapData)) + + val mapType = MapType(StringType, testType, valueContainsNull = false) + val exprs = Seq(BoundReference(0, mapType, nullable = false)) + val projection = GenerateUnsafeProjection.generate(exprs) + val unsafeRow = projection.apply(inputRow).copy() + + val resultMap = unsafeRow.getMap(0) + assert(resultMap.numElements() === 2) + val keys = resultMap.keyArray() + val values = resultMap.valueArray() + assert(keys.getUTF8String(0).toString === "k1") + assert(keys.getUTF8String(1).toString === "k2") + val v0 = values.getStruct(0, 2) + assert(v0.getUTF8String(0).toString === "m1") + assert(v0.getLong(1) === 100L) + val v1 = values.getStruct(1, 2) + assert(v1.getUTF8String(0).toString === "m2") + assert(v1.getLong(1) === 200L) + } + + // ==================== Safe Projection ==================== Review Comment: Done in 804c8d0a456: the ordering and mutable-projection tests moved under "Other Code Generation Helpers", and the round trips and the nested-null test have their own section. No test body changed. -- 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]
