Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement arrow_json encoder for Decimal128 & Decimal256 #6606

Merged
merged 5 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions arrow-json/src/writer/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,16 @@ fn make_encoder_impl<'a>(
};
(Box::new(encoder) as _, array.nulls().cloned())
}
DataType::Decimal128(_, _) => {
let array = array.as_any().downcast_ref::<Decimal128Array>()
.ok_or_else(|| ArrowError::InvalidArgumentError("Expected Decimal128Array".to_string()))?;
(Box::new(Decimal128Encoder::new(array)) as _, array.nulls().cloned())
}
DataType::Decimal256(_, _) => {
let array = array.as_any().downcast_ref::<Decimal256Array>()
.ok_or_else(|| ArrowError::InvalidArgumentError("Expected Decimal256Array".to_string()))?;
(Box::new(Decimal256Encoder::new(array)) as _, array.nulls().cloned())
}
d => match d.is_temporal() {
true => {
// Note: the implementation of Encoder for ArrayFormatter assumes it does not produce
Expand Down Expand Up @@ -545,3 +555,37 @@ where
out.push(b'"');
}
}

struct Decimal128Encoder<'a> {
array: &'a Decimal128Array,
}

impl<'a> Decimal128Encoder<'a> {
fn new(array: &'a Decimal128Array) -> Self {
Self { array }
}
}

impl<'a> Encoder for Decimal128Encoder<'a> {
fn encode(&mut self, idx: usize, out: &mut Vec<u8>) {
let formatted = self.array.value_as_string(idx);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me try this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried this, but it encoded them as strings not numbers, and I don't see any option that is relevant.

DataType::Decimal128(_, _) | DataType::Decimal256(_, _)=> {
            let options = FormatOptions::new();
            let formatter = ArrayFormatter::try_new(array, &options)?;
            (Box::new(formatter) as _, array.nulls().cloned())
        }
assertion `left == right` failed
  left: [Some(Object {"decimal": Number(12.34)}), Some(Object {"decimal": Number(56.78)}), Some(Object {"decimal": Number(90.12)}), None]
 right: [Some(Object {"decimal": String("12.34")}), Some(Object {"decimal": String("56.78")}), Some(Object {"decimal": String("90.12")}), None]

I'm not sure why though, it seems to call the same format_decimal method that value_as_string does?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes you will need to keep the custom encoder as a newtype as unlike the implementation for ArrayFormatter above, you don't want to write the quote characters

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took the liberty of doing this in c912fa1

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

out.extend_from_slice(formatted.as_bytes());
}
}

struct Decimal256Encoder<'a> {
array: &'a Decimal256Array,
}

impl<'a> Decimal256Encoder<'a> {
fn new(array: &'a Decimal256Array) -> Self {
Self { array }
}
}

impl<'a> Encoder for Decimal256Encoder<'a> {
fn encode(&mut self, idx: usize, out: &mut Vec<u8>) {
let formatted = self.array.value_as_string(idx);
out.extend_from_slice(formatted.as_bytes());
}
}
78 changes: 77 additions & 1 deletion arrow-json/src/writer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ mod tests {

use arrow_array::builder::*;
use arrow_array::types::*;
use arrow_buffer::{Buffer, NullBuffer, OffsetBuffer, ToByteSlice};
use arrow_buffer::{i256, Buffer, NullBuffer, OffsetBuffer, ToByteSlice};
use arrow_data::ArrayData;

use crate::reader::*;
Expand Down Expand Up @@ -1833,4 +1833,80 @@ mod tests {
r#"[{"my_dict":"a"},{"my_dict":null},{"my_dict":null}]"#
)
}

#[test]
fn test_decimal128_encoder() {
let array = Decimal128Array::from_iter_values([1234, 5678, 9012])
.with_precision_and_scale(10, 2)
.unwrap();
let field = Arc::new(Field::new("decimal", array.data_type().clone(), true));
let schema = Schema::new(vec![field]);
let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(array)]).unwrap();

let mut buf = Vec::new();
{
let mut writer = LineDelimitedWriter::new(&mut buf);
writer.write_batches(&[&batch]).unwrap();
}

assert_json_eq(
&buf,
r#"{"decimal":12.34}
{"decimal":56.78}
{"decimal":90.12}
"#,
);
}

#[test]
fn test_decimal256_encoder() {
let array = Decimal256Array::from_iter_values([
i256::from(123400),
i256::from(567800),
i256::from(901200),
])
.with_precision_and_scale(10, 4)
.unwrap();
let field = Arc::new(Field::new("decimal", array.data_type().clone(), true));
let schema = Schema::new(vec![field]);
let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(array)]).unwrap();

let mut buf = Vec::new();
{
let mut writer = LineDelimitedWriter::new(&mut buf);
writer.write_batches(&[&batch]).unwrap();
}

assert_json_eq(
&buf,
r#"{"decimal":12.3400}
{"decimal":56.7800}
{"decimal":90.1200}
"#,
);
}

#[test]
fn test_decimal_encoder_with_nulls() {
let array = Decimal128Array::from_iter([Some(1234), None, Some(5678)])
.with_precision_and_scale(10, 2)
.unwrap();
let field = Arc::new(Field::new("decimal", array.data_type().clone(), true));
let schema = Schema::new(vec![field]);
let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(array)]).unwrap();

let mut buf = Vec::new();
{
let mut writer = LineDelimitedWriter::new(&mut buf);
writer.write_batches(&[&batch]).unwrap();
}

assert_json_eq(
&buf,
r#"{"decimal":12.34}
{}
{"decimal":56.78}
"#,
);
}
}
Loading