diff --git a/parquet-protobuf/README.md b/parquet-protobuf/README.md index 34981065f7..831fcd25d2 100644 --- a/parquet-protobuf/README.md +++ b/parquet-protobuf/README.md @@ -22,6 +22,16 @@ parquet-protobuf Protocol Buffer support for Parquet columnar format. +## Unwrapping wrapper messages + +With `parquet.proto.unwrapProtoWrappers` set, wrapper messages such as `google.protobuf.Timestamp`, +`google.type.Date`, `google.protobuf.*Value` and `google.type.TimeOfDay` are stored as the +primitive value they carry instead of a nested group, annotated with the matching logical type. +Unwrapped `Timestamp` columns use microsecond (`parquet.proto.timestampUnit=MICROS`) or +millisecond (`MILLIS`) resolution when a reader or platform cannot consume nanosecond timestamps, +for example Iceberg v2 clients. The default stays `NANOS`. Values are truncated toward negative +infinity to the configured unit, so the stored value never lands after the original instant. + ## Message fields stored as proto bytes Two kinds of message fields cannot be mapped to a Parquet group, so `ProtoSchemaConverter` diff --git a/parquet-protobuf/src/main/java/org/apache/parquet/proto/ProtoSchemaConverter.java b/parquet-protobuf/src/main/java/org/apache/parquet/proto/ProtoSchemaConverter.java index f62bc525ad..1372cf7c40 100644 --- a/parquet-protobuf/src/main/java/org/apache/parquet/proto/ProtoSchemaConverter.java +++ b/parquet-protobuf/src/main/java/org/apache/parquet/proto/ProtoSchemaConverter.java @@ -94,6 +94,7 @@ public class ProtoSchemaConverter { private final boolean parquetSpecsCompliant; private final boolean unwrapProtoWrappers; + private final TimeUnit timestampUnit; // TODO: use proto custom options to override per field. private final int maxRecursion; @@ -138,7 +139,8 @@ public ProtoSchemaConverter(ParquetConfiguration config) { this( config.getBoolean(ProtoWriteSupport.PB_SPECS_COMPLIANT_WRITE, false), config.getInt(PB_MAX_RECURSION, 5), - config.getBoolean(ProtoWriteSupport.PB_UNWRAP_PROTO_WRAPPERS, false)); + config.getBoolean(ProtoWriteSupport.PB_UNWRAP_PROTO_WRAPPERS, false), + ProtoWriteSupport.parseTimestampUnit(config.get(ProtoWriteSupport.PB_TIMESTAMP_UNIT))); } /** @@ -169,9 +171,29 @@ public ProtoSchemaConverter(boolean parquetSpecsCompliant, int maxRecursion) { * except oneof members, which remain optional because only one can be set. */ public ProtoSchemaConverter(boolean parquetSpecsCompliant, int maxRecursion, boolean unwrapProtoWrappers) { + this(parquetSpecsCompliant, maxRecursion, unwrapProtoWrappers, TimeUnit.NANOS); + } + + /** + * Instantiate a schema converter with an explicit precision for unwrapped {@link Timestamp} fields. + * + * @param parquetSpecsCompliant If set to false, the parquet schema generated will be using the old + * schema style (prior to PARQUET-968) to provide backward-compatibility + * but which does not use LIST and MAP wrappers around collections as required + * by the parquet specifications. If set to true, specs compliant schemas are used. + * @param maxRecursion The maximum recursion depth messages are allowed to go before terminating as + * bytes instead of their actual schema. + * @param unwrapProtoWrappers If set to true, unwrap common Proto wrappers like Timestamp and DoubleValue + * with corresponding OPTIONAL logical annotations. Primitive types become REQUIRED, + * except oneof members, which remain optional because only one can be set. + * @param timestampUnit Logical type unit of unwrapped Timestamp columns. + */ + public ProtoSchemaConverter( + boolean parquetSpecsCompliant, int maxRecursion, boolean unwrapProtoWrappers, TimeUnit timestampUnit) { this.parquetSpecsCompliant = parquetSpecsCompliant; this.maxRecursion = maxRecursion; this.unwrapProtoWrappers = unwrapProtoWrappers; + this.timestampUnit = timestampUnit; } /** @@ -247,7 +269,7 @@ private Builder>, GroupBuilder> addF if (unwrapProtoWrappers) { Descriptor messageType = descriptor.getMessageType(); if (messageType.equals(Timestamp.getDescriptor())) { - return builder.primitive(INT64, getRepetition(descriptor)).as(timestampType(true, TimeUnit.NANOS)); + return builder.primitive(INT64, getRepetition(descriptor)).as(timestampType(true, timestampUnit)); } if (messageType.equals(Date.getDescriptor())) { return builder.primitive(INT32, getRepetition(descriptor)).as(dateType()); diff --git a/parquet-protobuf/src/main/java/org/apache/parquet/proto/ProtoWriteSupport.java b/parquet-protobuf/src/main/java/org/apache/parquet/proto/ProtoWriteSupport.java index c6109468f4..02a0a9bea8 100644 --- a/parquet-protobuf/src/main/java/org/apache/parquet/proto/ProtoWriteSupport.java +++ b/parquet-protobuf/src/main/java/org/apache/parquet/proto/ProtoWriteSupport.java @@ -22,6 +22,7 @@ import static org.apache.parquet.proto.ProtoConstants.METADATA_ENUM_ITEM_SEPARATOR; import static org.apache.parquet.proto.ProtoConstants.METADATA_ENUM_KEY_VALUE_SEPARATOR; import static org.apache.parquet.proto.ProtoConstants.METADATA_ENUM_PREFIX; +import static org.apache.parquet.schema.LogicalTypeAnnotation.TimeUnit; import com.google.protobuf.BoolValue; import com.google.protobuf.ByteString; @@ -49,6 +50,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import org.apache.hadoop.conf.Configuration; @@ -83,8 +85,12 @@ public class ProtoWriteSupport extends WriteSupport< public static final String PB_UNWRAP_PROTO_WRAPPERS = "parquet.proto.unwrapProtoWrappers"; + /** Precision used for unwrapped {@code google.protobuf.Timestamp} columns; defaults to {@code NANOS}. */ + public static final String PB_TIMESTAMP_UNIT = "parquet.proto.timestampUnit"; + private boolean writeSpecsCompliant = false; private boolean unwrapProtoWrappers = false; + private TimeUnit timestampUnit = TimeUnit.NANOS; private RecordConsumer recordConsumer; private Class protoMessage; private Descriptor descriptor; @@ -127,6 +133,16 @@ public static void setUnwrapProtoWrappers(Configuration configuration, boolean u configuration.setBoolean(PB_UNWRAP_PROTO_WRAPPERS, unwrapProtoWrappers); } + /** + * Sets the precision used when unwrapping {@link Timestamp} fields. Ignored unless unwrapping is enabled. + * + * @param configuration The hadoop configuration + * @param unit Logical type unit of the unwrapped column, defaults to {@link TimeUnit#NANOS} + */ + public static void setTimestampUnit(Configuration configuration, TimeUnit unit) { + configuration.set(PB_TIMESTAMP_UNIT, unit.name()); + } + /** * Writes Protocol buffer to parquet file. * @@ -179,6 +195,7 @@ public WriteContext init(ParquetConfiguration configuration) { } unwrapProtoWrappers = configuration.getBoolean(PB_UNWRAP_PROTO_WRAPPERS, unwrapProtoWrappers); + timestampUnit = parseTimestampUnit(configuration.get(PB_TIMESTAMP_UNIT)); writeSpecsCompliant = configuration.getBoolean(PB_SPECS_COMPLIANT_WRITE, writeSpecsCompliant); MessageType rootSchema = new ProtoSchemaConverter(configuration).convert(descriptor); validatedMapping(descriptor, rootSchema); @@ -188,6 +205,10 @@ public WriteContext init(ParquetConfiguration configuration) { extraMetaData.put(ProtoReadSupport.PB_DESCRIPTOR, descriptor.toProto().toString()); extraMetaData.put(PB_SPECS_COMPLIANT_WRITE, String.valueOf(writeSpecsCompliant)); extraMetaData.put(PB_UNWRAP_PROTO_WRAPPERS, String.valueOf(unwrapProtoWrappers)); + // The schema carries the unwrapped precision, so only record the key when it was configured. + if (configuration.get(PB_TIMESTAMP_UNIT) != null) { + extraMetaData.put(PB_TIMESTAMP_UNIT, configuration.get(PB_TIMESTAMP_UNIT)); + } return new WriteContext(rootSchema, extraMetaData); } @@ -222,6 +243,37 @@ private Map enumMetadata() { return enumMetadata; } + /** + * Converts a protobuf timestamp to the epoch value of the given logical type unit, truncating the + * sub-unit part. Truncation rather than rounding keeps the value monotonic and matches what a reader + * recovers, since the low-order digits are below the column's resolution. + */ + static long toTimestampUnit(Timestamp timestamp, TimeUnit unit) { + long nanos = Timestamps.toNanos(timestamp); + switch (unit) { + case MILLIS: + return Math.floorDiv(nanos, 1_000_000L); + case MICROS: + return Math.floorDiv(nanos, 1_000L); + case NANOS: + default: + return nanos; + } + } + + /** Parses the configured unit; an unset value means {@link TimeUnit#NANOS}. */ + static TimeUnit parseTimestampUnit(String value) { + if (value == null || value.trim().isEmpty()) { + return TimeUnit.NANOS; + } + try { + return TimeUnit.valueOf(value.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + throw new BadConfigurationException( + "Unknown " + PB_TIMESTAMP_UNIT + " value: " + value + ". Expected one of MILLIS, MICROS, NANOS."); + } + } + class FieldWriter { String fieldName; int index = -1; @@ -708,7 +760,7 @@ class TimestampWriter extends FieldWriter { @Override void writeRawValue(Object value) { Timestamp timestamp = (Timestamp) value; - recordConsumer.addLong(Timestamps.toNanos(timestamp)); + recordConsumer.addLong(toTimestampUnit(timestamp, timestampUnit)); } } diff --git a/parquet-protobuf/src/test/java/org/apache/parquet/proto/ProtoSchemaConverterTest.java b/parquet-protobuf/src/test/java/org/apache/parquet/proto/ProtoSchemaConverterTest.java index f4ac8c81e6..62e46b4796 100644 --- a/parquet-protobuf/src/test/java/org/apache/parquet/proto/ProtoSchemaConverterTest.java +++ b/parquet-protobuf/src/test/java/org/apache/parquet/proto/ProtoSchemaConverterTest.java @@ -18,12 +18,15 @@ */ package org.apache.parquet.proto; +import static org.apache.parquet.schema.LogicalTypeAnnotation.TimeUnit; +import static org.apache.parquet.schema.LogicalTypeAnnotation.timestampType; import static org.assertj.core.api.Assertions.assertThat; import com.google.common.base.Joiner; import com.google.protobuf.Message; import com.google.protobuf.Struct; import com.google.protobuf.Value; +import org.apache.hadoop.conf.Configuration; import org.apache.parquet.proto.test.TestProto3; import org.apache.parquet.proto.test.TestProtobuf; import org.apache.parquet.proto.test.Trees; @@ -393,6 +396,57 @@ public void testProto3ConvertDateTimeMessageUnwrapped() throws Exception { testConversion(TestProto3.DateTimeMessage.class, expectedSchema, false, true); } + @Test + public void testProto3ConvertTimestampUnwrappedWithMicros() throws Exception { + String expectedSchema = + "message TestProto3.DateTimeMessage {\n" + " optional int64 timestamp (TIMESTAMP(MICROS,true)) = 1;\n" + + " optional int32 date (DATE) = 2;\n" + + " optional int64 time (TIME(NANOS,true)) = 3;\n" + + "}"; + + testConversion( + TestProto3.DateTimeMessage.class, + expectedSchema, + new ProtoSchemaConverter(false, 5, true, TimeUnit.MICROS)); + } + + @Test + public void testProto3ConvertTimestampUnwrappedWithMillis() throws Exception { + String expectedSchema = + "message TestProto3.DateTimeMessage {\n" + " optional int64 timestamp (TIMESTAMP(MILLIS,true)) = 1;\n" + + " optional int32 date (DATE) = 2;\n" + + " optional int64 time (TIME(NANOS,true)) = 3;\n" + + "}"; + + testConversion( + TestProto3.DateTimeMessage.class, + expectedSchema, + new ProtoSchemaConverter(false, 5, true, TimeUnit.MILLIS)); + } + + @Test + public void testTimestampUnitIsReadFromConfiguration() { + Configuration conf = new Configuration(); + ProtoWriteSupport.setUnwrapProtoWrappers(conf, true); + ProtoWriteSupport.setTimestampUnit(conf, TimeUnit.MICROS); + + MessageType schema = new ProtoSchemaConverter(conf).convert(TestProto3.DateTimeMessage.class); + + assertThat(schema.getType("timestamp").getLogicalTypeAnnotation()) + .isEqualTo(timestampType(true, TimeUnit.MICROS)); + } + + @Test + public void testTimestampUnitDefaultsToNanos() { + Configuration conf = new Configuration(); + ProtoWriteSupport.setUnwrapProtoWrappers(conf, true); + + MessageType schema = new ProtoSchemaConverter(conf).convert(TestProto3.DateTimeMessage.class); + + assertThat(schema.getType("timestamp").getLogicalTypeAnnotation()) + .isEqualTo(timestampType(true, TimeUnit.NANOS)); + } + @Test public void testProto3ConvertOneOf() { String expectedSchema = JOINER.join( diff --git a/parquet-protobuf/src/test/java/org/apache/parquet/proto/ProtoWriteSupportTest.java b/parquet-protobuf/src/test/java/org/apache/parquet/proto/ProtoWriteSupportTest.java index 77f96c6b5d..b31c92f423 100644 --- a/parquet-protobuf/src/test/java/org/apache/parquet/proto/ProtoWriteSupportTest.java +++ b/parquet-protobuf/src/test/java/org/apache/parquet/proto/ProtoWriteSupportTest.java @@ -18,6 +18,7 @@ */ package org.apache.parquet.proto; +import static org.apache.parquet.schema.LogicalTypeAnnotation.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.data.Offset.offset; @@ -30,6 +31,7 @@ import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; +import org.apache.parquet.hadoop.BadConfigurationException; import org.apache.parquet.hadoop.ParquetWriter; import org.apache.parquet.io.api.Binary; import org.apache.parquet.io.api.RecordConsumer; @@ -1333,6 +1335,108 @@ public void testProto3DateTimeMessageRoundTrip() throws Exception { assertThat(gotBackFirst.getTime()).isEqualTo(protoTime); } + @Test + public void testTimestampUnwrappedWithMicrosRoundTrip(@TempDir java.nio.file.Path tempDir) throws Exception { + Timestamp timestamp = Timestamps.parse("2021-05-02T15:04:03.748123456Z"); + + Path tmpFilePath = new Path(tempDir.resolve("timestamp-micros.parquet").toUri()); + try (ParquetWriter writer = ProtoParquetWriter.builder(tmpFilePath) + .withMessage(TestProto3.DateTimeMessage.class) + .config(ProtoWriteSupport.PB_UNWRAP_PROTO_WRAPPERS, "true") + .config(ProtoWriteSupport.PB_TIMESTAMP_UNIT, TimeUnit.MICROS.name()) + .withValidation(true) + .build()) { + writer.write(TestProto3.DateTimeMessage.newBuilder() + .setTimestamp(timestamp) + .build()); + } + + List gotBack = + TestUtils.readMessages(tmpFilePath, TestProto3.DateTimeMessage.class); + + assertThat(gotBack).hasSize(1); + // Micros resolution drops the sub-microsecond digits of the original timestamp. + assertThat(Timestamps.toMicros(gotBack.get(0).getTimestamp())).isEqualTo(Timestamps.toMicros(timestamp)); + } + + @Test + public void testTimestampUnwrappedWithMillisRoundTrip(@TempDir java.nio.file.Path tempDir) throws Exception { + Timestamp timestamp = Timestamps.parse("2021-05-02T15:04:03.748123456Z"); + + Path tmpFilePath = new Path(tempDir.resolve("timestamp-millis.parquet").toUri()); + try (ParquetWriter writer = ProtoParquetWriter.builder(tmpFilePath) + .withMessage(TestProto3.DateTimeMessage.class) + .config(ProtoWriteSupport.PB_UNWRAP_PROTO_WRAPPERS, "true") + .config(ProtoWriteSupport.PB_TIMESTAMP_UNIT, TimeUnit.MILLIS.name()) + .withValidation(true) + .build()) { + writer.write(TestProto3.DateTimeMessage.newBuilder() + .setTimestamp(timestamp) + .build()); + } + + List gotBack = + TestUtils.readMessages(tmpFilePath, TestProto3.DateTimeMessage.class); + + assertThat(gotBack).hasSize(1); + assertThat(Timestamps.toMillis(gotBack.get(0).getTimestamp())).isEqualTo(Timestamps.toMillis(timestamp)); + } + + @Test + public void testTimestampUnwrappedWithMillisWritesMillisEpoch() throws Exception { + Timestamp timestamp = Timestamps.parse("2021-05-02T15:04:03.748Z"); + RecordConsumer readConsumerMock = Mockito.mock(RecordConsumer.class); + Configuration conf = new Configuration(); + ProtoWriteSupport.setUnwrapProtoWrappers(conf, true); + ProtoWriteSupport.setTimestampUnit(conf, TimeUnit.MILLIS); + ProtoWriteSupport instance = + createReadConsumerInstance(TestProto3.DateTimeMessage.class, readConsumerMock, conf); + + instance.write( + TestProto3.DateTimeMessage.newBuilder().setTimestamp(timestamp).build()); + + InOrder inOrder = Mockito.inOrder(readConsumerMock); + inOrder.verify(readConsumerMock).startMessage(); + inOrder.verify(readConsumerMock).startField("timestamp", 0); + inOrder.verify(readConsumerMock).addLong(Timestamps.toMillis(timestamp)); + inOrder.verify(readConsumerMock).endField("timestamp", 0); + } + + @Test + public void testTimestampWriterTruncatesTowardNegativeInfinity() { + // Timestamps before the epoch must floor, not round toward zero, so the stored value stays a + // lower bound of the original instant. + Timestamp oneNanoBeforeEpoch = + Timestamp.newBuilder().setSeconds(-1).setNanos(999_999_999).build(); + + assertThat(ProtoWriteSupport.toTimestampUnit(oneNanoBeforeEpoch, TimeUnit.MILLIS)) + .isEqualTo(-1L); + assertThat(ProtoWriteSupport.toTimestampUnit(oneNanoBeforeEpoch, TimeUnit.MICROS)) + .isEqualTo(-1L); + } + + @Test + public void testTimestampUnitRejectsUnknownValue() { + Configuration conf = new Configuration(); + conf.set(ProtoWriteSupport.PB_TIMESTAMP_UNIT, "SECONDS"); + + ProtoWriteSupport instance = new ProtoWriteSupport<>(); + ProtoWriteSupport.setSchema(conf, TestProto3.DateTimeMessage.class); + + assertThatThrownBy(() -> instance.init(conf)) + .isInstanceOf(BadConfigurationException.class) + .hasMessageContaining(ProtoWriteSupport.PB_TIMESTAMP_UNIT) + .hasMessageContaining("SECONDS"); + } + + @Test + public void testTimestampUnitIsCaseInsensitive() { + assertThat(ProtoWriteSupport.parseTimestampUnit("micros")).isEqualTo(TimeUnit.MICROS); + assertThat(ProtoWriteSupport.parseTimestampUnit(" MILLIS ")).isEqualTo(TimeUnit.MILLIS); + assertThat(ProtoWriteSupport.parseTimestampUnit(null)).isEqualTo(TimeUnit.NANOS); + assertThat(ProtoWriteSupport.parseTimestampUnit("")).isEqualTo(TimeUnit.NANOS); + } + @Test public void testProto3WrappedMessageUnwrapped() throws Exception { RecordConsumer readConsumerMock = Mockito.mock(RecordConsumer.class);