diff --git a/vector/src/main/codegen/data/ValueVectorTypes.tdd b/vector/src/main/codegen/data/ValueVectorTypes.tdd index ad1f1b93bb..cf3e397afe 100644 --- a/vector/src/main/codegen/data/ValueVectorTypes.tdd +++ b/vector/src/main/codegen/data/ValueVectorTypes.tdd @@ -114,6 +114,22 @@ { class: "TimeNano" } ] }, + { + major: "Fixed", + width: 4, + javaType: "ArrowBuf", + boxedType: "ArrowBuf", + + minor: [ + { + class: "Decimal32", + maxPrecisionDigits: 9, nDecimalDigits: 1, friendlyType: "BigDecimal", + typeParams: [ {name: "scale", type: "int"}, { name: "precision", type: "int"}], + arrowType: "org.apache.arrow.vector.types.pojo.ArrowType.Decimal", + fields: [{name: "start", type: "long"}, {name: "buffer", type: "ArrowBuf"}] + } + ] + }, { major: "Fixed", width: 8, diff --git a/vector/src/main/codegen/templates/UnionReader.java b/vector/src/main/codegen/templates/UnionReader.java index 0edae7ade0..7c4a201072 100644 --- a/vector/src/main/codegen/templates/UnionReader.java +++ b/vector/src/main/codegen/templates/UnionReader.java @@ -39,7 +39,9 @@ @SuppressWarnings("unused") public class UnionReader extends AbstractFieldReader { - private static final int NUM_SUPPORTED_TYPES = 51; + // The reader/type arrays are indexed by MinorType.ordinal(), so they must be sized to the total + // number of minor types (not a hardcoded count, which would break whenever a type is added). + private static final int NUM_SUPPORTED_TYPES = MinorType.values().length; private BaseReader[] readers = new BaseReader[NUM_SUPPORTED_TYPES]; public UnionVector data; diff --git a/vector/src/main/java/org/apache/arrow/vector/Decimal32Vector.java b/vector/src/main/java/org/apache/arrow/vector/Decimal32Vector.java new file mode 100644 index 0000000000..cf25e43d03 --- /dev/null +++ b/vector/src/main/java/org/apache/arrow/vector/Decimal32Vector.java @@ -0,0 +1,520 @@ +/* + * 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.arrow.vector; + +import static org.apache.arrow.vector.NullCheckingForGet.NULL_CHECKING_ENABLED; + +import java.math.BigDecimal; +import java.nio.ByteOrder; +import org.apache.arrow.memory.ArrowBuf; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.util.MemoryUtil; +import org.apache.arrow.vector.complex.impl.Decimal32ReaderImpl; +import org.apache.arrow.vector.complex.reader.FieldReader; +import org.apache.arrow.vector.holders.Decimal32Holder; +import org.apache.arrow.vector.holders.NullableDecimal32Holder; +import org.apache.arrow.vector.types.Types.MinorType; +import org.apache.arrow.vector.types.pojo.ArrowType; +import org.apache.arrow.vector.types.pojo.Field; +import org.apache.arrow.vector.types.pojo.FieldType; +import org.apache.arrow.vector.util.DecimalUtility; +import org.apache.arrow.vector.util.TransferPair; +import org.apache.arrow.vector.validate.ValidateUtil; + +/** + * Decimal32Vector implements a fixed width vector (4 bytes) of decimal values which could be null. + * A validity buffer (bit vector) is maintained to track which elements in the vector are null. + */ +public final class Decimal32Vector extends BaseFixedWidthVector + implements ValueIterableVector { + public static final int MAX_PRECISION = 9; + public static final byte TYPE_WIDTH = 4; + private static final boolean LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN; + + private final int precision; + private final int scale; + + /** + * Instantiate a Decimal32Vector. This doesn't allocate any memory for the data in vector. + * + * @param name name of the vector + * @param allocator allocator for memory management. + */ + public Decimal32Vector(String name, BufferAllocator allocator, int precision, int scale) { + this( + name, + FieldType.nullable(new ArrowType.Decimal(precision, scale, /* bitWidth= */ TYPE_WIDTH * 8)), + allocator); + } + + /** + * Instantiate a Decimal32Vector. This doesn't allocate any memory for the data in vector. + * + * @param name name of the vector + * @param fieldType type of Field materialized by this vector + * @param allocator allocator for memory management. + */ + public Decimal32Vector(String name, FieldType fieldType, BufferAllocator allocator) { + this(new Field(name, fieldType, null), allocator); + } + + /** + * Instantiate a Decimal32Vector. This doesn't allocate any memory for the data in vector. + * + * @param field field materialized by this vector + * @param allocator allocator for memory management. + */ + public Decimal32Vector(Field field, BufferAllocator allocator) { + super(field, allocator, TYPE_WIDTH); + ArrowType.Decimal arrowType = (ArrowType.Decimal) field.getFieldType().getType(); + this.precision = arrowType.getPrecision(); + this.scale = arrowType.getScale(); + } + + @Override + protected FieldReader getReaderImpl() { + return new Decimal32ReaderImpl(Decimal32Vector.this); + } + + /** + * Get minor type for this vector. The vector holds values belonging to a particular type. + * + * @return {@link org.apache.arrow.vector.types.Types.MinorType} + */ + @Override + public MinorType getMinorType() { + return MinorType.DECIMAL32; + } + + /*----------------------------------------------------------------* + | | + | vector value retrieval methods | + | | + *----------------------------------------------------------------*/ + + /** + * Get the element at the given index from the vector. + * + * @param index position of element + * @return element at given index + */ + public ArrowBuf get(int index) throws IllegalStateException { + if (NULL_CHECKING_ENABLED && isSet(index) == 0) { + throw new IllegalStateException("Value at index is null"); + } + return valueBuffer.slice((long) index * TYPE_WIDTH, TYPE_WIDTH); + } + + /** + * Get the element at the given index from the vector and sets the state in holder. If element at + * given index is null, holder.isSet will be zero. + * + * @param index position of element + */ + public void get(int index, NullableDecimal32Holder holder) { + if (isSet(index) == 0) { + holder.isSet = 0; + return; + } + holder.isSet = 1; + holder.buffer = valueBuffer; + holder.precision = precision; + holder.scale = scale; + holder.start = (long) index * TYPE_WIDTH; + } + + /** + * Same as {@link #get(int)}. + * + * @param index position of element + * @return element at given index + */ + @Override + public BigDecimal getObject(int index) { + if (isSet(index) == 0) { + return null; + } else { + return getObjectNotNull(index); + } + } + + /** + * Same as {@link #getObject(int)} but does not check for null. + * + * @param index position of element + * @return element at given index + */ + public BigDecimal getObjectNotNull(int index) { + return DecimalUtility.getBigDecimalFromArrowBuf(valueBuffer, index, scale, TYPE_WIDTH); + } + + /** Return precision for the decimal value. */ + public int getPrecision() { + return precision; + } + + /** Return scale for the decimal value. */ + public int getScale() { + return scale; + } + + /*----------------------------------------------------------------* + | | + | vector value setter methods | + | | + *----------------------------------------------------------------*/ + + /** + * Set the element at the given index to the given value. + * + * @param index position of element + * @param buffer ArrowBuf containing decimal value. + */ + public void set(int index, ArrowBuf buffer) { + BitVectorHelper.setBit(validityBuffer, index); + valueBuffer.setBytes((long) index * TYPE_WIDTH, buffer, 0, TYPE_WIDTH); + } + + /** + * Set the decimal element at given index to the provided array of bytes. Decimal is now + * implemented as Native Endian. This API allows the user to pass a decimal value in the form of + * byte array in BE byte order. + * + *

Consumers of Arrow code can use this API instead of first swapping the source bytes (doing a + * write and read) and then finally writing to ArrowBuf of decimal vector. + * + *

This method takes care of adding the necessary padding if the length of byte array is less + * than 4 (length of decimal type). + * + * @param index position of element + * @param value array of bytes containing decimal in big endian byte order. + */ + public void setBigEndian(int index, byte[] value) { + final int length = value.length; + if (length > TYPE_WIDTH) { + throw new IllegalArgumentException( + "Invalid decimal value length. Valid length in [0 - " + TYPE_WIDTH + "], got " + length); + } + BitVectorHelper.setBit(validityBuffer, index); + + // do the bound check. + valueBuffer.checkBytes((long) index * TYPE_WIDTH, (long) (index + 1) * TYPE_WIDTH); + + long outAddress = valueBuffer.memoryAddress() + (long) index * TYPE_WIDTH; + if (length == 0) { + MemoryUtil.setMemory(outAddress, Decimal32Vector.TYPE_WIDTH, (byte) 0); + return; + } + if (LITTLE_ENDIAN) { + // swap bytes to convert BE to LE + for (int byteIdx = 0; byteIdx < length; ++byteIdx) { + MemoryUtil.putByte(outAddress + byteIdx, value[length - 1 - byteIdx]); + } + if (length < TYPE_WIDTH) { + // sign extend + final byte pad = (byte) (value[0] < 0 ? 0xFF : 0x00); + MemoryUtil.setMemory(outAddress + length, Decimal32Vector.TYPE_WIDTH - length, pad); + } + } else { + // copy data from value to outAddress + MemoryUtil.copyToMemory(value, 0, outAddress + Decimal32Vector.TYPE_WIDTH - length, length); + if (length < TYPE_WIDTH) { + // sign extend + final byte pad = (byte) (value[0] < 0 ? 0xFF : 0x00); + MemoryUtil.setMemory(outAddress, Decimal32Vector.TYPE_WIDTH - length, pad); + } + } + } + + /** + * Set the element at the given index to the given value. + * + * @param index position of element + * @param start start index of data in the buffer + * @param buffer ArrowBuf containing decimal value. + */ + public void set(int index, long start, ArrowBuf buffer) { + BitVectorHelper.setBit(validityBuffer, index); + valueBuffer.setBytes((long) index * TYPE_WIDTH, buffer, start, TYPE_WIDTH); + } + + /** + * Set the element at the given index to the given value. + * + * @param index position of element + * @param value BigDecimal containing decimal value. + */ + public void set(int index, BigDecimal value) { + DecimalUtility.checkPrecisionAndScale(value, precision, scale); + BitVectorHelper.setBit(validityBuffer, index); + DecimalUtility.writeBigDecimalToArrowBuf(value, valueBuffer, index, TYPE_WIDTH); + } + + /** + * Set the element at the given index to the given value. + * + * @param index position of element + * @param value long value. + */ + public void set(int index, long value) { + // write the value first: it range-checks and may throw, and the slot must + // not be marked valid if the write does not happen. + DecimalUtility.writeLongToArrowBuf(value, valueBuffer, index, TYPE_WIDTH); + BitVectorHelper.setBit(validityBuffer, index); + } + + /** + * Set the element at the given index to the value set in data holder. If the value in holder is + * not indicated as set, element in the at the given index will be null. + * + * @param index position of element + * @param holder nullable data holder for value of element + */ + public void set(int index, NullableDecimal32Holder holder) throws IllegalArgumentException { + if (holder.isSet < 0) { + throw new IllegalArgumentException(); + } else if (holder.isSet > 0) { + BitVectorHelper.setBit(validityBuffer, index); + valueBuffer.setBytes((long) index * TYPE_WIDTH, holder.buffer, holder.start, TYPE_WIDTH); + } else { + BitVectorHelper.unsetBit(validityBuffer, index); + } + } + + /** + * Set the element at the given index to the value set in data holder. + * + * @param index position of element + * @param holder data holder for value of element + */ + public void set(int index, Decimal32Holder holder) { + BitVectorHelper.setBit(validityBuffer, index); + valueBuffer.setBytes((long) index * TYPE_WIDTH, holder.buffer, holder.start, TYPE_WIDTH); + } + + /** + * Same as {@link #set(int, ArrowBuf)} except that it handles the case when index is greater than + * or equal to existing value capacity {@link #getValueCapacity()}. + * + * @param index position of element + * @param buffer ArrowBuf containing decimal value. + */ + public void setSafe(int index, ArrowBuf buffer) { + handleSafe(index); + set(index, buffer); + } + + /** + * Same as {@link #setBigEndian(int, byte[])} except that it handles the case when index is + * greater than or equal to existing value capacity {@link #getValueCapacity()}. + */ + public void setBigEndianSafe(int index, byte[] value) { + handleSafe(index); + setBigEndian(index, value); + } + + /** + * Same as {@link #set(int, long, ArrowBuf)} except that it handles the case when index is greater + * than or equal to existing value capacity {@link #getValueCapacity()}. + * + * @param index position of element + * @param start start index of data in the buffer + * @param buffer ArrowBuf containing decimal value. + */ + public void setSafe(int index, long start, ArrowBuf buffer) { + handleSafe(index); + set(index, start, buffer); + } + + /** + * Same as {@link #set(int, BigDecimal)} except that it handles the case when index is greater + * than or equal to existing value capacity {@link #getValueCapacity()}. + * + * @param index position of element + * @param value BigDecimal containing decimal value. + */ + public void setSafe(int index, BigDecimal value) { + handleSafe(index); + set(index, value); + } + + /** + * Same as {@link #set(int, long)} except that it handles the case when index is greater than or + * equal to existing value capacity {@link #getValueCapacity()}. + * + * @param index position of element + * @param value long value. + */ + public void setSafe(int index, long value) { + handleSafe(index); + set(index, value); + } + + /** + * Same as {@link #set(int, NullableDecimal32Holder)} except that it handles the case when index + * is greater than or equal to existing value capacity {@link #getValueCapacity()}. + * + * @param index position of element + * @param holder nullable data holder for value of element + */ + public void setSafe(int index, NullableDecimal32Holder holder) throws IllegalArgumentException { + handleSafe(index); + set(index, holder); + } + + /** + * Same as {@link #set(int, Decimal32Holder)} except that it handles the case when index is + * greater than or equal to existing value capacity {@link #getValueCapacity()}. + * + * @param index position of element + * @param holder data holder for value of element + */ + public void setSafe(int index, Decimal32Holder holder) { + handleSafe(index); + set(index, holder); + } + + /** + * Store the given value at a particular position in the vector. isSet indicates whether the value + * is NULL or not. + * + * @param index position of the new value + * @param isSet 0 for NULL value, 1 otherwise + * @param start start position of the value in the buffer + * @param buffer buffer containing the value to be stored in the vector + */ + public void set(int index, int isSet, long start, ArrowBuf buffer) { + if (isSet > 0) { + set(index, start, buffer); + } else { + BitVectorHelper.unsetBit(validityBuffer, index); + } + } + + /** + * Same as {@link #set(int, int, long, ArrowBuf)} except that it handles the case when the + * position of new value is beyond the current value capacity of the vector. + * + * @param index position of the new value + * @param isSet 0 for NULL value, 1 otherwise + * @param start start position of the value in the buffer + * @param buffer buffer containing the value to be stored in the vector + */ + public void setSafe(int index, int isSet, long start, ArrowBuf buffer) { + handleSafe(index); + set(index, isSet, start, buffer); + } + + @Override + public void validateScalars() { + for (int i = 0; i < getValueCount(); ++i) { + BigDecimal value = getObject(i); + if (value != null) { + ValidateUtil.validateOrThrow( + DecimalUtility.checkPrecisionAndScaleNoThrow(value, getPrecision(), getScale()), + "Invalid value for Decimal32Vector at position " + + i + + ". Value does not fit in precision " + + getPrecision() + + " and scale " + + getScale() + + "."); + } + } + } + + /*----------------------------------------------------------------* + | | + | vector transfer | + | | + *----------------------------------------------------------------*/ + + /** + * Construct a TransferPair comprising this and a target vector of the same type. + * + * @param ref name of the target vector + * @param allocator allocator for the target vector + * @return {@link TransferPair} + */ + @Override + public TransferPair getTransferPair(String ref, BufferAllocator allocator) { + return new TransferImpl(ref, allocator); + } + + /** + * Construct a TransferPair comprising this and a target vector of the same type. + * + * @param field Field object used by the target vector + * @param allocator allocator for the target vector + * @return {@link TransferPair} + */ + @Override + public TransferPair getTransferPair(Field field, BufferAllocator allocator) { + return new TransferImpl(field, allocator); + } + + /** + * Construct a TransferPair with a desired target vector of the same type. + * + * @param to target vector + * @return {@link TransferPair} + */ + @Override + public TransferPair makeTransferPair(ValueVector to) { + return new TransferImpl((Decimal32Vector) to); + } + + private class TransferImpl implements TransferPair { + Decimal32Vector to; + + public TransferImpl(String ref, BufferAllocator allocator) { + to = + (Decimal32Vector.this.field != null && Decimal32Vector.this.field.getFieldType() != null) + ? new Decimal32Vector(ref, Decimal32Vector.this.field.getFieldType(), allocator) + : new Decimal32Vector( + ref, allocator, Decimal32Vector.this.precision, Decimal32Vector.this.scale); + } + + public TransferImpl(Field field, BufferAllocator allocator) { + to = new Decimal32Vector(field, allocator); + } + + public TransferImpl(Decimal32Vector to) { + this.to = to; + } + + @Override + public Decimal32Vector getTo() { + return to; + } + + @Override + public void transfer() { + transferTo(to); + } + + @Override + public void splitAndTransfer(int startIndex, int length) { + splitAndTransferTo(startIndex, length, to); + } + + @Override + public void copyValueSafe(int fromIndex, int toIndex) { + to.copyFromSafe(fromIndex, toIndex, Decimal32Vector.this); + } + } +} diff --git a/vector/src/main/java/org/apache/arrow/vector/types/Types.java b/vector/src/main/java/org/apache/arrow/vector/types/Types.java index 674bb554ae..2659ffdd06 100644 --- a/vector/src/main/java/org/apache/arrow/vector/types/Types.java +++ b/vector/src/main/java/org/apache/arrow/vector/types/Types.java @@ -28,6 +28,7 @@ import org.apache.arrow.vector.DateDayVector; import org.apache.arrow.vector.DateMilliVector; import org.apache.arrow.vector.Decimal256Vector; +import org.apache.arrow.vector.Decimal32Vector; import org.apache.arrow.vector.DecimalVector; import org.apache.arrow.vector.DurationVector; import org.apache.arrow.vector.ExtensionTypeVector; @@ -81,6 +82,7 @@ import org.apache.arrow.vector.complex.impl.DateDayWriterImpl; import org.apache.arrow.vector.complex.impl.DateMilliWriterImpl; import org.apache.arrow.vector.complex.impl.Decimal256WriterImpl; +import org.apache.arrow.vector.complex.impl.Decimal32WriterImpl; import org.apache.arrow.vector.complex.impl.DecimalWriterImpl; import org.apache.arrow.vector.complex.impl.DenseUnionWriter; import org.apache.arrow.vector.complex.impl.DurationWriterImpl; @@ -802,6 +804,18 @@ public FieldWriter getNewFieldWriter(ValueVector vector) { "FieldWriter for run-end encoded vector is not implemented yet."); } }, + DECIMAL32(null) { + @Override + public FieldVector getNewVector( + Field field, BufferAllocator allocator, CallBack schemaChangeCallback) { + return new Decimal32Vector(field, allocator); + } + + @Override + public FieldWriter getNewFieldWriter(ValueVector vector) { + return new Decimal32WriterImpl((Decimal32Vector) vector); + } + }, ; private final ArrowType type; @@ -948,10 +962,14 @@ public MinorType visit(Bool type) { @Override public MinorType visit(Decimal type) { - if (type.getBitWidth() == 256) { - return MinorType.DECIMAL256; + switch (type.getBitWidth()) { + case 32: + return MinorType.DECIMAL32; + case 256: + return MinorType.DECIMAL256; + default: + return MinorType.DECIMAL; } - return MinorType.DECIMAL; } @Override diff --git a/vector/src/main/java/org/apache/arrow/vector/util/DecimalUtility.java b/vector/src/main/java/org/apache/arrow/vector/util/DecimalUtility.java index 46c6fb70ce..07fbc6a903 100644 --- a/vector/src/main/java/org/apache/arrow/vector/util/DecimalUtility.java +++ b/vector/src/main/java/org/apache/arrow/vector/util/DecimalUtility.java @@ -170,14 +170,21 @@ public static void writeBigDecimalToArrowBuf( * original sign bit to a new upper area in 128-bit or 256-bit. */ public static void writeLongToArrowBuf(long value, ArrowBuf bytebuf, int index, int byteWidth) { - if (byteWidth != 16 && byteWidth != 32) { + if (byteWidth != 4 && byteWidth != 16 && byteWidth != 32) { throw new UnsupportedOperationException( "DecimalUtility.writeLongToArrowBuf() currently supports " - + "128-bit or 256-bit width data"); + + "32-bit, 128-bit or 256-bit width data"); } final long startIndex = (long) index * byteWidth; bytebuf.checkBytes(startIndex, startIndex + byteWidth); final long addressOfValue = bytebuf.memoryAddress() + startIndex; + if (byteWidth == 4) { + if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { + throw new IllegalArgumentException("Decimal value does not fit in 32-bit width: " + value); + } + MemoryUtil.putInt(addressOfValue, (int) value); + return; + } final long padValue = Long.signum(value) == -1 ? -1L : 0L; if (LITTLE_ENDIAN) { MemoryUtil.putLong(addressOfValue, value); diff --git a/vector/src/main/java/org/apache/arrow/vector/validate/ValidateVectorTypeVisitor.java b/vector/src/main/java/org/apache/arrow/vector/validate/ValidateVectorTypeVisitor.java index 210dc34766..b15e1a111b 100644 --- a/vector/src/main/java/org/apache/arrow/vector/validate/ValidateVectorTypeVisitor.java +++ b/vector/src/main/java/org/apache/arrow/vector/validate/ValidateVectorTypeVisitor.java @@ -27,6 +27,7 @@ import org.apache.arrow.vector.DateDayVector; import org.apache.arrow.vector.DateMilliVector; import org.apache.arrow.vector.Decimal256Vector; +import org.apache.arrow.vector.Decimal32Vector; import org.apache.arrow.vector.DecimalVector; import org.apache.arrow.vector.DurationVector; import org.apache.arrow.vector.ExtensionTypeVector; @@ -158,7 +159,22 @@ private void validateDecimalVector(ValueVector vector) { decimalType.getScale(), decimalType.getPrecision()); switch (decimalType.getBitWidth()) { + case Decimal32Vector.TYPE_WIDTH * 8: + validateOrThrow( + vector instanceof Decimal32Vector, + "Expected Decimal32Vector for decimal 32, actual %s.", + vector.getClass()); + validateOrThrow( + decimalType.getPrecision() >= 1 + && decimalType.getPrecision() <= Decimal32Vector.MAX_PRECISION, + "Invalid precision %s for decimal 32.", + decimalType.getPrecision()); + break; case DecimalVector.TYPE_WIDTH * 8: + validateOrThrow( + vector instanceof DecimalVector, + "Expected DecimalVector for decimal 128, actual %s.", + vector.getClass()); validateOrThrow( decimalType.getPrecision() >= 1 && decimalType.getPrecision() <= DecimalVector.MAX_PRECISION, @@ -166,6 +182,10 @@ private void validateDecimalVector(ValueVector vector) { decimalType.getPrecision()); break; case Decimal256Vector.TYPE_WIDTH * 8: + validateOrThrow( + vector instanceof Decimal256Vector, + "Expected Decimal256Vector for decimal 256, actual %s.", + vector.getClass()); validateOrThrow( decimalType.getPrecision() >= 1 && decimalType.getPrecision() <= Decimal256Vector.MAX_PRECISION, @@ -174,7 +194,8 @@ private void validateDecimalVector(ValueVector vector) { break; default: throw new ValidateUtil.ValidateException( - "Only decimal 128 or decimal 256 are supported for decimal types"); + "Only decimal 32, decimal 128 or decimal 256 are supported for decimal" + + " types"); } } @@ -276,7 +297,9 @@ public Void visit(BaseFixedWidthVector vector, Void value) { validateIntVector(vector, 64, false); } else if (vector instanceof BitVector) { validateVectorCommon(vector, ArrowType.Bool.class); - } else if (vector instanceof DecimalVector || vector instanceof Decimal256Vector) { + } else if (vector instanceof Decimal32Vector + || vector instanceof DecimalVector + || vector instanceof Decimal256Vector) { validateVectorCommon(vector, ArrowType.Decimal.class); validateDecimalVector(vector); } else if (vector instanceof DateDayVector) { diff --git a/vector/src/test/java/org/apache/arrow/vector/TestDecimal32Vector.java b/vector/src/test/java/org/apache/arrow/vector/TestDecimal32Vector.java new file mode 100644 index 0000000000..b6da4a733d --- /dev/null +++ b/vector/src/test/java/org/apache/arrow/vector/TestDecimal32Vector.java @@ -0,0 +1,348 @@ +/* + * 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.arrow.vector; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.math.BigDecimal; +import java.math.BigInteger; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.vector.complex.impl.Decimal32HolderReaderImpl; +import org.apache.arrow.vector.complex.impl.NullableDecimal32HolderReaderImpl; +import org.apache.arrow.vector.holders.Decimal32Holder; +import org.apache.arrow.vector.holders.NullableDecimal32Holder; +import org.apache.arrow.vector.types.pojo.ArrowType; +import org.apache.arrow.vector.util.TransferPair; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TestDecimal32Vector { + + private static long[] intValues; + + static { + intValues = new long[40]; + for (int i = 0; i < intValues.length / 2; i++) { + intValues[i] = 1L << (i + 1); + intValues[2 * i] = -1L * (1 << (i + 1)); + } + } + + private int scale = 3; + + private BufferAllocator allocator; + + @BeforeEach + public void init() { + allocator = new DirtyRootAllocator(Long.MAX_VALUE, (byte) 100); + } + + @AfterEach + public void terminate() throws Exception { + allocator.close(); + } + + @Test + public void testValuesWriteRead() { + try (Decimal32Vector decimalVector = + TestUtils.newVector( + Decimal32Vector.class, "decimal", new ArrowType.Decimal(9, scale, 32), allocator)) { + + try (Decimal32Vector oldConstructor = new Decimal32Vector("decimal", allocator, 9, scale)) { + assertEquals(decimalVector.getField().getType(), oldConstructor.getField().getType()); + } + + decimalVector.allocateNew(); + BigDecimal[] values = new BigDecimal[intValues.length]; + for (int i = 0; i < intValues.length; i++) { + BigDecimal decimal = new BigDecimal(BigInteger.valueOf(intValues[i]), scale); + values[i] = decimal; + decimalVector.setSafe(i, decimal); + } + + decimalVector.setValueCount(intValues.length); + + for (int i = 0; i < intValues.length; i++) { + BigDecimal value = decimalVector.getObject(i); + assertEquals(values[i], value, "unexpected data at index: " + i); + } + } + } + + @Test + public void testDecimal32DifferentScaleAndPrecision() { + try (Decimal32Vector decimalVector = + TestUtils.newVector( + Decimal32Vector.class, "decimal", new ArrowType.Decimal(4, 2, 32), allocator)) { + decimalVector.allocateNew(); + + // test Decimal32 with different scale + { + BigDecimal decimal = new BigDecimal(BigInteger.valueOf(0), 3); + UnsupportedOperationException ue = + assertThrows( + UnsupportedOperationException.class, () -> decimalVector.setSafe(0, decimal)); + assertEquals( + "BigDecimal scale must equal that in the Arrow vector: 3 != 2", ue.getMessage()); + } + + // test BigDecimal with larger precision than initialized + { + BigDecimal decimal = new BigDecimal(BigInteger.valueOf(12345), 2); + UnsupportedOperationException ue = + assertThrows( + UnsupportedOperationException.class, () -> decimalVector.setSafe(0, decimal)); + assertEquals( + "BigDecimal precision cannot be greater than that in the Arrow vector: 5 > 4", + ue.getMessage()); + } + decimalVector.setValueCount(1); + assertTrue(decimalVector.isNull(0)); + } + } + + @Test + public void testWriteBigEndian() { + try (Decimal32Vector decimalVector = + TestUtils.newVector( + Decimal32Vector.class, "decimal", new ArrowType.Decimal(9, 4, 32), allocator)) { + decimalVector.allocateNew(); + BigDecimal decimal1 = new BigDecimal("12345.6789"); + BigDecimal decimal2 = new BigDecimal("1.1234"); + BigDecimal decimal3 = new BigDecimal("1.0000"); + BigDecimal decimal4 = new BigDecimal("0.1111"); + BigDecimal decimal5 = new BigDecimal("98765.4321"); + BigDecimal decimal6 = new BigDecimal("-12345.6789"); + BigDecimal decimal7 = new BigDecimal("-1.0001"); + BigDecimal decimal8 = new BigDecimal("5.3434"); + + decimalVector.setBigEndian(0, decimal1.unscaledValue().toByteArray()); + decimalVector.setBigEndian(1, decimal2.unscaledValue().toByteArray()); + decimalVector.setBigEndian(2, decimal3.unscaledValue().toByteArray()); + decimalVector.setBigEndian(3, decimal4.unscaledValue().toByteArray()); + decimalVector.setBigEndian(4, decimal5.unscaledValue().toByteArray()); + decimalVector.setBigEndian(5, decimal6.unscaledValue().toByteArray()); + decimalVector.setBigEndian(6, decimal7.unscaledValue().toByteArray()); + decimalVector.setBigEndian(7, decimal8.unscaledValue().toByteArray()); + + decimalVector.setValueCount(8); + assertEquals(8, decimalVector.getValueCount()); + assertEquals(decimal1, decimalVector.getObject(0)); + assertEquals(decimal2, decimalVector.getObject(1)); + assertEquals(decimal3, decimalVector.getObject(2)); + assertEquals(decimal4, decimalVector.getObject(3)); + assertEquals(decimal5, decimalVector.getObject(4)); + assertEquals(decimal6, decimalVector.getObject(5)); + assertEquals(decimal7, decimalVector.getObject(6)); + assertEquals(decimal8, decimalVector.getObject(7)); + } + } + + @Test + public void testLongReadWrite() { + try (Decimal32Vector decimalVector = + TestUtils.newVector( + Decimal32Vector.class, "decimal", new ArrowType.Decimal(9, 0, 32), allocator)) { + decimalVector.allocateNew(); + + // The full precision-9 range fits in a Decimal32's 32-bit word. + long[] longValues = {0L, -2L, 999999999L, -999999999L, 187L}; + + for (int i = 0; i < longValues.length; ++i) { + decimalVector.set(i, longValues[i]); + } + + decimalVector.setValueCount(longValues.length); + + for (int i = 0; i < longValues.length; ++i) { + assertEquals(new BigDecimal(longValues[i]), decimalVector.getObject(i)); + } + + assertThrows(IllegalArgumentException.class, () -> decimalVector.set(0, Long.MAX_VALUE)); + + // a failed overflowing set must not mark the slot valid + final int overflowIdx = longValues.length; + assertThrows( + IllegalArgumentException.class, () -> decimalVector.set(overflowIdx, Long.MAX_VALUE)); + decimalVector.setValueCount(overflowIdx + 1); + assertTrue(decimalVector.isNull(overflowIdx)); + } + } + + @Test + public void testHolderReaderUsesDecimalByteOrder() { + try (Decimal32Vector decimalVector = + TestUtils.newVector( + Decimal32Vector.class, "decimal", new ArrowType.Decimal(9, 2, 32), allocator)) { + decimalVector.allocateNew(); + decimalVector.set(0, new BigDecimal("1.23")); + BigDecimal expected = new BigDecimal("1234567.89"); + decimalVector.set(1, expected); + decimalVector.setValueCount(2); + + NullableDecimal32Holder nullableHolder = new NullableDecimal32Holder(); + decimalVector.get(1, nullableHolder); + assertEquals( + expected, new NullableDecimal32HolderReaderImpl(nullableHolder).readBigDecimal()); + + Decimal32Holder holder = new Decimal32Holder(); + holder.buffer = nullableHolder.buffer; + holder.start = nullableHolder.start; + holder.precision = nullableHolder.precision; + holder.scale = nullableHolder.scale; + assertEquals(expected, new Decimal32HolderReaderImpl(holder).readBigDecimal()); + } + } + + @Test + public void testBigDecimalReadWrite() { + try (Decimal32Vector decimalVector = + TestUtils.newVector( + Decimal32Vector.class, "decimal", new ArrowType.Decimal(9, 4, 32), allocator)) { + decimalVector.allocateNew(); + BigDecimal decimal1 = new BigDecimal("12345.6789"); + BigDecimal decimal2 = new BigDecimal("1.1234"); + BigDecimal decimal3 = new BigDecimal("1.0000"); + BigDecimal decimal4 = new BigDecimal("-0.1111"); + BigDecimal decimal5 = new BigDecimal("-98765.4321"); + BigDecimal decimal6 = new BigDecimal("-2.2222"); + BigDecimal decimal7 = new BigDecimal("7.6666"); + BigDecimal decimal8 = new BigDecimal("12121.3434"); + + decimalVector.set(0, decimal1); + decimalVector.set(1, decimal2); + decimalVector.set(2, decimal3); + decimalVector.set(3, decimal4); + decimalVector.set(4, decimal5); + decimalVector.set(5, decimal6); + decimalVector.set(6, decimal7); + decimalVector.set(7, decimal8); + + decimalVector.setValueCount(8); + assertEquals(8, decimalVector.getValueCount()); + assertEquals(decimal1, decimalVector.getObject(0)); + assertEquals(decimal2, decimalVector.getObject(1)); + assertEquals(decimal3, decimalVector.getObject(2)); + assertEquals(decimal4, decimalVector.getObject(3)); + assertEquals(decimal5, decimalVector.getObject(4)); + assertEquals(decimal6, decimalVector.getObject(5)); + assertEquals(decimal7, decimalVector.getObject(6)); + assertEquals(decimal8, decimalVector.getObject(7)); + } + } + + /** + * Test {@link Decimal32Vector#setBigEndian(int, byte[])} which takes BE layout input and stores + * in native-endian (NE) layout. Cases to cover: input byte array in different lengths in range + * [1-4] and negative values. + */ + @Test + public void decimalBE2NE() { + try (Decimal32Vector decimalVector = + TestUtils.newVector( + Decimal32Vector.class, "decimal", new ArrowType.Decimal(9, 2, 32), allocator)) { + decimalVector.allocateNew(); + + BigInteger[] testBigInts = + new BigInteger[] { + new BigInteger("0"), + new BigInteger("-1"), + new BigInteger("23"), + new BigInteger("234234"), + new BigInteger("-234234"), + new BigInteger("12345"), + new BigInteger("-345345"), + new BigInteger("754533"), + new BigInteger("999999999"), // 9 nines, fits in 4 bytes + new BigInteger("-999999999") + }; + + int insertionIdx = 0; + insertionIdx++; // insert a null + for (BigInteger val : testBigInts) { + decimalVector.setBigEndian(insertionIdx++, val.toByteArray()); + } + insertionIdx++; // insert a null + // insert a zero length buffer + decimalVector.setBigEndian(insertionIdx++, new byte[0]); + + // Try inserting a buffer larger than 4 bytes and expect a failure + final int insertionIdxCapture = insertionIdx; + IllegalArgumentException ex = + assertThrows( + IllegalArgumentException.class, + () -> decimalVector.setBigEndian(insertionIdxCapture, new byte[5])); + assertTrue( + ex.getMessage().equals("Invalid decimal value length. Valid length in [0 - 4], got 5")); + decimalVector.setValueCount(insertionIdx); + + // retrieve values and check if they are correct + int outputIdx = 0; + assertTrue(decimalVector.isNull(outputIdx++)); + for (BigInteger expected : testBigInts) { + final BigDecimal actual = decimalVector.getObject(outputIdx++); + assertEquals(expected, actual.unscaledValue()); + } + assertTrue(decimalVector.isNull(outputIdx++)); + assertEquals(BigInteger.valueOf(0), decimalVector.getObject(outputIdx).unscaledValue()); + } + } + + @Test + public void testGetTransferPairWithField() { + final Decimal32Vector fromVector = new Decimal32Vector("decimal", allocator, 9, scale); + final TransferPair transferPair = fromVector.getTransferPair(fromVector.getField(), allocator); + final Decimal32Vector toVector = (Decimal32Vector) transferPair.getTo(); + // Field inside a new vector created by reusing a field should be the same in memory as the + // original field. + assertSame(fromVector.getField(), toVector.getField()); + fromVector.close(); + toVector.close(); + } + + @Test + public void testGetTransferPairWithoutField() { + final Decimal32Vector fromVector = new Decimal32Vector("decimal", allocator, 9, scale); + final TransferPair transferPair = + fromVector.getTransferPair(fromVector.getField().getName(), allocator); + final Decimal32Vector toVector = (Decimal32Vector) transferPair.getTo(); + // A new Field created inside a new vector should reuse the field type (should be the same in + // memory as the original Field's field type). + assertSame(fromVector.getField().getFieldType(), toVector.getField().getFieldType()); + fromVector.close(); + toVector.close(); + } + + @Test + public void testValidateScalarsAtMaxPrecision() { + // A value whose precision exactly equals the vector's precision must validate cleanly. + // Regression: DecimalUtility.checkPrecisionAndScaleNoThrow used a strict '<' comparison, so a + // value that set() accepts was wrongly rejected by validateScalars() at the precision boundary. + try (Decimal32Vector decimalVector = + TestUtils.newVector( + Decimal32Vector.class, "decimal", new ArrowType.Decimal(5, 2, 32), allocator)) { + decimalVector.allocateNew(); + decimalVector.set(0, new BigDecimal("999.99")); // precision 5 == vector precision + decimalVector.setValueCount(1); + decimalVector.validateScalars(); // must not throw + } + } +} diff --git a/vector/src/test/java/org/apache/arrow/vector/util/DecimalUtilityTest.java b/vector/src/test/java/org/apache/arrow/vector/util/DecimalUtilityTest.java index 37c38e9a64..5d7bf4d221 100644 --- a/vector/src/test/java/org/apache/arrow/vector/util/DecimalUtilityTest.java +++ b/vector/src/test/java/org/apache/arrow/vector/util/DecimalUtilityTest.java @@ -17,6 +17,7 @@ package org.apache.arrow.vector.util; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.math.BigDecimal; import java.math.BigInteger; @@ -24,8 +25,32 @@ import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; public class DecimalUtilityTest { + @ParameterizedTest + @ValueSource(ints = {4}) + public void testWriteLongChecksBufferBounds(int byteWidth) { + try (BufferAllocator allocator = new RootAllocator(128); + ArrowBuf buffer = allocator.buffer(3L * byteWidth)) { + for (long i = 0; i < buffer.capacity(); i++) { + buffer.setByte(i, 100); + } + // The surrounding allocation keeps this regression test safe even if bounds checks fail. + ArrowBuf value = buffer.slice(byteWidth, byteWidth); + assertThrows( + IndexOutOfBoundsException.class, + () -> DecimalUtility.writeLongToArrowBuf(1, value, -1, byteWidth)); + assertThrows( + IndexOutOfBoundsException.class, + () -> DecimalUtility.writeLongToArrowBuf(1, value, 1, byteWidth)); + for (long i = 0; i < buffer.capacity(); i++) { + assertEquals((byte) 100, buffer.getByte(i)); + } + } + } + private static final BigInteger[] MAX_BIG_INT = new BigInteger[] { BigInteger.valueOf(10).pow(38).subtract(java.math.BigInteger.ONE), diff --git a/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorFull.java b/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorFull.java index 6ad56f3946..ccedd0fabb 100644 --- a/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorFull.java +++ b/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorFull.java @@ -451,7 +451,7 @@ public void testValidateDecimal() { public void testValidateDecimal256() { try (final Decimal256Vector vector = new Decimal256Vector( - Field.nullable("v", new ArrowType.Decimal(2, 0, DecimalVector.TYPE_WIDTH * 8)), + Field.nullable("v", new ArrowType.Decimal(2, 0, Decimal256Vector.TYPE_WIDTH * 8)), allocator)) { vector.validateFull(); setVector(vector, 1L); diff --git a/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorTypeVisitor.java b/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorTypeVisitor.java index 5454008364..a8e7e2b217 100644 --- a/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorTypeVisitor.java +++ b/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorTypeVisitor.java @@ -26,6 +26,7 @@ import org.apache.arrow.vector.DateDayVector; import org.apache.arrow.vector.DateMilliVector; import org.apache.arrow.vector.Decimal256Vector; +import org.apache.arrow.vector.Decimal32Vector; import org.apache.arrow.vector.DecimalVector; import org.apache.arrow.vector.DurationVector; import org.apache.arrow.vector.FixedSizeBinaryVector; @@ -283,6 +284,10 @@ public void testDecimalVector() { "dec", FieldType.nullable(ArrowType.Decimal.createDecimal(38, 10, 128)), allocator)); + testPositiveCase( + () -> + new Decimal32Vector( + "dec", FieldType.nullable(ArrowType.Decimal.createDecimal(9, 2, 32)), allocator)); testPositiveCase( () -> new Decimal256Vector( @@ -321,6 +326,10 @@ public void testDecimalVector() { () -> new Decimal256Vector( "dec", FieldType.nullable(ArrowType.Decimal.createDecimal(30, 10, 64)), allocator)); + testNegativeCase( + () -> + new DecimalVector( + "dec", FieldType.nullable(ArrowType.Decimal.createDecimal(9, 2, 32)), allocator)); testNegativeCase( () -> new Decimal256Vector(