Skip to content
Closed
Changes from all 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
48 changes: 28 additions & 20 deletions rust/arrow/src/util/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
//! Utilities for printing record batches

use crate::array;
use crate::array::PrimitiveArrayOps;
use crate::array::{Array, PrimitiveArrayOps};
use crate::datatypes::{DataType, TimeUnit};
use crate::record_batch::RecordBatch;

Expand Down Expand Up @@ -71,24 +71,22 @@ fn create_table(results: &[RecordBatch]) -> Result<Table> {

macro_rules! make_string {
($array_type:ty, $column: ident, $row: ident) => {{
Ok($column
.as_any()
.downcast_ref::<$array_type>()
.unwrap()
.value($row)
.to_string())
let array = $column.as_any().downcast_ref::<$array_type>().unwrap();

let s = if array.is_null($row) {
"".to_string()
} else {
array.value($row).to_string()
};

Ok(s)
}};
}

/// Get the value at the given row in an array as a string
fn array_value_to_string(column: array::ArrayRef, row: usize) -> Result<String> {
match column.data_type() {
DataType::Utf8 => Ok(column
Copy link
Contributor Author

Choose a reason for hiding this comment

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

There was no reason Utf8 couldn't use the same make_string! macro so I unified the code paths

.as_any()
.downcast_ref::<array::StringArray>()
.unwrap()
.value(row)
.to_string()),
DataType::Utf8 => make_string!(array::StringArray, column, row),
DataType::Boolean => make_string!(array::BooleanArray, column, row),
DataType::Int16 => make_string!(array::Int16Array, column, row),
DataType::Int32 => make_string!(array::Int32Array, column, row),
Expand Down Expand Up @@ -143,16 +141,26 @@ mod tests {
fn test_pretty_format_batches() -> Result<()> {
// define a schema.
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Utf8, false),
Field::new("b", DataType::Int32, false),
Field::new("a", DataType::Utf8, true),
Field::new("b", DataType::Int32, true),
]));

// define data.
let batch = RecordBatch::try_new(
schema,
vec![
Arc::new(array::StringArray::from(vec!["a", "b", "c", "d"])),
Arc::new(array::Int32Array::from(vec![1, 10, 10, 100])),
Arc::new(array::StringArray::from(vec![
Some("a"),
Some("b"),
None,
Some("d"),
])),
Arc::new(array::Int32Array::from(vec![
Some(1),
None,
Some(10),
Some(100),
])),
],
)?;

Expand All @@ -163,15 +171,15 @@ mod tests {
"| a | b |",
"+---+-----+",
"| a | 1 |",
"| b | 10 |",
"| c | 10 |",
"| b | |",
"| | 10 |",
"| d | 100 |",
"+---+-----+",
];

let actual: Vec<&str> = table.lines().collect();

assert_eq!(expected, actual);
assert_eq!(expected, actual, "Actual result:\n{}", table);

Ok(())
}
Expand Down