diff --git a/vector/src/main/codegen/data/ValueVectorTypes.tdd b/vector/src/main/codegen/data/ValueVectorTypes.tdd index cf3e397afe..2014d96f0b 100644 --- a/vector/src/main/codegen/data/ValueVectorTypes.tdd +++ b/vector/src/main/codegen/data/ValueVectorTypes.tdd @@ -181,6 +181,22 @@ } ] }, + { + major: "Fixed", + width: 8, + javaType: "ArrowBuf", + boxedType: "ArrowBuf", + + minor: [ + { + class: "Decimal64", + maxPrecisionDigits: 18, nDecimalDigits: 2, 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", diff --git a/vector/src/main/java/org/apache/arrow/vector/Decimal64Vector.java b/vector/src/main/java/org/apache/arrow/vector/Decimal64Vector.java new file mode 100644 index 0000000000..3249fecb37 --- /dev/null +++ b/vector/src/main/java/org/apache/arrow/vector/Decimal64Vector.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.Decimal64ReaderImpl; +import org.apache.arrow.vector.complex.reader.FieldReader; +import org.apache.arrow.vector.holders.Decimal64Holder; +import org.apache.arrow.vector.holders.NullableDecimal64Holder; +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; + +/** + * Decimal64Vector implements a fixed width vector (8 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 Decimal64Vector extends BaseFixedWidthVector + implements ValueIterableVector { + public static final int MAX_PRECISION = 18; + public static final byte TYPE_WIDTH = 8; + private static final boolean LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN; + + private final int precision; + private final int scale; + + /** + * Instantiate a Decimal64Vector. This doesn't allocate any memory for the data in vector. + * + * @param name name of the vector + * @param allocator allocator for memory management. + */ + public Decimal64Vector(String name, BufferAllocator allocator, int precision, int scale) { + this( + name, + FieldType.nullable(new ArrowType.Decimal(precision, scale, /* bitWidth= */ TYPE_WIDTH * 8)), + allocator); + } + + /** + * Instantiate a Decimal64Vector. 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 Decimal64Vector(String name, FieldType fieldType, BufferAllocator allocator) { + this(new Field(name, fieldType, null), allocator); + } + + /** + * Instantiate a Decimal64Vector. 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 Decimal64Vector(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 Decimal64ReaderImpl(Decimal64Vector.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.DECIMAL64; + } + + /*----------------------------------------------------------------* + | | + | 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, NullableDecimal64Holder 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 8 (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, Decimal64Vector.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, Decimal64Vector.TYPE_WIDTH - length, pad); + } + } else { + // copy data from value to outAddress + MemoryUtil.copyToMemory(value, 0, outAddress + Decimal64Vector.TYPE_WIDTH - length, length); + if (length < TYPE_WIDTH) { + // sign extend + final byte pad = (byte) (value[0] < 0 ? 0xFF : 0x00); + MemoryUtil.setMemory(outAddress, Decimal64Vector.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, NullableDecimal64Holder 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, Decimal64Holder 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, NullableDecimal64Holder)} 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, NullableDecimal64Holder holder) throws IllegalArgumentException { + handleSafe(index); + set(index, holder); + } + + /** + * Same as {@link #set(int, Decimal64Holder)} 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, Decimal64Holder 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 Decimal64Vector 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((Decimal64Vector) to); + } + + private class TransferImpl implements TransferPair { + Decimal64Vector to; + + public TransferImpl(String ref, BufferAllocator allocator) { + to = + (Decimal64Vector.this.field != null && Decimal64Vector.this.field.getFieldType() != null) + ? new Decimal64Vector(ref, Decimal64Vector.this.field.getFieldType(), allocator) + : new Decimal64Vector( + ref, allocator, Decimal64Vector.this.precision, Decimal64Vector.this.scale); + } + + public TransferImpl(Field field, BufferAllocator allocator) { + to = new Decimal64Vector(field, allocator); + } + + public TransferImpl(Decimal64Vector to) { + this.to = to; + } + + @Override + public Decimal64Vector 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, Decimal64Vector.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 2659ffdd06..9fb9568e64 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 @@ -29,6 +29,7 @@ import org.apache.arrow.vector.DateMilliVector; import org.apache.arrow.vector.Decimal256Vector; import org.apache.arrow.vector.Decimal32Vector; +import org.apache.arrow.vector.Decimal64Vector; import org.apache.arrow.vector.DecimalVector; import org.apache.arrow.vector.DurationVector; import org.apache.arrow.vector.ExtensionTypeVector; @@ -83,6 +84,7 @@ 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.Decimal64WriterImpl; import org.apache.arrow.vector.complex.impl.DecimalWriterImpl; import org.apache.arrow.vector.complex.impl.DenseUnionWriter; import org.apache.arrow.vector.complex.impl.DurationWriterImpl; @@ -816,6 +818,18 @@ public FieldWriter getNewFieldWriter(ValueVector vector) { return new Decimal32WriterImpl((Decimal32Vector) vector); } }, + DECIMAL64(null) { + @Override + public FieldVector getNewVector( + Field field, BufferAllocator allocator, CallBack schemaChangeCallback) { + return new Decimal64Vector(field, allocator); + } + + @Override + public FieldWriter getNewFieldWriter(ValueVector vector) { + return new Decimal64WriterImpl((Decimal64Vector) vector); + } + }, ; private final ArrowType type; @@ -965,6 +979,8 @@ public MinorType visit(Decimal type) { switch (type.getBitWidth()) { case 32: return MinorType.DECIMAL32; + case 64: + return MinorType.DECIMAL64; case 256: return MinorType.DECIMAL256; default: 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 07fbc6a903..f3f3136a7e 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 @@ -167,13 +167,13 @@ public static void writeBigDecimalToArrowBuf( /** * Write the given long to the ArrowBuf at the given value index. This routine extends the - * original sign bit to a new upper area in 128-bit or 256-bit. + * original sign bit to a new upper area in 64-bit, 128-bit or 256-bit. */ public static void writeLongToArrowBuf(long value, ArrowBuf bytebuf, int index, int byteWidth) { - if (byteWidth != 4 && byteWidth != 16 && byteWidth != 32) { + if (byteWidth != 4 && byteWidth != 8 && byteWidth != 16 && byteWidth != 32) { throw new UnsupportedOperationException( "DecimalUtility.writeLongToArrowBuf() currently supports " - + "32-bit, 128-bit or 256-bit width data"); + + "32-bit, 64-bit, 128-bit or 256-bit width data"); } final long startIndex = (long) index * byteWidth; bytebuf.checkBytes(startIndex, startIndex + byteWidth); 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 b15e1a111b..ee1ad8427b 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 @@ -28,6 +28,7 @@ import org.apache.arrow.vector.DateMilliVector; import org.apache.arrow.vector.Decimal256Vector; import org.apache.arrow.vector.Decimal32Vector; +import org.apache.arrow.vector.Decimal64Vector; import org.apache.arrow.vector.DecimalVector; import org.apache.arrow.vector.DurationVector; import org.apache.arrow.vector.ExtensionTypeVector; @@ -170,6 +171,17 @@ private void validateDecimalVector(ValueVector vector) { "Invalid precision %s for decimal 32.", decimalType.getPrecision()); break; + case Decimal64Vector.TYPE_WIDTH * 8: + validateOrThrow( + vector instanceof Decimal64Vector, + "Expected Decimal64Vector for decimal 64, actual %s.", + vector.getClass()); + validateOrThrow( + decimalType.getPrecision() >= 1 + && decimalType.getPrecision() <= Decimal64Vector.MAX_PRECISION, + "Invalid precision %s for decimal 64.", + decimalType.getPrecision()); + break; case DecimalVector.TYPE_WIDTH * 8: validateOrThrow( vector instanceof DecimalVector, @@ -194,7 +206,7 @@ private void validateDecimalVector(ValueVector vector) { break; default: throw new ValidateUtil.ValidateException( - "Only decimal 32, decimal 128 or decimal 256 are supported for decimal" + "Only decimal 32, decimal 64, decimal 128 or decimal 256 are supported for decimal" + " types"); } } @@ -298,6 +310,7 @@ public Void visit(BaseFixedWidthVector vector, Void value) { } else if (vector instanceof BitVector) { validateVectorCommon(vector, ArrowType.Bool.class); } else if (vector instanceof Decimal32Vector + || vector instanceof Decimal64Vector || vector instanceof DecimalVector || vector instanceof Decimal256Vector) { validateVectorCommon(vector, ArrowType.Decimal.class); diff --git a/vector/src/test/java/org/apache/arrow/vector/TestDecimal64Vector.java b/vector/src/test/java/org/apache/arrow/vector/TestDecimal64Vector.java new file mode 100644 index 0000000000..b75dba28a1 --- /dev/null +++ b/vector/src/test/java/org/apache/arrow/vector/TestDecimal64Vector.java @@ -0,0 +1,354 @@ +/* + * 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.Decimal64HolderReaderImpl; +import org.apache.arrow.vector.complex.impl.NullableDecimal64HolderReaderImpl; +import org.apache.arrow.vector.holders.Decimal64Holder; +import org.apache.arrow.vector.holders.NullableDecimal64Holder; +import org.apache.arrow.vector.types.pojo.ArrowType; +import org.apache.arrow.vector.util.TransferPair; +import org.apache.arrow.vector.validate.ValidateUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TestDecimal64Vector { + + private static long[] intValues; + + static { + intValues = new long[60]; + 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 (Decimal64Vector decimalVector = + TestUtils.newVector( + Decimal64Vector.class, "decimal", new ArrowType.Decimal(18, scale, 64), allocator)) { + + try (Decimal64Vector oldConstructor = new Decimal64Vector("decimal", allocator, 18, 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 testDecimal64DifferentScaleAndPrecision() { + try (Decimal64Vector decimalVector = + TestUtils.newVector( + Decimal64Vector.class, "decimal", new ArrowType.Decimal(4, 2, 64), allocator)) { + decimalVector.allocateNew(); + + // test Decimal64 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 (Decimal64Vector decimalVector = + TestUtils.newVector( + Decimal64Vector.class, "decimal", new ArrowType.Decimal(18, 9, 64), allocator)) { + decimalVector.allocateNew(); + BigDecimal decimal1 = new BigDecimal("123456789.000000000"); + BigDecimal decimal2 = new BigDecimal("11.123456789"); + BigDecimal decimal3 = new BigDecimal("1.000000000"); + BigDecimal decimal4 = new BigDecimal("0.111111111"); + BigDecimal decimal5 = new BigDecimal("987654321.123456789"); + BigDecimal decimal6 = new BigDecimal("-123456789.123456789"); + BigDecimal decimal7 = new BigDecimal("-1.000000001"); + BigDecimal decimal8 = new BigDecimal("55.343434343"); + + byte[] decimalValue1 = decimal1.unscaledValue().toByteArray(); + byte[] decimalValue2 = decimal2.unscaledValue().toByteArray(); + byte[] decimalValue3 = decimal3.unscaledValue().toByteArray(); + byte[] decimalValue4 = decimal4.unscaledValue().toByteArray(); + byte[] decimalValue5 = decimal5.unscaledValue().toByteArray(); + byte[] decimalValue6 = decimal6.unscaledValue().toByteArray(); + byte[] decimalValue7 = decimal7.unscaledValue().toByteArray(); + byte[] decimalValue8 = decimal8.unscaledValue().toByteArray(); + + decimalVector.setBigEndian(0, decimalValue1); + decimalVector.setBigEndian(1, decimalValue2); + decimalVector.setBigEndian(2, decimalValue3); + decimalVector.setBigEndian(3, decimalValue4); + decimalVector.setBigEndian(4, decimalValue5); + decimalVector.setBigEndian(5, decimalValue6); + decimalVector.setBigEndian(6, decimalValue7); + decimalVector.setBigEndian(7, decimalValue8); + + 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 (Decimal64Vector decimalVector = + TestUtils.newVector( + Decimal64Vector.class, "decimal", new ArrowType.Decimal(18, 0, 64), allocator)) { + decimalVector.allocateNew(); + + long[] longValues = {0L, -2L, 999999999999999999L, -999999999999999999L, 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)); + } + + decimalVector.set(0, Long.MAX_VALUE); + decimalVector.set(1, Long.MIN_VALUE); + decimalVector.setValueCount(2); + assertThrows(ValidateUtil.ValidateException.class, decimalVector::validateScalars); + } + } + + @Test + public void testHolderReaderUsesDecimalByteOrder() { + try (Decimal64Vector decimalVector = + TestUtils.newVector( + Decimal64Vector.class, "decimal", new ArrowType.Decimal(18, 2, 64), allocator)) { + decimalVector.allocateNew(); + decimalVector.set(0, new BigDecimal("1.23")); + BigDecimal expected = new BigDecimal("1234567890123456.78"); + decimalVector.set(1, expected); + decimalVector.setValueCount(2); + + NullableDecimal64Holder nullableHolder = new NullableDecimal64Holder(); + decimalVector.get(1, nullableHolder); + assertEquals( + expected, new NullableDecimal64HolderReaderImpl(nullableHolder).readBigDecimal()); + + Decimal64Holder holder = new Decimal64Holder(); + holder.buffer = nullableHolder.buffer; + holder.start = nullableHolder.start; + holder.precision = nullableHolder.precision; + holder.scale = nullableHolder.scale; + assertEquals(expected, new Decimal64HolderReaderImpl(holder).readBigDecimal()); + } + } + + @Test + public void testBigDecimalReadWrite() { + try (Decimal64Vector decimalVector = + TestUtils.newVector( + Decimal64Vector.class, "decimal", new ArrowType.Decimal(18, 9, 64), allocator)) { + decimalVector.allocateNew(); + BigDecimal decimal1 = new BigDecimal("123456789.000000000"); + BigDecimal decimal2 = new BigDecimal("11.123456789"); + BigDecimal decimal3 = new BigDecimal("1.000000000"); + BigDecimal decimal4 = new BigDecimal("-0.111111111"); + BigDecimal decimal5 = new BigDecimal("-987654321.123456789"); + BigDecimal decimal6 = new BigDecimal("-2.222222222"); + BigDecimal decimal7 = new BigDecimal("7.666666667"); + BigDecimal decimal8 = new BigDecimal("121212121.343434343"); + + 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 Decimal64Vector#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-8] and negative values. + */ + @Test + public void decimalBE2NE() { + try (Decimal64Vector decimalVector = + TestUtils.newVector( + Decimal64Vector.class, "decimal", new ArrowType.Decimal(18, 2, 64), allocator)) { + decimalVector.allocateNew(); + + BigInteger[] testBigInts = + new BigInteger[] { + new BigInteger("0"), + new BigInteger("-1"), + new BigInteger("23"), + new BigInteger("234234"), + new BigInteger("-234234234"), + new BigInteger("234234234234"), + new BigInteger("-56345345345345"), + new BigInteger("999999999999999999"), // 18 nines, fits in 8 bytes + new BigInteger("-999999999999999999"), + new BigInteger("-345345"), + new BigInteger("754533") + }; + + 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 8 bytes and expect a failure + final int insertionIdxCapture = insertionIdx; + IllegalArgumentException ex = + assertThrows( + IllegalArgumentException.class, + () -> decimalVector.setBigEndian(insertionIdxCapture, new byte[9])); + assertTrue( + ex.getMessage().equals("Invalid decimal value length. Valid length in [0 - 8], got 9")); + 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 Decimal64Vector fromVector = new Decimal64Vector("decimal", allocator, 10, scale); + final TransferPair transferPair = fromVector.getTransferPair(fromVector.getField(), allocator); + final Decimal64Vector toVector = (Decimal64Vector) 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 Decimal64Vector fromVector = new Decimal64Vector("decimal", allocator, 10, scale); + final TransferPair transferPair = + fromVector.getTransferPair(fromVector.getField().getName(), allocator); + final Decimal64Vector toVector = (Decimal64Vector) 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 (Decimal64Vector decimalVector = + TestUtils.newVector( + Decimal64Vector.class, "decimal", new ArrowType.Decimal(18, 2, 64), allocator)) { + decimalVector.allocateNew(); + decimalVector.set(0, new BigDecimal("9999999999999999.99")); // precision 18 == vector prec + 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 5d7bf4d221..5b0eb18674 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 @@ -30,7 +30,7 @@ public class DecimalUtilityTest { @ParameterizedTest - @ValueSource(ints = {4}) + @ValueSource(ints = {4, 8}) public void testWriteLongChecksBufferBounds(int byteWidth) { try (BufferAllocator allocator = new RootAllocator(128); ArrowBuf buffer = allocator.buffer(3L * byteWidth)) { 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 a8e7e2b217..01a11ae428 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 @@ -27,6 +27,7 @@ import org.apache.arrow.vector.DateMilliVector; import org.apache.arrow.vector.Decimal256Vector; import org.apache.arrow.vector.Decimal32Vector; +import org.apache.arrow.vector.Decimal64Vector; import org.apache.arrow.vector.DecimalVector; import org.apache.arrow.vector.DurationVector; import org.apache.arrow.vector.FixedSizeBinaryVector; @@ -288,6 +289,10 @@ public void testDecimalVector() { () -> new Decimal32Vector( "dec", FieldType.nullable(ArrowType.Decimal.createDecimal(9, 2, 32)), allocator)); + testPositiveCase( + () -> + new Decimal64Vector( + "dec", FieldType.nullable(ArrowType.Decimal.createDecimal(18, 2, 64)), allocator)); testPositiveCase( () -> new Decimal256Vector( @@ -330,6 +335,10 @@ public void testDecimalVector() { () -> new DecimalVector( "dec", FieldType.nullable(ArrowType.Decimal.createDecimal(9, 2, 32)), allocator)); + testNegativeCase( + () -> + new Decimal64Vector( + "dec", FieldType.nullable(ArrowType.Decimal.createDecimal(18, 2, 128)), allocator)); testNegativeCase( () -> new Decimal256Vector(