You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2020/06/02 01:11:38 UTC

[GitHub] [arrow] houqp opened a new pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

houqp opened a new pull request #7324:
URL: https://github.com/apache/arrow/pull/7324


   The only missing piece is updating sqlparser to parse null ordering expression, which is going to be a rather big change due to major refactoring from upstream sqlparer crate. So I am going to leave that to a follow up PR to make this one easier to review.


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r435069031



##########
File path: rust/arrow/src/compute/kernels/sort.rs
##########
@@ -122,7 +122,7 @@ impl Default for SortOptions {
     fn default() -> Self {
         Self {
             descending: false,
-            nulls_first: false,
+            nulls_first: true,

Review comment:
       Okay, that's fine, we could set the default in DataFusion instead, but the way you've done it is fine. I would have taken that as a lazy approach to avoid changing all the test cases :)




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] github-actions[bot] commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-637210669


   https://issues.apache.org/jira/browse/ARROW-9005


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] andygrove commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
andygrove commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-638232933


   This looks great @houqp. I will review in detail in the next day or two.


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r439567609



##########
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:
       I have the same question while developing this, curious what @andygrove thoughts on this as well. I left it as one single batch for performance reason (to avoid having to run the split code).




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r435384974



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let rows_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut builder = PrimitiveBuilder::<T>::new(rows_count);
+
+    for array_data in array_data_list {
+        let a = PrimitiveArray::<T>::from(array_data.clone());
+        for i in 0..a.len() {
+            if a.is_valid(i) {
+                builder.append_value(a.value(i))?;
+            } else {
+                builder.append_null()?;
+            }
+        }
+    }
+
+    Ok(Arc::new(builder.finish()) as ArrayRef)
+}
+
+// for better performance, we manually concat primitive value buffers instead of using
+// PrimitiveBuilder
+fn concat_raw_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let value_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut null_count = 0;
+    let mut values_builder = BufferBuilder::<T>::new(value_count);
+    let mut null_bit_builder = BooleanBufferBuilder::new(value_count);
+
+    for array_data in array_data_list {
+        null_count += array_data.null_count();
+        let value_buffer = &array_data.buffers()[0];
+        values_builder.write_bytes(value_buffer.data(), value_buffer.len())?;
+        for i in 0..array_data.len() {
+            null_bit_builder.append(array_data.is_valid(i))?;
+        }
+    }
+
+    Ok(Arc::new(PrimitiveArray::<T>::from(
+        ArrayData::builder(T::get_data_type())
+            .len(value_count)
+            .add_buffer(values_builder.finish())
+            .null_count(null_count)
+            .null_bit_buffer(null_bit_builder.finish())
+            .build(),
+    )))
+}
+
+// for better performance, we manually concat string value buffers instead of using StringBuilder
+fn concat_raw_string(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef> {

Review comment:
       Ha, I see, good catch. I will work on the offset fix.




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
nevi-me commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-637378472


   > @nevi-me do you prefer to move concat kernel logic into append_data in this set of change or as a follow up after #7306 gets merged?
   
   I've opened https://issues.apache.org/jira/browse/ARROW-9007, so we can address `append_data` as part of that


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp edited a comment on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp edited a comment on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-637209800


   @nevi-me do you prefer to move concat kernel logic into append_data in this set of change or as a follow up after https://github.com/apache/arrow/pull/7306 gets merged?


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-640380594


   alright, i have added nulls ordering support through sqlparser 0.2.6. only thing left is waiting for merge of #7365.


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
nevi-me commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-644232183


   We can address any queries in follow up Jiras


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-637209800


   @nevi-me do you prefer to move concat kernel logic into append_data in this set of change or as a follow up after https://github.com/apache/arrow/pull/7306 get merged?


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r434704814



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let rows_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut builder = PrimitiveBuilder::<T>::new(rows_count);
+
+    for array_data in array_data_list {
+        let a = PrimitiveArray::<T>::from(array_data.clone());
+        for i in 0..a.len() {
+            if a.is_valid(i) {
+                builder.append_value(a.value(i))?;
+            } else {
+                builder.append_null()?;
+            }
+        }
+    }
+
+    Ok(Arc::new(builder.finish()) as ArrayRef)
+}
+
+// for better performance, we manually concat primitive value buffers instead of using
+// PrimitiveBuilder
+fn concat_raw_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let value_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut null_count = 0;
+    let mut values_builder = BufferBuilder::<T>::new(value_count);
+    let mut null_bit_builder = BooleanBufferBuilder::new(value_count);
+
+    for array_data in array_data_list {
+        null_count += array_data.null_count();
+        let value_buffer = &array_data.buffers()[0];
+        values_builder.write_bytes(value_buffer.data(), value_buffer.len())?;
+        for i in 0..array_data.len() {
+            null_bit_builder.append(array_data.is_valid(i))?;
+        }
+    }
+
+    Ok(Arc::new(PrimitiveArray::<T>::from(
+        ArrayData::builder(T::get_data_type())
+            .len(value_count)
+            .add_buffer(values_builder.finish())
+            .null_count(null_count)
+            .null_bit_buffer(null_bit_builder.finish())
+            .build(),
+    )))
+}
+
+// for better performance, we manually concat string value buffers instead of using StringBuilder
+fn concat_raw_string(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef> {

Review comment:
       Would this function handle array slices correctly? May you please test this, either in a new test case or by slicing the second string array in `test_concat_string_arrays`?

##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".to_string(),

Review comment:
       `... with different data types`

##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>

Review comment:
       do you mind changing these to `&[ArrayDataRef]`? There was a PR a few weeks ago to change borrowed vecs to slices, I think it's one of the clippy lints

##########
File path: rust/arrow/src/compute/kernels/sort.rs
##########
@@ -122,7 +122,7 @@ impl Default for SortOptions {
     fn default() -> Self {
         Self {
             descending: false,
-            nulls_first: false,
+            nulls_first: true,

Review comment:
       Why the change here?




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r435027946



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let rows_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut builder = PrimitiveBuilder::<T>::new(rows_count);
+
+    for array_data in array_data_list {
+        let a = PrimitiveArray::<T>::from(array_data.clone());
+        for i in 0..a.len() {
+            if a.is_valid(i) {
+                builder.append_value(a.value(i))?;
+            } else {
+                builder.append_null()?;
+            }
+        }
+    }
+
+    Ok(Arc::new(builder.finish()) as ArrayRef)
+}
+
+// for better performance, we manually concat primitive value buffers instead of using
+// PrimitiveBuilder
+fn concat_raw_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let value_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut null_count = 0;
+    let mut values_builder = BufferBuilder::<T>::new(value_count);
+    let mut null_bit_builder = BooleanBufferBuilder::new(value_count);
+
+    for array_data in array_data_list {
+        null_count += array_data.null_count();
+        let value_buffer = &array_data.buffers()[0];
+        values_builder.write_bytes(value_buffer.data(), value_buffer.len())?;
+        for i in 0..array_data.len() {
+            null_bit_builder.append(array_data.is_valid(i))?;
+        }
+    }
+
+    Ok(Arc::new(PrimitiveArray::<T>::from(
+        ArrayData::builder(T::get_data_type())
+            .len(value_count)
+            .add_buffer(values_builder.finish())
+            .null_count(null_count)
+            .null_bit_buffer(null_bit_builder.finish())
+            .build(),
+    )))
+}
+
+// for better performance, we manually concat string value buffers instead of using StringBuilder
+fn concat_raw_string(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef> {

Review comment:
       By handling array slices did you mean StringArray created from str array slice?




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r435024541



##########
File path: rust/arrow/src/compute/kernels/sort.rs
##########
@@ -122,7 +122,7 @@ impl Default for SortOptions {
     fn default() -> Self {
         Self {
             descending: false,
-            nulls_first: false,
+            nulls_first: true,

Review comment:
       this is to match spark's default behavior, i have added a comment.




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me closed pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
nevi-me closed pull request #7324:
URL: https://github.com/apache/arrow/pull/7324


   


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] andygrove commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
andygrove commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-640336526


   @houqp I released sqlparser 0.2.6


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r436242734



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let rows_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut builder = PrimitiveBuilder::<T>::new(rows_count);
+
+    for array_data in array_data_list {
+        let a = PrimitiveArray::<T>::from(array_data.clone());
+        for i in 0..a.len() {
+            if a.is_valid(i) {
+                builder.append_value(a.value(i))?;
+            } else {
+                builder.append_null()?;
+            }
+        }
+    }
+
+    Ok(Arc::new(builder.finish()) as ArrayRef)
+}
+
+// for better performance, we manually concat primitive value buffers instead of using
+// PrimitiveBuilder
+fn concat_raw_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let value_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut null_count = 0;
+    let mut values_builder = BufferBuilder::<T>::new(value_count);
+    let mut null_bit_builder = BooleanBufferBuilder::new(value_count);
+
+    for array_data in array_data_list {
+        null_count += array_data.null_count();
+        let value_buffer = &array_data.buffers()[0];
+        values_builder.write_bytes(value_buffer.data(), value_buffer.len())?;
+        for i in 0..array_data.len() {
+            null_bit_builder.append(array_data.is_valid(i))?;
+        }
+    }
+
+    Ok(Arc::new(PrimitiveArray::<T>::from(
+        ArrayData::builder(T::get_data_type())
+            .len(value_count)
+            .add_buffer(values_builder.finish())
+            .null_count(null_count)
+            .null_bit_buffer(null_bit_builder.finish())
+            .build(),
+    )))
+}
+
+// for better performance, we manually concat string value buffers instead of using StringBuilder
+fn concat_raw_string(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef> {

Review comment:
       @houqp I need concat support, so I'm going to temporarily merge your code into a fork of mine. Hopefully we can merge this, #7306  and #7365 in the coming days :)




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r435071238



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let rows_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut builder = PrimitiveBuilder::<T>::new(rows_count);
+
+    for array_data in array_data_list {
+        let a = PrimitiveArray::<T>::from(array_data.clone());
+        for i in 0..a.len() {
+            if a.is_valid(i) {
+                builder.append_value(a.value(i))?;
+            } else {
+                builder.append_null()?;
+            }
+        }
+    }
+
+    Ok(Arc::new(builder.finish()) as ArrayRef)
+}
+
+// for better performance, we manually concat primitive value buffers instead of using
+// PrimitiveBuilder
+fn concat_raw_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let value_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut null_count = 0;
+    let mut values_builder = BufferBuilder::<T>::new(value_count);
+    let mut null_bit_builder = BooleanBufferBuilder::new(value_count);
+
+    for array_data in array_data_list {
+        null_count += array_data.null_count();
+        let value_buffer = &array_data.buffers()[0];
+        values_builder.write_bytes(value_buffer.data(), value_buffer.len())?;
+        for i in 0..array_data.len() {
+            null_bit_builder.append(array_data.is_valid(i))?;
+        }
+    }
+
+    Ok(Arc::new(PrimitiveArray::<T>::from(
+        ArrayData::builder(T::get_data_type())
+            .len(value_count)
+            .add_buffer(values_builder.finish())
+            .null_count(null_count)
+            .null_bit_buffer(null_bit_builder.finish())
+            .build(),
+    )))
+}
+
+// for better performance, we manually concat string value buffers instead of using StringBuilder
+fn concat_raw_string(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef> {

Review comment:
       Sorry, I meant slicing the second string array, something like below, which slices out "1" and "6" from the second array:
   
   ```rust
       fn test_concat_string_arrays() -> Result<()> {
           let arr = concat(&vec![
               Arc::new(
                   StringArray::try_from(vec![Some("hello"), Some("world")])
                       .expect("Unable to create string array"),
               ) as ArrayRef,
               StringArray::from(vec!["1", "2", "3", "4", "6"]).slice(1, 3),
               Arc::new(
                   StringArray::try_from(vec![Some("foo"), Some("bar"), None, Some("baz")])
                       .expect("Unable to create string array"),
               ) as ArrayRef,
           ])?;
   
           let expected_output = Arc::new(
               StringArray::try_from(vec![
                   Some("hello"),
                   Some("world"),
                   // Some("1"),
                   Some("2"),
                   Some("3"),
                   Some("4"),
                   // Some("6"),
                   Some("foo"),
                   Some("bar"),
                   None,
                   Some("baz"),
               ])
               .expect("Unable to create string array"),
           ) as ArrayRef;
   
           assert!(
               arr.equals(&(*expected_output)),
               "expect {:#?} to be: {:#?}",
               arr,
               &expected_output
           );
   
           Ok(())
       }
   ```
   
   The same might need to be verified with numeric arrays because we write the whole data in `write_slice`, so if there's an offset, we might get unexpected outputs.
   
   I'll check your branch out locally and check this.




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r435080612



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let rows_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut builder = PrimitiveBuilder::<T>::new(rows_count);
+
+    for array_data in array_data_list {
+        let a = PrimitiveArray::<T>::from(array_data.clone());
+        for i in 0..a.len() {
+            if a.is_valid(i) {
+                builder.append_value(a.value(i))?;
+            } else {
+                builder.append_null()?;
+            }
+        }
+    }
+
+    Ok(Arc::new(builder.finish()) as ArrayRef)
+}
+
+// for better performance, we manually concat primitive value buffers instead of using
+// PrimitiveBuilder
+fn concat_raw_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let value_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut null_count = 0;
+    let mut values_builder = BufferBuilder::<T>::new(value_count);
+    let mut null_bit_builder = BooleanBufferBuilder::new(value_count);
+
+    for array_data in array_data_list {
+        null_count += array_data.null_count();
+        let value_buffer = &array_data.buffers()[0];
+        values_builder.write_bytes(value_buffer.data(), value_buffer.len())?;
+        for i in 0..array_data.len() {
+            null_bit_builder.append(array_data.is_valid(i))?;
+        }
+    }
+
+    Ok(Arc::new(PrimitiveArray::<T>::from(
+        ArrayData::builder(T::get_data_type())
+            .len(value_count)
+            .add_buffer(values_builder.finish())
+            .null_count(null_count)
+            .null_bit_buffer(null_bit_builder.finish())
+            .build(),
+    )))
+}
+
+// for better performance, we manually concat string value buffers instead of using StringBuilder
+fn concat_raw_string(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef> {

Review comment:
       I've checked, we get this failure below:
   
   The same test failure occurs if you slice a numeric array.
   
   ```
   thread 'compute::kernels::concat::tests::test_concat_string_arrays' panicked at 'expect StringArray
   [
     "hello",
     "world",
     "1",
     "2",
     "3",
     "46f",
     "oob",
     null,
     "arb",
   ] to be: StringArray
   [
     "hello",
     "world",
     "2",
     "3",
     "4",
     "foo",
     "bar",
     null,
     "baz",
   ]', arrow/src/compute/kernels/concat.rs:296:9
   ```




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-641742155


   @nevi-me @andygrove rebased and ready for review


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r435071238



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let rows_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut builder = PrimitiveBuilder::<T>::new(rows_count);
+
+    for array_data in array_data_list {
+        let a = PrimitiveArray::<T>::from(array_data.clone());
+        for i in 0..a.len() {
+            if a.is_valid(i) {
+                builder.append_value(a.value(i))?;
+            } else {
+                builder.append_null()?;
+            }
+        }
+    }
+
+    Ok(Arc::new(builder.finish()) as ArrayRef)
+}
+
+// for better performance, we manually concat primitive value buffers instead of using
+// PrimitiveBuilder
+fn concat_raw_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let value_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut null_count = 0;
+    let mut values_builder = BufferBuilder::<T>::new(value_count);
+    let mut null_bit_builder = BooleanBufferBuilder::new(value_count);
+
+    for array_data in array_data_list {
+        null_count += array_data.null_count();
+        let value_buffer = &array_data.buffers()[0];
+        values_builder.write_bytes(value_buffer.data(), value_buffer.len())?;
+        for i in 0..array_data.len() {
+            null_bit_builder.append(array_data.is_valid(i))?;
+        }
+    }
+
+    Ok(Arc::new(PrimitiveArray::<T>::from(
+        ArrayData::builder(T::get_data_type())
+            .len(value_count)
+            .add_buffer(values_builder.finish())
+            .null_count(null_count)
+            .null_bit_buffer(null_bit_builder.finish())
+            .build(),
+    )))
+}
+
+// for better performance, we manually concat string value buffers instead of using StringBuilder
+fn concat_raw_string(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef> {

Review comment:
       Sorry, I meant slicing the second string array, something like below, which slices out "1" and "6" from the second array:
   
   ```rust
       fn test_concat_string_arrays() -> Result<()> {
           let arr = concat(&vec![
               Arc::new(
                   StringArray::try_from(vec![Some("hello"), Some("world")])
                       .expect("Unable to create string array"),
               ) as ArrayRef,
   
               // adding a comment for better visibility, slicing the array here
               StringArray::from(vec!["1", "2", "3", "4", "6"]).slice(1, 3),
               Arc::new(
                   StringArray::try_from(vec![Some("foo"), Some("bar"), None, Some("baz")])
                       .expect("Unable to create string array"),
               ) as ArrayRef,
           ])?;
   
           let expected_output = Arc::new(
               StringArray::try_from(vec![
                   Some("hello"),
                   Some("world"),
                   // Some("1"), // removed by offset of 1
                   Some("2"),
                   Some("3"),
                   Some("4"),
                   // Some("6"), // truncated by length of 3
                   Some("foo"),
                   Some("bar"),
                   None,
                   Some("baz"),
               ])
               .expect("Unable to create string array"),
           ) as ArrayRef;
   
           assert!(
               arr.equals(&(*expected_output)),
               "expect {:#?} to be: {:#?}",
               arr,
               &expected_output
           );
   
           Ok(())
       }
   ```
   
   The same might need to be verified with numeric arrays because we write the whole data in `write_slice`, so if there's an offset, we might get unexpected outputs.
   
   I'll check your branch out locally and check this.




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r437861027



##########
File path: rust/arrow/src/array/builder.rs
##########
@@ -1123,29 +1123,35 @@ fn append_binary_data(
         }
     }
 
-    for array in data {
-        // convert string to List<u8> to reuse list's cast
-        let int_data = &array.buffers()[1];
-        let int_data = Arc::new(ArrayData::new(
-            DataType::UInt8,
-            int_data.len(),
-            None,
-            None,
-            0,
-            vec![int_data.clone()],
-            vec![],
-        )) as ArrayDataRef;
-        let list_data = Arc::new(ArrayData::new(
-            DataType::List(Box::new(DataType::UInt8)),
-            array.len(),
-            None,
-            array.null_buffer().map(|buf| buf.clone()),
-            array.offset(),
-            vec![(&array.buffers()[0]).clone()],
-            vec![int_data],
-        ));
-        builder.append_data(&[list_data])?;
-    }
+    builder.append_data(

Review comment:
       move append_data out of the for loop so memory allocation count for buffers is constant.




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r435388355



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let rows_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut builder = PrimitiveBuilder::<T>::new(rows_count);
+
+    for array_data in array_data_list {
+        let a = PrimitiveArray::<T>::from(array_data.clone());
+        for i in 0..a.len() {
+            if a.is_valid(i) {
+                builder.append_value(a.value(i))?;
+            } else {
+                builder.append_null()?;
+            }
+        }
+    }
+
+    Ok(Arc::new(builder.finish()) as ArrayRef)
+}
+
+// for better performance, we manually concat primitive value buffers instead of using
+// PrimitiveBuilder
+fn concat_raw_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let value_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut null_count = 0;
+    let mut values_builder = BufferBuilder::<T>::new(value_count);
+    let mut null_bit_builder = BooleanBufferBuilder::new(value_count);
+
+    for array_data in array_data_list {
+        null_count += array_data.null_count();
+        let value_buffer = &array_data.buffers()[0];
+        values_builder.write_bytes(value_buffer.data(), value_buffer.len())?;
+        for i in 0..array_data.len() {
+            null_bit_builder.append(array_data.is_valid(i))?;
+        }
+    }
+
+    Ok(Arc::new(PrimitiveArray::<T>::from(
+        ArrayData::builder(T::get_data_type())
+            .len(value_count)
+            .add_buffer(values_builder.finish())
+            .null_count(null_count)
+            .null_bit_buffer(null_bit_builder.finish())
+            .build(),
+    )))
+}
+
+// for better performance, we manually concat string value buffers instead of using StringBuilder
+fn concat_raw_string(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef> {

Review comment:
       I'm nearly done with `append_data()`, which handles offsets. Is it worthwhile to wait for it? I can put up a draft PR tonight




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r436252687



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let rows_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut builder = PrimitiveBuilder::<T>::new(rows_count);
+
+    for array_data in array_data_list {
+        let a = PrimitiveArray::<T>::from(array_data.clone());
+        for i in 0..a.len() {
+            if a.is_valid(i) {
+                builder.append_value(a.value(i))?;
+            } else {
+                builder.append_null()?;
+            }
+        }
+    }
+
+    Ok(Arc::new(builder.finish()) as ArrayRef)
+}
+
+// for better performance, we manually concat primitive value buffers instead of using
+// PrimitiveBuilder
+fn concat_raw_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let value_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut null_count = 0;
+    let mut values_builder = BufferBuilder::<T>::new(value_count);
+    let mut null_bit_builder = BooleanBufferBuilder::new(value_count);
+
+    for array_data in array_data_list {
+        null_count += array_data.null_count();
+        let value_buffer = &array_data.buffers()[0];
+        values_builder.write_bytes(value_buffer.data(), value_buffer.len())?;
+        for i in 0..array_data.len() {
+            null_bit_builder.append(array_data.is_valid(i))?;
+        }
+    }
+
+    Ok(Arc::new(PrimitiveArray::<T>::from(
+        ArrayData::builder(T::get_data_type())
+            .len(value_count)
+            .add_buffer(values_builder.finish())
+            .null_count(null_count)
+            .null_bit_buffer(null_bit_builder.finish())
+            .build(),
+    )))
+}
+
+// for better performance, we manually concat string value buffers instead of using StringBuilder
+fn concat_raw_string(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef> {

Review comment:
       great work on #7365, looking forward to refactor/simplify this PR after it's merged!




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-640006429


   @andygrove sent PR to sqlparser: https://github.com/andygrove/sqlparser-rs/pull/185.
   
   I recommend we focus on reviewing and getting https://github.com/apache/arrow/pull/7365 merged first. Then I can refactor this PR to use append_data methods.


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-638641720


   @andygrove since you mentioned 0.2 branch, do you expect datafusion to migrate to latest sqlparser-rs in the near future or are we going to stay with 0.2 for a long time? I already started a local branch to for the migration, but if we do want to stay on 0.2 release, then I should probably stop working on that ;)


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r435430674



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let rows_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut builder = PrimitiveBuilder::<T>::new(rows_count);
+
+    for array_data in array_data_list {
+        let a = PrimitiveArray::<T>::from(array_data.clone());
+        for i in 0..a.len() {
+            if a.is_valid(i) {
+                builder.append_value(a.value(i))?;
+            } else {
+                builder.append_null()?;
+            }
+        }
+    }
+
+    Ok(Arc::new(builder.finish()) as ArrayRef)
+}
+
+// for better performance, we manually concat primitive value buffers instead of using
+// PrimitiveBuilder
+fn concat_raw_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let value_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut null_count = 0;
+    let mut values_builder = BufferBuilder::<T>::new(value_count);
+    let mut null_bit_builder = BooleanBufferBuilder::new(value_count);
+
+    for array_data in array_data_list {
+        null_count += array_data.null_count();
+        let value_buffer = &array_data.buffers()[0];
+        values_builder.write_bytes(value_buffer.data(), value_buffer.len())?;
+        for i in 0..array_data.len() {
+            null_bit_builder.append(array_data.is_valid(i))?;
+        }
+    }
+
+    Ok(Arc::new(PrimitiveArray::<T>::from(
+        ArrayData::builder(T::get_data_type())
+            .len(value_count)
+            .add_buffer(values_builder.finish())
+            .null_count(null_count)
+            .null_bit_buffer(null_bit_builder.finish())
+            .build(),
+    )))
+}
+
+// for better performance, we manually concat string value buffers instead of using StringBuilder
+fn concat_raw_string(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef> {

Review comment:
       Yeah, let's wait for that. I was going to refactor this code by implementing append_data. Good to avoid duplicate efforts :D




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] andygrove commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
andygrove commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-638230644


   @houqp There is a 0.2 branch in sqlparser-rs where you can apply your changes and I can make a new 0.2.x release


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] andygrove commented on pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
andygrove commented on pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#issuecomment-639193504


   @houqp Please take a look at https://issues.apache.org/jira/browse/ARROW-8824 regarding the SQL parser conversation


----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] nevi-me commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r435423018



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let rows_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut builder = PrimitiveBuilder::<T>::new(rows_count);
+
+    for array_data in array_data_list {
+        let a = PrimitiveArray::<T>::from(array_data.clone());
+        for i in 0..a.len() {
+            if a.is_valid(i) {
+                builder.append_value(a.value(i))?;
+            } else {
+                builder.append_null()?;
+            }
+        }
+    }
+
+    Ok(Arc::new(builder.finish()) as ArrayRef)
+}
+
+// for better performance, we manually concat primitive value buffers instead of using
+// PrimitiveBuilder
+fn concat_raw_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>
+where
+    T: ArrowPrimitiveType,
+{
+    let value_count = array_data_list.iter().map(|a| a.len()).sum::<usize>();
+    let mut null_count = 0;
+    let mut values_builder = BufferBuilder::<T>::new(value_count);
+    let mut null_bit_builder = BooleanBufferBuilder::new(value_count);
+
+    for array_data in array_data_list {
+        null_count += array_data.null_count();
+        let value_buffer = &array_data.buffers()[0];
+        values_builder.write_bytes(value_buffer.data(), value_buffer.len())?;
+        for i in 0..array_data.len() {
+            null_bit_builder.append(array_data.is_valid(i))?;
+        }
+    }
+
+    Ok(Arc::new(PrimitiveArray::<T>::from(
+        ArrayData::builder(T::get_data_type())
+            .len(value_count)
+            .add_buffer(values_builder.finish())
+            .null_count(null_count)
+            .null_bit_buffer(null_bit_builder.finish())
+            .build(),
+    )))
+}
+
+// for better performance, we manually concat string value buffers instead of using StringBuilder
+fn concat_raw_string(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef> {

Review comment:
       @houqp here's a WIP of the changes: https://github.com/apache/arrow/compare/master...nevi-me:ARROW-9007
   
   I'm still testing the string and nested array types, but the primitive types behave fine with offsets




----------------------------------------------------------------
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:
users@infra.apache.org



[GitHub] [arrow] houqp commented on a change in pull request #7324: ARROW-9005: [Rust] [Datafusion] support sort expression

Posted by GitBox <gi...@apache.org>.
houqp commented on a change in pull request #7324:
URL: https://github.com/apache/arrow/pull/7324#discussion_r435023936



##########
File path: rust/arrow/src/compute/kernels/concat.rs
##########
@@ -0,0 +1,395 @@
+// 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 std::sync::Arc;
+
+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 data type".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(
+                "Cannot concat 0 array".to_string(),
+            ));
+        }
+        Some(t) => t,
+    };
+    match data_type {
+        DataType::Utf8 => concat_raw_string(array_data_list),
+        DataType::Boolean => concat_primitive::<BooleanType>(array_data_list),
+        DataType::Int8 => concat_raw_primitive::<Int8Type>(array_data_list),
+        DataType::Int16 => concat_raw_primitive::<Int16Type>(array_data_list),
+        DataType::Int32 => concat_raw_primitive::<Int32Type>(array_data_list),
+        DataType::Int64 => concat_raw_primitive::<Int64Type>(array_data_list),
+        DataType::UInt8 => concat_raw_primitive::<UInt8Type>(array_data_list),
+        DataType::UInt16 => concat_raw_primitive::<UInt16Type>(array_data_list),
+        DataType::UInt32 => concat_raw_primitive::<UInt32Type>(array_data_list),
+        DataType::UInt64 => concat_raw_primitive::<UInt64Type>(array_data_list),
+        DataType::Float32 => concat_raw_primitive::<Float32Type>(array_data_list),
+        DataType::Float64 => concat_raw_primitive::<Float64Type>(array_data_list),
+        DataType::Date32(_) => concat_raw_primitive::<Date32Type>(array_data_list),
+        DataType::Date64(_) => concat_raw_primitive::<Date64Type>(array_data_list),
+        DataType::Time32(Second) => {
+            concat_raw_primitive::<Time32SecondType>(array_data_list)
+        }
+        DataType::Time32(Millisecond) => {
+            concat_raw_primitive::<Time32MillisecondType>(array_data_list)
+        }
+        DataType::Time64(Microsecond) => {
+            concat_raw_primitive::<Time64MicrosecondType>(array_data_list)
+        }
+        DataType::Time64(Nanosecond) => {
+            concat_raw_primitive::<Time64NanosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Second, _) => {
+            concat_raw_primitive::<TimestampSecondType>(array_data_list)
+        }
+        DataType::Timestamp(Millisecond, _) => {
+            concat_raw_primitive::<TimestampMillisecondType>(array_data_list)
+        }
+        DataType::Timestamp(Microsecond, _) => {
+            concat_raw_primitive::<TimestampMicrosecondType>(array_data_list)
+        }
+        DataType::Timestamp(Nanosecond, _) => {
+            concat_raw_primitive::<TimestampNanosecondType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::YearMonth) => {
+            concat_raw_primitive::<IntervalYearMonthType>(array_data_list)
+        }
+        DataType::Interval(IntervalUnit::DayTime) => {
+            concat_raw_primitive::<IntervalDayTimeType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Second) => {
+            concat_raw_primitive::<DurationSecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Millisecond) => {
+            concat_raw_primitive::<DurationMillisecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Microsecond) => {
+            concat_raw_primitive::<DurationMicrosecondType>(array_data_list)
+        }
+        DataType::Duration(TimeUnit::Nanosecond) => {
+            concat_raw_primitive::<DurationNanosecondType>(array_data_list)
+        }
+        t => unimplemented!("Concat not supported for data type {:?}", t),
+    }
+}
+
+fn concat_primitive<T>(array_data_list: &Vec<ArrayDataRef>) -> Result<ArrayRef>

Review comment:
       good catch. I have updated it.




----------------------------------------------------------------
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:
users@infra.apache.org