datatypes/vectors/
helper.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Vector helper functions, inspired by databend Series mod
16
17use std::any::Any;
18use std::sync::Arc;
19
20use arrow::array::{Array, ArrayRef, StringArray};
21use arrow::compute;
22use arrow::compute::kernels::comparison;
23use arrow::datatypes::{
24    DataType as ArrowDataType, Int8Type, Int16Type, Int32Type, Int64Type, TimeUnit, UInt8Type,
25    UInt16Type, UInt32Type, UInt64Type,
26};
27use arrow_array::{DictionaryArray, StructArray};
28use arrow_schema::IntervalUnit;
29use datafusion_common::ScalarValue;
30use snafu::{OptionExt, ResultExt};
31
32use crate::data_type::ConcreteDataType;
33use crate::error::{self, ConvertArrowArrayToScalarsSnafu, Result};
34use crate::prelude::DataType;
35use crate::scalars::{Scalar, ScalarVectorBuilder};
36use crate::types::StructType;
37use crate::value::{ListValue, ListValueRef, Value};
38use crate::vectors::struct_vector::StructVector;
39use crate::vectors::{
40    BinaryVector, BooleanVector, ConstantVector, DateVector, Decimal128Vector, DictionaryVector,
41    DurationMicrosecondVector, DurationMillisecondVector, DurationNanosecondVector,
42    DurationSecondVector, Float32Vector, Float64Vector, Int8Vector, Int16Vector, Int32Vector,
43    Int64Vector, IntervalDayTimeVector, IntervalMonthDayNanoVector, IntervalYearMonthVector,
44    ListVector, ListVectorBuilder, MutableVector, NullVector, StringVector, TimeMicrosecondVector,
45    TimeMillisecondVector, TimeNanosecondVector, TimeSecondVector, TimestampMicrosecondVector,
46    TimestampMillisecondVector, TimestampNanosecondVector, TimestampSecondVector, UInt8Vector,
47    UInt16Vector, UInt32Vector, UInt64Vector, Vector, VectorRef,
48};
49
50/// Helper functions for `Vector`.
51pub struct Helper;
52
53impl Helper {
54    /// Get a pointer to the underlying data of this vectors.
55    /// Can be useful for fast comparisons.
56    /// # Safety
57    /// Assumes that the `vector` is  T.
58    pub unsafe fn static_cast<T: Any>(vector: &VectorRef) -> &T {
59        let object = vector.as_ref();
60        debug_assert!(object.as_any().is::<T>());
61        unsafe { &*(object as *const dyn Vector as *const T) }
62    }
63
64    pub fn check_get_scalar<T: Scalar>(vector: &VectorRef) -> Result<&<T as Scalar>::VectorType> {
65        vector
66            .as_any()
67            .downcast_ref::<<T as Scalar>::VectorType>()
68            .with_context(|| error::UnknownVectorSnafu {
69                msg: format!(
70                    "downcast vector error, vector type: {:?}, expected vector: {:?}",
71                    vector.vector_type_name(),
72                    std::any::type_name::<T>(),
73                ),
74            })
75    }
76
77    pub fn check_get<T: 'static + Vector>(vector: &VectorRef) -> Result<&T> {
78        vector
79            .as_any()
80            .downcast_ref::<T>()
81            .with_context(|| error::UnknownVectorSnafu {
82                msg: format!(
83                    "downcast vector error, vector type: {:?}, expected vector: {:?}",
84                    vector.vector_type_name(),
85                    std::any::type_name::<T>(),
86                ),
87            })
88    }
89
90    pub fn check_get_mutable_vector<T: 'static + MutableVector>(
91        vector: &mut dyn MutableVector,
92    ) -> Result<&mut T> {
93        let ty = vector.data_type();
94        vector
95            .as_mut_any()
96            .downcast_mut()
97            .with_context(|| error::UnknownVectorSnafu {
98                msg: format!(
99                    "downcast vector error, vector type: {:?}, expected vector: {:?}",
100                    ty,
101                    std::any::type_name::<T>(),
102                ),
103            })
104    }
105
106    pub fn check_get_scalar_vector<T: Scalar>(
107        vector: &VectorRef,
108    ) -> Result<&<T as Scalar>::VectorType> {
109        vector
110            .as_any()
111            .downcast_ref::<<T as Scalar>::VectorType>()
112            .with_context(|| error::UnknownVectorSnafu {
113                msg: format!(
114                    "downcast vector error, vector type: {:?}, expected vector: {:?}",
115                    vector.vector_type_name(),
116                    std::any::type_name::<T>(),
117                ),
118            })
119    }
120
121    /// Try to cast an arrow scalar value into vector
122    pub fn try_from_scalar_value(value: ScalarValue, length: usize) -> Result<VectorRef> {
123        let vector = match value {
124            ScalarValue::Null => ConstantVector::new(Arc::new(NullVector::new(1)), length),
125            ScalarValue::Boolean(v) => {
126                ConstantVector::new(Arc::new(BooleanVector::from(vec![v])), length)
127            }
128            ScalarValue::Float16(v) => ConstantVector::new(
129                Arc::new(Float32Vector::from(vec![v.map(f32::from)])),
130                length,
131            ),
132            ScalarValue::Float32(v) => {
133                ConstantVector::new(Arc::new(Float32Vector::from(vec![v])), length)
134            }
135            ScalarValue::Float64(v) => {
136                ConstantVector::new(Arc::new(Float64Vector::from(vec![v])), length)
137            }
138            ScalarValue::Int8(v) => {
139                ConstantVector::new(Arc::new(Int8Vector::from(vec![v])), length)
140            }
141            ScalarValue::Int16(v) => {
142                ConstantVector::new(Arc::new(Int16Vector::from(vec![v])), length)
143            }
144            ScalarValue::Int32(v) => {
145                ConstantVector::new(Arc::new(Int32Vector::from(vec![v])), length)
146            }
147            ScalarValue::Int64(v) => {
148                ConstantVector::new(Arc::new(Int64Vector::from(vec![v])), length)
149            }
150            ScalarValue::UInt8(v) => {
151                ConstantVector::new(Arc::new(UInt8Vector::from(vec![v])), length)
152            }
153            ScalarValue::UInt16(v) => {
154                ConstantVector::new(Arc::new(UInt16Vector::from(vec![v])), length)
155            }
156            ScalarValue::UInt32(v) => {
157                ConstantVector::new(Arc::new(UInt32Vector::from(vec![v])), length)
158            }
159            ScalarValue::UInt64(v) => {
160                ConstantVector::new(Arc::new(UInt64Vector::from(vec![v])), length)
161            }
162            ScalarValue::Utf8(v) | ScalarValue::LargeUtf8(v) => {
163                ConstantVector::new(Arc::new(StringVector::from(vec![v])), length)
164            }
165            ScalarValue::Binary(v)
166            | ScalarValue::LargeBinary(v)
167            | ScalarValue::FixedSizeBinary(_, v) => {
168                ConstantVector::new(Arc::new(BinaryVector::from(vec![v])), length)
169            }
170            ScalarValue::List(array) => {
171                let item_type = Arc::new(ConcreteDataType::try_from(&array.value_type())?);
172                let mut builder = ListVectorBuilder::with_type_capacity(item_type.clone(), 1);
173                let scalar_values = ScalarValue::convert_array_to_scalar_vec(array.as_ref())
174                    .context(ConvertArrowArrayToScalarsSnafu)?;
175                let values = scalar_values
176                    .into_iter()
177                    .flat_map(|v| v.unwrap_or_else(|| vec![ScalarValue::Null]))
178                    .map(ScalarValue::try_into)
179                    .collect::<Result<Vec<Value>>>()?;
180                builder.push(Some(ListValueRef::Ref {
181                    val: &ListValue::new(values, item_type),
182                }));
183                let list_vector = builder.to_vector();
184                ConstantVector::new(list_vector, length)
185            }
186            ScalarValue::Date32(v) => {
187                ConstantVector::new(Arc::new(DateVector::from(vec![v])), length)
188            }
189            ScalarValue::TimestampSecond(v, _) => {
190                // Timezone is unimplemented now.
191                ConstantVector::new(Arc::new(TimestampSecondVector::from(vec![v])), length)
192            }
193            ScalarValue::TimestampMillisecond(v, _) => {
194                // Timezone is unimplemented now.
195                ConstantVector::new(Arc::new(TimestampMillisecondVector::from(vec![v])), length)
196            }
197            ScalarValue::TimestampMicrosecond(v, _) => {
198                // Timezone is unimplemented now.
199                ConstantVector::new(Arc::new(TimestampMicrosecondVector::from(vec![v])), length)
200            }
201            ScalarValue::TimestampNanosecond(v, _) => {
202                // Timezone is unimplemented now.
203                ConstantVector::new(Arc::new(TimestampNanosecondVector::from(vec![v])), length)
204            }
205            ScalarValue::Time32Second(v) => {
206                ConstantVector::new(Arc::new(TimeSecondVector::from(vec![v])), length)
207            }
208            ScalarValue::Time32Millisecond(v) => {
209                ConstantVector::new(Arc::new(TimeMillisecondVector::from(vec![v])), length)
210            }
211            ScalarValue::Time64Microsecond(v) => {
212                ConstantVector::new(Arc::new(TimeMicrosecondVector::from(vec![v])), length)
213            }
214            ScalarValue::Time64Nanosecond(v) => {
215                ConstantVector::new(Arc::new(TimeNanosecondVector::from(vec![v])), length)
216            }
217            ScalarValue::IntervalYearMonth(v) => {
218                ConstantVector::new(Arc::new(IntervalYearMonthVector::from(vec![v])), length)
219            }
220            ScalarValue::IntervalDayTime(v) => {
221                ConstantVector::new(Arc::new(IntervalDayTimeVector::from(vec![v])), length)
222            }
223            ScalarValue::IntervalMonthDayNano(v) => {
224                ConstantVector::new(Arc::new(IntervalMonthDayNanoVector::from(vec![v])), length)
225            }
226            ScalarValue::DurationSecond(v) => {
227                ConstantVector::new(Arc::new(DurationSecondVector::from(vec![v])), length)
228            }
229            ScalarValue::DurationMillisecond(v) => {
230                ConstantVector::new(Arc::new(DurationMillisecondVector::from(vec![v])), length)
231            }
232            ScalarValue::DurationMicrosecond(v) => {
233                ConstantVector::new(Arc::new(DurationMicrosecondVector::from(vec![v])), length)
234            }
235            ScalarValue::DurationNanosecond(v) => {
236                ConstantVector::new(Arc::new(DurationNanosecondVector::from(vec![v])), length)
237            }
238            ScalarValue::Decimal128(v, p, s) => {
239                let vector = Decimal128Vector::from(vec![v]).with_precision_and_scale(p, s)?;
240                ConstantVector::new(Arc::new(vector), length)
241            }
242            ScalarValue::Struct(v) => {
243                let struct_type = StructType::try_from(v.fields())?;
244                ConstantVector::new(
245                    Arc::new(StructVector::try_new(struct_type, (*v).clone())?),
246                    length,
247                )
248            }
249            ScalarValue::Decimal32(_, _, _)
250            | ScalarValue::Decimal64(_, _, _)
251            | ScalarValue::Decimal256(_, _, _)
252            | ScalarValue::FixedSizeList(_)
253            | ScalarValue::LargeList(_)
254            | ScalarValue::Dictionary(_, _)
255            | ScalarValue::Union(_, _, _)
256            | ScalarValue::Utf8View(_)
257            | ScalarValue::BinaryView(_)
258            | ScalarValue::Map(_)
259            | ScalarValue::Date64(_) => {
260                return error::ConversionSnafu {
261                    from: format!("Unsupported scalar value: {value}"),
262                }
263                .fail();
264            }
265        };
266
267        Ok(Arc::new(vector))
268    }
269
270    /// Try to cast an arrow array into vector
271    ///
272    /// # Panics
273    /// Panic if given arrow data type is not supported.
274    pub fn try_into_vector(array: impl AsRef<dyn Array>) -> Result<VectorRef> {
275        Ok(match array.as_ref().data_type() {
276            ArrowDataType::Null => Arc::new(NullVector::try_from_arrow_array(array)?),
277            ArrowDataType::Boolean => Arc::new(BooleanVector::try_from_arrow_array(array)?),
278            ArrowDataType::Binary | ArrowDataType::BinaryView => {
279                Arc::new(BinaryVector::try_from_arrow_array(array)?)
280            }
281            ArrowDataType::LargeBinary | ArrowDataType::FixedSizeBinary(_) => {
282                let array = arrow::compute::cast(array.as_ref(), &ArrowDataType::Binary)
283                    .context(crate::error::ArrowComputeSnafu)?;
284                Arc::new(BinaryVector::try_from_arrow_array(array)?)
285            }
286            ArrowDataType::Int8 => Arc::new(Int8Vector::try_from_arrow_array(array)?),
287            ArrowDataType::Int16 => Arc::new(Int16Vector::try_from_arrow_array(array)?),
288            ArrowDataType::Int32 => Arc::new(Int32Vector::try_from_arrow_array(array)?),
289            ArrowDataType::Int64 => Arc::new(Int64Vector::try_from_arrow_array(array)?),
290            ArrowDataType::UInt8 => Arc::new(UInt8Vector::try_from_arrow_array(array)?),
291            ArrowDataType::UInt16 => Arc::new(UInt16Vector::try_from_arrow_array(array)?),
292            ArrowDataType::UInt32 => Arc::new(UInt32Vector::try_from_arrow_array(array)?),
293            ArrowDataType::UInt64 => Arc::new(UInt64Vector::try_from_arrow_array(array)?),
294            ArrowDataType::Float32 => Arc::new(Float32Vector::try_from_arrow_array(array)?),
295            ArrowDataType::Float64 => Arc::new(Float64Vector::try_from_arrow_array(array)?),
296            ArrowDataType::Utf8 | ArrowDataType::LargeUtf8 | ArrowDataType::Utf8View => {
297                Arc::new(StringVector::try_from_arrow_array(array)?)
298            }
299            ArrowDataType::Date32 => Arc::new(DateVector::try_from_arrow_array(array)?),
300            ArrowDataType::List(_) => Arc::new(ListVector::try_from_arrow_array(array)?),
301            ArrowDataType::Timestamp(unit, _) => match unit {
302                TimeUnit::Second => Arc::new(TimestampSecondVector::try_from_arrow_array(array)?),
303                TimeUnit::Millisecond => {
304                    Arc::new(TimestampMillisecondVector::try_from_arrow_array(array)?)
305                }
306                TimeUnit::Microsecond => {
307                    Arc::new(TimestampMicrosecondVector::try_from_arrow_array(array)?)
308                }
309                TimeUnit::Nanosecond => {
310                    Arc::new(TimestampNanosecondVector::try_from_arrow_array(array)?)
311                }
312            },
313            ArrowDataType::Time32(unit) => match unit {
314                TimeUnit::Second => Arc::new(TimeSecondVector::try_from_arrow_array(array)?),
315                TimeUnit::Millisecond => {
316                    Arc::new(TimeMillisecondVector::try_from_arrow_array(array)?)
317                }
318                // Arrow use time32 for second/millisecond.
319                _ => unreachable!(
320                    "unexpected arrow array datatype: {:?}",
321                    array.as_ref().data_type()
322                ),
323            },
324            ArrowDataType::Time64(unit) => match unit {
325                TimeUnit::Microsecond => {
326                    Arc::new(TimeMicrosecondVector::try_from_arrow_array(array)?)
327                }
328                TimeUnit::Nanosecond => {
329                    Arc::new(TimeNanosecondVector::try_from_arrow_array(array)?)
330                }
331                // Arrow use time64 for microsecond/nanosecond.
332                _ => unreachable!(
333                    "unexpected arrow array datatype: {:?}",
334                    array.as_ref().data_type()
335                ),
336            },
337            ArrowDataType::Interval(unit) => match unit {
338                IntervalUnit::YearMonth => {
339                    Arc::new(IntervalYearMonthVector::try_from_arrow_array(array)?)
340                }
341                IntervalUnit::DayTime => {
342                    Arc::new(IntervalDayTimeVector::try_from_arrow_array(array)?)
343                }
344                IntervalUnit::MonthDayNano => {
345                    Arc::new(IntervalMonthDayNanoVector::try_from_arrow_array(array)?)
346                }
347            },
348            ArrowDataType::Duration(unit) => match unit {
349                TimeUnit::Second => Arc::new(DurationSecondVector::try_from_arrow_array(array)?),
350                TimeUnit::Millisecond => {
351                    Arc::new(DurationMillisecondVector::try_from_arrow_array(array)?)
352                }
353                TimeUnit::Microsecond => {
354                    Arc::new(DurationMicrosecondVector::try_from_arrow_array(array)?)
355                }
356                TimeUnit::Nanosecond => {
357                    Arc::new(DurationNanosecondVector::try_from_arrow_array(array)?)
358                }
359            },
360            ArrowDataType::Decimal128(_, _) => {
361                Arc::new(Decimal128Vector::try_from_arrow_array(array)?)
362            }
363            ArrowDataType::Dictionary(key, value) => {
364                macro_rules! handle_dictionary_key_type {
365                    ($key_type:ident) => {{
366                        let array = array
367                            .as_ref()
368                            .as_any()
369                            .downcast_ref::<DictionaryArray<$key_type>>()
370                            .unwrap(); // Safety: the type is guarded by match arm condition
371                        Arc::new(DictionaryVector::new(
372                            array.clone(),
373                            ConcreteDataType::try_from(value.as_ref())?,
374                        )?)
375                    }};
376                }
377
378                match key.as_ref() {
379                    ArrowDataType::Int8 => handle_dictionary_key_type!(Int8Type),
380                    ArrowDataType::Int16 => handle_dictionary_key_type!(Int16Type),
381                    ArrowDataType::Int32 => handle_dictionary_key_type!(Int32Type),
382                    ArrowDataType::Int64 => handle_dictionary_key_type!(Int64Type),
383                    ArrowDataType::UInt8 => handle_dictionary_key_type!(UInt8Type),
384                    ArrowDataType::UInt16 => handle_dictionary_key_type!(UInt16Type),
385                    ArrowDataType::UInt32 => handle_dictionary_key_type!(UInt32Type),
386                    ArrowDataType::UInt64 => handle_dictionary_key_type!(UInt64Type),
387                    _ => {
388                        return error::UnsupportedArrowTypeSnafu {
389                            arrow_type: array.as_ref().data_type().clone(),
390                        }
391                        .fail();
392                    }
393                }
394            }
395
396            ArrowDataType::Struct(fields) => {
397                let array = array
398                    .as_ref()
399                    .as_any()
400                    .downcast_ref::<StructArray>()
401                    .unwrap();
402                Arc::new(StructVector::try_new(
403                    StructType::try_from(fields)?,
404                    array.clone(),
405                )?)
406            }
407            ArrowDataType::Float16
408            | ArrowDataType::LargeList(_)
409            | ArrowDataType::FixedSizeList(_, _)
410            | ArrowDataType::Union(_, _)
411            | ArrowDataType::Decimal256(_, _)
412            | ArrowDataType::Map(_, _)
413            | ArrowDataType::RunEndEncoded(_, _)
414            | ArrowDataType::ListView(_)
415            | ArrowDataType::LargeListView(_)
416            | ArrowDataType::Date64
417            | ArrowDataType::Decimal32(_, _)
418            | ArrowDataType::Decimal64(_, _) => {
419                return error::UnsupportedArrowTypeSnafu {
420                    arrow_type: array.as_ref().data_type().clone(),
421                }
422                .fail();
423            }
424        })
425    }
426
427    /// Try to cast an vec of values into vector, fail if type is not the same across all values.
428    pub fn try_from_row_into_vector(row: &[Value], dt: &ConcreteDataType) -> Result<VectorRef> {
429        let mut builder = dt.create_mutable_vector(row.len());
430        for val in row {
431            builder.try_push_value_ref(&val.as_value_ref())?;
432        }
433        let vector = builder.to_vector();
434        Ok(vector)
435    }
436
437    /// Try to cast slice of `arrays` to vectors.
438    pub fn try_into_vectors(arrays: &[ArrayRef]) -> Result<Vec<VectorRef>> {
439        arrays.iter().map(Self::try_into_vector).collect()
440    }
441
442    /// Perform SQL like operation on `names` and a scalar `s`.
443    pub fn like_utf8(names: Vec<String>, s: &str) -> Result<VectorRef> {
444        let array = StringArray::from(names);
445
446        let s = StringArray::new_scalar(s);
447        let filter = comparison::like(&array, &s).context(error::ArrowComputeSnafu)?;
448
449        let result = compute::filter(&array, &filter).context(error::ArrowComputeSnafu)?;
450        Helper::try_into_vector(result)
451    }
452
453    pub fn like_utf8_filter(names: Vec<String>, s: &str) -> Result<(VectorRef, BooleanVector)> {
454        let array = StringArray::from(names);
455        let s = StringArray::new_scalar(s);
456        let filter = comparison::like(&array, &s).context(error::ArrowComputeSnafu)?;
457        let result = compute::filter(&array, &filter).context(error::ArrowComputeSnafu)?;
458        let vector = Helper::try_into_vector(result)?;
459
460        Ok((vector, BooleanVector::from(filter)))
461    }
462}
463
464#[cfg(test)]
465pub(crate) fn pretty_print(vector: VectorRef) -> String {
466    let array = vector.to_arrow_array();
467    arrow::util::pretty::pretty_format_columns(&vector.vector_type_name(), &[array])
468        .map(|x| x.to_string())
469        .unwrap_or_else(|e| e.to_string())
470}
471
472#[cfg(test)]
473mod tests {
474    use arrow::array::{
475        ArrayRef, BooleanArray, Date32Array, Float32Array, Float64Array, Int8Array, Int16Array,
476        Int32Array, Int64Array, LargeBinaryArray, ListArray, NullArray, Time32MillisecondArray,
477        Time32SecondArray, Time64MicrosecondArray, Time64NanosecondArray,
478        TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,
479        TimestampSecondArray, UInt8Array, UInt16Array, UInt32Array, UInt64Array,
480    };
481    use arrow::buffer::Buffer;
482    use arrow::datatypes::{Int32Type, IntervalMonthDayNano};
483    use arrow_array::{BinaryArray, DictionaryArray, FixedSizeBinaryArray, LargeStringArray};
484    use arrow_schema::DataType;
485    use common_decimal::Decimal128;
486    use common_time::time::Time;
487    use common_time::timestamp::TimeUnit;
488    use common_time::{Date, Duration};
489
490    use super::*;
491    use crate::value::Value;
492    use crate::vectors::ConcreteDataType;
493
494    #[test]
495    fn test_try_into_vectors() {
496        let arrays: Vec<ArrayRef> = vec![
497            Arc::new(Int32Array::from(vec![1])),
498            Arc::new(Int32Array::from(vec![2])),
499            Arc::new(Int32Array::from(vec![3])),
500        ];
501        let vectors = Helper::try_into_vectors(&arrays).unwrap();
502        vectors.iter().for_each(|v| assert_eq!(1, v.len()));
503        assert_eq!(Value::Int32(1), vectors[0].get(0));
504        assert_eq!(Value::Int32(2), vectors[1].get(0));
505        assert_eq!(Value::Int32(3), vectors[2].get(0));
506    }
507
508    #[test]
509    fn test_try_into_date_vector() {
510        let vector = DateVector::from(vec![Some(1), Some(2), None]);
511        let arrow_array = vector.to_arrow_array();
512        assert_eq!(&ArrowDataType::Date32, arrow_array.data_type());
513        let vector_converted = Helper::try_into_vector(arrow_array).unwrap();
514        assert_eq!(vector.len(), vector_converted.len());
515        for i in 0..vector_converted.len() {
516            assert_eq!(vector.get(i), vector_converted.get(i));
517        }
518    }
519
520    #[test]
521    fn test_try_from_scalar_date_value() {
522        let vector = Helper::try_from_scalar_value(ScalarValue::Date32(Some(42)), 3).unwrap();
523        assert_eq!(ConcreteDataType::date_datatype(), vector.data_type());
524        assert_eq!(3, vector.len());
525        for i in 0..vector.len() {
526            assert_eq!(Value::Date(Date::new(42)), vector.get(i));
527        }
528    }
529
530    #[test]
531    fn test_try_from_scalar_duration_value() {
532        let vector =
533            Helper::try_from_scalar_value(ScalarValue::DurationSecond(Some(42)), 3).unwrap();
534        assert_eq!(
535            ConcreteDataType::duration_second_datatype(),
536            vector.data_type()
537        );
538        assert_eq!(3, vector.len());
539        for i in 0..vector.len() {
540            assert_eq!(
541                Value::Duration(Duration::new(42, TimeUnit::Second)),
542                vector.get(i)
543            );
544        }
545    }
546
547    #[test]
548    fn test_try_from_scalar_decimal128_value() {
549        let vector =
550            Helper::try_from_scalar_value(ScalarValue::Decimal128(Some(42), 3, 1), 3).unwrap();
551        assert_eq!(
552            ConcreteDataType::decimal128_datatype(3, 1),
553            vector.data_type()
554        );
555        assert_eq!(3, vector.len());
556        for i in 0..vector.len() {
557            assert_eq!(Value::Decimal128(Decimal128::new(42, 3, 1)), vector.get(i));
558        }
559    }
560
561    #[test]
562    fn test_try_from_list_value() {
563        let value = ScalarValue::List(ScalarValue::new_list(
564            &[ScalarValue::Int32(Some(1)), ScalarValue::Int32(Some(2))],
565            &ArrowDataType::Int32,
566            true,
567        ));
568        let vector = Helper::try_from_scalar_value(value, 3).unwrap();
569        assert_eq!(
570            ConcreteDataType::list_datatype(Arc::new(ConcreteDataType::int32_datatype())),
571            vector.data_type()
572        );
573        assert_eq!(3, vector.len());
574        for i in 0..vector.len() {
575            let v = vector.get(i);
576            let items = v.as_list().unwrap().unwrap().items();
577            assert_eq!(vec![Value::Int32(1), Value::Int32(2)], items);
578        }
579    }
580
581    #[test]
582    fn test_like_utf8() {
583        fn assert_vector(expected: Vec<&str>, actual: &VectorRef) {
584            let actual = actual.as_any().downcast_ref::<StringVector>().unwrap();
585            assert_eq!(*actual, StringVector::from(expected));
586        }
587
588        let names: Vec<String> = vec!["greptime", "hello", "public", "world"]
589            .into_iter()
590            .map(|x| x.to_string())
591            .collect();
592
593        let ret = Helper::like_utf8(names.clone(), "%ll%").unwrap();
594        assert_vector(vec!["hello"], &ret);
595
596        let ret = Helper::like_utf8(names.clone(), "%time").unwrap();
597        assert_vector(vec!["greptime"], &ret);
598
599        let ret = Helper::like_utf8(names.clone(), "%ld").unwrap();
600        assert_vector(vec!["world"], &ret);
601
602        let ret = Helper::like_utf8(names, "%").unwrap();
603        assert_vector(vec!["greptime", "hello", "public", "world"], &ret);
604    }
605
606    #[test]
607    fn test_like_utf8_filter() {
608        fn assert_vector(expected: Vec<&str>, actual: &VectorRef) {
609            let actual = actual.as_any().downcast_ref::<StringVector>().unwrap();
610            assert_eq!(*actual, StringVector::from(expected));
611        }
612
613        fn assert_filter(array: Vec<String>, s: &str, expected_filter: &BooleanVector) {
614            let array = StringArray::from(array);
615            let s = StringArray::new_scalar(s);
616            let actual_filter = comparison::like(&array, &s).unwrap();
617            assert_eq!(BooleanVector::from(actual_filter), *expected_filter);
618        }
619
620        let names: Vec<String> = vec!["greptime", "timeseries", "cloud", "database"]
621            .into_iter()
622            .map(|x| x.to_string())
623            .collect();
624
625        let (table, filter) = Helper::like_utf8_filter(names.clone(), "%ti%").unwrap();
626        assert_vector(vec!["greptime", "timeseries"], &table);
627        assert_filter(names.clone(), "%ti%", &filter);
628
629        let (tables, filter) = Helper::like_utf8_filter(names.clone(), "%lou").unwrap();
630        assert_vector(vec![], &tables);
631        assert_filter(names.clone(), "%lou", &filter);
632
633        let (tables, filter) = Helper::like_utf8_filter(names.clone(), "%d%").unwrap();
634        assert_vector(vec!["cloud", "database"], &tables);
635        assert_filter(names.clone(), "%d%", &filter);
636    }
637
638    fn check_try_into_vector(array: impl Array + 'static) {
639        let array: ArrayRef = Arc::new(array);
640        let vector = Helper::try_into_vector(array.clone()).unwrap();
641        assert_eq!(&array, &vector.to_arrow_array());
642    }
643
644    #[test]
645    fn test_try_into_vector() {
646        check_try_into_vector(NullArray::new(2));
647        check_try_into_vector(BooleanArray::from(vec![true, false]));
648        check_try_into_vector(Int8Array::from(vec![1, 2, 3]));
649        check_try_into_vector(Int16Array::from(vec![1, 2, 3]));
650        check_try_into_vector(Int32Array::from(vec![1, 2, 3]));
651        check_try_into_vector(Int64Array::from(vec![1, 2, 3]));
652        check_try_into_vector(UInt8Array::from(vec![1, 2, 3]));
653        check_try_into_vector(UInt16Array::from(vec![1, 2, 3]));
654        check_try_into_vector(UInt32Array::from(vec![1, 2, 3]));
655        check_try_into_vector(UInt64Array::from(vec![1, 2, 3]));
656        check_try_into_vector(Float32Array::from(vec![1.0, 2.0, 3.0]));
657        check_try_into_vector(Float64Array::from(vec![1.0, 2.0, 3.0]));
658        check_try_into_vector(StringArray::from(vec!["hello", "world"]));
659        check_try_into_vector(Date32Array::from(vec![1, 2, 3]));
660        let data = vec![None, Some(vec![Some(6), Some(7)])];
661        let list_array = ListArray::from_iter_primitive::<Int32Type, _, _>(data);
662        check_try_into_vector(list_array);
663        check_try_into_vector(TimestampSecondArray::from(vec![1, 2, 3]));
664        check_try_into_vector(TimestampMillisecondArray::from(vec![1, 2, 3]));
665        check_try_into_vector(TimestampMicrosecondArray::from(vec![1, 2, 3]));
666        check_try_into_vector(TimestampNanosecondArray::from(vec![1, 2, 3]));
667        check_try_into_vector(Time32SecondArray::from(vec![1, 2, 3]));
668        check_try_into_vector(Time32MillisecondArray::from(vec![1, 2, 3]));
669        check_try_into_vector(Time64MicrosecondArray::from(vec![1, 2, 3]));
670        check_try_into_vector(Time64NanosecondArray::from(vec![1, 2, 3]));
671
672        // Test dictionary arrays with different key types
673        let values = StringArray::from_iter_values(["a", "b", "c"]);
674
675        // Test Int8 keys
676        let keys = Int8Array::from_iter_values([0, 0, 1, 2]);
677        let array: ArrayRef =
678            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
679        Helper::try_into_vector(array).unwrap();
680
681        // Test Int16 keys
682        let keys = Int16Array::from_iter_values([0, 0, 1, 2]);
683        let array: ArrayRef =
684            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
685        Helper::try_into_vector(array).unwrap();
686
687        // Test Int32 keys
688        let keys = Int32Array::from_iter_values([0, 0, 1, 2]);
689        let array: ArrayRef =
690            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
691        Helper::try_into_vector(array).unwrap();
692
693        // Test Int64 keys
694        let keys = Int64Array::from_iter_values([0, 0, 1, 2]);
695        let array: ArrayRef =
696            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
697        Helper::try_into_vector(array).unwrap();
698
699        // Test UInt8 keys
700        let keys = UInt8Array::from_iter_values([0, 0, 1, 2]);
701        let array: ArrayRef =
702            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
703        Helper::try_into_vector(array).unwrap();
704
705        // Test UInt16 keys
706        let keys = UInt16Array::from_iter_values([0, 0, 1, 2]);
707        let array: ArrayRef =
708            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
709        Helper::try_into_vector(array).unwrap();
710
711        // Test UInt32 keys
712        let keys = UInt32Array::from_iter_values([0, 0, 1, 2]);
713        let array: ArrayRef =
714            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
715        Helper::try_into_vector(array).unwrap();
716
717        // Test UInt64 keys
718        let keys = UInt64Array::from_iter_values([0, 0, 1, 2]);
719        let array: ArrayRef = Arc::new(DictionaryArray::try_new(keys, Arc::new(values)).unwrap());
720        Helper::try_into_vector(array).unwrap();
721    }
722
723    #[test]
724    fn test_try_binary_array_into_vector() {
725        let input_vec: Vec<&[u8]> = vec!["hello".as_bytes(), "world".as_bytes()];
726        let assertion_vector = BinaryVector::from(input_vec.clone());
727
728        let input_arrays: Vec<ArrayRef> = vec![
729            Arc::new(LargeBinaryArray::from(input_vec.clone())) as ArrayRef,
730            Arc::new(BinaryArray::from(input_vec.clone())) as ArrayRef,
731            Arc::new(FixedSizeBinaryArray::new(
732                5,
733                Buffer::from_vec("helloworld".as_bytes().to_vec()),
734                None,
735            )) as ArrayRef,
736        ];
737
738        for input_array in input_arrays {
739            let vector = Helper::try_into_vector(input_array).unwrap();
740
741            assert_eq!(2, vector.len());
742            assert_eq!(0, vector.null_count());
743
744            let output_arrow_array: ArrayRef = vector.to_arrow_array();
745            assert_eq!(&DataType::Binary, output_arrow_array.data_type());
746            assert_eq!(&assertion_vector.to_arrow_array(), &output_arrow_array);
747        }
748    }
749
750    #[test]
751    fn test_large_string_array_into_vector() {
752        let input_vec = vec!["a", "b"];
753        let assertion_array = LargeStringArray::from(input_vec.clone());
754
755        let large_string_array: ArrayRef = Arc::new(LargeStringArray::from(input_vec));
756        let vector = Helper::try_into_vector(large_string_array).unwrap();
757        assert_eq!(2, vector.len());
758        assert_eq!(0, vector.null_count());
759
760        let output_arrow_array: LargeStringArray = vector
761            .to_arrow_array()
762            .as_any()
763            .downcast_ref::<LargeStringArray>()
764            .unwrap()
765            .clone();
766        assert_eq!(&assertion_array, &output_arrow_array);
767    }
768
769    #[test]
770    fn test_try_from_scalar_time_value() {
771        let vector = Helper::try_from_scalar_value(ScalarValue::Time32Second(Some(42)), 3).unwrap();
772        assert_eq!(ConcreteDataType::time_second_datatype(), vector.data_type());
773        assert_eq!(3, vector.len());
774        for i in 0..vector.len() {
775            assert_eq!(Value::Time(Time::new_second(42)), vector.get(i));
776        }
777    }
778
779    #[test]
780    fn test_try_from_scalar_interval_value() {
781        let vector = Helper::try_from_scalar_value(
782            ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano::new(1, 1, 2000))),
783            3,
784        )
785        .unwrap();
786
787        assert_eq!(
788            ConcreteDataType::interval_month_day_nano_datatype(),
789            vector.data_type()
790        );
791        assert_eq!(3, vector.len());
792        for i in 0..vector.len() {
793            assert_eq!(
794                Value::IntervalMonthDayNano(IntervalMonthDayNano::new(1, 1, 2000).into()),
795                vector.get(i)
796            );
797        }
798    }
799
800    fn check_try_from_row_to_vector(row: Vec<Value>, dt: &ConcreteDataType) {
801        let vector = Helper::try_from_row_into_vector(&row, dt).unwrap();
802        for (i, item) in row.iter().enumerate().take(vector.len()) {
803            assert_eq!(*item, vector.get(i));
804        }
805    }
806
807    fn check_into_and_from(array: impl Array + 'static) {
808        let array: ArrayRef = Arc::new(array);
809        let vector = Helper::try_into_vector(array.clone()).unwrap();
810        assert_eq!(&array, &vector.to_arrow_array());
811        let row: Vec<Value> = (0..array.len()).map(|i| vector.get(i)).collect();
812        let dt = vector.data_type();
813        check_try_from_row_to_vector(row, &dt);
814    }
815
816    #[test]
817    fn test_try_from_row_to_vector() {
818        check_into_and_from(NullArray::new(2));
819        check_into_and_from(BooleanArray::from(vec![true, false]));
820        check_into_and_from(Int8Array::from(vec![1, 2, 3]));
821        check_into_and_from(Int16Array::from(vec![1, 2, 3]));
822        check_into_and_from(Int32Array::from(vec![1, 2, 3]));
823        check_into_and_from(Int64Array::from(vec![1, 2, 3]));
824        check_into_and_from(UInt8Array::from(vec![1, 2, 3]));
825        check_into_and_from(UInt16Array::from(vec![1, 2, 3]));
826        check_into_and_from(UInt32Array::from(vec![1, 2, 3]));
827        check_into_and_from(UInt64Array::from(vec![1, 2, 3]));
828        check_into_and_from(Float32Array::from(vec![1.0, 2.0, 3.0]));
829        check_into_and_from(Float64Array::from(vec![1.0, 2.0, 3.0]));
830        check_into_and_from(StringArray::from(vec!["hello", "world"]));
831        check_into_and_from(Date32Array::from(vec![1, 2, 3]));
832
833        check_into_and_from(TimestampSecondArray::from(vec![1, 2, 3]));
834        check_into_and_from(TimestampMillisecondArray::from(vec![1, 2, 3]));
835        check_into_and_from(TimestampMicrosecondArray::from(vec![1, 2, 3]));
836        check_into_and_from(TimestampNanosecondArray::from(vec![1, 2, 3]));
837        check_into_and_from(Time32SecondArray::from(vec![1, 2, 3]));
838        check_into_and_from(Time32MillisecondArray::from(vec![1, 2, 3]));
839        check_into_and_from(Time64MicrosecondArray::from(vec![1, 2, 3]));
840        check_into_and_from(Time64NanosecondArray::from(vec![1, 2, 3]));
841    }
842}