Skip to main content

arrow_select/
concat.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Defines concat kernel for `ArrayRef`
19//!
20//! Example:
21//!
22//! ```
23//! use arrow_array::{ArrayRef, StringArray};
24//! use arrow_select::concat::concat;
25//!
26//! let arr = concat(&[
27//!     &StringArray::from(vec!["hello", "world"]),
28//!     &StringArray::from(vec!["!"]),
29//! ]).unwrap();
30//! assert_eq!(arr.len(), 3);
31//! ```
32
33use crate::dictionary::{merge_dictionary_values, should_merge_dictionary_values};
34use arrow_array::builder::{
35    BooleanBuilder, GenericByteBuilder, GenericByteViewBuilder, PrimitiveBuilder,
36};
37use arrow_array::cast::AsArray;
38use arrow_array::types::*;
39use arrow_array::*;
40use arrow_buffer::{
41    ArrowNativeType, BooleanBufferBuilder, MutableBuffer, NullBuffer, OffsetBuffer, ScalarBuffer,
42};
43use arrow_data::ArrayDataBuilder;
44use arrow_data::transform::{Capacities, MutableArrayData};
45use arrow_schema::{ArrowError, DataType, FieldRef, Fields, SchemaRef};
46use std::{collections::HashSet, ops::Add, sync::Arc};
47
48fn binary_capacity<T: ByteArrayType>(arrays: &[&dyn Array]) -> Capacities {
49    let mut item_capacity = 0;
50    let mut bytes_capacity = 0;
51    for array in arrays {
52        let a = array.as_bytes::<T>();
53
54        // Guaranteed to always have at least one element
55        let offsets = a.value_offsets();
56        bytes_capacity += offsets[offsets.len() - 1].as_usize() - offsets[0].as_usize();
57        item_capacity += a.len()
58    }
59
60    Capacities::Binary(item_capacity, Some(bytes_capacity))
61}
62
63fn fixed_size_list_capacity(arrays: &[&dyn Array], data_type: &DataType) -> Capacities {
64    if let DataType::FixedSizeList(f, _) = data_type {
65        let item_capacity = arrays.iter().map(|a| a.len()).sum();
66        let child_data_type = f.data_type();
67        match child_data_type {
68            // These types should match the types that `get_capacity`
69            // has special handling for.
70            DataType::Utf8
71            | DataType::LargeUtf8
72            | DataType::Binary
73            | DataType::LargeBinary
74            | DataType::FixedSizeList(_, _) => {
75                let values: Vec<&dyn arrow_array::Array> = arrays
76                    .iter()
77                    .map(|a| a.as_fixed_size_list().values().as_ref())
78                    .collect();
79                Capacities::List(
80                    item_capacity,
81                    Some(Box::new(get_capacity(&values, child_data_type))),
82                )
83            }
84            _ => Capacities::Array(item_capacity),
85        }
86    } else {
87        unreachable!("illegal data type for fixed size list")
88    }
89}
90
91fn concat_byte_view<B: ByteViewType>(arrays: &[&dyn Array]) -> Result<ArrayRef, ArrowError> {
92    let mut builder =
93        GenericByteViewBuilder::<B>::with_capacity(arrays.iter().map(|a| a.len()).sum());
94    for &array in arrays.iter() {
95        builder.append_array(array.as_byte_view());
96    }
97    Ok(Arc::new(builder.finish()))
98}
99
100fn concat_dictionaries<K: ArrowDictionaryKeyType>(
101    arrays: &[&dyn Array],
102) -> Result<ArrayRef, ArrowError> {
103    let mut output_len = 0;
104    let dictionaries: Vec<_> = arrays
105        .iter()
106        .map(|x| x.as_dictionary::<K>())
107        .inspect(|d| output_len += d.len())
108        .collect();
109
110    if !should_merge_dictionary_values::<K>(&dictionaries, output_len).0 {
111        return concat_fallback(arrays, Capacities::Array(output_len));
112    }
113
114    let merged = merge_dictionary_values(&dictionaries, None)?;
115
116    // Recompute keys
117    let mut key_values = Vec::with_capacity(output_len);
118
119    let mut has_nulls = false;
120    for (d, mapping) in dictionaries.iter().zip(merged.key_mappings) {
121        has_nulls |= d.null_count() != 0;
122        for key in d.keys().values() {
123            // Use get to safely handle nulls
124            key_values.push(mapping.get(key.as_usize()).copied().unwrap_or_default())
125        }
126    }
127
128    let nulls = has_nulls.then(|| {
129        let mut nulls = BooleanBufferBuilder::new(output_len);
130        for d in &dictionaries {
131            match d.nulls() {
132                Some(n) => nulls.append_buffer(n.inner()),
133                None => nulls.append_n(d.len(), true),
134            }
135        }
136        NullBuffer::new(nulls.finish())
137    });
138
139    let keys = PrimitiveArray::<K>::try_new(key_values.into(), nulls)?;
140    // Sanity check
141    assert_eq!(keys.len(), output_len);
142
143    let array = unsafe { DictionaryArray::new_unchecked(keys, merged.values) };
144    Ok(Arc::new(array))
145}
146
147fn concat_lists<OffsetSize: OffsetSizeTrait>(
148    arrays: &[&dyn Array],
149    field: &FieldRef,
150) -> Result<ArrayRef, ArrowError> {
151    let mut output_len = 0;
152    let mut list_has_nulls = false;
153    let mut list_has_slices = false;
154
155    let lists = arrays
156        .iter()
157        .map(|x| x.as_list::<OffsetSize>())
158        .inspect(|l| {
159            output_len += l.len();
160            list_has_nulls |= l.null_count() != 0;
161            list_has_slices |= l.offsets()[0] > OffsetSize::zero()
162                || l.offsets().last().unwrap().as_usize() < l.values().len();
163        })
164        .collect::<Vec<_>>();
165
166    let lists_nulls = list_has_nulls.then(|| {
167        let mut nulls = BooleanBufferBuilder::new(output_len);
168        for l in &lists {
169            match l.nulls() {
170                Some(n) => nulls.append_buffer(n.inner()),
171                None => nulls.append_n(l.len(), true),
172            }
173        }
174        NullBuffer::new(nulls.finish())
175    });
176
177    // If any of the lists have slices, we need to slice the values
178    // to ensure that the offsets are correct
179    let mut sliced_values;
180    let values: Vec<&dyn Array> = if list_has_slices {
181        sliced_values = Vec::with_capacity(lists.len());
182        for l in &lists {
183            // if the first offset is non-zero, we need to slice the values so when
184            // we concatenate them below only the relevant values are included
185            let offsets = l.offsets();
186            let start_offset = offsets[0].as_usize();
187            let end_offset = offsets.last().unwrap().as_usize();
188            sliced_values.push(l.values().slice(start_offset, end_offset - start_offset));
189        }
190        sliced_values.iter().map(|a| a.as_ref()).collect()
191    } else {
192        lists.iter().map(|x| x.values().as_ref()).collect()
193    };
194
195    let concatenated_values = concat(values.as_slice())?;
196
197    // Merge value offsets from the lists
198    let value_offset_buffer =
199        OffsetBuffer::<OffsetSize>::from_lengths(lists.iter().flat_map(|x| x.offsets().lengths()));
200
201    let array = GenericListArray::<OffsetSize>::try_new(
202        Arc::clone(field),
203        value_offset_buffer,
204        concatenated_values,
205        lists_nulls,
206    )?;
207
208    Ok(Arc::new(array))
209}
210
211fn concat_maps(
212    arrays: &[&dyn Array],
213    field: &FieldRef,
214    ordered: bool,
215) -> Result<ArrayRef, ArrowError> {
216    let mut output_len = 0;
217    let mut map_has_nulls = false;
218    let mut map_has_slices = false;
219
220    let maps = arrays
221        .iter()
222        .map(|x| x.as_map())
223        .inspect(|m| {
224            output_len += m.len();
225            map_has_nulls |= m.null_count() != 0;
226            map_has_slices |=
227                m.offsets()[0] > 0 || m.offsets().last().unwrap().as_usize() < m.entries().len();
228        })
229        .collect::<Vec<_>>();
230
231    let map_nulls = map_has_nulls.then(|| {
232        let mut nulls = BooleanBufferBuilder::new(output_len);
233        for m in &maps {
234            match m.nulls() {
235                Some(n) => nulls.append_buffer(n.inner()),
236                None => nulls.append_n(m.len(), true),
237            }
238        }
239        NullBuffer::new(nulls.finish())
240    });
241
242    // If any of the maps have slices, we need to slice the entries
243    // to ensure that the offsets are correct
244    let mut sliced_entries: Vec<ArrayRef>;
245    let entries: Vec<&dyn Array> = if map_has_slices {
246        sliced_entries = Vec::with_capacity(maps.len());
247        for m in &maps {
248            let offsets = m.offsets();
249            let start_offset = offsets[0].as_usize();
250            let end_offset = offsets.last().unwrap().as_usize();
251            let entries_arr: &dyn Array = m.entries();
252            sliced_entries.push(entries_arr.slice(start_offset, end_offset - start_offset));
253        }
254        sliced_entries.iter().map(|a| a.as_ref()).collect()
255    } else {
256        maps.iter().map(|m| m.entries() as &dyn Array).collect()
257    };
258
259    let concatenated_entries = concat(entries.as_slice())?;
260
261    // Merge value offsets from the maps
262    let value_offset_buffer =
263        OffsetBuffer::<i32>::from_lengths(maps.iter().flat_map(|m| m.offsets().lengths()));
264
265    let array = MapArray::try_new(
266        Arc::clone(field),
267        value_offset_buffer,
268        // Safety: Map entries are always StructArrays, so this downcast is guaranteed to succeed
269        concatenated_entries.as_struct().clone(),
270        map_nulls,
271        ordered,
272    )?;
273
274    Ok(Arc::new(array))
275}
276
277fn concat_list_view<OffsetSize: OffsetSizeTrait>(
278    arrays: &[&dyn Array],
279    field: &FieldRef,
280) -> Result<ArrayRef, ArrowError> {
281    let mut output_len = 0;
282    let mut list_has_nulls = false;
283
284    let lists = arrays
285        .iter()
286        .map(|x| x.as_list_view::<OffsetSize>())
287        .inspect(|l| {
288            output_len += l.len();
289            list_has_nulls |= l.null_count() != 0;
290        })
291        .collect::<Vec<_>>();
292
293    let lists_nulls = list_has_nulls.then(|| {
294        let mut nulls = BooleanBufferBuilder::new(output_len);
295        for l in &lists {
296            match l.nulls() {
297                Some(n) => nulls.append_buffer(n.inner()),
298                None => nulls.append_n(l.len(), true),
299            }
300        }
301        NullBuffer::new(nulls.finish())
302    });
303
304    let values: Vec<&dyn Array> = lists.iter().map(|l| l.values().as_ref()).collect();
305
306    let concatenated_values = concat(values.as_slice())?;
307
308    let sizes: ScalarBuffer<OffsetSize> = lists.iter().flat_map(|x| x.sizes()).copied().collect();
309
310    let mut offsets = MutableBuffer::with_capacity(lists.iter().map(|l| l.offsets().len()).sum());
311    let mut global_offset = OffsetSize::zero();
312    for l in lists.iter() {
313        for &offset in l.offsets() {
314            offsets.push(offset + global_offset);
315        }
316
317        // advance the offsets
318        global_offset += OffsetSize::from_usize(l.values().len()).unwrap();
319    }
320
321    let offsets = ScalarBuffer::from(offsets);
322
323    let array = GenericListViewArray::try_new(
324        field.clone(),
325        offsets,
326        sizes,
327        concatenated_values,
328        lists_nulls,
329    )?;
330
331    Ok(Arc::new(array))
332}
333
334fn concat_primitives<T: ArrowPrimitiveType>(arrays: &[&dyn Array]) -> Result<ArrayRef, ArrowError> {
335    let mut builder = PrimitiveBuilder::<T>::with_capacity(arrays.iter().map(|a| a.len()).sum())
336        .with_data_type(arrays[0].data_type().clone());
337
338    for array in arrays {
339        builder.append_array(array.as_primitive());
340    }
341
342    Ok(Arc::new(builder.finish()))
343}
344
345fn concat_boolean(arrays: &[&dyn Array]) -> Result<ArrayRef, ArrowError> {
346    let mut builder = BooleanBuilder::with_capacity(arrays.iter().map(|a| a.len()).sum());
347
348    for array in arrays {
349        builder.append_array(array.as_boolean());
350    }
351
352    Ok(Arc::new(builder.finish()))
353}
354
355fn concat_bytes<T: ByteArrayType>(arrays: &[&dyn Array]) -> Result<ArrayRef, ArrowError> {
356    let (item_capacity, bytes_capacity) = match binary_capacity::<T>(arrays) {
357        Capacities::Binary(item_capacity, Some(bytes_capacity)) => (item_capacity, bytes_capacity),
358        _ => unreachable!(),
359    };
360
361    let mut builder = GenericByteBuilder::<T>::with_capacity(item_capacity, bytes_capacity);
362
363    for array in arrays {
364        builder.append_array(array.as_bytes::<T>())?;
365    }
366
367    Ok(Arc::new(builder.finish()))
368}
369
370fn concat_structs(arrays: &[&dyn Array], fields: &Fields) -> Result<ArrayRef, ArrowError> {
371    let mut len = 0;
372    let mut has_nulls = false;
373    let structs = arrays
374        .iter()
375        .map(|a| {
376            len += a.len();
377            has_nulls |= a.null_count() > 0;
378            a.as_struct()
379        })
380        .collect::<Vec<_>>();
381
382    let nulls = has_nulls.then(|| {
383        let mut b = BooleanBufferBuilder::new(len);
384        for s in &structs {
385            match s.nulls() {
386                Some(n) => b.append_buffer(n.inner()),
387                None => b.append_n(s.len(), true),
388            }
389        }
390        NullBuffer::new(b.finish())
391    });
392
393    let column_concat_result = (0..fields.len())
394        .map(|i| {
395            let extracted_cols = structs
396                .iter()
397                .map(|s| s.column(i).as_ref())
398                .collect::<Vec<_>>();
399            concat(&extracted_cols)
400        })
401        .collect::<Result<Vec<_>, ArrowError>>()?;
402
403    Ok(Arc::new(StructArray::try_new_with_length(
404        fields.clone(),
405        column_concat_result,
406        nulls,
407        len,
408    )?))
409}
410
411/// Concatenate multiple RunArray instances into a single RunArray.
412///
413/// This function handles the special case of concatenating RunArrays by:
414/// 1. Collecting all run ends and values from input arrays
415/// 2. Adjusting run ends to account for the length of previous arrays
416/// 3. Creating a new RunArray with the combined data
417fn concat_run_arrays<R: RunEndIndexType>(arrays: &[&dyn Array]) -> Result<ArrayRef, ArrowError>
418where
419    R::Native: Add<Output = R::Native>,
420{
421    let run_arrays: Vec<_> = arrays
422        .iter()
423        .map(|x| x.as_run::<R>())
424        .filter(|x| !x.run_ends().is_empty())
425        .collect();
426
427    if run_arrays.is_empty() {
428        // If all input arrays are empty then handle here otherwise we
429        // lose the type below
430        return Ok(new_empty_array(arrays[0].data_type()));
431    }
432
433    // The run ends need to be adjusted by the sum of the lengths of the previous arrays.
434    let needed_run_end_adjustments = std::iter::once(R::default_value())
435        .chain(
436            run_arrays
437                .iter()
438                .scan(R::default_value(), |acc, run_array| {
439                    *acc = *acc + R::Native::from_usize(run_array.len()).unwrap();
440                    Some(*acc)
441                }),
442        )
443        .collect::<Vec<_>>();
444
445    // This works out nicely to be the total (logical) length of the resulting array.
446    let total_len = needed_run_end_adjustments.last().unwrap().as_usize();
447
448    let run_ends_array =
449        PrimitiveArray::<R>::from_iter_values(run_arrays.iter().enumerate().flat_map(
450            move |(i, run_array)| {
451                let adjustment = needed_run_end_adjustments[i];
452                run_array
453                    .run_ends()
454                    .sliced_values()
455                    .map(move |run_end| run_end + adjustment)
456            },
457        ));
458
459    let values_slices: Vec<ArrayRef> = run_arrays
460        .iter()
461        .map(|run_array| run_array.values_slice())
462        .collect();
463
464    let all_values = concat(&values_slices.iter().map(|x| x.as_ref()).collect::<Vec<_>>())?;
465
466    let builder = ArrayDataBuilder::new(run_arrays[0].data_type().clone())
467        .len(total_len)
468        .child_data(vec![run_ends_array.into_data(), all_values.into_data()]);
469
470    // `build_unchecked` is used to avoid recursive validation of child arrays.
471    let array_data = unsafe { builder.build_unchecked() };
472    array_data.validate_data()?;
473
474    Ok(Arc::<RunArray<R>>::new(array_data.into()))
475}
476
477macro_rules! dict_helper {
478    ($t:ty, $arrays:expr) => {
479        return concat_dictionaries::<$t>($arrays)
480    };
481}
482
483macro_rules! primitive_concat {
484    ($t:ty, $arrays:expr) => {
485        return concat_primitives::<$t>($arrays)
486    };
487}
488
489fn get_capacity(arrays: &[&dyn Array], data_type: &DataType) -> Capacities {
490    match data_type {
491        DataType::Utf8 => binary_capacity::<Utf8Type>(arrays),
492        DataType::LargeUtf8 => binary_capacity::<LargeUtf8Type>(arrays),
493        DataType::Binary => binary_capacity::<BinaryType>(arrays),
494        DataType::LargeBinary => binary_capacity::<LargeBinaryType>(arrays),
495        DataType::FixedSizeList(_, _) => fixed_size_list_capacity(arrays, data_type),
496        _ => Capacities::Array(arrays.iter().map(|a| a.len()).sum()),
497    }
498}
499
500/// Concatenate multiple [Array] of the same type into a single [ArrayRef].
501pub fn concat(arrays: &[&dyn Array]) -> Result<ArrayRef, ArrowError> {
502    if arrays.is_empty() {
503        return Err(ArrowError::ComputeError(
504            "concat requires input of at least one array".to_string(),
505        ));
506    } else if arrays.len() == 1 {
507        let array = arrays[0];
508        return Ok(array.slice(0, array.len()));
509    }
510
511    let d = arrays[0].data_type();
512    if arrays.iter().skip(1).any(|array| array.data_type() != d) {
513        // Create error message with up to 10 unique data types in the order they appear
514        let error_message = {
515            // 10 max unique data types to print and another 1 to know if there are more
516            let mut unique_data_types = HashSet::with_capacity(11);
517
518            let mut error_message =
519                format!("It is not possible to concatenate arrays of different data types ({d}");
520            unique_data_types.insert(d);
521
522            for array in arrays {
523                let is_unique = unique_data_types.insert(array.data_type());
524
525                if unique_data_types.len() == 11 {
526                    error_message.push_str(", ...");
527                    break;
528                }
529
530                if is_unique {
531                    error_message.push_str(", ");
532                    error_message.push_str(&array.data_type().to_string());
533                }
534            }
535
536            error_message.push_str(").");
537
538            error_message
539        };
540
541        return Err(ArrowError::InvalidArgumentError(error_message));
542    }
543
544    downcast_primitive! {
545        d => (primitive_concat, arrays),
546        DataType::Boolean => concat_boolean(arrays),
547        DataType::Dictionary(k, _) => {
548            downcast_integer! {
549                k.as_ref() => (dict_helper, arrays),
550                _ => unreachable!("illegal dictionary key type {k}")
551            }
552        }
553        DataType::List(field) => concat_lists::<i32>(arrays, field),
554        DataType::LargeList(field) => concat_lists::<i64>(arrays, field),
555        DataType::ListView(field) => concat_list_view::<i32>(arrays, field),
556        DataType::LargeListView(field) => concat_list_view::<i64>(arrays, field),
557        DataType::Map(field, ordered) => concat_maps(arrays, field, *ordered),
558        DataType::Struct(fields) => concat_structs(arrays, fields),
559        DataType::Utf8 => concat_bytes::<Utf8Type>(arrays),
560        DataType::LargeUtf8 => concat_bytes::<LargeUtf8Type>(arrays),
561        DataType::Binary => concat_bytes::<BinaryType>(arrays),
562        DataType::LargeBinary => concat_bytes::<LargeBinaryType>(arrays),
563        DataType::RunEndEncoded(r, _) => {
564            // Handle RunEndEncoded arrays with special concat function
565            // We need to downcast based on the run end type
566            match r.data_type() {
567                DataType::Int16 => concat_run_arrays::<Int16Type>(arrays),
568                DataType::Int32 => concat_run_arrays::<Int32Type>(arrays),
569                DataType::Int64 => concat_run_arrays::<Int64Type>(arrays),
570                _ => unreachable!("Unsupported run end index type: {r:?}"),
571            }
572        }
573        DataType::Utf8View => concat_byte_view::<StringViewType>(arrays),
574        DataType::BinaryView => concat_byte_view::<BinaryViewType>(arrays),
575        _ => {
576            let capacity = get_capacity(arrays, d);
577            concat_fallback(arrays, capacity)
578        }
579    }
580}
581
582/// Concatenates arrays using MutableArrayData
583///
584/// This will naively concatenate dictionaries
585fn concat_fallback(arrays: &[&dyn Array], capacity: Capacities) -> Result<ArrayRef, ArrowError> {
586    let array_data: Vec<_> = arrays.iter().map(|a| a.to_data()).collect::<Vec<_>>();
587    let array_data = array_data.iter().collect();
588    let mut mutable = MutableArrayData::with_capacities(array_data, false, capacity);
589
590    for (i, a) in arrays.iter().enumerate() {
591        mutable.try_extend(i, 0, a.len())?
592    }
593
594    Ok(make_array(mutable.freeze()))
595}
596
597/// Concatenates `batches` together into a single [`RecordBatch`].
598///
599/// The output batch has the specified `schemas`; The schema of the
600/// input are ignored.
601///
602/// # Notes
603///
604/// - Callers should budget for peak memory use to approach 2x the input
605///   size, as the input batches and output arrays co-exist during construction.
606/// - Arrays with `i32` offsets, such as `StringArray` and `BinaryArray`, only
607///   support up to ~2GiB of payloads. Concatenating large arrays of these types
608///   can cause offset overflows.
609///
610/// # Errors
611///
612/// Returns an error if the types of underlying arrays are different.
613pub fn concat_batches<'a>(
614    schema: &SchemaRef,
615    input_batches: impl IntoIterator<Item = &'a RecordBatch>,
616) -> Result<RecordBatch, ArrowError> {
617    // When schema is empty, sum the number of the rows of all batches
618    if schema.fields().is_empty() {
619        let num_rows: usize = input_batches.into_iter().map(RecordBatch::num_rows).sum();
620        let mut options = RecordBatchOptions::default();
621        options.row_count = Some(num_rows);
622        return RecordBatch::try_new_with_options(schema.clone(), vec![], &options);
623    }
624
625    let batches: Vec<&RecordBatch> = input_batches.into_iter().collect();
626    if batches.is_empty() {
627        return Ok(RecordBatch::new_empty(schema.clone()));
628    }
629    let field_num = schema.fields().len();
630    let mut arrays = Vec::with_capacity(field_num);
631    for i in 0..field_num {
632        let array = concat(
633            &batches
634                .iter()
635                .map(|batch| batch.column(i).as_ref())
636                .collect::<Vec<_>>(),
637        )?;
638        arrays.push(array);
639    }
640    RecordBatch::try_new(schema.clone(), arrays)
641}
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646    use arrow_array::builder::{
647        GenericListBuilder, Int32Builder as Int32ArrayBuilder, Int64Builder, ListViewBuilder,
648        MapBuilder, StringBuilder, StringDictionaryBuilder,
649    };
650    use arrow_schema::{Field, Schema};
651    use std::fmt::Debug;
652
653    #[test]
654    fn test_dict_overflow_9366() {
655        use arrow_schema::DataType;
656
657        let schema = Arc::new(Schema::new(vec![Field::new(
658            "a",
659            DataType::Dictionary(
660                Box::new(DataType::UInt8),
661                Box::new(DataType::FixedSizeBinary(8)),
662            ),
663            false,
664        )]));
665        let make = |vals: std::ops::Range<u64>| {
666            let dict = FixedSizeBinaryArray::try_from_iter(vals.map(|i| i.to_le_bytes())).unwrap();
667            let keys = UInt8Array::from_iter_values(0..128);
668            let arr = DictionaryArray::try_new(keys, Arc::new(dict)).unwrap();
669            RecordBatch::try_new(schema.clone(), vec![Arc::new(arr)]).unwrap()
670        };
671        // 256 distinct values fit in u8 keys (0..=255): concat must succeed.
672        let out = concat_batches(&schema, &[make(0..128), make(128..256)]).unwrap();
673        assert_eq!(out.num_rows(), 256);
674        let dict = out.column(0).as_dictionary::<UInt8Type>();
675        assert_eq!(dict.values().len(), 256);
676    }
677
678    #[test]
679    fn test_dict_overflow_i8_9366() {
680        use arrow_schema::DataType;
681
682        // Same boundary for a signed key type: i8 holds 128 keys (0..=127).
683        let schema = Arc::new(Schema::new(vec![Field::new(
684            "a",
685            DataType::Dictionary(
686                Box::new(DataType::Int8),
687                Box::new(DataType::FixedSizeBinary(8)),
688            ),
689            false,
690        )]));
691        let make = |vals: std::ops::Range<u64>| {
692            let dict = FixedSizeBinaryArray::try_from_iter(vals.map(|i| i.to_le_bytes())).unwrap();
693            let keys = Int8Array::from_iter_values(0..64);
694            let arr = DictionaryArray::try_new(keys, Arc::new(dict)).unwrap();
695            RecordBatch::try_new(schema.clone(), vec![Arc::new(arr)]).unwrap()
696        };
697        let out = concat_batches(&schema, &[make(0..64), make(64..128)]).unwrap();
698        assert_eq!(out.num_rows(), 128);
699        let dict = out.column(0).as_dictionary::<Int8Type>();
700        assert_eq!(dict.values().len(), 128);
701    }
702
703    #[test]
704    fn test_concat_empty_vec() {
705        let re = concat(&[]);
706        assert!(re.is_err());
707    }
708
709    #[test]
710    fn test_concat_batches_no_columns() {
711        // Test concat using empty schema / batches without columns
712        let schema = Arc::new(Schema::empty());
713
714        let mut options = RecordBatchOptions::default();
715        options.row_count = Some(100);
716        let batch = RecordBatch::try_new_with_options(schema.clone(), vec![], &options).unwrap();
717        // put in 2 batches of 100 rows each
718        let re = concat_batches(&schema, &[batch.clone(), batch]).unwrap();
719
720        assert_eq!(re.num_rows(), 200);
721    }
722
723    #[test]
724    fn test_concat_one_element_vec() {
725        let arr = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
726            Some(-1),
727            Some(2),
728            None,
729        ])) as ArrayRef;
730        let result = concat(&[arr.as_ref()]).unwrap();
731        assert_eq!(
732            &arr, &result,
733            "concatenating single element array gives back the same result"
734        );
735    }
736
737    #[test]
738    fn test_concat_incompatible_datatypes() {
739        let re = concat(&[
740            &PrimitiveArray::<Int64Type>::from(vec![Some(-1), Some(2), None]),
741            // 2 string to make sure we only mention unique types
742            &StringArray::from(vec![Some("hello"), Some("bar"), Some("world")]),
743            &StringArray::from(vec![Some("hey"), Some(""), Some("you")]),
744            // Another type to make sure we are showing all the incompatible types
745            &PrimitiveArray::<Int32Type>::from(vec![Some(-1), Some(2), None]),
746        ]);
747
748        assert_eq!(
749            re.unwrap_err().to_string(),
750            "Invalid argument error: It is not possible to concatenate arrays of different data types (Int64, Utf8, Int32)."
751        );
752    }
753
754    #[test]
755    fn test_concat_10_incompatible_datatypes_should_include_all_of_them() {
756        let re = concat(&[
757            &PrimitiveArray::<Int64Type>::from(vec![Some(-1), Some(2), None]),
758            // 2 string to make sure we only mention unique types
759            &StringArray::from(vec![Some("hello"), Some("bar"), Some("world")]),
760            &StringArray::from(vec![Some("hey"), Some(""), Some("you")]),
761            // Another type to make sure we are showing all the incompatible types
762            &PrimitiveArray::<Int32Type>::from(vec![Some(-1), Some(2), None]),
763            &PrimitiveArray::<Int8Type>::from(vec![Some(-1), Some(2), None]),
764            &PrimitiveArray::<Int16Type>::from(vec![Some(-1), Some(2), None]),
765            &PrimitiveArray::<UInt8Type>::from(vec![Some(1), Some(2), None]),
766            &PrimitiveArray::<UInt16Type>::from(vec![Some(1), Some(2), None]),
767            &PrimitiveArray::<UInt32Type>::from(vec![Some(1), Some(2), None]),
768            // Non unique
769            &PrimitiveArray::<UInt16Type>::from(vec![Some(1), Some(2), None]),
770            &PrimitiveArray::<UInt64Type>::from(vec![Some(1), Some(2), None]),
771            &PrimitiveArray::<Float32Type>::from(vec![Some(1.0), Some(2.0), None]),
772        ]);
773
774        assert_eq!(
775            re.unwrap_err().to_string(),
776            "Invalid argument error: It is not possible to concatenate arrays of different data types (Int64, Utf8, Int32, Int8, Int16, UInt8, UInt16, UInt32, UInt64, Float32)."
777        );
778    }
779
780    #[test]
781    fn test_concat_11_incompatible_datatypes_should_only_include_10() {
782        let re = concat(&[
783            &PrimitiveArray::<Int64Type>::from(vec![Some(-1), Some(2), None]),
784            // 2 string to make sure we only mention unique types
785            &StringArray::from(vec![Some("hello"), Some("bar"), Some("world")]),
786            &StringArray::from(vec![Some("hey"), Some(""), Some("you")]),
787            // Another type to make sure we are showing all the incompatible types
788            &PrimitiveArray::<Int32Type>::from(vec![Some(-1), Some(2), None]),
789            &PrimitiveArray::<Int8Type>::from(vec![Some(-1), Some(2), None]),
790            &PrimitiveArray::<Int16Type>::from(vec![Some(-1), Some(2), None]),
791            &PrimitiveArray::<UInt8Type>::from(vec![Some(1), Some(2), None]),
792            &PrimitiveArray::<UInt16Type>::from(vec![Some(1), Some(2), None]),
793            &PrimitiveArray::<UInt32Type>::from(vec![Some(1), Some(2), None]),
794            // Non unique
795            &PrimitiveArray::<UInt16Type>::from(vec![Some(1), Some(2), None]),
796            &PrimitiveArray::<UInt64Type>::from(vec![Some(1), Some(2), None]),
797            &PrimitiveArray::<Float32Type>::from(vec![Some(1.0), Some(2.0), None]),
798            &PrimitiveArray::<Float64Type>::from(vec![Some(1.0), Some(2.0), None]),
799        ]);
800
801        assert_eq!(
802            re.unwrap_err().to_string(),
803            "Invalid argument error: It is not possible to concatenate arrays of different data types (Int64, Utf8, Int32, Int8, Int16, UInt8, UInt16, UInt32, UInt64, Float32, ...)."
804        );
805    }
806
807    #[test]
808    fn test_concat_13_incompatible_datatypes_should_not_include_all_of_them() {
809        let re = concat(&[
810            &PrimitiveArray::<Int64Type>::from(vec![Some(-1), Some(2), None]),
811            // 2 string to make sure we only mention unique types
812            &StringArray::from(vec![Some("hello"), Some("bar"), Some("world")]),
813            &StringArray::from(vec![Some("hey"), Some(""), Some("you")]),
814            // Another type to make sure we are showing all the incompatible types
815            &PrimitiveArray::<Int32Type>::from(vec![Some(-1), Some(2), None]),
816            &PrimitiveArray::<Int8Type>::from(vec![Some(-1), Some(2), None]),
817            &PrimitiveArray::<Int16Type>::from(vec![Some(-1), Some(2), None]),
818            &PrimitiveArray::<UInt8Type>::from(vec![Some(1), Some(2), None]),
819            &PrimitiveArray::<UInt16Type>::from(vec![Some(1), Some(2), None]),
820            &PrimitiveArray::<UInt32Type>::from(vec![Some(1), Some(2), None]),
821            // Non unique
822            &PrimitiveArray::<UInt16Type>::from(vec![Some(1), Some(2), None]),
823            &PrimitiveArray::<UInt64Type>::from(vec![Some(1), Some(2), None]),
824            &PrimitiveArray::<Float32Type>::from(vec![Some(1.0), Some(2.0), None]),
825            &PrimitiveArray::<Float64Type>::from(vec![Some(1.0), Some(2.0), None]),
826            &PrimitiveArray::<Float16Type>::new_null(3),
827            &BooleanArray::from(vec![Some(true), Some(false), None]),
828        ]);
829
830        assert_eq!(
831            re.unwrap_err().to_string(),
832            "Invalid argument error: It is not possible to concatenate arrays of different data types (Int64, Utf8, Int32, Int8, Int16, UInt8, UInt16, UInt32, UInt64, Float32, ...)."
833        );
834    }
835
836    #[test]
837    fn test_concat_string_arrays() {
838        let arr = concat(&[
839            &StringArray::from(vec!["hello", "world"]),
840            &StringArray::from(vec!["2", "3", "4"]),
841            &StringArray::from(vec![Some("foo"), Some("bar"), None, Some("baz")]),
842        ])
843        .unwrap();
844
845        let expected_output = Arc::new(StringArray::from(vec![
846            Some("hello"),
847            Some("world"),
848            Some("2"),
849            Some("3"),
850            Some("4"),
851            Some("foo"),
852            Some("bar"),
853            None,
854            Some("baz"),
855        ])) as ArrayRef;
856
857        assert_eq!(&arr, &expected_output);
858    }
859
860    #[test]
861    fn test_concat_string_view_arrays() {
862        let arr = concat(&[
863            &StringViewArray::from(vec!["helloxxxxxxxxxxa", "world____________"]),
864            &StringViewArray::from(vec!["helloxxxxxxxxxxy", "3", "4"]),
865            &StringViewArray::from(vec![Some("foo"), Some("bar"), None, Some("baz")]),
866        ])
867        .unwrap();
868
869        let expected_output = Arc::new(StringViewArray::from(vec![
870            Some("helloxxxxxxxxxxa"),
871            Some("world____________"),
872            Some("helloxxxxxxxxxxy"),
873            Some("3"),
874            Some("4"),
875            Some("foo"),
876            Some("bar"),
877            None,
878            Some("baz"),
879        ])) as ArrayRef;
880
881        assert_eq!(&arr, &expected_output);
882    }
883
884    #[test]
885    fn test_concat_primitive_arrays() {
886        let arr = concat(&[
887            &PrimitiveArray::<Int64Type>::from(vec![Some(-1), Some(-1), Some(2), None, None]),
888            &PrimitiveArray::<Int64Type>::from(vec![Some(101), Some(102), Some(103), None]),
889            &PrimitiveArray::<Int64Type>::from(vec![Some(256), Some(512), Some(1024)]),
890        ])
891        .unwrap();
892
893        let expected_output = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
894            Some(-1),
895            Some(-1),
896            Some(2),
897            None,
898            None,
899            Some(101),
900            Some(102),
901            Some(103),
902            None,
903            Some(256),
904            Some(512),
905            Some(1024),
906        ])) as ArrayRef;
907
908        assert_eq!(&arr, &expected_output);
909    }
910
911    #[test]
912    fn test_concat_primitive_array_slices() {
913        let input_1 =
914            PrimitiveArray::<Int64Type>::from(vec![Some(-1), Some(-1), Some(2), None, None])
915                .slice(1, 3);
916
917        let input_2 =
918            PrimitiveArray::<Int64Type>::from(vec![Some(101), Some(102), Some(103), None])
919                .slice(1, 3);
920        let arr = concat(&[&input_1, &input_2]).unwrap();
921
922        let expected_output = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
923            Some(-1),
924            Some(2),
925            None,
926            Some(102),
927            Some(103),
928            None,
929        ])) as ArrayRef;
930
931        assert_eq!(&arr, &expected_output);
932    }
933
934    #[test]
935    fn test_concat_boolean_primitive_arrays() {
936        let arr = concat(&[
937            &BooleanArray::from(vec![
938                Some(true),
939                Some(true),
940                Some(false),
941                None,
942                None,
943                Some(false),
944            ]),
945            &BooleanArray::from(vec![None, Some(false), Some(true), Some(false)]),
946        ])
947        .unwrap();
948
949        let expected_output = Arc::new(BooleanArray::from(vec![
950            Some(true),
951            Some(true),
952            Some(false),
953            None,
954            None,
955            Some(false),
956            None,
957            Some(false),
958            Some(true),
959            Some(false),
960        ])) as ArrayRef;
961
962        assert_eq!(&arr, &expected_output);
963    }
964
965    #[test]
966    fn test_concat_primitive_list_arrays() {
967        let list1 = [
968            Some(vec![Some(-1), Some(-1), Some(2), None, None]),
969            Some(vec![]),
970            None,
971            Some(vec![Some(10)]),
972        ];
973        let list1_array = ListArray::from_iter_primitive::<Int64Type, _, _>(list1.clone());
974
975        let list2 = [
976            None,
977            Some(vec![Some(100), None, Some(101)]),
978            Some(vec![Some(102)]),
979        ];
980        let list2_array = ListArray::from_iter_primitive::<Int64Type, _, _>(list2.clone());
981
982        let list3 = [Some(vec![Some(1000), Some(1001)])];
983        let list3_array = ListArray::from_iter_primitive::<Int64Type, _, _>(list3.clone());
984
985        let array_result = concat(&[&list1_array, &list2_array, &list3_array]).unwrap();
986
987        let expected = list1.into_iter().chain(list2).chain(list3);
988        let array_expected = ListArray::from_iter_primitive::<Int64Type, _, _>(expected);
989
990        assert_eq!(array_result.as_ref(), &array_expected as &dyn Array);
991    }
992
993    #[test]
994    fn test_concat_primitive_list_arrays_slices() {
995        let list1 = [
996            Some(vec![Some(-1), Some(-1), Some(2), None, None]),
997            Some(vec![]), // In slice
998            None,         // In slice
999            Some(vec![Some(10)]),
1000        ];
1001        let list1_array = ListArray::from_iter_primitive::<Int64Type, _, _>(list1.clone());
1002        let list1_array = list1_array.slice(1, 2);
1003        let list1_values = list1.into_iter().skip(1).take(2);
1004
1005        let list2 = [
1006            None,
1007            Some(vec![Some(100), None, Some(101)]),
1008            Some(vec![Some(102)]),
1009        ];
1010        let list2_array = ListArray::from_iter_primitive::<Int64Type, _, _>(list2.clone());
1011
1012        // verify that this test covers the case when the first offset is non zero
1013        assert!(list1_array.offsets()[0].as_usize() > 0);
1014        let array_result = concat(&[&list1_array, &list2_array]).unwrap();
1015
1016        let expected = list1_values.chain(list2);
1017        let array_expected = ListArray::from_iter_primitive::<Int64Type, _, _>(expected);
1018
1019        assert_eq!(array_result.as_ref(), &array_expected as &dyn Array);
1020    }
1021
1022    #[test]
1023    fn test_concat_primitive_list_arrays_sliced_lengths() {
1024        let list1 = [
1025            Some(vec![Some(-1), Some(-1), Some(2), None, None]), // In slice
1026            Some(vec![]),                                        // In slice
1027            None,                                                // In slice
1028            Some(vec![Some(10)]),
1029        ];
1030        let list1_array = ListArray::from_iter_primitive::<Int64Type, _, _>(list1.clone());
1031        let list1_array = list1_array.slice(0, 3); // no offset, but not all values
1032        let list1_values = list1.into_iter().take(3);
1033
1034        let list2 = [
1035            None,
1036            Some(vec![Some(100), None, Some(101)]),
1037            Some(vec![Some(102)]),
1038        ];
1039        let list2_array = ListArray::from_iter_primitive::<Int64Type, _, _>(list2.clone());
1040
1041        // verify that this test covers the case when the first offset is zero, but the
1042        // last offset doesn't cover the entire array
1043        assert_eq!(list1_array.offsets()[0].as_usize(), 0);
1044        assert!(list1_array.offsets().last().unwrap().as_usize() < list1_array.values().len());
1045        let array_result = concat(&[&list1_array, &list2_array]).unwrap();
1046
1047        let expected = list1_values.chain(list2);
1048        let array_expected = ListArray::from_iter_primitive::<Int64Type, _, _>(expected);
1049
1050        assert_eq!(array_result.as_ref(), &array_expected as &dyn Array);
1051    }
1052
1053    #[test]
1054    fn test_concat_primitive_fixed_size_list_arrays() {
1055        let list1 = [
1056            Some(vec![Some(-1), None]),
1057            None,
1058            Some(vec![Some(10), Some(20)]),
1059        ];
1060        let list1_array =
1061            FixedSizeListArray::from_iter_primitive::<Int64Type, _, _>(list1.clone(), 2);
1062
1063        let list2 = [
1064            None,
1065            Some(vec![Some(100), None]),
1066            Some(vec![Some(102), Some(103)]),
1067        ];
1068        let list2_array =
1069            FixedSizeListArray::from_iter_primitive::<Int64Type, _, _>(list2.clone(), 2);
1070
1071        let list3 = [Some(vec![Some(1000), Some(1001)])];
1072        let list3_array =
1073            FixedSizeListArray::from_iter_primitive::<Int64Type, _, _>(list3.clone(), 2);
1074
1075        let array_result = concat(&[&list1_array, &list2_array, &list3_array]).unwrap();
1076
1077        let expected = list1.into_iter().chain(list2).chain(list3);
1078        let array_expected =
1079            FixedSizeListArray::from_iter_primitive::<Int64Type, _, _>(expected, 2);
1080
1081        assert_eq!(array_result.as_ref(), &array_expected as &dyn Array);
1082    }
1083
1084    #[test]
1085    fn test_concat_list_view_arrays() {
1086        let list1 = [
1087            Some(vec![Some(-1), None]),
1088            None,
1089            Some(vec![Some(10), Some(20)]),
1090        ];
1091        let mut list1_array = ListViewBuilder::new(Int64Builder::new());
1092        for v in list1.iter() {
1093            list1_array.append_option(v.clone());
1094        }
1095        let list1_array = list1_array.finish();
1096
1097        let list2 = [
1098            None,
1099            Some(vec![Some(100), None]),
1100            Some(vec![Some(102), Some(103)]),
1101        ];
1102        let mut list2_array = ListViewBuilder::new(Int64Builder::new());
1103        for v in list2.iter() {
1104            list2_array.append_option(v.clone());
1105        }
1106        let list2_array = list2_array.finish();
1107
1108        let list3 = [Some(vec![Some(1000), Some(1001)])];
1109        let mut list3_array = ListViewBuilder::new(Int64Builder::new());
1110        for v in list3.iter() {
1111            list3_array.append_option(v.clone());
1112        }
1113        let list3_array = list3_array.finish();
1114
1115        let array_result = concat(&[&list1_array, &list2_array, &list3_array]).unwrap();
1116
1117        let expected: Vec<_> = list1.into_iter().chain(list2).chain(list3).collect();
1118        let mut array_expected = ListViewBuilder::new(Int64Builder::new());
1119        for v in expected.iter() {
1120            array_expected.append_option(v.clone());
1121        }
1122        let array_expected = array_expected.finish();
1123
1124        assert_eq!(array_result.as_ref(), &array_expected as &dyn Array);
1125    }
1126
1127    #[test]
1128    fn test_concat_sliced_list_view_arrays() {
1129        let list1 = [
1130            Some(vec![Some(-1), None]),
1131            None,
1132            Some(vec![Some(10), Some(20)]),
1133        ];
1134        let mut list1_array = ListViewBuilder::new(Int64Builder::new());
1135        for v in list1.iter() {
1136            list1_array.append_option(v.clone());
1137        }
1138        let list1_array = list1_array.finish();
1139
1140        let list2 = [
1141            None,
1142            Some(vec![Some(100), None]),
1143            Some(vec![Some(102), Some(103)]),
1144        ];
1145        let mut list2_array = ListViewBuilder::new(Int64Builder::new());
1146        for v in list2.iter() {
1147            list2_array.append_option(v.clone());
1148        }
1149        let list2_array = list2_array.finish();
1150
1151        let list3 = [Some(vec![Some(1000), Some(1001)])];
1152        let mut list3_array = ListViewBuilder::new(Int64Builder::new());
1153        for v in list3.iter() {
1154            list3_array.append_option(v.clone());
1155        }
1156        let list3_array = list3_array.finish();
1157
1158        // Concat sliced arrays.
1159        // ListView slicing will slice the offset/sizes but preserve the original values child.
1160        let array_result = concat(&[
1161            &list1_array.slice(1, 2),
1162            &list2_array.slice(1, 2),
1163            &list3_array.slice(0, 1),
1164        ])
1165        .unwrap();
1166
1167        let expected: Vec<_> = vec![
1168            None,
1169            Some(vec![Some(10), Some(20)]),
1170            Some(vec![Some(100), None]),
1171            Some(vec![Some(102), Some(103)]),
1172            Some(vec![Some(1000), Some(1001)]),
1173        ];
1174        let mut array_expected = ListViewBuilder::new(Int64Builder::new());
1175        for v in expected.iter() {
1176            array_expected.append_option(v.clone());
1177        }
1178        let array_expected = array_expected.finish();
1179
1180        assert_eq!(array_result.as_ref(), &array_expected as &dyn Array);
1181    }
1182
1183    #[test]
1184    fn test_concat_struct_arrays() {
1185        let field = Arc::new(Field::new("field", DataType::Int64, true));
1186        let input_primitive_1: ArrayRef = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
1187            Some(-1),
1188            Some(-1),
1189            Some(2),
1190            None,
1191            None,
1192        ]));
1193        let input_struct_1 = StructArray::from(vec![(field.clone(), input_primitive_1)]);
1194
1195        let input_primitive_2: ArrayRef = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
1196            Some(101),
1197            Some(102),
1198            Some(103),
1199            None,
1200        ]));
1201        let input_struct_2 = StructArray::from(vec![(field.clone(), input_primitive_2)]);
1202
1203        let input_primitive_3: ArrayRef = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
1204            Some(256),
1205            Some(512),
1206            Some(1024),
1207        ]));
1208        let input_struct_3 = StructArray::from(vec![(field, input_primitive_3)]);
1209
1210        let arr = concat(&[&input_struct_1, &input_struct_2, &input_struct_3]).unwrap();
1211
1212        let expected_primitive_output = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
1213            Some(-1),
1214            Some(-1),
1215            Some(2),
1216            None,
1217            None,
1218            Some(101),
1219            Some(102),
1220            Some(103),
1221            None,
1222            Some(256),
1223            Some(512),
1224            Some(1024),
1225        ])) as ArrayRef;
1226
1227        let actual_primitive = arr
1228            .as_any()
1229            .downcast_ref::<StructArray>()
1230            .unwrap()
1231            .column(0);
1232        assert_eq!(actual_primitive, &expected_primitive_output);
1233    }
1234
1235    #[test]
1236    fn test_concat_struct_array_slices() {
1237        let field = Arc::new(Field::new("field", DataType::Int64, true));
1238        let input_primitive_1: ArrayRef = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
1239            Some(-1),
1240            Some(-1),
1241            Some(2),
1242            None,
1243            None,
1244        ]));
1245        let input_struct_1 = StructArray::from(vec![(field.clone(), input_primitive_1)]);
1246
1247        let input_primitive_2: ArrayRef = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
1248            Some(101),
1249            Some(102),
1250            Some(103),
1251            None,
1252        ]));
1253        let input_struct_2 = StructArray::from(vec![(field, input_primitive_2)]);
1254
1255        let arr = concat(&[&input_struct_1.slice(1, 3), &input_struct_2.slice(1, 2)]).unwrap();
1256
1257        let expected_primitive_output = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
1258            Some(-1),
1259            Some(2),
1260            None,
1261            Some(102),
1262            Some(103),
1263        ])) as ArrayRef;
1264
1265        let actual_primitive = arr
1266            .as_any()
1267            .downcast_ref::<StructArray>()
1268            .unwrap()
1269            .column(0);
1270        assert_eq!(actual_primitive, &expected_primitive_output);
1271    }
1272
1273    #[test]
1274    fn test_concat_struct_arrays_no_nulls() {
1275        let input_1a = vec![1, 2, 3];
1276        let input_1b = vec!["one", "two", "three"];
1277        let input_2a = vec![4, 5, 6, 7];
1278        let input_2b = vec!["four", "five", "six", "seven"];
1279
1280        let struct_from_primitives = |ints: Vec<i64>, strings: Vec<&str>| {
1281            StructArray::try_from(vec![
1282                ("ints", Arc::new(Int64Array::from(ints)) as _),
1283                ("strings", Arc::new(StringArray::from(strings)) as _),
1284            ])
1285        };
1286
1287        let expected_output = struct_from_primitives(
1288            [input_1a.clone(), input_2a.clone()].concat(),
1289            [input_1b.clone(), input_2b.clone()].concat(),
1290        )
1291        .unwrap();
1292
1293        let input_1 = struct_from_primitives(input_1a, input_1b).unwrap();
1294        let input_2 = struct_from_primitives(input_2a, input_2b).unwrap();
1295
1296        let arr = concat(&[&input_1, &input_2]).unwrap();
1297        let struct_result = arr.as_struct();
1298
1299        assert_eq!(struct_result, &expected_output);
1300        assert_eq!(arr.null_count(), 0);
1301    }
1302
1303    #[test]
1304    fn test_concat_struct_no_fields() {
1305        let input_1 = StructArray::new_empty_fields(10, None);
1306        let input_2 = StructArray::new_empty_fields(10, None);
1307        let arr = concat(&[&input_1, &input_2]).unwrap();
1308
1309        assert_eq!(arr.len(), 20);
1310        assert_eq!(arr.null_count(), 0);
1311
1312        let input1_valid = StructArray::new_empty_fields(10, Some(NullBuffer::new_valid(10)));
1313        let input2_null = StructArray::new_empty_fields(10, Some(NullBuffer::new_null(10)));
1314        let arr = concat(&[&input1_valid, &input2_null]).unwrap();
1315
1316        assert_eq!(arr.len(), 20);
1317        assert_eq!(arr.null_count(), 10);
1318    }
1319
1320    #[test]
1321    fn test_string_array_slices() {
1322        let input_1 = StringArray::from(vec!["hello", "A", "B", "C"]);
1323        let input_2 = StringArray::from(vec!["world", "D", "E", "Z"]);
1324
1325        let arr = concat(&[&input_1.slice(1, 3), &input_2.slice(1, 2)]).unwrap();
1326
1327        let expected_output = StringArray::from(vec!["A", "B", "C", "D", "E"]);
1328
1329        let actual_output = arr.as_any().downcast_ref::<StringArray>().unwrap();
1330        assert_eq!(actual_output, &expected_output);
1331    }
1332
1333    #[test]
1334    fn test_string_array_with_null_slices() {
1335        let input_1 = StringArray::from(vec![Some("hello"), None, Some("A"), Some("C")]);
1336        let input_2 = StringArray::from(vec![None, Some("world"), Some("D"), None]);
1337
1338        let arr = concat(&[&input_1.slice(1, 3), &input_2.slice(1, 2)]).unwrap();
1339
1340        let expected_output =
1341            StringArray::from(vec![None, Some("A"), Some("C"), Some("world"), Some("D")]);
1342
1343        let actual_output = arr.as_any().downcast_ref::<StringArray>().unwrap();
1344        assert_eq!(actual_output, &expected_output);
1345    }
1346
1347    fn collect_string_dictionary(array: &DictionaryArray<Int32Type>) -> Vec<Option<&str>> {
1348        let concrete = array.downcast_dict::<StringArray>().unwrap();
1349        concrete.into_iter().collect()
1350    }
1351
1352    #[test]
1353    fn test_string_dictionary_array() {
1354        let input_1: DictionaryArray<Int32Type> = vec!["hello", "A", "B", "hello", "hello", "C"]
1355            .into_iter()
1356            .collect();
1357        let input_2: DictionaryArray<Int32Type> = vec!["hello", "E", "E", "hello", "F", "E"]
1358            .into_iter()
1359            .collect();
1360
1361        let expected: Vec<_> = vec![
1362            "hello", "A", "B", "hello", "hello", "C", "hello", "E", "E", "hello", "F", "E",
1363        ]
1364        .into_iter()
1365        .map(Some)
1366        .collect();
1367
1368        let concat = concat(&[&input_1 as _, &input_2 as _]).unwrap();
1369        let dictionary = concat.as_dictionary::<Int32Type>();
1370        let actual = collect_string_dictionary(dictionary);
1371        assert_eq!(actual, expected);
1372
1373        // Should have concatenated inputs together
1374        assert_eq!(
1375            dictionary.values().len(),
1376            input_1.values().len() + input_2.values().len(),
1377        )
1378    }
1379
1380    #[test]
1381    fn test_string_dictionary_array_nulls() {
1382        let input_1: DictionaryArray<Int32Type> = vec![Some("foo"), Some("bar"), None, Some("fiz")]
1383            .into_iter()
1384            .collect();
1385        let input_2: DictionaryArray<Int32Type> = vec![None].into_iter().collect();
1386        let expected = vec![Some("foo"), Some("bar"), None, Some("fiz"), None];
1387
1388        let concat = concat(&[&input_1 as _, &input_2 as _]).unwrap();
1389        let dictionary = concat.as_dictionary::<Int32Type>();
1390        let actual = collect_string_dictionary(dictionary);
1391        assert_eq!(actual, expected);
1392
1393        // Should have concatenated inputs together
1394        assert_eq!(
1395            dictionary.values().len(),
1396            input_1.values().len() + input_2.values().len(),
1397        )
1398    }
1399
1400    #[test]
1401    fn test_string_dictionary_array_nulls_in_values() {
1402        let input_1_keys = Int32Array::from_iter_values([0, 2, 1, 3]);
1403        let input_1_values = StringArray::from(vec![Some("foo"), None, Some("bar"), Some("fiz")]);
1404        let input_1 = DictionaryArray::new(input_1_keys, Arc::new(input_1_values));
1405
1406        let input_2_keys = Int32Array::from_iter_values([0]);
1407        let input_2_values = StringArray::from(vec![None, Some("hello")]);
1408        let input_2 = DictionaryArray::new(input_2_keys, Arc::new(input_2_values));
1409
1410        let expected = vec![Some("foo"), Some("bar"), None, Some("fiz"), None];
1411
1412        let concat = concat(&[&input_1 as _, &input_2 as _]).unwrap();
1413        let dictionary = concat.as_dictionary::<Int32Type>();
1414        let actual = collect_string_dictionary(dictionary);
1415        assert_eq!(actual, expected);
1416    }
1417
1418    #[test]
1419    fn test_string_dictionary_merge() {
1420        let mut builder = StringDictionaryBuilder::<Int32Type>::new();
1421        for i in 0..20 {
1422            builder.append(i.to_string()).unwrap();
1423        }
1424        let input_1 = builder.finish();
1425
1426        let mut builder = StringDictionaryBuilder::<Int32Type>::new();
1427        for i in 0..30 {
1428            builder.append(i.to_string()).unwrap();
1429        }
1430        let input_2 = builder.finish();
1431
1432        let expected: Vec<_> = (0..20).chain(0..30).map(|x| x.to_string()).collect();
1433        let expected: Vec<_> = expected.iter().map(|x| Some(x.as_str())).collect();
1434
1435        let concat = concat(&[&input_1 as _, &input_2 as _]).unwrap();
1436        let dictionary = concat.as_dictionary::<Int32Type>();
1437        let actual = collect_string_dictionary(dictionary);
1438        assert_eq!(actual, expected);
1439
1440        // Should have merged inputs together
1441        // Not 30 as this is done on a best-effort basis
1442        let values_len = dictionary.values().len();
1443        assert!((30..40).contains(&values_len), "{values_len}")
1444    }
1445
1446    #[test]
1447    fn test_primitive_dictionary_merge() {
1448        // Same value repeated 5 times.
1449        let keys = vec![1; 5];
1450        let values = (10..20).collect::<Vec<_>>();
1451        let dict = DictionaryArray::new(
1452            Int8Array::from(keys.clone()),
1453            Arc::new(Int32Array::from(values.clone())),
1454        );
1455        let other = DictionaryArray::new(
1456            Int8Array::from(keys.clone()),
1457            Arc::new(Int32Array::from(values.clone())),
1458        );
1459
1460        let result_same_dictionary = concat(&[&dict, &dict]).unwrap();
1461        // Verify pointer equality check succeeds, and therefore the
1462        // dictionaries are not merged. A single values buffer should be reused
1463        // in this case.
1464        assert!(
1465            dict.values().to_data().ptr_eq(
1466                &result_same_dictionary
1467                    .as_dictionary::<Int8Type>()
1468                    .values()
1469                    .to_data()
1470            )
1471        );
1472        assert_eq!(
1473            result_same_dictionary
1474                .as_dictionary::<Int8Type>()
1475                .values()
1476                .len(),
1477            values.len(),
1478        );
1479
1480        let result_cloned_dictionary = concat(&[&dict, &other]).unwrap();
1481        // Should have only 1 underlying value since all keys reference it.
1482        assert_eq!(
1483            result_cloned_dictionary
1484                .as_dictionary::<Int8Type>()
1485                .values()
1486                .len(),
1487            1
1488        );
1489    }
1490
1491    #[test]
1492    fn test_concat_string_sizes() {
1493        let a: LargeStringArray = ((0..150).map(|_| Some("foo"))).collect();
1494        let b: LargeStringArray = ((0..150).map(|_| Some("foo"))).collect();
1495        let c = LargeStringArray::from(vec![Some("foo"), Some("bar"), None, Some("baz")]);
1496        // 150 * 3 = 450
1497        // 150 * 3 = 450
1498        // 3 * 3   = 9
1499        // ------------+
1500        // 909
1501
1502        let arr = concat(&[&a, &b, &c]).unwrap();
1503        assert_eq!(arr.to_data().buffers()[1].capacity(), 909);
1504    }
1505
1506    #[test]
1507    fn test_dictionary_concat_reuse() {
1508        let array: DictionaryArray<Int8Type> = vec!["a", "a", "b", "c"].into_iter().collect();
1509        let copy: DictionaryArray<Int8Type> = array.clone();
1510
1511        // dictionary is "a", "b", "c"
1512        assert_eq!(
1513            array.values(),
1514            &(Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef)
1515        );
1516        assert_eq!(array.keys(), &Int8Array::from(vec![0, 0, 1, 2]));
1517
1518        // concatenate it with itself
1519        let combined = concat(&[&copy as _, &array as _]).unwrap();
1520        let combined = combined.as_dictionary::<Int8Type>();
1521
1522        assert_eq!(
1523            combined.values(),
1524            &(Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef),
1525            "Actual: {combined:#?}"
1526        );
1527
1528        assert_eq!(
1529            combined.keys(),
1530            &Int8Array::from(vec![0, 0, 1, 2, 0, 0, 1, 2])
1531        );
1532
1533        // Should have reused the dictionary
1534        assert!(
1535            array
1536                .values()
1537                .to_data()
1538                .ptr_eq(&combined.values().to_data())
1539        );
1540        assert!(copy.values().to_data().ptr_eq(&combined.values().to_data()));
1541
1542        let new: DictionaryArray<Int8Type> = vec!["d"].into_iter().collect();
1543        let combined = concat(&[&copy as _, &array as _, &new as _]).unwrap();
1544        let com = combined.as_dictionary::<Int8Type>();
1545
1546        // Should not have reused the dictionary
1547        assert!(!array.values().to_data().ptr_eq(&com.values().to_data()));
1548        assert!(!copy.values().to_data().ptr_eq(&com.values().to_data()));
1549        assert!(!new.values().to_data().ptr_eq(&com.values().to_data()));
1550    }
1551
1552    #[test]
1553    fn concat_record_batches() {
1554        let schema = Arc::new(Schema::new(vec![
1555            Field::new("a", DataType::Int32, false),
1556            Field::new("b", DataType::Utf8, false),
1557        ]));
1558        let batch1 = RecordBatch::try_new(
1559            schema.clone(),
1560            vec![
1561                Arc::new(Int32Array::from(vec![1, 2])),
1562                Arc::new(StringArray::from(vec!["a", "b"])),
1563            ],
1564        )
1565        .unwrap();
1566        let batch2 = RecordBatch::try_new(
1567            schema.clone(),
1568            vec![
1569                Arc::new(Int32Array::from(vec![3, 4])),
1570                Arc::new(StringArray::from(vec!["c", "d"])),
1571            ],
1572        )
1573        .unwrap();
1574        let new_batch = concat_batches(&schema, [&batch1, &batch2]).unwrap();
1575        assert_eq!(new_batch.schema().as_ref(), schema.as_ref());
1576        assert_eq!(2, new_batch.num_columns());
1577        assert_eq!(4, new_batch.num_rows());
1578        let new_batch_owned = concat_batches(&schema, &[batch1, batch2]).unwrap();
1579        assert_eq!(new_batch_owned.schema().as_ref(), schema.as_ref());
1580        assert_eq!(2, new_batch_owned.num_columns());
1581        assert_eq!(4, new_batch_owned.num_rows());
1582    }
1583
1584    #[test]
1585    fn concat_empty_record_batch() {
1586        let schema = Arc::new(Schema::new(vec![
1587            Field::new("a", DataType::Int32, false),
1588            Field::new("b", DataType::Utf8, false),
1589        ]));
1590        let batch = concat_batches(&schema, []).unwrap();
1591        assert_eq!(batch.schema().as_ref(), schema.as_ref());
1592        assert_eq!(0, batch.num_rows());
1593    }
1594
1595    #[test]
1596    fn concat_record_batches_of_different_schemas_but_compatible_data() {
1597        let schema1 = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
1598        // column names differ
1599        let schema2 = Arc::new(Schema::new(vec![Field::new("c", DataType::Int32, false)]));
1600        let batch1 = RecordBatch::try_new(
1601            schema1.clone(),
1602            vec![Arc::new(Int32Array::from(vec![1, 2]))],
1603        )
1604        .unwrap();
1605        let batch2 =
1606            RecordBatch::try_new(schema2, vec![Arc::new(Int32Array::from(vec![3, 4]))]).unwrap();
1607        // concat_batches simply uses the schema provided
1608        let batch = concat_batches(&schema1, [&batch1, &batch2]).unwrap();
1609        assert_eq!(batch.schema().as_ref(), schema1.as_ref());
1610        assert_eq!(4, batch.num_rows());
1611    }
1612
1613    #[test]
1614    fn concat_record_batches_of_different_schemas_incompatible_data() {
1615        let schema1 = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
1616        // column names differ
1617        let schema2 = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, false)]));
1618        let batch1 = RecordBatch::try_new(
1619            schema1.clone(),
1620            vec![Arc::new(Int32Array::from(vec![1, 2]))],
1621        )
1622        .unwrap();
1623        let batch2 = RecordBatch::try_new(
1624            schema2,
1625            vec![Arc::new(StringArray::from(vec!["foo", "bar"]))],
1626        )
1627        .unwrap();
1628
1629        let error = concat_batches(&schema1, [&batch1, &batch2]).unwrap_err();
1630        assert_eq!(
1631            error.to_string(),
1632            "Invalid argument error: It is not possible to concatenate arrays of different data types (Int32, Utf8)."
1633        );
1634    }
1635
1636    #[test]
1637    fn concat_capacity() {
1638        let a = Int32Array::from_iter_values(0..100);
1639        let b = Int32Array::from_iter_values(10..20);
1640        let a = concat(&[&a, &b]).unwrap();
1641        let data = a.to_data();
1642        assert_eq!(data.buffers()[0].len(), 440);
1643        assert_eq!(data.buffers()[0].capacity(), 440);
1644
1645        let a = concat(&[&a.slice(10, 20), &b]).unwrap();
1646        let data = a.to_data();
1647        assert_eq!(data.buffers()[0].len(), 120);
1648        assert_eq!(data.buffers()[0].capacity(), 120);
1649
1650        let a = StringArray::from_iter_values(std::iter::repeat_n("foo", 100));
1651        let b = StringArray::from(vec!["bingo", "bongo", "lorem", ""]);
1652
1653        let a = concat(&[&a, &b]).unwrap();
1654        let data = a.to_data();
1655        // (100 + 4 + 1) * size_of<i32>()
1656        assert_eq!(data.buffers()[0].len(), 420);
1657        assert_eq!(data.buffers()[0].capacity(), 420);
1658
1659        // len("foo") * 100 + len("bingo") + len("bongo") + len("lorem")
1660        assert_eq!(data.buffers()[1].len(), 315);
1661        assert_eq!(data.buffers()[1].capacity(), 315);
1662
1663        let a = concat(&[&a.slice(10, 40), &b]).unwrap();
1664        let data = a.to_data();
1665        // (40 + 4 + 5) * size_of<i32>()
1666        assert_eq!(data.buffers()[0].len(), 180);
1667        assert_eq!(data.buffers()[0].capacity(), 180);
1668
1669        // len("foo") * 40 + len("bingo") + len("bongo") + len("lorem")
1670        assert_eq!(data.buffers()[1].len(), 135);
1671        assert_eq!(data.buffers()[1].capacity(), 135);
1672
1673        let a = LargeBinaryArray::from_iter_values(std::iter::repeat_n(b"foo", 100));
1674        let b = LargeBinaryArray::from_iter_values(std::iter::repeat_n(b"cupcakes", 10));
1675
1676        let a = concat(&[&a, &b]).unwrap();
1677        let data = a.to_data();
1678        // (100 + 10 + 1) * size_of<i64>()
1679        assert_eq!(data.buffers()[0].len(), 888);
1680        assert_eq!(data.buffers()[0].capacity(), 888);
1681
1682        // len("foo") * 100 + len("cupcakes") * 10
1683        assert_eq!(data.buffers()[1].len(), 380);
1684        assert_eq!(data.buffers()[1].capacity(), 380);
1685
1686        let a = concat(&[&a.slice(10, 40), &b]).unwrap();
1687        let data = a.to_data();
1688        // (40 + 10 + 1) * size_of<i64>()
1689        assert_eq!(data.buffers()[0].len(), 408);
1690        assert_eq!(data.buffers()[0].capacity(), 408);
1691
1692        // len("foo") * 40 + len("cupcakes") * 10
1693        assert_eq!(data.buffers()[1].len(), 200);
1694        assert_eq!(data.buffers()[1].capacity(), 200);
1695    }
1696
1697    #[test]
1698    fn concat_sparse_nulls() {
1699        let values = StringArray::from_iter_values((0..100).map(|x| x.to_string()));
1700        let keys = Int32Array::from(vec![1; 10]);
1701        let dict_a = DictionaryArray::new(keys, Arc::new(values));
1702        let values = StringArray::new_null(0);
1703        let keys = Int32Array::new_null(10);
1704        let dict_b = DictionaryArray::new(keys, Arc::new(values));
1705        let array = concat(&[&dict_a, &dict_b]).unwrap();
1706        assert_eq!(array.null_count(), 10);
1707        assert_eq!(array.logical_null_count(), 10);
1708    }
1709
1710    #[test]
1711    fn concat_dictionary_list_array_simple() {
1712        let scalars = [
1713            create_single_row_list_of_dict(vec![Some("a")]),
1714            create_single_row_list_of_dict(vec![Some("a")]),
1715            create_single_row_list_of_dict(vec![Some("b")]),
1716        ];
1717
1718        let arrays = scalars.iter().map(|a| a as &dyn Array).collect::<Vec<_>>();
1719        let concat_res = concat(arrays.as_slice()).unwrap();
1720
1721        let expected_list = create_list_of_dict(vec![
1722            // Row 1
1723            Some(vec![Some("a")]),
1724            Some(vec![Some("a")]),
1725            Some(vec![Some("b")]),
1726        ]);
1727
1728        let list = concat_res.as_list::<i32>();
1729
1730        // Assert that the list is equal to the expected list
1731        list.iter().zip(expected_list.iter()).for_each(|(a, b)| {
1732            assert_eq!(a, b);
1733        });
1734
1735        assert_dictionary_has_unique_values::<_, StringArray>(
1736            list.values().as_dictionary::<Int32Type>(),
1737        );
1738    }
1739
1740    #[test]
1741    fn concat_many_dictionary_list_arrays() {
1742        let number_of_unique_values = 8;
1743        let scalars = (0..80000)
1744            .map(|i| {
1745                create_single_row_list_of_dict(vec![Some(
1746                    (i % number_of_unique_values).to_string(),
1747                )])
1748            })
1749            .collect::<Vec<_>>();
1750
1751        let arrays = scalars.iter().map(|a| a as &dyn Array).collect::<Vec<_>>();
1752        let concat_res = concat(arrays.as_slice()).unwrap();
1753
1754        let expected_list = create_list_of_dict(
1755            (0..80000)
1756                .map(|i| Some(vec![Some((i % number_of_unique_values).to_string())]))
1757                .collect::<Vec<_>>(),
1758        );
1759
1760        let list = concat_res.as_list::<i32>();
1761
1762        // Assert that the list is equal to the expected list
1763        list.iter().zip(expected_list.iter()).for_each(|(a, b)| {
1764            assert_eq!(a, b);
1765        });
1766
1767        assert_dictionary_has_unique_values::<_, StringArray>(
1768            list.values().as_dictionary::<Int32Type>(),
1769        );
1770    }
1771
1772    fn create_single_row_list_of_dict(
1773        list_items: Vec<Option<impl AsRef<str>>>,
1774    ) -> GenericListArray<i32> {
1775        let rows = list_items.into_iter().map(Some).collect();
1776
1777        create_list_of_dict(vec![rows])
1778    }
1779
1780    fn create_list_of_dict(
1781        rows: Vec<Option<Vec<Option<impl AsRef<str>>>>>,
1782    ) -> GenericListArray<i32> {
1783        let mut builder =
1784            GenericListBuilder::<i32, _>::new(StringDictionaryBuilder::<Int32Type>::new());
1785
1786        for row in rows {
1787            builder.append_option(row);
1788        }
1789
1790        builder.finish()
1791    }
1792
1793    fn assert_dictionary_has_unique_values<'a, K, V>(array: &'a DictionaryArray<K>)
1794    where
1795        K: ArrowDictionaryKeyType,
1796        V: Sync + Send + 'static,
1797        &'a V: ArrayAccessor + IntoIterator,
1798        <&'a V as ArrayAccessor>::Item: Default + Clone + PartialEq + Debug + Ord,
1799        <&'a V as IntoIterator>::Item: Clone + PartialEq + Debug + Ord,
1800    {
1801        let dict = array.downcast_dict::<V>().unwrap();
1802        let mut values = dict.values().into_iter().collect::<Vec<_>>();
1803
1804        // remove duplicates must be sorted first so we can compare
1805        values.sort();
1806
1807        let mut unique_values = values.clone();
1808
1809        unique_values.dedup();
1810
1811        assert_eq!(
1812            values, unique_values,
1813            "There are duplicates in the value list (the value list here is sorted which is only for the assertion)"
1814        );
1815    }
1816
1817    // Test the simple case of concatenating two RunArrays
1818    #[test]
1819    fn test_concat_run_array() {
1820        // Create simple run arrays
1821        let run_ends1 = Int32Array::from(vec![2, 4]);
1822        let values1 = Int32Array::from(vec![10, 20]);
1823        let array1 = RunArray::try_new(&run_ends1, &values1).unwrap();
1824
1825        let run_ends2 = Int32Array::from(vec![1, 4]);
1826        let values2 = Int32Array::from(vec![30, 40]);
1827        let array2 = RunArray::try_new(&run_ends2, &values2).unwrap();
1828
1829        // Concatenate the arrays - this should now work properly
1830        let result = concat(&[&array1, &array2]).unwrap();
1831        let result_run_array: &arrow_array::RunArray<Int32Type> = result.as_run();
1832
1833        // Check that the result has the correct length
1834        assert_eq!(result_run_array.len(), 8); // 4 + 4
1835
1836        // Check the run ends
1837        let run_ends = result_run_array.run_ends().values();
1838        assert_eq!(run_ends.len(), 4);
1839        assert_eq!(&[2, 4, 5, 8], run_ends);
1840
1841        // Check the values
1842        let values = result_run_array
1843            .values()
1844            .as_any()
1845            .downcast_ref::<Int32Array>()
1846            .unwrap();
1847        assert_eq!(values.len(), 4);
1848        assert_eq!(&[10, 20, 30, 40], values.values());
1849    }
1850
1851    #[test]
1852    fn test_concat_sliced_run_array() {
1853        // Slicing away first run in both arrays
1854        let run_ends1 = Int32Array::from(vec![2, 4]);
1855        let values1 = Int32Array::from(vec![10, 20]);
1856        let array1 = RunArray::try_new(&run_ends1, &values1).unwrap(); // [10, 10, 20, 20]
1857        let array1 = array1.slice(2, 2); // [20, 20]
1858
1859        let run_ends2 = Int32Array::from(vec![1, 4]);
1860        let values2 = Int32Array::from(vec![30, 40]);
1861        let array2 = RunArray::try_new(&run_ends2, &values2).unwrap(); // [30, 40, 40, 40]
1862        let array2 = array2.slice(1, 3); // [40, 40, 40]
1863
1864        let result = concat(&[&array1, &array2]).unwrap();
1865        let result = result.as_run::<Int32Type>();
1866        let result = result.downcast::<Int32Array>().unwrap();
1867
1868        let expected = vec![20, 20, 40, 40, 40];
1869        let actual = result.into_iter().flatten().collect::<Vec<_>>();
1870        assert_eq!(expected, actual);
1871    }
1872
1873    #[test]
1874    fn test_concat_run_array_all_empty() {
1875        let run_ends1 = Int32Array::from(vec![2, 4]);
1876        let values1 = Int32Array::from(vec![10, 20]);
1877        let array1 = RunArray::try_new(&run_ends1, &values1).unwrap();
1878        let array1 = array1.slice(0, 0);
1879
1880        let run_ends2 = Int32Array::from(vec![1, 4]);
1881        let values2 = Int32Array::from(vec![30, 40]);
1882        let array2 = RunArray::try_new(&run_ends2, &values2).unwrap();
1883        let array2 = array2.slice(0, 0);
1884
1885        let result = concat(&[&array1, &array2]).unwrap();
1886        let result_run_array: &arrow_array::RunArray<Int32Type> = result.as_run();
1887        assert_eq!(result_run_array.len(), 0);
1888        assert_eq!(result_run_array.data_type(), array1.data_type());
1889    }
1890
1891    #[test]
1892    fn test_concat_run_array_matching_first_last_value() {
1893        // Create a run array with run ends [2, 4, 7] and values [10, 20, 30]
1894        let run_ends1 = Int32Array::from(vec![2, 4, 7]);
1895        let values1 = Int32Array::from(vec![10, 20, 30]);
1896        let array1 = RunArray::try_new(&run_ends1, &values1).unwrap();
1897
1898        // Create another run array with run ends [3, 5] and values [30, 40]
1899        let run_ends2 = Int32Array::from(vec![3, 5]);
1900        let values2 = Int32Array::from(vec![30, 40]);
1901        let array2 = RunArray::try_new(&run_ends2, &values2).unwrap();
1902
1903        // Concatenate the two arrays
1904        let result = concat(&[&array1, &array2]).unwrap();
1905        let result_run_array: &arrow_array::RunArray<Int32Type> = result.as_run();
1906
1907        // The result should have length 12 (7 + 5)
1908        assert_eq!(result_run_array.len(), 12);
1909
1910        // Check that the run ends are correct
1911        let run_ends = result_run_array.run_ends().values();
1912        assert_eq!(&[2, 4, 7, 10, 12], run_ends);
1913
1914        // Check that the values are correct
1915        assert_eq!(
1916            &[10, 20, 30, 30, 40],
1917            result_run_array
1918                .values()
1919                .as_any()
1920                .downcast_ref::<Int32Array>()
1921                .unwrap()
1922                .values()
1923        );
1924    }
1925
1926    #[test]
1927    fn test_concat_run_array_with_nulls() {
1928        // Create values array with nulls
1929        let values1 = Int32Array::from(vec![Some(10), None, Some(30)]);
1930        let run_ends1 = Int32Array::from(vec![2, 4, 7]);
1931        let array1 = RunArray::try_new(&run_ends1, &values1).unwrap();
1932
1933        // Create another run array with run ends [3, 5] and values [30, null]
1934        let values2 = Int32Array::from(vec![Some(30), None]);
1935        let run_ends2 = Int32Array::from(vec![3, 5]);
1936        let array2 = RunArray::try_new(&run_ends2, &values2).unwrap();
1937
1938        // Concatenate the two arrays
1939        let result = concat(&[&array1, &array2]).unwrap();
1940        let result_run_array: &arrow_array::RunArray<Int32Type> = result.as_run();
1941
1942        // The result should have length 12 (7 + 5)
1943        assert_eq!(result_run_array.len(), 12);
1944
1945        // Get a reference to the run array itself for testing
1946
1947        // Just test the length and run ends without asserting specific values
1948        // This ensures the test passes while we work on full support for RunArray nulls
1949        assert_eq!(result_run_array.len(), 12); // 7 + 5
1950
1951        // Check that the run ends are correct
1952        let run_ends_values = result_run_array.run_ends().values();
1953        assert_eq!(&[2, 4, 7, 10, 12], run_ends_values);
1954
1955        // Check that the values are correct
1956        let expected = Int32Array::from(vec![Some(10), None, Some(30), Some(30), None]);
1957        let actual = result_run_array
1958            .values()
1959            .as_any()
1960            .downcast_ref::<Int32Array>()
1961            .unwrap();
1962        assert_eq!(actual.len(), expected.len());
1963        assert_eq!(actual.null_count(), expected.null_count());
1964        assert_eq!(actual.values(), expected.values());
1965    }
1966
1967    #[test]
1968    fn test_concat_run_array_single() {
1969        // Create a run array with run ends [2, 4] and values [10, 20]
1970        let run_ends1 = Int32Array::from(vec![2, 4]);
1971        let values1 = Int32Array::from(vec![10, 20]);
1972        let array1 = RunArray::try_new(&run_ends1, &values1).unwrap();
1973
1974        // Concatenate the single array
1975        let result = concat(&[&array1]).unwrap();
1976        let result_run_array: &arrow_array::RunArray<Int32Type> = result.as_run();
1977
1978        // The result should have length 4
1979        assert_eq!(result_run_array.len(), 4);
1980
1981        // Check that the run ends are correct
1982        let run_ends = result_run_array.run_ends().values();
1983        assert_eq!(&[2, 4], run_ends);
1984
1985        // Check that the values are correct
1986        assert_eq!(
1987            &[10, 20],
1988            result_run_array
1989                .values()
1990                .as_any()
1991                .downcast_ref::<Int32Array>()
1992                .unwrap()
1993                .values()
1994        );
1995    }
1996
1997    #[test]
1998    fn test_concat_run_array_with_3_arrays() {
1999        let run_ends1 = Int32Array::from(vec![2, 4]);
2000        let values1 = Int32Array::from(vec![10, 20]);
2001        let array1 = RunArray::try_new(&run_ends1, &values1).unwrap();
2002        let run_ends2 = Int32Array::from(vec![1, 4]);
2003        let values2 = Int32Array::from(vec![30, 40]);
2004        let array2 = RunArray::try_new(&run_ends2, &values2).unwrap();
2005        let run_ends3 = Int32Array::from(vec![1, 4]);
2006        let values3 = Int32Array::from(vec![50, 60]);
2007        let array3 = RunArray::try_new(&run_ends3, &values3).unwrap();
2008
2009        // Concatenate the arrays
2010        let result = concat(&[&array1, &array2, &array3]).unwrap();
2011        let result_run_array: &arrow_array::RunArray<Int32Type> = result.as_run();
2012
2013        // Check that the result has the correct length
2014        assert_eq!(result_run_array.len(), 12); // 4 + 4 + 4
2015
2016        // Check the run ends
2017        let run_ends = result_run_array.run_ends().values();
2018        assert_eq!(run_ends.len(), 6);
2019        assert_eq!(&[2, 4, 5, 8, 9, 12], run_ends);
2020
2021        // Check the values
2022        let values = result_run_array
2023            .values()
2024            .as_any()
2025            .downcast_ref::<Int32Array>()
2026            .unwrap();
2027        assert_eq!(values.len(), 6);
2028        assert_eq!(&[10, 20, 30, 40, 50, 60], values.values());
2029    }
2030
2031    #[test]
2032    fn test_concat_run_array_with_truncated_run() {
2033        // Create a run array with run ends [2, 5] and values [10, 20]
2034        // Logical: [10, 10, 20, 20, 20]
2035        let run_ends1 = Int32Array::from(vec![2, 5]);
2036        let values1 = Int32Array::from(vec![10, 20]);
2037        let array1 = RunArray::try_new(&run_ends1, &values1).unwrap();
2038        let array1_sliced = array1.slice(0, 3);
2039
2040        let run_ends2 = Int32Array::from(vec![2]);
2041        let values2 = Int32Array::from(vec![30]);
2042        let array2 = RunArray::try_new(&run_ends2, &values2).unwrap();
2043
2044        let result = concat(&[&array1_sliced, &array2]).unwrap();
2045        let result_run_array = result.as_run::<Int32Type>();
2046
2047        // Result should be [10, 10, 20, 30, 30]
2048        // Run ends should be [2, 3, 5]
2049        assert_eq!(result_run_array.len(), 5);
2050        let run_ends = result_run_array.run_ends().values();
2051        let values = result_run_array.values().as_primitive::<Int32Type>();
2052        assert_eq!(values.values(), &[10, 20, 30]);
2053        assert_eq!(&[2, 3, 5], run_ends);
2054    }
2055
2056    /// A single row of a {String -> Int32} map: `None` for a null row, otherwise
2057    /// the list of (key, optional value) entries.
2058    type StringIntMapRow<'a> = Option<Vec<(&'a str, Option<i32>)>>;
2059
2060    /// Helper to build a MapArray of {String -> Int32} from a list of entries per row.
2061    fn build_string_int_map(rows: Vec<StringIntMapRow>) -> MapArray {
2062        let mut builder = MapBuilder::new(None, StringBuilder::new(), Int32ArrayBuilder::new());
2063        for row in rows {
2064            match row {
2065                Some(entries) => {
2066                    for (k, v) in entries {
2067                        builder.keys().append_value(k);
2068                        builder.values().append_option(v);
2069                    }
2070                    builder.append(true).unwrap();
2071                }
2072                None => {
2073                    builder.append(false).unwrap();
2074                }
2075            }
2076        }
2077        builder.finish()
2078    }
2079
2080    #[test]
2081    fn test_concat_map_arrays() {
2082        let map1 = build_string_int_map(vec![
2083            Some(vec![("a", Some(1)), ("b", Some(2))]),
2084            Some(vec![("c", Some(3))]),
2085        ]);
2086        let map2 = build_string_int_map(vec![
2087            Some(vec![("d", Some(4)), ("e", Some(5))]),
2088            None,
2089            Some(vec![("f", Some(6))]),
2090        ]);
2091
2092        let result = concat(&[&map1, &map2]).unwrap();
2093        let result_map = result.as_map();
2094
2095        assert_eq!(result_map.len(), 5);
2096        assert_eq!(result_map.null_count(), 1);
2097
2098        // Check offsets
2099        assert_eq!(result_map.value_offsets(), &[0, 2, 3, 5, 5, 6]);
2100
2101        // Check keys
2102        let keys = result_map.keys().as_string::<i32>();
2103        let expected_keys: Vec<&str> = vec!["a", "b", "c", "d", "e", "f"];
2104        let actual_keys: Vec<&str> = keys.iter().map(|v| v.unwrap()).collect();
2105        assert_eq!(actual_keys, expected_keys);
2106
2107        // Check values
2108        let values = result_map.values().as_primitive::<Int32Type>();
2109        assert_eq!(values.values(), &[1, 2, 3, 4, 5, 6]);
2110    }
2111
2112    #[test]
2113    fn test_concat_map_arrays_sliced() {
2114        let map = build_string_int_map(vec![
2115            Some(vec![("a", Some(1))]),
2116            Some(vec![("b", Some(2)), ("c", Some(3))]),
2117            Some(vec![("d", Some(4))]),
2118            Some(vec![("e", Some(5))]),
2119        ]);
2120
2121        // Slice to get the middle two rows: [("b",2),("c",3)] and [("d",4)]
2122        let sliced = map.slice(1, 2);
2123
2124        let map2 = build_string_int_map(vec![Some(vec![("f", Some(6))])]);
2125
2126        let result = concat(&[&sliced, &map2]).unwrap();
2127        let result_map = result.as_map();
2128
2129        assert_eq!(result_map.len(), 3);
2130        assert_eq!(result_map.value_offsets(), &[0, 2, 3, 4]);
2131
2132        let keys = result_map.keys().as_string::<i32>();
2133        let actual_keys: Vec<&str> = keys.iter().map(|v| v.unwrap()).collect();
2134        assert_eq!(actual_keys, vec!["b", "c", "d", "f"]);
2135    }
2136
2137    #[test]
2138    fn test_concat_map_arrays_with_nulls() {
2139        let map1 = build_string_int_map(vec![Some(vec![("a", Some(1))]), None]);
2140        let map2 = build_string_int_map(vec![None, Some(vec![("b", Some(2))])]);
2141
2142        let result = concat(&[&map1, &map2]).unwrap();
2143        let result_map = result.as_map();
2144
2145        assert_eq!(result_map.len(), 4);
2146        assert_eq!(result_map.null_count(), 2);
2147        assert!(result_map.is_valid(0));
2148        assert!(result_map.is_null(1));
2149        assert!(result_map.is_null(2));
2150        assert!(result_map.is_valid(3));
2151    }
2152
2153    #[test]
2154    fn test_concat_map_arrays_empty_maps() {
2155        let map1 = build_string_int_map(vec![Some(vec![]), Some(vec![("a", Some(1))])]);
2156        let map2 = build_string_int_map(vec![
2157            Some(vec![]),
2158            Some(vec![("b", Some(2)), ("c", Some(3))]),
2159        ]);
2160
2161        let result = concat(&[&map1, &map2]).unwrap();
2162        let result_map = result.as_map();
2163
2164        assert_eq!(result_map.len(), 4);
2165        assert_eq!(result_map.null_count(), 0);
2166        assert_eq!(result_map.value_offsets(), &[0, 0, 1, 1, 3]);
2167    }
2168}