This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hudi.git
The following commit(s) were added to refs/heads/master by this push:
new 2b3586c7cf01 fix(spark): write and read byte/short columns as the
table's int (#20760)
2b3586c7cf01 is described below
commit 2b3586c7cf010f6d3fe874e734ca2dc08b3b780d
Author: voonhous <[email protected]>
AuthorDate: Mon Nov 23 23:15:11 2026 +0000
fix(spark): write and read byte/short columns as the table's int (#20760)
bulk_insert's row writer built the Parquet schema from the DataFrame,
so a ShortType column was written as INT32 annotated INT(16) while the
table schema, which has no 8- or 16-bit integer type, records it as
int. ByteType had no writer at all. Write both as plain INT32, as the
other Spark write paths do.
Files with INT(8)/INT(16) columns, written by earlier releases of
bulk_insert and by Flink's bulk_insert and append writers up to 1.2.0
for TINYINT/SMALLINT, stay readable:
- The vectorized read filled a short vector for an int column, since
convertColumnVectorType skipped byte/short, and failed with a
NullPointerException (#9845). Widen byte/short like int/long.
- Column stats failed on the INT(8)/INT(16) annotation and were
skipped. Map signed integer annotations, and unsigned 8/16-bit, to
INT/LONG in both the LogicalType and OriginalType adapters; unsigned
32/64-bit stay unsupported, as they do not order as signed.
Closes #20503
---
.../client/utils/SparkInternalSchemaConverter.java | 52 ++++++++++++------
.../storage/row/HoodieRowParquetWriteSupport.java | 10 ++--
.../metadata/stats/LogicalTypeParquetAdapter.java | 11 ++++
.../metadata/stats/OriginalTypeParquetAdapter.java | 9 ++++
.../apache/hudi/metadata/stats/TestValueType.java | 42 +++++++++++++++
.../hudi/functional/TestSparkParquetReader.java | 48 +++++++++++++++++
.../row/TestHoodieInternalRowParquetWriter.java | 62 ++++++++++++++++++++++
.../org/apache/hudi/util/JavaConversions.scala | 19 ++++++-
8 files changed, 232 insertions(+), 21 deletions(-)
diff --git
a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/utils/SparkInternalSchemaConverter.java
b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/utils/SparkInternalSchemaConverter.java
index 08feb7f38539..3f2acecd9e7e 100644
---
a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/utils/SparkInternalSchemaConverter.java
+++
b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/utils/SparkInternalSchemaConverter.java
@@ -343,31 +343,39 @@ public class SparkInternalSchemaConverter {
}
/**
- * Convert Int/long type to other Type.
- * Now only support int/long -> long/float/double/string/Decimal
+ * Convert byte/short/int/long type to other Type.
+ * Now only support byte/short -> int and byte/short/int/long ->
long/float/double/string/Decimal.
+ * byte/short columns come from parquet files holding INT32 annotated INT(8)
/ INT(16) (written by
+ * Spark's bulk_insert before #20503, and by Flink's bulk_insert and append
writers up to 1.2.0
+ * for TINYINT / SMALLINT), which Spark reads as ByteType / ShortType while
the table schema, which
+ * has no 8- or 16-bit integer type, records the column as int (#20503).
* TODO: support more types
*/
- private static boolean convertIntLongType(WritableColumnVector oldV,
WritableColumnVector newV, DataType newType, int len) {
- boolean isInt = oldV.dataType() instanceof IntegerType;
- if (newType instanceof LongType || newType instanceof FloatType
+ private static boolean convertIntegralType(WritableColumnVector oldV,
WritableColumnVector newV, DataType newType, int len) {
+ DataType oldType = oldV.dataType();
+ boolean isNarrowerThanInt = oldType instanceof ByteType || oldType
instanceof ShortType;
+ if ((newType instanceof IntegerType && isNarrowerThanInt) || newType
instanceof LongType || newType instanceof FloatType
|| newType instanceof DoubleType || newType instanceof StringType ||
newType instanceof DecimalType) {
for (int i = 0; i < len; i++) {
if (oldV.isNullAt(i)) {
newV.putNull(i);
continue;
}
- // int/long -> long/float/double/string/decimal
- if (newType instanceof LongType) {
- newV.putLong(i, isInt ? oldV.getInt(i) : oldV.getLong(i));
+ long value = getIntegralValue(oldV, oldType, i);
+ // byte/short -> int, byte/short/int/long ->
long/float/double/string/decimal
+ if (newType instanceof IntegerType) {
+ newV.putInt(i, (int) value);
+ } else if (newType instanceof LongType) {
+ newV.putLong(i, value);
} else if (newType instanceof FloatType) {
- newV.putFloat(i, isInt ? oldV.getInt(i) : oldV.getLong(i));
+ newV.putFloat(i, value);
} else if (newType instanceof DoubleType) {
- newV.putDouble(i, isInt ? oldV.getInt(i) : oldV.getLong(i));
+ newV.putDouble(i, value);
} else if (newType instanceof StringType) {
- newV.putByteArray(i, getUTF8Bytes((isInt ? oldV.getInt(i) :
oldV.getLong(i)) + ""));
+ newV.putByteArray(i, getUTF8Bytes(value + ""));
} else if (newType instanceof DecimalType) {
DecimalType decimalType = (DecimalType) newType;
- Decimal oldDecimal = Decimal.apply(isInt ? oldV.getInt(i) :
oldV.getLong(i));
+ Decimal oldDecimal = Decimal.apply(value);
putDecimalOrNull(newV, i, oldDecimal, decimalType);
}
}
@@ -376,6 +384,18 @@ public class SparkInternalSchemaConverter {
return false;
}
+ private static long getIntegralValue(WritableColumnVector vector, DataType
type, int rowId) {
+ if (type instanceof ByteType) {
+ return vector.getByte(rowId);
+ } else if (type instanceof ShortType) {
+ return vector.getShort(rowId);
+ } else if (type instanceof IntegerType) {
+ return vector.getInt(rowId);
+ } else {
+ return vector.getLong(rowId);
+ }
+ }
+
/**
* Convert float type to other Type.
* Now only support float -> double/String/Decimal
@@ -516,13 +536,13 @@ public class SparkInternalSchemaConverter {
if (oldType instanceof BooleanType) {
return false;
} else if (oldType instanceof ByteType) {
- return false;
+ return convertIntegralType(oldV, newV, newType, len);
} else if (oldType instanceof ShortType) {
- return false;
+ return convertIntegralType(oldV, newV, newType, len);
} else if (oldType instanceof IntegerType) {
- return convertIntLongType(oldV, newV, newType, len);
+ return convertIntegralType(oldV, newV, newType, len);
} else if (oldType instanceof LongType) {
- return convertIntLongType(oldV, newV, newType, len);
+ return convertIntegralType(oldV, newV, newType, len);
} else if (oldType instanceof FloatType) {
return convertFloatType(oldV, newV, newType, len);
} else if (oldType instanceof DoubleType) {
diff --git
a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowParquetWriteSupport.java
b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowParquetWriteSupport.java
index 587afba3a612..36c98b098d1e 100644
---
a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowParquetWriteSupport.java
+++
b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowParquetWriteSupport.java
@@ -521,6 +521,8 @@ public class HoodieRowParquetWriteSupport extends
WriteSupport<InternalRow> {
return (row, ordinal) ->
recordConsumer.addBoolean(row.getBoolean(ordinal));
} else if (dataType == DataTypes.DateType) {
return (row, ordinal) -> recordConsumer.addInteger((Integer)
dateRebaseFunction.apply(row.getInt(ordinal)));
+ } else if (dataType == DataTypes.ByteType) {
+ return (row, ordinal) -> recordConsumer.addInteger(row.getByte(ordinal));
} else if (dataType == DataTypes.ShortType) {
return (row, ordinal) ->
recordConsumer.addInteger(row.getShort(ordinal));
} else if (dataType == DataTypes.IntegerType || dataType instanceof
YearMonthIntervalType) {
@@ -788,9 +790,11 @@ public class HoodieRowParquetWriteSupport extends
WriteSupport<InternalRow> {
} else if (dataType == DataTypes.DateType) {
return Types.primitive(INT32, repetition)
.as(LogicalTypeAnnotation.dateType()).named(structField.name());
- } else if (dataType == DataTypes.ShortType) {
- return Types.primitive(INT32, repetition)
- .as(LogicalTypeAnnotation.intType(16,
true)).named(structField.name());
+ } else if (dataType == DataTypes.ByteType || dataType ==
DataTypes.ShortType) {
+ // Plain INT32 without an INT(8) / INT(16) annotation: the table schema
has no 8- or 16-bit
+ // integer type and records these columns as int, which is what the
other Spark write paths
+ // write too. An annotated column reads back as ByteType / ShortType
instead of the table's int (#20503).
+ return Types.primitive(INT32, repetition).named(structField.name());
} else if (dataType == DataTypes.IntegerType || dataType instanceof
YearMonthIntervalType) {
return Types.primitive(INT32, repetition).named(structField.name());
} else if (dataType == DataTypes.LongType || dataType instanceof
DayTimeIntervalType) {
diff --git
a/hudi-common/src/main/java/org/apache/hudi/metadata/stats/LogicalTypeParquetAdapter.java
b/hudi-common/src/main/java/org/apache/hudi/metadata/stats/LogicalTypeParquetAdapter.java
index 0a6445ff0492..5cbfadd48c90 100644
---
a/hudi-common/src/main/java/org/apache/hudi/metadata/stats/LogicalTypeParquetAdapter.java
+++
b/hudi-common/src/main/java/org/apache/hudi/metadata/stats/LogicalTypeParquetAdapter.java
@@ -63,6 +63,17 @@ public class LogicalTypeParquetAdapter implements
ParquetAdapter {
}
} else if (annotation instanceof
LogicalTypeAnnotation.UUIDLogicalTypeAnnotation) {
return ValueType.UUID;
+ } else if (annotation instanceof
LogicalTypeAnnotation.IntLogicalTypeAnnotation) {
+ // INT(8) / INT(16) columns are written by Spark (and by the row writer
before #20503) for
+ // byte / short columns, and by Flink's bulk_insert and append writers
up to 1.2.0 for
+ // TINYINT / SMALLINT. Unsigned INT(8) / INT(16) values fit an int and
order the same as
+ // signed; unsigned INT(32) / INT(64) do not, so they stay unsupported.
+ LogicalTypeAnnotation.IntLogicalTypeAnnotation intAnnotation =
(LogicalTypeAnnotation.IntLogicalTypeAnnotation) annotation;
+ if (intAnnotation.isSigned()) {
+ return intAnnotation.getBitWidth() == 64 ? ValueType.LONG :
ValueType.INT;
+ } else if (intAnnotation.getBitWidth() <= 16) {
+ return ValueType.INT;
+ }
}
throw new IllegalArgumentException("Unsupported logical type annotation: "
+ annotation);
diff --git
a/hudi-common/src/main/java/org/apache/hudi/metadata/stats/OriginalTypeParquetAdapter.java
b/hudi-common/src/main/java/org/apache/hudi/metadata/stats/OriginalTypeParquetAdapter.java
index 4d50726ff8d0..7282fcf38b7f 100644
---
a/hudi-common/src/main/java/org/apache/hudi/metadata/stats/OriginalTypeParquetAdapter.java
+++
b/hudi-common/src/main/java/org/apache/hudi/metadata/stats/OriginalTypeParquetAdapter.java
@@ -54,6 +54,15 @@ public class OriginalTypeParquetAdapter implements
ParquetAdapter {
return ValueType.LOCAL_TIMESTAMP_MICROS;
}
return ValueType.TIMESTAMP_MICROS;
+ // Same mapping as LogicalTypeParquetAdapter: unsigned 32/64-bit values
do not order as signed
+ case INT_8:
+ case INT_16:
+ case INT_32:
+ case UINT_8:
+ case UINT_16:
+ return ValueType.INT;
+ case INT_64:
+ return ValueType.LONG;
default:
throw new IllegalArgumentException("Unsupported original type: " +
primitiveType.getOriginalType());
}
diff --git
a/hudi-common/src/test/java/org/apache/hudi/metadata/stats/TestValueType.java
b/hudi-common/src/test/java/org/apache/hudi/metadata/stats/TestValueType.java
index 0cf3d240a6d6..fa57d146c918 100644
---
a/hudi-common/src/test/java/org/apache/hudi/metadata/stats/TestValueType.java
+++
b/hudi-common/src/test/java/org/apache/hudi/metadata/stats/TestValueType.java
@@ -24,6 +24,7 @@ import org.apache.hudi.common.schema.HoodieSchemaType;
import org.apache.avro.generic.GenericData;
import org.apache.parquet.io.api.Binary;
+import org.apache.parquet.schema.LogicalTypeAnnotation;
import org.apache.parquet.schema.PrimitiveType;
import org.apache.parquet.schema.Types;
import org.junit.jupiter.api.Test;
@@ -252,6 +253,47 @@ public class TestValueType {
assertEquals(ValueType.DOUBLE,
valueTypeFor(PrimitiveType.PrimitiveTypeName.DOUBLE));
}
+ @Test
+ public void testFromParquetIntegerAnnotations() {
+ // Spark writes byte / short columns as INT32 annotated INT(8) / INT(16)
(#20503)
+ assertEquals(ValueType.INT,
valueTypeFor(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(8, true)));
+ assertEquals(ValueType.INT,
valueTypeFor(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(16, true)));
+ assertEquals(ValueType.INT,
valueTypeFor(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(32, true)));
+ assertEquals(ValueType.LONG,
valueTypeFor(PrimitiveType.PrimitiveTypeName.INT64,
LogicalTypeAnnotation.intType(64, true)));
+ // Unsigned 8 / 16-bit values fit an int and order as signed; unsigned 32
/ 64-bit ones do not
+ assertEquals(ValueType.INT,
valueTypeFor(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(8, false)));
+ assertEquals(ValueType.INT,
valueTypeFor(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(16, false)));
+ assertThrows(IllegalArgumentException.class,
+ () -> valueTypeFor(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(32, false)));
+ assertThrows(IllegalArgumentException.class,
+ () -> valueTypeFor(PrimitiveType.PrimitiveTypeName.INT64,
LogicalTypeAnnotation.intType(64, false)));
+ }
+
+ @Test
+ public void testOriginalTypeAdapterIntegerAnnotations() {
+ // ValueType picks LogicalTypeParquetAdapter with the current Parquet, so
exercise the pre-1.11
+ // OriginalType path directly; it must map the integer annotations the
same way
+ ParquetAdapter adapter = new OriginalTypeParquetAdapter();
+ assertEquals(ValueType.INT,
adapter.getValueTypeFromAnnotation(primitiveType(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(8, true))));
+ assertEquals(ValueType.INT,
adapter.getValueTypeFromAnnotation(primitiveType(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(16, true))));
+ assertEquals(ValueType.INT,
adapter.getValueTypeFromAnnotation(primitiveType(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(32, true))));
+ assertEquals(ValueType.LONG,
adapter.getValueTypeFromAnnotation(primitiveType(PrimitiveType.PrimitiveTypeName.INT64,
LogicalTypeAnnotation.intType(64, true))));
+ assertEquals(ValueType.INT,
adapter.getValueTypeFromAnnotation(primitiveType(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(8, false))));
+ assertEquals(ValueType.INT,
adapter.getValueTypeFromAnnotation(primitiveType(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(16, false))));
+ assertThrows(IllegalArgumentException.class,
+ () ->
adapter.getValueTypeFromAnnotation(primitiveType(PrimitiveType.PrimitiveTypeName.INT32,
LogicalTypeAnnotation.intType(32, false))));
+ assertThrows(IllegalArgumentException.class,
+ () ->
adapter.getValueTypeFromAnnotation(primitiveType(PrimitiveType.PrimitiveTypeName.INT64,
LogicalTypeAnnotation.intType(64, false))));
+ }
+
+ private static ValueType valueTypeFor(PrimitiveType.PrimitiveTypeName name,
LogicalTypeAnnotation annotation) {
+ return ValueType.fromParquetPrimitiveType(primitiveType(name, annotation));
+ }
+
+ private static PrimitiveType primitiveType(PrimitiveType.PrimitiveTypeName
name, LogicalTypeAnnotation annotation) {
+ return Types.required(name).as(annotation).named("f");
+ }
+
private static ValueType valueTypeFor(PrimitiveType.PrimitiveTypeName name) {
PrimitiveType type = name ==
PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY
? Types.required(name).length(4).named("f")
diff --git
a/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestSparkParquetReader.java
b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestSparkParquetReader.java
index 4b6ce42866fd..7e4f9c9fa367 100644
---
a/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestSparkParquetReader.java
+++
b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestSparkParquetReader.java
@@ -25,9 +25,17 @@ import org.apache.hudi.util.JavaConversions;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
+import org.apache.spark.sql.RowFactory;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.StructType;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.stream.Collectors;
+
import static org.junit.jupiter.api.Assertions.assertEquals;
@Tag("functional")
@@ -46,4 +54,44 @@ public class TestSparkParquetReader extends
TestBootstrapReadBase {
assertEquals(datasourceReadRows.except(parquetReadRows).count(), 0);
assertEquals(parquetReadRows.except(datasourceReadRows).count(), 0);
}
+
+ /**
+ * Base files holding ShortType / ByteType columns as INT32 annotated
INT(16) / INT(8) exist in
+ * tables written by bulk_insert before #20503 (and by Spark's own
ParquetWriteSupport), and by
+ * Flink's bulk_insert and append writers up to 1.2.0 for TINYINT /
SMALLINT, while the table
+ * schema records the columns as int. Reading them with the table schema
must widen the values
+ * on the vectorized path too, not hand an int consumer the file's short
vector.
+ */
+ @Test
+ public void testReadInt16AndInt8ColumnsWithWiderTableSchema() {
+ StructType fileSchema = new StructType()
+ .add("id", DataTypes.IntegerType, false)
+ .add("small", DataTypes.ShortType, true)
+ .add("tiny", DataTypes.ByteType, true)
+ .add("small_as_long", DataTypes.ShortType, true);
+ List<Row> rows = Arrays.asList(
+ RowFactory.create(1, (short) -5, (byte) -7, Short.MIN_VALUE),
+ RowFactory.create(2, (short) 300, Byte.MAX_VALUE, Short.MAX_VALUE),
+ RowFactory.create(3, null, null, null));
+ sparkSession.createDataFrame(rows,
fileSchema).coalesce(1).write().parquet(bootstrapBasePath);
+ // Spark maps INT32 + INT(16) / INT(8) back to ShortType / ByteType, so
this pins that the
+ // file carries the annotations under test
+ assertEquals(fileSchema.fields()[1].dataType(),
sparkSession.read().parquet(bootstrapBasePath).schema().apply("small").dataType());
+ assertEquals(fileSchema.fields()[2].dataType(),
sparkSession.read().parquet(bootstrapBasePath).schema().apply("tiny").dataType());
+
+ StructType tableSchema = new StructType()
+ .add("id", DataTypes.IntegerType, false)
+ .add("small", DataTypes.IntegerType, true)
+ .add("tiny", DataTypes.IntegerType, true)
+ .add("small_as_long", DataTypes.LongType, true);
+ assertEquals("true",
sparkSession.conf().get("spark.sql.parquet.enableVectorizedReader"));
+ List<Row> actual = JavaConversions.createTestDataFrame(sparkSession,
bootstrapBasePath, HoodieFileFormat.PARQUET, tableSchema)
+ .collectAsList().stream()
+ .sorted(Comparator.comparingInt(r -> r.getInt(0)))
+ .collect(Collectors.toList());
+ assertEquals(Arrays.asList(
+ RowFactory.create(1, -5, -7, (long) Short.MIN_VALUE),
+ RowFactory.create(2, 300, (int) Byte.MAX_VALUE, (long)
Short.MAX_VALUE),
+ RowFactory.create(3, null, null, null)), actual);
+ }
}
diff --git
a/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/io/storage/row/TestHoodieInternalRowParquetWriter.java
b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/io/storage/row/TestHoodieInternalRowParquetWriter.java
index 4092ccbd9694..d304086a304b 100644
---
a/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/io/storage/row/TestHoodieInternalRowParquetWriter.java
+++
b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/io/storage/row/TestHoodieInternalRowParquetWriter.java
@@ -18,6 +18,7 @@
package org.apache.hudi.io.storage.row;
+import org.apache.hudi.HoodieSchemaConversionUtils;
import org.apache.hudi.common.avro.HoodieBloomFilterWriteSupport;
import org.apache.hudi.common.bloom.BloomFilter;
import org.apache.hudi.common.bloom.BloomFilterFactory;
@@ -34,6 +35,7 @@ import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
import org.apache.hudi.testutils.SparkDatasetTestUtils;
import org.apache.hadoop.conf.Configuration;
+import org.apache.parquet.column.ColumnDescriptor;
import org.apache.parquet.hadoop.metadata.CompressionCodecName;
import org.apache.parquet.hadoop.metadata.FileMetaData;
import org.apache.parquet.schema.LogicalTypeAnnotation;
@@ -42,20 +44,27 @@ import org.apache.parquet.schema.PrimitiveType;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.catalyst.expressions.GenericInternalRow;
+import org.apache.spark.sql.catalyst.util.ArrayBasedMapData;
+import org.apache.spark.sql.catalyst.util.GenericArrayData;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
+import java.util.Arrays;
+import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -144,6 +153,59 @@ public class TestHoodieInternalRowParquetWriter extends
HoodieSparkClientTestHar
"bytes decimal keeps the precision-minimal FIXED_LEN width (9)");
}
+ /**
+ * Byte and short columns, top level and nested, are written as plain INT32:
the table schema
+ * records them as int (it has no 8- or 16-bit integer type), and so do the
other Spark write paths.
+ */
+ @Test
+ public void testByteAndShortWrittenAsPlainInt32() throws Exception {
+ StructType nested = new StructType()
+ .add("b", DataTypes.ByteType, true)
+ .add("s", DataTypes.ShortType, true);
+ StructType structType = new StructType()
+ .add("b", DataTypes.ByteType, true)
+ .add("s", DataTypes.ShortType, true)
+ .add("st", nested, true)
+ .add("arr", DataTypes.createArrayType(DataTypes.ShortType), true)
+ .add("m", DataTypes.createMapType(DataTypes.StringType,
DataTypes.ByteType), true);
+ HoodieWriteConfig config = HoodieWriteConfig.newBuilder()
+ .withPath(basePath)
+
.withSchema(HoodieSchemaConversionUtils.convertStructTypeToHoodieSchema(structType,
"rec").toString())
+ .build();
+ HoodieRowParquetWriteSupport writeSupport =
HoodieRowParquetWriteSupport.getHoodieRowParquetWriteSupport(
+ storageConf.unwrap(), structType, Option.empty(), config);
+
+ MessageType parquetSchema =
writeSupport.init(writeSupport.getHadoopConf()).getSchema();
+ for (ColumnDescriptor column : parquetSchema.getColumns()) {
+ if (column.getPath()[0].equals("m") &&
column.getPath()[column.getPath().length - 1].equals("key")) {
+ continue;
+ }
+ PrimitiveType type = column.getPrimitiveType();
+ assertEquals(PrimitiveType.PrimitiveTypeName.INT32,
type.getPrimitiveTypeName(), String.join(".", column.getPath()));
+ assertNull(type.getLogicalTypeAnnotation(), String.join(".",
column.getPath()));
+ }
+
+ // Write a row through the byte and short value writers and read it back
as the table's int
+ HoodieParquetConfig<HoodieRowParquetWriteSupport> parquetConfig = new
HoodieParquetConfig<>(writeSupport,
+ CompressionCodecName.SNAPPY, config.getParquetBlockSize(),
config.getParquetPageSize(), config.getParquetMaxFileSize(),
+ new HadoopStorageConfiguration(writeSupport.getHadoopConf()),
config.getParquetCompressionRatio(), config.parquetDictionaryEnabled());
+ StoragePath filePath = new StoragePath(basePath + "/byte_short.parquet");
+ InternalRow row = new GenericInternalRow(new Object[] {(byte) -7, (short)
300,
+ new GenericInternalRow(new Object[] {Byte.MAX_VALUE, Short.MIN_VALUE}),
+ new GenericArrayData(new Object[] {(short) -1, Short.MAX_VALUE}),
+ new ArrayBasedMapData(new GenericArrayData(new Object[]
{UTF8String.fromString("k")}), new GenericArrayData(new Object[]
{Byte.MIN_VALUE}))});
+ try (HoodieInternalRowParquetWriter writer = new
HoodieInternalRowParquetWriter(filePath, parquetConfig)) {
+ writer.writeRow(row);
+ }
+ Row actual =
sqlContext.read().parquet(filePath.toString()).collectAsList().get(0);
+ assertEquals(-7, actual.getInt(0));
+ assertEquals(300, actual.getInt(1));
+ assertEquals(Byte.MAX_VALUE, actual.getStruct(2).getInt(0));
+ assertEquals(Short.MIN_VALUE, actual.getStruct(2).getInt(1));
+ assertEquals(Arrays.asList(-1, (int) Short.MAX_VALUE), actual.getList(3));
+ assertEquals(Collections.singletonMap("k", (int) Byte.MIN_VALUE),
actual.getJavaMap(4));
+ }
+
/**
* hoodie.parquet.outputtimestamptype has had no effect since #13882: the
Parquet timestamp
* unit comes from the writer schema's logical type, not from the config.
Pin both directions
diff --git
a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/util/JavaConversions.scala
b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/util/JavaConversions.scala
index 7aa8d8c073f9..2e56776f6e14 100644
---
a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/util/JavaConversions.scala
+++
b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/util/JavaConversions.scala
@@ -24,6 +24,7 @@ import org.apache.hudi.common.model.HoodieFileFormat
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.apache.spark.sql.execution.datasources.DataSource
import
org.apache.spark.sql.execution.datasources.parquet.TestSparkParquetReaderFormat
+import org.apache.spark.sql.types.StructType
import java.util.function.Predicate
@@ -49,7 +50,20 @@ object JavaConversions extends SparkAdapterSupport {
* @param paths comma separated list of files or directories containing files
* @return dataframe containing the data from the input paths
*/
- def createTestDataFrame(sparkSession: SparkSession, paths: String,
fileFormat: HoodieFileFormat): DataFrame = {
+ def createTestDataFrame(sparkSession: SparkSession, paths: String,
fileFormat: HoodieFileFormat): DataFrame =
+ createTestDataFrame(sparkSession, paths, fileFormat, None)
+
+ /**
+ * Same as the overload above, but reads the files
+ * with the given schema instead of the one inferred from them, the way a
table read asks for
+ * the table schema.
+ */
+ def createTestDataFrame(sparkSession: SparkSession, paths: String,
fileFormat: HoodieFileFormat,
+ schema: StructType): DataFrame =
+ createTestDataFrame(sparkSession, paths, fileFormat, Some(schema))
+
+ private def createTestDataFrame(sparkSession: SparkSession, paths: String,
fileFormat: HoodieFileFormat,
+ schema: Option[StructType]): DataFrame = {
val splitPaths = paths.split(",").toSeq
val className = fileFormat match {
case HoodieFileFormat.PARQUET =>
"org.apache.spark.sql.execution.datasources.parquet.TestSparkParquetReaderFormat"
@@ -61,7 +75,8 @@ object JavaConversions extends SparkAdapterSupport {
sparkSession.sqlContext.baseRelationToDataFrame(DataSource.apply(
sparkSession = sparkSession,
className = className,
- paths = splitPaths
+ paths = splitPaths,
+ userSpecifiedSchema = schema
).resolveRelation())
}
}