Skip to content

Apache DataFusion SQL Query Engine

ARROW-8590: [Rust] Use arrow crate pretty util in DataFusion

Mark Hildreth2b3336622b2f
diff --git a/rust/datafusion/examples/csv_sql.rs b/rust/datafusion/examples/csv_sql.rs
index 310c90a2f1..17106d2414 100644
--- a/rust/datafusion/examples/csv_sql.rs
+++ b/rust/datafusion/examples/csv_sql.rs
@@ -16,10 +16,10 @@
// under the License.
use arrow::datatypes::{DataType, Field, Schema};
+use arrow::util::pretty;
use datafusion::error::Result;
use datafusion::execution::context::ExecutionContext;
-use datafusion::utils;
/// This example demonstrates executing a simple query against an Arrow data source (CSV) and
/// fetching results
@@ -65,7 +65,7 @@ fn main() -> Result<()> {
let results = ctx.collect(plan.as_ref())?;
// print the results
- utils::print_batches(&results)?;
+ pretty::print_batches(&results)?;
Ok(())
}
diff --git a/rust/datafusion/examples/flight_client.rs b/rust/datafusion/examples/flight_client.rs
index f96eb86a08..cdc697c9ae 100644
--- a/rust/datafusion/examples/flight_client.rs
+++ b/rust/datafusion/examples/flight_client.rs
@@ -20,8 +20,7 @@ use std::sync::Arc;
use arrow::datatypes::Schema;
use arrow::flight::flight_data_to_batch;
-
-use datafusion::utils;
+use arrow::util::pretty;
use flight::flight_descriptor;
use flight::flight_service_client::FlightServiceClient;
@@ -68,7 +67,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
// print the results
- utils::print_batches(&results).unwrap();
+ pretty::print_batches(&results)?;
Ok(())
}
diff --git a/rust/datafusion/examples/memory_table_api.rs b/rust/datafusion/examples/memory_table_api.rs
index 27b308c4d8..2a69fe93ea 100644
--- a/rust/datafusion/examples/memory_table_api.rs
+++ b/rust/datafusion/examples/memory_table_api.rs
@@ -21,12 +21,12 @@ use std::sync::Arc;
use arrow::array::{Int32Array, StringArray};
use arrow::datatypes::{DataType, Field, Schema};
use arrow::record_batch::RecordBatch;
+use arrow::util::pretty;
use datafusion::datasource::MemTable;
use datafusion::error::Result;
use datafusion::execution::context::ExecutionContext;
use datafusion::logicalplan::{Expr, ScalarValue};
-use datafusion::utils;
/// This example demonstrates basic uses of the Table API on an in-memory table
fn main() -> Result<()> {
@@ -62,7 +62,7 @@ fn main() -> Result<()> {
let results = t.collect(&mut ctx, 10)?;
// print the results
- utils::print_batches(&results)?;
+ pretty::print_batches(&results)?;
Ok(())
}
diff --git a/rust/datafusion/examples/parquet_sql.rs b/rust/datafusion/examples/parquet_sql.rs
index 696854da09..6e635dcc73 100644
--- a/rust/datafusion/examples/parquet_sql.rs
+++ b/rust/datafusion/examples/parquet_sql.rs
@@ -15,9 +15,9 @@
// specific language governing permissions and limitations
// under the License.
+use arrow::util::pretty;
use datafusion::error::Result;
use datafusion::execution::context::ExecutionContext;
-use datafusion::utils;
/// This example demonstrates executing a simple query against an Arrow data source (Parquet) and
/// fetching results
@@ -46,7 +46,7 @@ fn main() -> Result<()> {
let results = ctx.collect(plan.as_ref())?;
// print the results
- utils::print_batches(&results)?;
+ pretty::print_batches(&results)?;
Ok(())
}
diff --git a/rust/datafusion/src/bin/repl.rs b/rust/datafusion/src/bin/repl.rs
index a16068a35c..4a8464b600 100644
--- a/rust/datafusion/src/bin/repl.rs
+++ b/rust/datafusion/src/bin/repl.rs
@@ -17,10 +17,10 @@
#![allow(bare_trait_objects)]
+use arrow::util::pretty;
use clap::{crate_version, App, Arg};
use datafusion::error::Result;
use datafusion::execution::context::ExecutionContext;
-use datafusion::utils;
use rustyline::Editor;
use std::env;
use std::path::Path;
@@ -116,7 +116,7 @@ fn exec_and_print(
return Ok(());
}
- utils::print_batches(&results)?;
+ pretty::print_batches(&results)?;
let row_count: usize = results.iter().map(|b| b.num_rows()).sum();
diff --git a/rust/datafusion/src/lib.rs b/rust/datafusion/src/lib.rs
index 4db66a2f02..fb4e5af303 100644
--- a/rust/datafusion/src/lib.rs
+++ b/rust/datafusion/src/lib.rs
@@ -36,7 +36,6 @@ pub mod logicalplan;
pub mod optimizer;
pub mod sql;
pub mod table;
-pub mod utils;
#[cfg(test)]
pub mod test;
diff --git a/rust/datafusion/src/utils.rs b/rust/datafusion/src/utils.rs
deleted file mode 100644
index 826d6e2362..0000000000
--- a/rust/datafusion/src/utils.rs
+++ /dev/null
@@ -1,173 +0,0 @@
-// 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.
-
-//! Utilities for printing record batches
-
-use arrow::array;
-use arrow::datatypes::{DataType, TimeUnit};
-use arrow::record_batch::RecordBatch;
-
-use prettytable::format;
-use prettytable::{Cell, Row, Table};
-
-use crate::error::{ExecutionError, Result};
-
-///! Print a series of record batches to stdout
-pub fn print_batches(results: &Vec<RecordBatch>) -> Result<()> {
- create_table(results)?.printstd();
- Ok(())
-}
-
-///! Convert a series of record batches into a table
-pub fn create_table(results: &Vec<RecordBatch>) -> Result<Table> {
- let mut table = Table::new();
- table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
-
- if results.is_empty() {
- return Ok(table);
- }
-
- let schema = results[0].schema();
-
- let mut header = Vec::new();
- for field in schema.fields() {
- header.push(Cell::new(&field.name()));
- }
- table.set_titles(Row::new(header));
-
- for batch in results {
- for row in 0..batch.num_rows() {
- let mut cells = Vec::new();
- for col in 0..batch.num_columns() {
- let column = batch.column(col);
- cells.push(Cell::new(&array_value_to_string(column.clone(), row)?));
- }
- table.add_row(Row::new(cells));
- }
- }
-
- Ok(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())
- }};
-}
-
-/// Get the value at the given row in an array as a string
-pub fn array_value_to_string(column: array::ArrayRef, row: usize) -> Result<String> {
- match column.data_type() {
- DataType::Utf8 => Ok(column
- .as_any()
- .downcast_ref::<array::StringArray>()
- .unwrap()
- .value(row)
- .to_string()),
- DataType::Boolean => make_string!(array::BooleanArray, column, row),
- DataType::Int16 => make_string!(array::Int16Array, column, row),
- DataType::Int32 => make_string!(array::Int32Array, column, row),
- DataType::Int64 => make_string!(array::Int64Array, column, row),
- DataType::UInt8 => make_string!(array::UInt8Array, column, row),
- DataType::UInt16 => make_string!(array::UInt16Array, column, row),
- DataType::UInt32 => make_string!(array::UInt32Array, column, row),
- DataType::UInt64 => make_string!(array::UInt64Array, column, row),
- DataType::Float16 => make_string!(array::Float32Array, column, row),
- DataType::Float32 => make_string!(array::Float32Array, column, row),
- DataType::Float64 => make_string!(array::Float64Array, column, row),
- DataType::Timestamp(unit, _) if *unit == TimeUnit::Second => {
- make_string!(array::TimestampSecondArray, column, row)
- }
- DataType::Timestamp(unit, _) if *unit == TimeUnit::Millisecond => {
- make_string!(array::TimestampMillisecondArray, column, row)
- }
- DataType::Timestamp(unit, _) if *unit == TimeUnit::Microsecond => {
- make_string!(array::TimestampMicrosecondArray, column, row)
- }
- DataType::Timestamp(unit, _) if *unit == TimeUnit::Nanosecond => {
- make_string!(array::TimestampNanosecondArray, column, row)
- }
- DataType::Date32(_) => make_string!(array::Date32Array, column, row),
- DataType::Date64(_) => make_string!(array::Date64Array, column, row),
- DataType::Time32(unit) if *unit == TimeUnit::Second => {
- make_string!(array::Time32SecondArray, column, row)
- }
- DataType::Time32(unit) if *unit == TimeUnit::Millisecond => {
- make_string!(array::Time32MillisecondArray, column, row)
- }
- DataType::Time32(unit) if *unit == TimeUnit::Microsecond => {
- make_string!(array::Time64MicrosecondArray, column, row)
- }
- DataType::Time64(unit) if *unit == TimeUnit::Nanosecond => {
- make_string!(array::Time64NanosecondArray, column, row)
- }
- _ => Err(ExecutionError::ExecutionError(format!(
- "Unsupported {:?} type for repl.",
- column.data_type()
- ))),
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use arrow::array;
- use arrow::datatypes::{DataType, Field, Schema};
- use std::sync::Arc;
-
- #[test]
- fn table() -> Result<()> {
- // define a schema.
- let schema = Arc::new(Schema::new(vec![
- Field::new("a", DataType::Utf8, false),
- Field::new("b", DataType::Int32, false),
- ]));
-
- // define data.
- let batch = RecordBatch::try_new(
- schema.clone(),
- vec![
- Arc::new(array::StringArray::from(vec!["a", "b", "c", "d"])),
- Arc::new(array::Int32Array::from(vec![1, 10, 10, 100])),
- ],
- )?;
-
- let table = create_table(&vec![batch])?.to_string();
-
- let expected = vec![
- "+---+-----+",
- "| a | b |",
- "+---+-----+",
- "| a | 1 |",
- "| b | 10 |",
- "| c | 10 |",
- "| d | 100 |",
- "+---+-----+",
- ];
-
- let actual: Vec<&str> = table.lines().collect();
-
- assert_eq!(expected, actual);
-
- Ok(())
- }
-}