nevi-me commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r437923771



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,310 @@
+// 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.
+
+//! Defines concat kernel for `ArrayRef`
+//!
+//! Example:
+//!
+//! ```
+//! use std::sync::Arc;
+//! use arrow::array::{ArrayRef, StringArray};
+//! use arrow::compute::concat;
+//!
+//! let arr = concat(&vec![
+//!     Arc::new(StringArray::from(vec!["hello", "world"])) as ArrayRef,
+//!     Arc::new(StringArray::from(vec!["!"])) as ArrayRef,
+//! ]).unwrap();
+//! assert_eq!(arr.len(), 3);
+//! ```
+
+use crate::array::*;
+use crate::datatypes::*;
+use crate::error::{ArrowError, Result};
+
+use TimeUnit::*;
+
+/// Concatenate multiple `ArrayRef` with the same type.
+///
+/// Returns a new ArrayRef.
+pub fn concat(array_list: &Vec<ArrayRef>) -> Result<ArrayRef> {
+    let mut data_type: Option<DataType> = None;
+    let array_data_list = &array_list
+        .iter()
+        .map(|a| {
+            let array_data = a.data_ref().clone();
+            let curr_data_type = array_data.data_type().clone();
+            match &data_type {
+                Some(t) => {
+                    if t != &curr_data_type {
+                        return Err(ArrowError::ComputeError(
+                            "Cannot concat arrays with different data 
types".to_string(),
+                        ));
+                    }
+                }
+                None => {
+                    data_type = Some(curr_data_type);
+                }
+            }
+            Ok(array_data)
+        })
+        .collect::<Result<Vec<ArrayDataRef>>>()?;
+
+    let data_type = match data_type {

Review comment:
       If you change this to check that `!array_list.is_empty()` at the start 
of the function, you could then get the datatype from the first element in 
`array_list`, then avoid validating data types as `append_data` will do that 
for us

##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,310 @@
+// 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.
+
+//! Defines concat kernel for `ArrayRef`
+//!
+//! Example:
+//!
+//! ```
+//! use std::sync::Arc;
+//! use arrow::array::{ArrayRef, StringArray};
+//! use arrow::compute::concat;
+//!
+//! let arr = concat(&vec![
+//!     Arc::new(StringArray::from(vec!["hello", "world"])) as ArrayRef,
+//!     Arc::new(StringArray::from(vec!["!"])) as ArrayRef,
+//! ]).unwrap();
+//! assert_eq!(arr.len(), 3);
+//! ```
+
+use crate::array::*;
+use crate::datatypes::*;
+use crate::error::{ArrowError, Result};
+
+use TimeUnit::*;
+
+/// Concatenate multiple `ArrayRef` with the same type.
+///
+/// Returns a new ArrayRef.
+pub fn concat(array_list: &Vec<ArrayRef>) -> Result<ArrayRef> {
+    let mut data_type: Option<DataType> = None;
+    let array_data_list = &array_list
+        .iter()
+        .map(|a| {
+            let array_data = a.data_ref().clone();
+            let curr_data_type = array_data.data_type().clone();
+            match &data_type {
+                Some(t) => {
+                    if t != &curr_data_type {
+                        return Err(ArrowError::ComputeError(
+                            "Cannot concat arrays with different data 
types".to_string(),
+                        ));
+                    }
+                }
+                None => {
+                    data_type = Some(curr_data_type);
+                }
+            }
+            Ok(array_data)
+        })
+        .collect::<Result<Vec<ArrayDataRef>>>()?;
+
+    let data_type = match data_type {
+        None => {
+            return Err(ArrowError::ComputeError(
+                "cocat requires input of at least one array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+
+    match data_type {
+        DataType::Utf8 => {
+            let mut builder = StringArray::builder(0);
+            builder.append_data(array_data_list)?;
+            Ok(ArrayBuilder::finish(&mut builder))
+        }
+        DataType::Boolean => {
+            let mut builder = PrimitiveArray::<BooleanType>::builder(0);
+            builder.append_data(array_data_list)?;
+            Ok(ArrayBuilder::finish(&mut builder))
+        }
+        DataType::Int8 => concat_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => 
concat_primitive::<Time32SecondType>(array_data_list),
+        DataType::Time32(Millisecond) => {
+            concat_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),

Review comment:
       It's better to return `Err(ArrowError)` instead of panicking here

##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,310 @@
+// 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.
+
+//! Defines concat kernel for `ArrayRef`
+//!
+//! Example:
+//!
+//! ```
+//! use std::sync::Arc;
+//! use arrow::array::{ArrayRef, StringArray};
+//! use arrow::compute::concat;
+//!
+//! let arr = concat(&vec![
+//!     Arc::new(StringArray::from(vec!["hello", "world"])) as ArrayRef,
+//!     Arc::new(StringArray::from(vec!["!"])) as ArrayRef,
+//! ]).unwrap();
+//! assert_eq!(arr.len(), 3);
+//! ```
+
+use crate::array::*;
+use crate::datatypes::*;
+use crate::error::{ArrowError, Result};
+
+use TimeUnit::*;
+
+/// Concatenate multiple `ArrayRef` with the same type.
+///
+/// Returns a new ArrayRef.
+pub fn concat(array_list: &Vec<ArrayRef>) -> Result<ArrayRef> {
+    let mut data_type: Option<DataType> = None;
+    let array_data_list = &array_list
+        .iter()
+        .map(|a| {
+            let array_data = a.data_ref().clone();
+            let curr_data_type = array_data.data_type().clone();
+            match &data_type {
+                Some(t) => {
+                    if t != &curr_data_type {
+                        return Err(ArrowError::ComputeError(
+                            "Cannot concat arrays with different data 
types".to_string(),
+                        ));
+                    }
+                }
+                None => {
+                    data_type = Some(curr_data_type);
+                }
+            }
+            Ok(array_data)
+        })
+        .collect::<Result<Vec<ArrayDataRef>>>()?;
+
+    let data_type = match data_type {
+        None => {
+            return Err(ArrowError::ComputeError(
+                "cocat requires input of at least one array".to_string(),

Review comment:
       typo, `cocat` -> `concat`

##########
File path: rust/arrow/src/array/array.rs
##########
@@ -1309,6 +1309,11 @@ impl StringArray {
     fn value_offset_at(&self, i: usize) -> i32 {
         unsafe { *self.value_offsets.get().add(i) }
     }
+

Review comment:
       For consistency, may you please also add `builder` to `BinaaryArray`. 
They both behave the same way

##########
File path: rust/datafusion/src/execution/physical_plan/sort.rs
##########
@@ -0,0 +1,211 @@
+// 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.
+
+//! Defines the SORT plan
+
+use std::sync::{Arc, Mutex};
+use std::thread;
+use std::thread::JoinHandle;
+
+use arrow::array::ArrayRef;
+pub use arrow::compute::SortOptions;
+use arrow::compute::{concat, lexsort_to_indices, take, SortColumn, 
TakeOptions};
+use arrow::datatypes::Schema;
+use arrow::record_batch::RecordBatch;
+
+use crate::error::Result;
+use crate::execution::physical_plan::common::RecordBatchIterator;
+use crate::execution::physical_plan::expressions::PhysicalSortExpr;
+use crate::execution::physical_plan::{common, BatchIterator, ExecutionPlan, 
Partition};
+
+/// Sort execution plan
+pub struct SortExec {
+    /// Input schema
+    input: Arc<dyn ExecutionPlan>,
+    expr: Vec<PhysicalSortExpr>,
+}
+
+impl SortExec {
+    /// Create a new sort execution plan
+    pub fn try_new(
+        expr: Vec<PhysicalSortExpr>,
+        input: Arc<dyn ExecutionPlan>,
+    ) -> Result<Self> {
+        Ok(Self { expr, input })
+    }
+}
+
+impl ExecutionPlan for SortExec {
+    fn schema(&self) -> Arc<Schema> {
+        self.input.schema().clone()
+    }
+
+    fn partitions(&self) -> Result<Vec<Arc<dyn Partition>>> {
+        Ok(vec![
+            (Arc::new(SortPartition {
+                input: self.input.partitions()?,
+                expr: self.expr.clone(),
+                schema: self.schema(),
+            })),
+        ])
+    }
+}
+
+/// Represents a single partition of a Sort execution plan
+struct SortPartition {
+    schema: Arc<Schema>,
+    expr: Vec<PhysicalSortExpr>,
+    input: Vec<Arc<dyn Partition>>,
+}
+
+impl Partition for SortPartition {
+    /// Execute the sort
+    fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {
+        let threads: Vec<JoinHandle<Result<Vec<RecordBatch>>>> = self
+            .input
+            .iter()
+            .map(|p| {
+                let p = p.clone();
+                thread::spawn(move || {
+                    let it = p.execute()?;
+                    common::collect(it)
+                })
+            })
+            .collect();
+
+        // generate record batches from input in parallel
+        let mut all_batches: Vec<Arc<RecordBatch>> = vec![];
+        for thread in threads {
+            let join = thread.join().expect("Failed to join thread");
+            let result = join?;
+            result
+                .iter()
+                .for_each(|batch| all_batches.push(Arc::new(batch.clone())));
+        }
+
+        // combine all record batches into one for each column
+        let combined_batch = RecordBatch::try_new(
+            self.schema.clone(),
+            self.schema
+                .fields()
+                .iter()
+                .enumerate()
+                .map(|(i, _)| -> Result<ArrayRef> {
+                    Ok(concat(
+                        &all_batches
+                            .iter()
+                            .map(|batch| batch.columns()[i].clone())
+                            .collect::<Vec<ArrayRef>>(),
+                    )?)
+                })
+                .collect::<Result<Vec<ArrayRef>>>()?,
+        )?;
+
+        // sort combined record batch
+        let indices = lexsort_to_indices(
+            &self
+                .expr
+                .iter()
+                .map(|e| e.evaluate_to_sort_column(&combined_batch))
+                .collect::<Result<Vec<SortColumn>>>()?,
+        )?;
+
+        // reorder all rows based on sorted indices
+        let sorted_batch = RecordBatch::try_new(
+            self.schema.clone(),
+            combined_batch
+                .columns()
+                .iter()
+                .map(|column| -> Result<ArrayRef> {
+                    Ok(take(
+                        column,
+                        &indices,
+                        // disable bound check overhead since indices are 
already generated from
+                        // the same record batch
+                        Some(TakeOptions {
+                            check_bounds: false,
+                        }),
+                    )?)
+                })
+                .collect::<Result<Vec<ArrayRef>>>()?,
+        )?;
+
+        Ok(Arc::new(Mutex::new(RecordBatchIterator::new(

Review comment:
       More a question for @andygrove; in the case of a sort operation 
consolidating all partitions into a single larger partition, would we need to 
repartition the record batches?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to