You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@arrow.apache.org by et...@apache.org on 2025/06/27 16:35:10 UTC
(arrow-rs) branch main updated: Implement Type and Array for Decimal32 and Decimal64 (#7098)
This is an automated email from the ASF dual-hosted git repository.
etseidl pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
The following commit(s) were added to refs/heads/main by this push:
new be338f9bda Implement Type and Array for Decimal32 and Decimal64 (#7098)
be338f9bda is described below
commit be338f9bdaab719dd569130ea882e10a58ef9d17
Author: Curt Hagenlocher <cu...@hagenlocher.org>
AuthorDate: Fri Jun 27 09:35:05 2025 -0700
Implement Type and Array for Decimal32 and Decimal64 (#7098)
# Which issue does this PR close?
Part of addressing #6661 but does not close it.
# What changes are included in this PR?
This change implements `Decimal32Array`, `Decimal32Type`,
`Decimal64Array` and `Decimal64Type` in a relatively minimal fashion. It
doesn't implement the full range of casts or support for Parquet or CSV
reader. These will come in the next change.
# Are there any user-facing changes?
Adds several public types. Adds new entries for the `DataType` enum,
which is a breaking change.
---
arrow-arith/src/numeric.rs | 40 ++++++
arrow-array/src/array/mod.rs | 2 +
arrow-array/src/array/primitive_array.rs | 192 +++++++++++++++++++++++++-
arrow-array/src/builder/buffer_builder.rs | 4 +
arrow-array/src/builder/mod.rs | 6 +
arrow-array/src/builder/primitive_builder.rs | 7 +-
arrow-array/src/cast.rs | 6 +
arrow-array/src/record_batch.rs | 4 +-
arrow-array/src/types.rs | 87 +++++++++++-
arrow-cast/src/display.rs | 2 +-
arrow-data/src/data.rs | 4 +
arrow-data/src/decimal.rs | 195 ++++++++++++++++++++++++++-
arrow-data/src/equal/mod.rs | 2 +
arrow-data/src/transform/mod.rs | 8 +-
arrow-integration-test/src/datatype.rs | 8 ++
arrow-integration-test/src/lib.rs | 36 +++++
arrow-ipc/src/convert.rs | 24 ++++
arrow-schema/src/datatype.rs | 52 +++++++
arrow-schema/src/datatype_parse.rs | 35 +++++
arrow-schema/src/ffi.rs | 10 +-
arrow-schema/src/field.rs | 2 +
parquet/src/arrow/arrow_reader/statistics.rs | 107 +++++++++++++--
parquet/src/arrow/schema/mod.rs | 5 +-
23 files changed, 812 insertions(+), 26 deletions(-)
diff --git a/arrow-arith/src/numeric.rs b/arrow-arith/src/numeric.rs
index 0bcf300032..198447b4db 100644
--- a/arrow-arith/src/numeric.rs
+++ b/arrow-arith/src/numeric.rs
@@ -111,6 +111,20 @@ pub fn neg(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
Float16 => neg_wrapping!(Float16Type, array),
Float32 => neg_wrapping!(Float32Type, array),
Float64 => neg_wrapping!(Float64Type, array),
+ Decimal32(p, s) => {
+ let a = array
+ .as_primitive::<Decimal32Type>()
+ .try_unary::<_, Decimal32Type, _>(|x| x.neg_checked())?;
+
+ Ok(Arc::new(a.with_precision_and_scale(*p, *s)?))
+ }
+ Decimal64(p, s) => {
+ let a = array
+ .as_primitive::<Decimal64Type>()
+ .try_unary::<_, Decimal64Type, _>(|x| x.neg_checked())?;
+
+ Ok(Arc::new(a.with_precision_and_scale(*p, *s)?))
+ }
Decimal128(p, s) => {
let a = array
.as_primitive::<Decimal128Type>()
@@ -234,6 +248,8 @@ fn arithmetic_op(op: Op, lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, A
(Interval(MonthDayNano), Interval(MonthDayNano)) => interval_op::<IntervalMonthDayNanoType>(op, l, l_scalar, r, r_scalar),
(Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
(Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+ (Decimal32(_, _), Decimal32(_, _)) => decimal_op::<Decimal32Type>(op, l, l_scalar, r, r_scalar),
+ (Decimal64(_, _), Decimal64(_, _)) => decimal_op::<Decimal64Type>(op, l, l_scalar, r, r_scalar),
(Decimal128(_, _), Decimal128(_, _)) => decimal_op::<Decimal128Type>(op, l, l_scalar, r, r_scalar),
(Decimal256(_, _), Decimal256(_, _)) => decimal_op::<Decimal256Type>(op, l, l_scalar, r, r_scalar),
(l_t, r_t) => match (l_t, r_t) {
@@ -801,6 +817,8 @@ fn decimal_op<T: DecimalType>(
let r = r.as_primitive::<T>();
let (p1, s1, p2, s2) = match (l.data_type(), r.data_type()) {
+ (DataType::Decimal32(p1, s1), DataType::Decimal32(p2, s2)) => (p1, s1, p2, s2),
+ (DataType::Decimal64(p1, s1), DataType::Decimal64(p2, s2)) => (p1, s1, p2, s2),
(DataType::Decimal128(p1, s1), DataType::Decimal128(p2, s2)) => (p1, s1, p2, s2),
(DataType::Decimal256(p1, s1), DataType::Decimal256(p2, s2)) => (p1, s1, p2, s2),
_ => unreachable!(),
@@ -989,6 +1007,28 @@ mod tests {
"Arithmetic overflow: Overflow happened on: - -9223372036854775808"
);
+ let a = Decimal32Array::from(vec![1, 3, -44, 2, 4])
+ .with_precision_and_scale(9, 6)
+ .unwrap();
+
+ let r = neg(&a).unwrap();
+ assert_eq!(r.data_type(), a.data_type());
+ assert_eq!(
+ r.as_primitive::<Decimal32Type>().values(),
+ &[-1, -3, 44, -2, -4]
+ );
+
+ let a = Decimal64Array::from(vec![1, 3, -44, 2, 4])
+ .with_precision_and_scale(9, 6)
+ .unwrap();
+
+ let r = neg(&a).unwrap();
+ assert_eq!(r.data_type(), a.data_type());
+ assert_eq!(
+ r.as_primitive::<Decimal64Type>().values(),
+ &[-1, -3, 44, -2, -4]
+ );
+
let a = Decimal128Array::from(vec![1, 3, -44, 2, 4])
.with_precision_and_scale(9, 6)
.unwrap();
diff --git a/arrow-array/src/array/mod.rs b/arrow-array/src/array/mod.rs
index 29d284e3c5..5fdfb9fb22 100644
--- a/arrow-array/src/array/mod.rs
+++ b/arrow-array/src/array/mod.rs
@@ -833,6 +833,8 @@ pub fn make_array(data: ArrayData) -> ArrayRef {
dt => panic!("Unexpected data type for run_ends array {dt:?}"),
},
DataType::Null => Arc::new(NullArray::from(data)) as ArrayRef,
+ DataType::Decimal32(_, _) => Arc::new(Decimal32Array::from(data)) as ArrayRef,
+ DataType::Decimal64(_, _) => Arc::new(Decimal64Array::from(data)) as ArrayRef,
DataType::Decimal128(_, _) => Arc::new(Decimal128Array::from(data)) as ArrayRef,
DataType::Decimal256(_, _) => Arc::new(Decimal256Array::from(data)) as ArrayRef,
dt => panic!("Unexpected data type {dt:?}"),
diff --git a/arrow-array/src/array/primitive_array.rs b/arrow-array/src/array/primitive_array.rs
index 6fd319aa42..9327668824 100644
--- a/arrow-array/src/array/primitive_array.rs
+++ b/arrow-array/src/array/primitive_array.rs
@@ -410,6 +410,44 @@ pub type DurationMicrosecondArray = PrimitiveArray<DurationMicrosecondType>;
/// A [`PrimitiveArray`] of elapsed durations in nanoseconds
pub type DurationNanosecondArray = PrimitiveArray<DurationNanosecondType>;
+/// A [`PrimitiveArray`] of 32-bit fixed point decimals
+///
+/// # Examples
+///
+/// Construction
+///
+/// ```
+/// # use arrow_array::Decimal32Array;
+/// // Create from Vec<Option<i32>>
+/// let arr = Decimal32Array::from(vec![Some(1), None, Some(2)]);
+/// // Create from Vec<i32>
+/// let arr = Decimal32Array::from(vec![1, 2, 3]);
+/// // Create iter/collect
+/// let arr: Decimal32Array = std::iter::repeat(42).take(10).collect();
+/// ```
+///
+/// See [`PrimitiveArray`] for more information and examples
+pub type Decimal32Array = PrimitiveArray<Decimal32Type>;
+
+/// A [`PrimitiveArray`] of 64-bit fixed point decimals
+///
+/// # Examples
+///
+/// Construction
+///
+/// ```
+/// # use arrow_array::Decimal64Array;
+/// // Create from Vec<Option<i64>>
+/// let arr = Decimal64Array::from(vec![Some(1), None, Some(2)]);
+/// // Create from Vec<i64>
+/// let arr = Decimal64Array::from(vec![1, 2, 3]);
+/// // Create iter/collect
+/// let arr: Decimal64Array = std::iter::repeat(42).take(10).collect();
+/// ```
+///
+/// See [`PrimitiveArray`] for more information and examples
+pub type Decimal64Array = PrimitiveArray<Decimal64Type>;
+
/// A [`PrimitiveArray`] of 128-bit fixed point decimals
///
/// # Examples
@@ -672,6 +710,8 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
DataType::Timestamp(t1, _) => {
matches!(data_type, DataType::Timestamp(t2, _) if &t1 == t2)
}
+ DataType::Decimal32(_, _) => matches!(data_type, DataType::Decimal32(_, _)),
+ DataType::Decimal64(_, _) => matches!(data_type, DataType::Decimal64(_, _)),
DataType::Decimal128(_, _) => matches!(data_type, DataType::Decimal128(_, _)),
DataType::Decimal256(_, _) => matches!(data_type, DataType::Decimal256(_, _)),
_ => T::DATA_TYPE.eq(data_type),
@@ -1343,6 +1383,8 @@ def_from_for_primitive!(UInt64Type, u64);
def_from_for_primitive!(Float16Type, f16);
def_from_for_primitive!(Float32Type, f32);
def_from_for_primitive!(Float64Type, f64);
+def_from_for_primitive!(Decimal32Type, i32);
+def_from_for_primitive!(Decimal64Type, i64);
def_from_for_primitive!(Decimal128Type, i128);
def_from_for_primitive!(Decimal256Type, i256);
@@ -1455,6 +1497,8 @@ def_numeric_from_vec!(UInt64Type);
def_numeric_from_vec!(Float16Type);
def_numeric_from_vec!(Float32Type);
def_numeric_from_vec!(Float64Type);
+def_numeric_from_vec!(Decimal32Type);
+def_numeric_from_vec!(Decimal64Type);
def_numeric_from_vec!(Decimal128Type);
def_numeric_from_vec!(Decimal256Type);
@@ -1563,6 +1607,26 @@ impl<T: DecimalType + ArrowPrimitiveType> PrimitiveArray<T> {
/// Returns the decimal precision of this array
pub fn precision(&self) -> u8 {
match T::BYTE_LENGTH {
+ 4 => {
+ if let DataType::Decimal32(p, _) = self.data_type() {
+ *p
+ } else {
+ unreachable!(
+ "Decimal32Array datatype is not DataType::Decimal32 but {}",
+ self.data_type()
+ )
+ }
+ }
+ 8 => {
+ if let DataType::Decimal64(p, _) = self.data_type() {
+ *p
+ } else {
+ unreachable!(
+ "Decimal64Array datatype is not DataType::Decimal64 but {}",
+ self.data_type()
+ )
+ }
+ }
16 => {
if let DataType::Decimal128(p, _) = self.data_type() {
*p
@@ -1590,6 +1654,26 @@ impl<T: DecimalType + ArrowPrimitiveType> PrimitiveArray<T> {
/// Returns the decimal scale of this array
pub fn scale(&self) -> i8 {
match T::BYTE_LENGTH {
+ 4 => {
+ if let DataType::Decimal32(_, s) = self.data_type() {
+ *s
+ } else {
+ unreachable!(
+ "Decimal32Array datatype is not DataType::Decimal32 but {}",
+ self.data_type()
+ )
+ }
+ }
+ 8 => {
+ if let DataType::Decimal64(_, s) = self.data_type() {
+ *s
+ } else {
+ unreachable!(
+ "Decimal64Array datatype is not DataType::Decimal64 but {}",
+ self.data_type()
+ )
+ }
+ }
16 => {
if let DataType::Decimal128(_, s) = self.data_type() {
*s
@@ -1618,7 +1702,9 @@ impl<T: DecimalType + ArrowPrimitiveType> PrimitiveArray<T> {
#[cfg(test)]
mod tests {
use super::*;
- use crate::builder::{Decimal128Builder, Decimal256Builder};
+ use crate::builder::{
+ Decimal128Builder, Decimal256Builder, Decimal32Builder, Decimal64Builder,
+ };
use crate::cast::downcast_array;
use crate::BooleanArray;
use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano};
@@ -2228,6 +2314,42 @@ mod tests {
let _ = PrimitiveArray::<Int64Type>::from(foo.into_data());
}
+ #[test]
+ fn test_decimal32() {
+ let values: Vec<_> = vec![0, 1, -1, i32::MIN, i32::MAX];
+ let array: PrimitiveArray<Decimal32Type> =
+ PrimitiveArray::from_iter(values.iter().copied());
+ assert_eq!(array.values(), &values);
+
+ let array: PrimitiveArray<Decimal32Type> =
+ PrimitiveArray::from_iter_values(values.iter().copied());
+ assert_eq!(array.values(), &values);
+
+ let array = PrimitiveArray::<Decimal32Type>::from(values.clone());
+ assert_eq!(array.values(), &values);
+
+ let array = PrimitiveArray::<Decimal32Type>::from(array.to_data());
+ assert_eq!(array.values(), &values);
+ }
+
+ #[test]
+ fn test_decimal64() {
+ let values: Vec<_> = vec![0, 1, -1, i64::MIN, i64::MAX];
+ let array: PrimitiveArray<Decimal64Type> =
+ PrimitiveArray::from_iter(values.iter().copied());
+ assert_eq!(array.values(), &values);
+
+ let array: PrimitiveArray<Decimal64Type> =
+ PrimitiveArray::from_iter_values(values.iter().copied());
+ assert_eq!(array.values(), &values);
+
+ let array = PrimitiveArray::<Decimal64Type>::from(values.clone());
+ assert_eq!(array.values(), &values);
+
+ let array = PrimitiveArray::<Decimal64Type>::from(array.to_data());
+ assert_eq!(array.values(), &values);
+ }
+
#[test]
fn test_decimal128() {
let values: Vec<_> = vec![0, 1, -1, i128::MIN, i128::MAX];
@@ -2499,6 +2621,74 @@ mod tests {
assert!(!array.is_null(2));
}
+ #[test]
+ fn test_decimal64_iter() {
+ let mut builder = Decimal64Builder::with_capacity(30);
+ let decimal1 = 12345;
+ builder.append_value(decimal1);
+
+ builder.append_null();
+
+ let decimal2 = 56789;
+ builder.append_value(decimal2);
+
+ let array: Decimal64Array = builder.finish().with_precision_and_scale(18, 4).unwrap();
+
+ let collected: Vec<_> = array.iter().collect();
+ assert_eq!(vec![Some(decimal1), None, Some(decimal2)], collected);
+ }
+
+ #[test]
+ fn test_from_iter_decimal64array() {
+ let value1 = 12345;
+ let value2 = 56789;
+
+ let mut array: Decimal64Array =
+ vec![Some(value1), None, Some(value2)].into_iter().collect();
+ array = array.with_precision_and_scale(18, 4).unwrap();
+ assert_eq!(array.len(), 3);
+ assert_eq!(array.data_type(), &DataType::Decimal64(18, 4));
+ assert_eq!(value1, array.value(0));
+ assert!(!array.is_null(0));
+ assert!(array.is_null(1));
+ assert_eq!(value2, array.value(2));
+ assert!(!array.is_null(2));
+ }
+
+ #[test]
+ fn test_decimal32_iter() {
+ let mut builder = Decimal32Builder::with_capacity(30);
+ let decimal1 = 12345;
+ builder.append_value(decimal1);
+
+ builder.append_null();
+
+ let decimal2 = 56789;
+ builder.append_value(decimal2);
+
+ let array: Decimal32Array = builder.finish().with_precision_and_scale(9, 2).unwrap();
+
+ let collected: Vec<_> = array.iter().collect();
+ assert_eq!(vec![Some(decimal1), None, Some(decimal2)], collected);
+ }
+
+ #[test]
+ fn test_from_iter_decimal32array() {
+ let value1 = 12345;
+ let value2 = 56789;
+
+ let mut array: Decimal32Array =
+ vec![Some(value1), None, Some(value2)].into_iter().collect();
+ array = array.with_precision_and_scale(9, 2).unwrap();
+ assert_eq!(array.len(), 3);
+ assert_eq!(array.data_type(), &DataType::Decimal32(9, 2));
+ assert_eq!(value1, array.value(0));
+ assert!(!array.is_null(0));
+ assert!(array.is_null(1));
+ assert_eq!(value2, array.value(2));
+ assert!(!array.is_null(2));
+ }
+
#[test]
fn test_unary_opt() {
let array = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7]);
diff --git a/arrow-array/src/builder/buffer_builder.rs b/arrow-array/src/builder/buffer_builder.rs
index c0cabb1f73..5975654667 100644
--- a/arrow-array/src/builder/buffer_builder.rs
+++ b/arrow-array/src/builder/buffer_builder.rs
@@ -45,6 +45,10 @@ pub type Float32BufferBuilder = BufferBuilder<f32>;
/// Buffer builder for 64-bit floating point type.
pub type Float64BufferBuilder = BufferBuilder<f64>;
+/// Buffer builder for 32-bit decimal type.
+pub type Decimal32BufferBuilder = BufferBuilder<<Decimal32Type as ArrowPrimitiveType>::Native>;
+/// Buffer builder for 64-bit decimal type.
+pub type Decimal64BufferBuilder = BufferBuilder<<Decimal64Type as ArrowPrimitiveType>::Native>;
/// Buffer builder for 128-bit decimal type.
pub type Decimal128BufferBuilder = BufferBuilder<<Decimal128Type as ArrowPrimitiveType>::Native>;
/// Buffer builder for 256-bit decimal type.
diff --git a/arrow-array/src/builder/mod.rs b/arrow-array/src/builder/mod.rs
index 680563c6cf..cbbf423467 100644
--- a/arrow-array/src/builder/mod.rs
+++ b/arrow-array/src/builder/mod.rs
@@ -450,6 +450,12 @@ pub fn make_builder(datatype: &DataType, capacity: usize) -> Box<dyn ArrayBuilde
DataType::FixedSizeBinary(len) => {
Box::new(FixedSizeBinaryBuilder::with_capacity(capacity, *len))
}
+ DataType::Decimal32(p, s) => Box::new(
+ Decimal32Builder::with_capacity(capacity).with_data_type(DataType::Decimal32(*p, *s)),
+ ),
+ DataType::Decimal64(p, s) => Box::new(
+ Decimal64Builder::with_capacity(capacity).with_data_type(DataType::Decimal64(*p, *s)),
+ ),
DataType::Decimal128(p, s) => Box::new(
Decimal128Builder::with_capacity(capacity).with_data_type(DataType::Decimal128(*p, *s)),
),
diff --git a/arrow-array/src/builder/primitive_builder.rs b/arrow-array/src/builder/primitive_builder.rs
index 41c65fe34e..7aca730ce1 100644
--- a/arrow-array/src/builder/primitive_builder.rs
+++ b/arrow-array/src/builder/primitive_builder.rs
@@ -87,6 +87,10 @@ pub type DurationMicrosecondBuilder = PrimitiveBuilder<DurationMicrosecondType>;
/// An elapsed time in nanoseconds array builder.
pub type DurationNanosecondBuilder = PrimitiveBuilder<DurationNanosecondType>;
+/// A decimal 32 array builder
+pub type Decimal32Builder = PrimitiveBuilder<Decimal32Type>;
+/// A decimal 64 array builder
+pub type Decimal64Builder = PrimitiveBuilder<Decimal64Type>;
/// A decimal 128 array builder
pub type Decimal128Builder = PrimitiveBuilder<Decimal128Type>;
/// A decimal 256 array builder
@@ -175,7 +179,8 @@ impl<T: ArrowPrimitiveType> PrimitiveBuilder<T> {
/// data type of the generated array.
///
/// This method allows overriding the data type, to allow specifying timezones
- /// for [`DataType::Timestamp`] or precision and scale for [`DataType::Decimal128`] and [`DataType::Decimal256`]
+ /// for [`DataType::Timestamp`] or precision and scale for [`DataType::Decimal32`],
+ /// [`DataType::Decimal64`], [`DataType::Decimal128`] and [`DataType::Decimal256`]
///
/// # Panics
///
diff --git a/arrow-array/src/cast.rs b/arrow-array/src/cast.rs
index c9b92efe6c..41fffc4bc8 100644
--- a/arrow-array/src/cast.rs
+++ b/arrow-array/src/cast.rs
@@ -365,6 +365,12 @@ macro_rules! downcast_primitive {
$crate::repeat_pat!($crate::cast::__private::DataType::Float64, $($data_type),+) => {
$m!($crate::types::Float64Type $(, $args)*)
}
+ $crate::repeat_pat!($crate::cast::__private::DataType::Decimal32(_, _), $($data_type),+) => {
+ $m!($crate::types::Decimal32Type $(, $args)*)
+ }
+ $crate::repeat_pat!($crate::cast::__private::DataType::Decimal64(_, _), $($data_type),+) => {
+ $m!($crate::types::Decimal64Type $(, $args)*)
+ }
$crate::repeat_pat!($crate::cast::__private::DataType::Decimal128(_, _), $($data_type),+) => {
$m!($crate::types::Decimal128Type $(, $args)*)
}
diff --git a/arrow-array/src/record_batch.rs b/arrow-array/src/record_batch.rs
index 7346435865..c1023b7390 100644
--- a/arrow-array/src/record_batch.rs
+++ b/arrow-array/src/record_batch.rs
@@ -65,7 +65,7 @@ pub trait RecordBatchWriter {
/// Support for limited data types is available. The macro will return a compile error if an unsupported data type is used.
/// Presently supported data types are:
/// - `Boolean`, `Null`
-/// - `Decimal128`, `Decimal256`
+/// - `Decimal32`, `Decimal64`, `Decimal128`, `Decimal256`
/// - `Float16`, `Float32`, `Float64`
/// - `Int8`, `Int16`, `Int32`, `Int64`
/// - `UInt8`, `UInt16`, `UInt32`, `UInt64`
@@ -107,6 +107,8 @@ macro_rules! create_array {
(@from DurationMillisecond) => { $crate::DurationMillisecondArray };
(@from DurationMicrosecond) => { $crate::DurationMicrosecondArray };
(@from DurationNanosecond) => { $crate::DurationNanosecondArray };
+ (@from Decimal32) => { $crate::Decimal32Array };
+ (@from Decimal64) => { $crate::Decimal64Array };
(@from Decimal128) => { $crate::Decimal128Array };
(@from Decimal256) => { $crate::Decimal256Array };
(@from TimestampSecond) => { $crate::TimestampSecondArray };
diff --git a/arrow-array/src/types.rs b/arrow-array/src/types.rs
index e403d67785..da5a5c6da0 100644
--- a/arrow-array/src/types.rs
+++ b/arrow-array/src/types.rs
@@ -25,13 +25,16 @@ use crate::timezone::Tz;
use crate::{ArrowNativeTypeOp, OffsetSizeTrait};
use arrow_buffer::{i256, Buffer, OffsetBuffer};
use arrow_data::decimal::{
- is_validate_decimal256_precision, is_validate_decimal_precision, validate_decimal256_precision,
- validate_decimal_precision,
+ is_validate_decimal256_precision, is_validate_decimal32_precision,
+ is_validate_decimal64_precision, is_validate_decimal_precision, validate_decimal256_precision,
+ validate_decimal32_precision, validate_decimal64_precision, validate_decimal_precision,
};
use arrow_data::{validate_binary_view, validate_string_view};
use arrow_schema::{
ArrowError, DataType, IntervalUnit, TimeUnit, DECIMAL128_MAX_PRECISION, DECIMAL128_MAX_SCALE,
- DECIMAL256_MAX_PRECISION, DECIMAL256_MAX_SCALE, DECIMAL_DEFAULT_SCALE,
+ DECIMAL256_MAX_PRECISION, DECIMAL256_MAX_SCALE, DECIMAL32_DEFAULT_SCALE,
+ DECIMAL32_MAX_PRECISION, DECIMAL32_MAX_SCALE, DECIMAL64_DEFAULT_SCALE, DECIMAL64_MAX_PRECISION,
+ DECIMAL64_MAX_SCALE, DECIMAL_DEFAULT_SCALE,
};
use chrono::{Duration, NaiveDate, NaiveDateTime};
use half::f16;
@@ -1300,6 +1303,8 @@ mod decimal {
use super::*;
pub trait DecimalTypeSealed {}
+ impl DecimalTypeSealed for Decimal32Type {}
+ impl DecimalTypeSealed for Decimal64Type {}
impl DecimalTypeSealed for Decimal128Type {}
impl DecimalTypeSealed for Decimal256Type {}
}
@@ -1307,10 +1312,12 @@ mod decimal {
/// A trait over the decimal types, used by [`PrimitiveArray`] to provide a generic
/// implementation across the various decimal types
///
-/// Implemented by [`Decimal128Type`] and [`Decimal256Type`] for [`Decimal128Array`]
-/// and [`Decimal256Array`] respectively
+/// Implemented by [`Decimal32Type`], [`Decimal64Type`], [`Decimal128Type`] and [`Decimal256Type`]
+/// for [`Decimal32Array`], [`Decimal64Array`], [`Decimal128Array`] and [`Decimal256Array`] respectively
///
/// [`PrimitiveArray`]: crate::array::PrimitiveArray
+/// [`Decimal32Array`]: crate::array::Decimal32Array
+/// [`Decimal64Array`]: crate::array::Decimal64Array
/// [`Decimal128Array`]: crate::array::Decimal128Array
/// [`Decimal256Array`]: crate::array::Decimal256Array
pub trait DecimalType:
@@ -1327,7 +1334,7 @@ pub trait DecimalType:
/// Default values for [`DataType`]
const DEFAULT_TYPE: DataType;
- /// "Decimal128" or "Decimal256", for use in error messages
+ /// "Decimal32", "Decimal64", "Decimal128" or "Decimal256", for use in error messages
const PREFIX: &'static str;
/// Formats the decimal value with the provided precision and scale
@@ -1380,6 +1387,74 @@ pub fn validate_decimal_precision_and_scale<T: DecimalType>(
Ok(())
}
+/// The decimal type for a Decimal32Array
+#[derive(Debug)]
+pub struct Decimal32Type {}
+
+impl DecimalType for Decimal32Type {
+ const BYTE_LENGTH: usize = 4;
+ const MAX_PRECISION: u8 = DECIMAL32_MAX_PRECISION;
+ const MAX_SCALE: i8 = DECIMAL32_MAX_SCALE;
+ const TYPE_CONSTRUCTOR: fn(u8, i8) -> DataType = DataType::Decimal32;
+ const DEFAULT_TYPE: DataType =
+ DataType::Decimal32(DECIMAL32_MAX_PRECISION, DECIMAL32_DEFAULT_SCALE);
+ const PREFIX: &'static str = "Decimal32";
+
+ fn format_decimal(value: Self::Native, precision: u8, scale: i8) -> String {
+ format_decimal_str(&value.to_string(), precision as usize, scale)
+ }
+
+ fn validate_decimal_precision(num: i32, precision: u8) -> Result<(), ArrowError> {
+ validate_decimal32_precision(num, precision)
+ }
+
+ fn is_valid_decimal_precision(value: Self::Native, precision: u8) -> bool {
+ is_validate_decimal32_precision(value, precision)
+ }
+}
+
+impl ArrowPrimitiveType for Decimal32Type {
+ type Native = i32;
+
+ const DATA_TYPE: DataType = <Self as DecimalType>::DEFAULT_TYPE;
+}
+
+impl primitive::PrimitiveTypeSealed for Decimal32Type {}
+
+/// The decimal type for a Decimal64Array
+#[derive(Debug)]
+pub struct Decimal64Type {}
+
+impl DecimalType for Decimal64Type {
+ const BYTE_LENGTH: usize = 8;
+ const MAX_PRECISION: u8 = DECIMAL64_MAX_PRECISION;
+ const MAX_SCALE: i8 = DECIMAL64_MAX_SCALE;
+ const TYPE_CONSTRUCTOR: fn(u8, i8) -> DataType = DataType::Decimal64;
+ const DEFAULT_TYPE: DataType =
+ DataType::Decimal64(DECIMAL64_MAX_PRECISION, DECIMAL64_DEFAULT_SCALE);
+ const PREFIX: &'static str = "Decimal64";
+
+ fn format_decimal(value: Self::Native, precision: u8, scale: i8) -> String {
+ format_decimal_str(&value.to_string(), precision as usize, scale)
+ }
+
+ fn validate_decimal_precision(num: i64, precision: u8) -> Result<(), ArrowError> {
+ validate_decimal64_precision(num, precision)
+ }
+
+ fn is_valid_decimal_precision(value: Self::Native, precision: u8) -> bool {
+ is_validate_decimal64_precision(value, precision)
+ }
+}
+
+impl ArrowPrimitiveType for Decimal64Type {
+ type Native = i64;
+
+ const DATA_TYPE: DataType = <Self as DecimalType>::DEFAULT_TYPE;
+}
+
+impl primitive::PrimitiveTypeSealed for Decimal64Type {}
+
/// The decimal type for a Decimal128Array
#[derive(Debug)]
pub struct Decimal128Type {}
diff --git a/arrow-cast/src/display.rs b/arrow-cast/src/display.rs
index b466a59c20..caa9804507 100644
--- a/arrow-cast/src/display.rs
+++ b/arrow-cast/src/display.rs
@@ -489,7 +489,7 @@ macro_rules! decimal_display {
};
}
-decimal_display!(Decimal128Type, Decimal256Type);
+decimal_display!(Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type);
fn write_timestamp(
f: &mut dyn Write,
diff --git a/arrow-data/src/data.rs b/arrow-data/src/data.rs
index 4c117184de..473645d758 100644
--- a/arrow-data/src/data.rs
+++ b/arrow-data/src/data.rs
@@ -83,6 +83,8 @@ pub(crate) fn new_buffers(data_type: &DataType, capacity: usize) -> [MutableBuff
| DataType::Float16
| DataType::Float32
| DataType::Float64
+ | DataType::Decimal32(_, _)
+ | DataType::Decimal64(_, _)
| DataType::Decimal128(_, _)
| DataType::Decimal256(_, _)
| DataType::Date32
@@ -1612,6 +1614,8 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout {
DataTypeLayout::new_fixed_width::<IntervalMonthDayNano>()
}
DataType::Duration(_) => DataTypeLayout::new_fixed_width::<i64>(),
+ DataType::Decimal32(_, _) => DataTypeLayout::new_fixed_width::<i32>(),
+ DataType::Decimal64(_, _) => DataTypeLayout::new_fixed_width::<i64>(),
DataType::Decimal128(_, _) => DataTypeLayout::new_fixed_width::<i128>(),
DataType::Decimal256(_, _) => DataTypeLayout::new_fixed_width::<i256>(),
DataType::FixedSizeBinary(size) => {
diff --git a/arrow-data/src/decimal.rs b/arrow-data/src/decimal.rs
index e84461f2ec..35a7c08d8e 100644
--- a/arrow-data/src/decimal.rs
+++ b/arrow-data/src/decimal.rs
@@ -15,11 +15,13 @@
// specific language governing permissions and limitations
// under the License.
-//! Maximum and minimum values for [`Decimal256`] and [`Decimal128`].
+//! Maximum and minimum values for [`Decimal256`], [`Decimal128`], [`Decimal64`] and [`Decimal32`].
//!
//! Also provides functions to validate if a given decimal value is within
//! the valid range of the decimal type.
//!
+//! [`Decimal32`]: arrow_schema::DataType::Decimal32
+//! [`Decimal64`]: arrow_schema::DataType::Decimal64
//! [`Decimal128`]: arrow_schema::DataType::Decimal128
//! [`Decimal256`]: arrow_schema::DataType::Decimal256
use arrow_buffer::i256;
@@ -27,7 +29,8 @@ use arrow_schema::ArrowError;
pub use arrow_schema::{
DECIMAL128_MAX_PRECISION, DECIMAL128_MAX_SCALE, DECIMAL256_MAX_PRECISION, DECIMAL256_MAX_SCALE,
- DECIMAL_DEFAULT_SCALE,
+ DECIMAL32_DEFAULT_SCALE, DECIMAL32_MAX_PRECISION, DECIMAL32_MAX_SCALE, DECIMAL64_DEFAULT_SCALE,
+ DECIMAL64_MAX_PRECISION, DECIMAL64_MAX_SCALE, DECIMAL_DEFAULT_SCALE,
};
/// `MAX_DECIMAL256_FOR_EACH_PRECISION[p]` holds the maximum [`i256`] value that can
@@ -899,6 +902,194 @@ pub const MIN_DECIMAL128_FOR_EACH_PRECISION: [i128; 39] = [
-99999999999999999999999999999999999999,
];
+/// `MAX_DECIMAL64_FOR_EACH_PRECISION[p]` holds the maximum `i64` value that can
+/// be stored in [`Decimal64`] value of precision `p`.
+///
+/// # Notes
+///
+/// The first element is unused and is inserted so that we can look up using
+/// precision as the index without the need to subtract 1 first.
+///
+/// # Example
+/// ```
+/// # use arrow_data::decimal::MAX_DECIMAL64_FOR_EACH_PRECISION;
+/// assert_eq!(MAX_DECIMAL64_FOR_EACH_PRECISION[3], 999);
+/// ```
+///
+/// [`Decimal64`]: arrow_schema::DataType::Decimal64
+pub const MAX_DECIMAL64_FOR_EACH_PRECISION: [i64; 19] = [
+ 0, // unused first element
+ 9,
+ 99,
+ 999,
+ 9999,
+ 99999,
+ 999999,
+ 9999999,
+ 99999999,
+ 999999999,
+ 9999999999,
+ 99999999999,
+ 999999999999,
+ 9999999999999,
+ 99999999999999,
+ 999999999999999,
+ 9999999999999999,
+ 99999999999999999,
+ 999999999999999999,
+];
+
+/// `MIN_DECIMAL64_FOR_EACH_PRECISION[p]` holds the minimum `i64` value that can
+/// be stored in a [`Decimal64`] value of precision `p`.
+///
+/// # Notes
+///
+/// The first element is unused and is inserted so that we can look up using
+/// precision as the index without the need to subtract 1 first.
+///
+/// # Example
+/// ```
+/// # use arrow_data::decimal::MIN_DECIMAL64_FOR_EACH_PRECISION;
+/// assert_eq!(MIN_DECIMAL64_FOR_EACH_PRECISION[3], -999);
+/// ```
+///
+/// [`Decimal64`]: arrow_schema::DataType::Decimal64
+pub const MIN_DECIMAL64_FOR_EACH_PRECISION: [i64; 19] = [
+ 0, // unused first element
+ -9,
+ -99,
+ -999,
+ -9999,
+ -99999,
+ -999999,
+ -9999999,
+ -99999999,
+ -999999999,
+ -9999999999,
+ -99999999999,
+ -999999999999,
+ -9999999999999,
+ -99999999999999,
+ -999999999999999,
+ -9999999999999999,
+ -99999999999999999,
+ -999999999999999999,
+];
+
+/// `MAX_DECIMAL32_FOR_EACH_PRECISION[p]` holds the maximum `i32` value that can
+/// be stored in [`Decimal32`] value of precision `p`.
+///
+/// # Notes
+///
+/// The first element is unused and is inserted so that we can look up using
+/// precision as the index without the need to subtract 1 first.
+///
+/// # Example
+/// ```
+/// # use arrow_data::decimal::MAX_DECIMAL32_FOR_EACH_PRECISION;
+/// assert_eq!(MAX_DECIMAL32_FOR_EACH_PRECISION[3], 999);
+/// ```
+///
+/// [`Decimal32`]: arrow_schema::DataType::Decimal32
+pub const MAX_DECIMAL32_FOR_EACH_PRECISION: [i32; 10] = [
+ 0, // unused first element
+ 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999,
+];
+
+/// `MIN_DECIMAL32_FOR_EACH_PRECISION[p]` holds the minimum `ialue that can
+/// be stored in a [`Decimal32`] value of precision `p`.
+///
+/// # Notes
+///
+/// The first element is unused and is inserted so that we can look up using
+/// precision as the index without the need to subtract 1 first.
+///
+/// # Example
+/// ```
+/// # use arrow_data::decimal::MIN_DECIMAL32_FOR_EACH_PRECISION;
+/// assert_eq!(MIN_DECIMAL32_FOR_EACH_PRECISION[3], -999);
+/// ```
+///
+/// [`Decimal32`]: arrow_schema::DataType::Decimal32
+pub const MIN_DECIMAL32_FOR_EACH_PRECISION: [i32; 10] = [
+ 0, // unused first element
+ -9, -99, -999, -9999, -99999, -999999, -9999999, -99999999, -999999999,
+];
+
+/// Validates that the specified `i32` value can be properly
+/// interpreted as a [`Decimal32`] number with precision `precision`
+///
+/// [`Decimal32`]: arrow_schema::DataType::Decimal32
+#[inline]
+pub fn validate_decimal32_precision(value: i32, precision: u8) -> Result<(), ArrowError> {
+ if precision > DECIMAL32_MAX_PRECISION {
+ return Err(ArrowError::InvalidArgumentError(format!(
+ "Max precision of a Decimal32 is {DECIMAL32_MAX_PRECISION}, but got {precision}",
+ )));
+ }
+ if value > MAX_DECIMAL32_FOR_EACH_PRECISION[precision as usize] {
+ Err(ArrowError::InvalidArgumentError(format!(
+ "{value} is too large to store in a Decimal32 of precision {precision}. Max is {}",
+ MAX_DECIMAL32_FOR_EACH_PRECISION[precision as usize]
+ )))
+ } else if value < MIN_DECIMAL32_FOR_EACH_PRECISION[precision as usize] {
+ Err(ArrowError::InvalidArgumentError(format!(
+ "{value} is too small to store in a Decimal32 of precision {precision}. Min is {}",
+ MIN_DECIMAL32_FOR_EACH_PRECISION[precision as usize]
+ )))
+ } else {
+ Ok(())
+ }
+}
+
+/// Returns true if the specified `i32` value can be properly
+/// interpreted as a [`Decimal32`] number with precision `precision`
+///
+/// [`Decimal32`]: arrow_schema::DataType::Decimal32
+#[inline]
+pub fn is_validate_decimal32_precision(value: i32, precision: u8) -> bool {
+ precision <= DECIMAL32_MAX_PRECISION
+ && value >= MIN_DECIMAL32_FOR_EACH_PRECISION[precision as usize]
+ && value <= MAX_DECIMAL32_FOR_EACH_PRECISION[precision as usize]
+}
+
+/// Validates that the specified `i64` value can be properly
+/// interpreted as a [`Decimal64`] number with precision `precision`
+///
+/// [`Decimal64`]: arrow_schema::DataType::Decimal64
+#[inline]
+pub fn validate_decimal64_precision(value: i64, precision: u8) -> Result<(), ArrowError> {
+ if precision > DECIMAL64_MAX_PRECISION {
+ return Err(ArrowError::InvalidArgumentError(format!(
+ "Max precision of a Decimal64 is {DECIMAL64_MAX_PRECISION}, but got {precision}",
+ )));
+ }
+ if value > MAX_DECIMAL64_FOR_EACH_PRECISION[precision as usize] {
+ Err(ArrowError::InvalidArgumentError(format!(
+ "{value} is too large to store in a Decimal64 of precision {precision}. Max is {}",
+ MAX_DECIMAL64_FOR_EACH_PRECISION[precision as usize]
+ )))
+ } else if value < MIN_DECIMAL64_FOR_EACH_PRECISION[precision as usize] {
+ Err(ArrowError::InvalidArgumentError(format!(
+ "{value} is too small to store in a Decimal64 of precision {precision}. Min is {}",
+ MIN_DECIMAL64_FOR_EACH_PRECISION[precision as usize]
+ )))
+ } else {
+ Ok(())
+ }
+}
+
+/// Returns true if the specified `i64` value can be properly
+/// interpreted as a [`Decimal64`] number with precision `precision`
+///
+/// [`Decimal64`]: arrow_schema::DataType::Decimal64
+#[inline]
+pub fn is_validate_decimal64_precision(value: i64, precision: u8) -> bool {
+ precision <= DECIMAL64_MAX_PRECISION
+ && value >= MIN_DECIMAL64_FOR_EACH_PRECISION[precision as usize]
+ && value <= MAX_DECIMAL64_FOR_EACH_PRECISION[precision as usize]
+}
+
/// Validates that the specified `i128` value can be properly
/// interpreted as a [`Decimal128`] number with precision `precision`
///
diff --git a/arrow-data/src/equal/mod.rs b/arrow-data/src/equal/mod.rs
index f24179b617..1c16ee2f8a 100644
--- a/arrow-data/src/equal/mod.rs
+++ b/arrow-data/src/equal/mod.rs
@@ -78,6 +78,8 @@ fn equal_values(
DataType::Int64 => primitive_equal::<i64>(lhs, rhs, lhs_start, rhs_start, len),
DataType::Float32 => primitive_equal::<f32>(lhs, rhs, lhs_start, rhs_start, len),
DataType::Float64 => primitive_equal::<f64>(lhs, rhs, lhs_start, rhs_start, len),
+ DataType::Decimal32(_, _) => primitive_equal::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+ DataType::Decimal64(_, _) => primitive_equal::<i64>(lhs, rhs, lhs_start, rhs_start, len),
DataType::Decimal128(_, _) => primitive_equal::<i128>(lhs, rhs, lhs_start, rhs_start, len),
DataType::Decimal256(_, _) => primitive_equal::<i256>(lhs, rhs, lhs_start, rhs_start, len),
DataType::Date32 | DataType::Time32(_) | DataType::Interval(IntervalUnit::YearMonth) => {
diff --git a/arrow-data/src/transform/mod.rs b/arrow-data/src/transform/mod.rs
index af0e1c104f..5071bf8c41 100644
--- a/arrow-data/src/transform/mod.rs
+++ b/arrow-data/src/transform/mod.rs
@@ -257,6 +257,8 @@ fn build_extend(array: &ArrayData) -> Extend {
| DataType::Duration(_)
| DataType::Interval(IntervalUnit::DayTime) => primitive::build_extend::<i64>(array),
DataType::Interval(IntervalUnit::MonthDayNano) => primitive::build_extend::<i128>(array),
+ DataType::Decimal32(_, _) => primitive::build_extend::<i32>(array),
+ DataType::Decimal64(_, _) => primitive::build_extend::<i64>(array),
DataType::Decimal128(_, _) => primitive::build_extend::<i128>(array),
DataType::Decimal256(_, _) => primitive::build_extend::<i256>(array),
DataType::Utf8 | DataType::Binary => variable_size::build_extend::<i32>(array),
@@ -303,6 +305,8 @@ fn build_extend_nulls(data_type: &DataType) -> ExtendNulls {
| DataType::Duration(_)
| DataType::Interval(IntervalUnit::DayTime) => primitive::extend_nulls::<i64>,
DataType::Interval(IntervalUnit::MonthDayNano) => primitive::extend_nulls::<i128>,
+ DataType::Decimal32(_, _) => primitive::extend_nulls::<i32>,
+ DataType::Decimal64(_, _) => primitive::extend_nulls::<i64>,
DataType::Decimal128(_, _) => primitive::extend_nulls::<i128>,
DataType::Decimal256(_, _) => primitive::extend_nulls::<i256>,
DataType::Utf8 | DataType::Binary => variable_size::extend_nulls::<i32>,
@@ -456,7 +460,9 @@ impl<'a> MutableArrayData<'a> {
};
let child_data = match &data_type {
- DataType::Decimal128(_, _)
+ DataType::Decimal32(_, _)
+ | DataType::Decimal64(_, _)
+ | DataType::Decimal128(_, _)
| DataType::Decimal256(_, _)
| DataType::Null
| DataType::Boolean
diff --git a/arrow-integration-test/src/datatype.rs b/arrow-integration-test/src/datatype.rs
index 24e02c8430..4c17fbe76b 100644
--- a/arrow-integration-test/src/datatype.rs
+++ b/arrow-integration-test/src/datatype.rs
@@ -61,6 +61,8 @@ pub fn data_type_from_json(json: &serde_json::Value) -> Result<DataType> {
};
match bit_width {
+ 32 => Ok(DataType::Decimal32(precision, scale)),
+ 64 => Ok(DataType::Decimal64(precision, scale)),
128 => Ok(DataType::Decimal128(precision, scale)),
256 => Ok(DataType::Decimal256(precision, scale)),
_ => Err(ArrowError::ParseError(
@@ -335,6 +337,12 @@ pub fn data_type_to_json(data_type: &DataType) -> serde_json::Value {
TimeUnit::Nanosecond => "NANOSECOND",
}}),
DataType::Dictionary(_, _) => json!({ "name": "dictionary"}),
+ DataType::Decimal32(precision, scale) => {
+ json!({"name": "decimal", "precision": precision, "scale": scale, "bitWidth": 32})
+ }
+ DataType::Decimal64(precision, scale) => {
+ json!({"name": "decimal", "precision": precision, "scale": scale, "bitWidth": 64})
+ }
DataType::Decimal128(precision, scale) => {
json!({"name": "decimal", "precision": precision, "scale": scale, "bitWidth": 128})
}
diff --git a/arrow-integration-test/src/lib.rs b/arrow-integration-test/src/lib.rs
index baa76059f9..177a1c47f3 100644
--- a/arrow-integration-test/src/lib.rs
+++ b/arrow-integration-test/src/lib.rs
@@ -818,6 +818,42 @@ pub fn array_from_json(
))),
}
}
+ DataType::Decimal32(precision, scale) => {
+ let mut b = Decimal32Builder::with_capacity(json_col.count);
+ for (is_valid, value) in json_col
+ .validity
+ .as_ref()
+ .unwrap()
+ .iter()
+ .zip(json_col.data.unwrap())
+ {
+ match is_valid {
+ 1 => b.append_value(value.as_str().unwrap().parse::<i32>().unwrap()),
+ _ => b.append_null(),
+ };
+ }
+ Ok(Arc::new(
+ b.finish().with_precision_and_scale(*precision, *scale)?,
+ ))
+ }
+ DataType::Decimal64(precision, scale) => {
+ let mut b = Decimal64Builder::with_capacity(json_col.count);
+ for (is_valid, value) in json_col
+ .validity
+ .as_ref()
+ .unwrap()
+ .iter()
+ .zip(json_col.data.unwrap())
+ {
+ match is_valid {
+ 1 => b.append_value(value.as_str().unwrap().parse::<i64>().unwrap()),
+ _ => b.append_null(),
+ };
+ }
+ Ok(Arc::new(
+ b.finish().with_precision_and_scale(*precision, *scale)?,
+ ))
+ }
DataType::Decimal128(precision, scale) => {
let mut b = Decimal128Builder::with_capacity(json_col.count);
for (is_valid, value) in json_col
diff --git a/arrow-ipc/src/convert.rs b/arrow-ipc/src/convert.rs
index 9c6c383106..0be74bf6d9 100644
--- a/arrow-ipc/src/convert.rs
+++ b/arrow-ipc/src/convert.rs
@@ -471,6 +471,8 @@ pub(crate) fn get_data_type(field: crate::Field, may_be_dictionary: bool) -> Dat
let precision: u8 = fsb.precision().try_into().unwrap();
let scale: i8 = fsb.scale().try_into().unwrap();
match bit_width {
+ 32 => DataType::Decimal32(precision, scale),
+ 64 => DataType::Decimal64(precision, scale),
128 => DataType::Decimal128(precision, scale),
256 => DataType::Decimal256(precision, scale),
_ => panic!("Unexpected decimal bit width {bit_width}"),
@@ -841,6 +843,28 @@ pub(crate) fn get_fb_field_type<'a>(
// type in the DictionaryEncoding metadata in the parent field
get_fb_field_type(value_type, dictionary_tracker, fbb)
}
+ Decimal32(precision, scale) => {
+ let mut builder = crate::DecimalBuilder::new(fbb);
+ builder.add_precision(*precision as i32);
+ builder.add_scale(*scale as i32);
+ builder.add_bitWidth(32);
+ FBFieldType {
+ type_type: crate::Type::Decimal,
+ type_: builder.finish().as_union_value(),
+ children: Some(fbb.create_vector(&empty_fields[..])),
+ }
+ }
+ Decimal64(precision, scale) => {
+ let mut builder = crate::DecimalBuilder::new(fbb);
+ builder.add_precision(*precision as i32);
+ builder.add_scale(*scale as i32);
+ builder.add_bitWidth(64);
+ FBFieldType {
+ type_type: crate::Type::Decimal,
+ type_: builder.finish().as_union_value(),
+ children: Some(fbb.create_vector(&empty_fields[..])),
+ }
+ }
Decimal128(precision, scale) => {
let mut builder = crate::DecimalBuilder::new(fbb);
builder.add_precision(*precision as i32);
diff --git a/arrow-schema/src/datatype.rs b/arrow-schema/src/datatype.rs
index f742d99cda..08b3b4cd3c 100644
--- a/arrow-schema/src/datatype.rs
+++ b/arrow-schema/src/datatype.rs
@@ -357,6 +357,34 @@ pub enum DataType {
/// This type mostly used to represent low cardinality string
/// arrays or a limited set of primitive types as integers.
Dictionary(Box<DataType>, Box<DataType>),
+ /// Exact 32-bit width decimal value with precision and scale
+ ///
+ /// * precision is the total number of digits
+ /// * scale is the number of digits past the decimal
+ ///
+ /// For example the number 123.45 has precision 5 and scale 2.
+ ///
+ /// In certain situations, scale could be negative number. For
+ /// negative scale, it is the number of padding 0 to the right
+ /// of the digits.
+ ///
+ /// For example the number 12300 could be treated as a decimal
+ /// has precision 3 and scale -2.
+ Decimal32(u8, i8),
+ /// Exact 64-bit width decimal value with precision and scale
+ ///
+ /// * precision is the total number of digits
+ /// * scale is the number of digits past the decimal
+ ///
+ /// For example the number 123.45 has precision 5 and scale 2.
+ ///
+ /// In certain situations, scale could be negative number. For
+ /// negative scale, it is the number of padding 0 to the right
+ /// of the digits.
+ ///
+ /// For example the number 12300 could be treated as a decimal
+ /// has precision 3 and scale -2.
+ Decimal64(u8, i8),
/// Exact 128-bit width decimal value with precision and scale
///
/// * precision is the total number of digits
@@ -530,6 +558,8 @@ impl DataType {
| Float16
| Float32
| Float64
+ | Decimal32(_, _)
+ | Decimal64(_, _)
| Decimal128(_, _)
| Decimal256(_, _)
)
@@ -690,6 +720,8 @@ impl DataType {
DataType::Interval(IntervalUnit::YearMonth) => Some(4),
DataType::Interval(IntervalUnit::DayTime) => Some(8),
DataType::Interval(IntervalUnit::MonthDayNano) => Some(16),
+ DataType::Decimal32(_, _) => Some(4),
+ DataType::Decimal64(_, _) => Some(8),
DataType::Decimal128(_, _) => Some(16),
DataType::Decimal256(_, _) => Some(32),
DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => None,
@@ -740,6 +772,8 @@ impl DataType {
| DataType::Utf8
| DataType::LargeUtf8
| DataType::Utf8View
+ | DataType::Decimal32(_, _)
+ | DataType::Decimal64(_, _)
| DataType::Decimal128(_, _)
| DataType::Decimal256(_, _) => 0,
DataType::Timestamp(_, s) => s.as_ref().map(|s| s.len()).unwrap_or_default(),
@@ -815,6 +849,18 @@ impl DataType {
}
}
+/// The maximum precision for [DataType::Decimal32] values
+pub const DECIMAL32_MAX_PRECISION: u8 = 9;
+
+/// The maximum scale for [DataType::Decimal32] values
+pub const DECIMAL32_MAX_SCALE: i8 = 9;
+
+/// The maximum precision for [DataType::Decimal64] values
+pub const DECIMAL64_MAX_PRECISION: u8 = 18;
+
+/// The maximum scale for [DataType::Decimal64] values
+pub const DECIMAL64_MAX_SCALE: i8 = 18;
+
/// The maximum precision for [DataType::Decimal128] values
pub const DECIMAL128_MAX_PRECISION: u8 = 38;
@@ -827,6 +873,12 @@ pub const DECIMAL256_MAX_PRECISION: u8 = 76;
/// The maximum scale for [DataType::Decimal256] values
pub const DECIMAL256_MAX_SCALE: i8 = 76;
+/// The default scale for [DataType::Decimal32] values
+pub const DECIMAL32_DEFAULT_SCALE: i8 = 2;
+
+/// The default scale for [DataType::Decimal64] values
+pub const DECIMAL64_DEFAULT_SCALE: i8 = 6;
+
/// The default scale for [DataType::Decimal128] and [DataType::Decimal256]
/// values
pub const DECIMAL_DEFAULT_SCALE: i8 = 10;
diff --git a/arrow-schema/src/datatype_parse.rs b/arrow-schema/src/datatype_parse.rs
index d0fc962fb1..7e71d53ccb 100644
--- a/arrow-schema/src/datatype_parse.rs
+++ b/arrow-schema/src/datatype_parse.rs
@@ -72,6 +72,8 @@ impl<'a> Parser<'a> {
Token::Duration => self.parse_duration(),
Token::Interval => self.parse_interval(),
Token::FixedSizeBinary => self.parse_fixed_size_binary(),
+ Token::Decimal32 => self.parse_decimal_32(),
+ Token::Decimal64 => self.parse_decimal_64(),
Token::Decimal128 => self.parse_decimal_128(),
Token::Decimal256 => self.parse_decimal_256(),
Token::Dictionary => self.parse_dictionary(),
@@ -266,6 +268,26 @@ impl<'a> Parser<'a> {
Ok(DataType::FixedSizeBinary(length))
}
+ /// Parses the next Decimal32 (called after `Decimal32` has been consumed)
+ fn parse_decimal_32(&mut self) -> ArrowResult<DataType> {
+ self.expect_token(Token::LParen)?;
+ let precision = self.parse_u8("Decimal32")?;
+ self.expect_token(Token::Comma)?;
+ let scale = self.parse_i8("Decimal32")?;
+ self.expect_token(Token::RParen)?;
+ Ok(DataType::Decimal32(precision, scale))
+ }
+
+ /// Parses the next Decimal64 (called after `Decimal64` has been consumed)
+ fn parse_decimal_64(&mut self) -> ArrowResult<DataType> {
+ self.expect_token(Token::LParen)?;
+ let precision = self.parse_u8("Decimal64")?;
+ self.expect_token(Token::Comma)?;
+ let scale = self.parse_i8("Decimal64")?;
+ self.expect_token(Token::RParen)?;
+ Ok(DataType::Decimal64(precision, scale))
+ }
+
/// Parses the next Decimal128 (called after `Decimal128` has been consumed)
fn parse_decimal_128(&mut self) -> ArrowResult<DataType> {
self.expect_token(Token::LParen)?;
@@ -516,6 +538,9 @@ impl<'a> Tokenizer<'a> {
"Dictionary" => Token::Dictionary,
"FixedSizeBinary" => Token::FixedSizeBinary,
+
+ "Decimal32" => Token::Decimal32,
+ "Decimal64" => Token::Decimal64,
"Decimal128" => Token::Decimal128,
"Decimal256" => Token::Decimal256,
@@ -575,6 +600,8 @@ enum Token {
Duration,
Interval,
FixedSizeBinary,
+ Decimal32,
+ Decimal64,
Decimal128,
Decimal256,
Dictionary,
@@ -614,6 +641,8 @@ impl Display for Token {
Token::Some => write!(f, "Some"),
Token::None => write!(f, "None"),
Token::FixedSizeBinary => write!(f, "FixedSizeBinary"),
+ Token::Decimal32 => write!(f, "Decimal32"),
+ Token::Decimal64 => write!(f, "Decimal64"),
Token::Decimal128 => write!(f, "Decimal128"),
Token::Decimal256 => write!(f, "Decimal256"),
Token::Dictionary => write!(f, "Dictionary"),
@@ -706,6 +735,8 @@ mod test {
DataType::Utf8,
DataType::Utf8View,
DataType::LargeUtf8,
+ DataType::Decimal32(7, 8),
+ DataType::Decimal64(6, 9),
DataType::Decimal128(7, 12),
DataType::Decimal256(6, 13),
// ---------
@@ -828,8 +859,12 @@ mod test {
// too large for i32
("FixedSizeBinary(4000000000), ", "Error converting 4000000000 into i32 for FixedSizeBinary: out of range integral type conversion attempted"),
// can't have negative precision
+ ("Decimal32(-3, 5)", "Error converting -3 into u8 for Decimal32: out of range integral type conversion attempted"),
+ ("Decimal64(-3, 5)", "Error converting -3 into u8 for Decimal64: out of range integral type conversion attempted"),
("Decimal128(-3, 5)", "Error converting -3 into u8 for Decimal128: out of range integral type conversion attempted"),
("Decimal256(-3, 5)", "Error converting -3 into u8 for Decimal256: out of range integral type conversion attempted"),
+ ("Decimal32(3, 500)", "Error converting 500 into i8 for Decimal32: out of range integral type conversion attempted"),
+ ("Decimal64(3, 500)", "Error converting 500 into i8 for Decimal64: out of range integral type conversion attempted"),
("Decimal128(3, 500)", "Error converting 500 into i8 for Decimal128: out of range integral type conversion attempted"),
("Decimal256(3, 500)", "Error converting 500 into i8 for Decimal256: out of range integral type conversion attempted"),
("Struct(f1, Int64)", "Error finding next type, got unexpected ','"),
diff --git a/arrow-schema/src/ffi.rs b/arrow-schema/src/ffi.rs
index d86fb66190..fda309c01a 100644
--- a/arrow-schema/src/ffi.rs
+++ b/arrow-schema/src/ffi.rs
@@ -521,9 +521,11 @@ impl TryFrom<&FFI_ArrowSchema> for DataType {
)
})?;
match *bits {
+ "32" => DataType::Decimal32(parsed_precision, parsed_scale),
+ "64" => DataType::Decimal64(parsed_precision, parsed_scale),
"128" => DataType::Decimal128(parsed_precision, parsed_scale),
"256" => DataType::Decimal256(parsed_precision, parsed_scale),
- _ => return Err(ArrowError::CDataInterface("Only 128- and 256- bit wide decimals are supported in the Rust implementation".to_string())),
+ _ => return Err(ArrowError::CDataInterface("Only 32/64/128/256 bit wide decimals are supported in the Rust implementation".to_string())),
}
}
_ => {
@@ -706,6 +708,12 @@ fn get_format_string(dtype: &DataType) -> Result<Cow<'static, str>, ArrowError>
DataType::LargeUtf8 => Ok("U".into()),
DataType::FixedSizeBinary(num_bytes) => Ok(Cow::Owned(format!("w:{num_bytes}"))),
DataType::FixedSizeList(_, num_elems) => Ok(Cow::Owned(format!("+w:{num_elems}"))),
+ DataType::Decimal32(precision, scale) => {
+ Ok(Cow::Owned(format!("d:{precision},{scale},32")))
+ }
+ DataType::Decimal64(precision, scale) => {
+ Ok(Cow::Owned(format!("d:{precision},{scale},64")))
+ }
DataType::Decimal128(precision, scale) => Ok(Cow::Owned(format!("d:{precision},{scale}"))),
DataType::Decimal256(precision, scale) => {
Ok(Cow::Owned(format!("d:{precision},{scale},256")))
diff --git a/arrow-schema/src/field.rs b/arrow-schema/src/field.rs
index 16573d8cdc..9aa1a40f4e 100644
--- a/arrow-schema/src/field.rs
+++ b/arrow-schema/src/field.rs
@@ -815,6 +815,8 @@ impl Field {
| DataType::Utf8
| DataType::LargeUtf8
| DataType::Utf8View
+ | DataType::Decimal32(_, _)
+ | DataType::Decimal64(_, _)
| DataType::Decimal128(_, _)
| DataType::Decimal256(_, _) => {
if from.data_type == DataType::Null {
diff --git a/parquet/src/arrow/arrow_reader/statistics.rs b/parquet/src/arrow/arrow_reader/statistics.rs
index cffa60e62e..b976955129 100644
--- a/parquet/src/arrow/arrow_reader/statistics.rs
+++ b/parquet/src/arrow/arrow_reader/statistics.rs
@@ -34,11 +34,11 @@ use arrow_array::builder::{
};
use arrow_array::{
new_empty_array, new_null_array, ArrayRef, BinaryArray, BooleanArray, Date32Array, Date64Array,
- Decimal128Array, Decimal256Array, Float16Array, Float32Array, Float64Array, Int16Array,
- Int32Array, Int64Array, Int8Array, LargeBinaryArray, Time32MillisecondArray, Time32SecondArray,
- Time64MicrosecondArray, Time64NanosecondArray, TimestampMicrosecondArray,
- TimestampMillisecondArray, TimestampNanosecondArray, TimestampSecondArray, UInt16Array,
- UInt32Array, UInt64Array, UInt8Array,
+ Decimal128Array, Decimal256Array, Decimal32Array, Decimal64Array, Float16Array, Float32Array,
+ Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, LargeBinaryArray,
+ Time32MillisecondArray, Time32SecondArray, Time64MicrosecondArray, Time64NanosecondArray,
+ TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,
+ TimestampSecondArray, UInt16Array, UInt32Array, UInt64Array, UInt8Array,
};
use arrow_buffer::i256;
use arrow_schema::{DataType, Field, Schema, TimeUnit};
@@ -46,12 +46,24 @@ use half::f16;
use paste::paste;
use std::sync::Arc;
-// Convert the bytes array to i128.
+// Convert the bytes array to i32.
// The endian of the input bytes array must be big-endian.
-pub(crate) fn from_bytes_to_i128(b: &[u8]) -> i128 {
+pub(crate) fn from_bytes_to_i32(b: &[u8]) -> i32 {
// The bytes array are from parquet file and must be the big-endian.
// The endian is defined by parquet format, and the reference document
// https://github.com/apache/parquet-format/blob/54e53e5d7794d383529dd30746378f19a12afd58/src/main/thrift/parquet.thrift#L66
+ i32::from_be_bytes(sign_extend_be::<4>(b))
+}
+
+// Convert the bytes array to i64.
+// The endian of the input bytes array must be big-endian.
+pub(crate) fn from_bytes_to_i64(b: &[u8]) -> i64 {
+ i64::from_be_bytes(sign_extend_be::<8>(b))
+}
+
+// Convert the bytes array to i128.
+// The endian of the input bytes array must be big-endian.
+pub(crate) fn from_bytes_to_i128(b: &[u8]) -> i128 {
i128::from_be_bytes(sign_extend_be::<16>(b))
}
@@ -263,9 +275,10 @@ macro_rules! make_decimal_stats_iterator {
ParquetStatistics::Int32(s) => {
s.$func().map(|x| $stat_value_type::from(*x))
}
- ParquetStatistics::Int64(s) => {
- s.$func().map(|x| $stat_value_type::from(*x))
- }
+ ParquetStatistics::Int64(s) => s
+ .$func()
+ .map(|x| $stat_value_type::try_from(*x).ok())
+ .flatten(),
ParquetStatistics::ByteArray(s) => s.$bytes_func().map($convert_func),
ParquetStatistics::FixedLenByteArray(s) => {
s.$bytes_func().map($convert_func)
@@ -282,6 +295,34 @@ macro_rules! make_decimal_stats_iterator {
};
}
+make_decimal_stats_iterator!(
+ MinDecimal32StatsIterator,
+ min_opt,
+ min_bytes_opt,
+ i32,
+ from_bytes_to_i32
+);
+make_decimal_stats_iterator!(
+ MaxDecimal32StatsIterator,
+ max_opt,
+ max_bytes_opt,
+ i32,
+ from_bytes_to_i32
+);
+make_decimal_stats_iterator!(
+ MinDecimal64StatsIterator,
+ min_opt,
+ min_bytes_opt,
+ i64,
+ from_bytes_to_i64
+);
+make_decimal_stats_iterator!(
+ MaxDecimal64StatsIterator,
+ max_opt,
+ max_bytes_opt,
+ i64,
+ from_bytes_to_i64
+);
make_decimal_stats_iterator!(
MinDecimal128StatsIterator,
min_opt,
@@ -476,6 +517,18 @@ macro_rules! get_statistics {
}
Ok(Arc::new(builder.finish()))
},
+ DataType::Decimal32(precision, scale) => {
+ let arr = Decimal32Array::from_iter(
+ [<$stat_type_prefix Decimal32StatsIterator>]::new($iterator)
+ ).with_precision_and_scale(*precision, *scale)?;
+ Ok(Arc::new(arr))
+ },
+ DataType::Decimal64(precision, scale) => {
+ let arr = Decimal64Array::from_iter(
+ [<$stat_type_prefix Decimal64StatsIterator>]::new($iterator)
+ ).with_precision_and_scale(*precision, *scale)?;
+ Ok(Arc::new(arr))
+ },
DataType::Decimal128(precision, scale) => {
let arr = Decimal128Array::from_iter(
[<$stat_type_prefix Decimal128StatsIterator>]::new($iterator)
@@ -730,7 +783,7 @@ macro_rules! get_decimal_page_stats_iterator {
native_index
.indexes
.iter()
- .map(|x| x.$func.and_then(|x| Some($stat_value_type::from(x))))
+ .map(|x| x.$func.and_then(|x| $stat_value_type::try_from(x).ok()))
.collect::<Vec<_>>(),
),
Index::BYTE_ARRAY(native_index) => Some(
@@ -764,6 +817,34 @@ macro_rules! get_decimal_page_stats_iterator {
};
}
+get_decimal_page_stats_iterator!(
+ MinDecimal32DataPageStatsIterator,
+ min,
+ i32,
+ from_bytes_to_i32
+);
+
+get_decimal_page_stats_iterator!(
+ MaxDecimal32DataPageStatsIterator,
+ max,
+ i32,
+ from_bytes_to_i32
+);
+
+get_decimal_page_stats_iterator!(
+ MinDecimal64DataPageStatsIterator,
+ min,
+ i64,
+ from_bytes_to_i64
+);
+
+get_decimal_page_stats_iterator!(
+ MaxDecimal64DataPageStatsIterator,
+ max,
+ i64,
+ from_bytes_to_i64
+);
+
get_decimal_page_stats_iterator!(
MinDecimal128DataPageStatsIterator,
min,
@@ -958,6 +1039,10 @@ macro_rules! get_data_page_statistics {
)
),
DataType::Date64 if $physical_type == Some(PhysicalType::INT64) => Ok(Arc::new(Date64Array::from_iter([<$stat_type_prefix Int64DataPageStatsIterator>]::new($iterator).flatten()))),
+ DataType::Decimal32(precision, scale) => Ok(Arc::new(
+ Decimal32Array::from_iter([<$stat_type_prefix Decimal32DataPageStatsIterator>]::new($iterator).flatten()).with_precision_and_scale(*precision, *scale)?)),
+ DataType::Decimal64(precision, scale) => Ok(Arc::new(
+ Decimal64Array::from_iter([<$stat_type_prefix Decimal64DataPageStatsIterator>]::new($iterator).flatten()).with_precision_and_scale(*precision, *scale)?)),
DataType::Decimal128(precision, scale) => Ok(Arc::new(
Decimal128Array::from_iter([<$stat_type_prefix Decimal128DataPageStatsIterator>]::new($iterator).flatten()).with_precision_and_scale(*precision, *scale)?)),
DataType::Decimal256(precision, scale) => Ok(Arc::new(
diff --git a/parquet/src/arrow/schema/mod.rs b/parquet/src/arrow/schema/mod.rs
index 975b48dd04..888040afdd 100644
--- a/parquet/src/arrow/schema/mod.rs
+++ b/parquet/src/arrow/schema/mod.rs
@@ -640,7 +640,10 @@ fn arrow_to_parquet_type(field: &Field, coerce_types: bool) -> Result<Type> {
.with_repetition(repetition)
.with_id(id)
.build(),
- DataType::Decimal128(precision, scale) | DataType::Decimal256(precision, scale) => {
+ DataType::Decimal32(precision, scale)
+ | DataType::Decimal64(precision, scale)
+ | DataType::Decimal128(precision, scale)
+ | DataType::Decimal256(precision, scale) => {
// Decimal precision determines the Parquet physical type to use.
// Following the: https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#decimal
let (physical_type, length) = if *precision > 1 && *precision <= 9 {