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 = ConcreteDataType::try_from(&array.value_type())?;
172                let mut builder = ListVectorBuilder::with_type_capacity(item_type.clone(), 1);
173                let values = ScalarValue::convert_array_to_scalar_vec(array.as_ref())
174                    .context(ConvertArrowArrayToScalarsSnafu)?
175                    .into_iter()
176                    .flatten()
177                    .map(ScalarValue::try_into)
178                    .collect::<Result<Vec<Value>>>()?;
179                builder.push(Some(ListValueRef::Ref {
180                    val: &ListValue::new(values, item_type),
181                }));
182                let list_vector = builder.to_vector();
183                ConstantVector::new(list_vector, length)
184            }
185            ScalarValue::Date32(v) => {
186                ConstantVector::new(Arc::new(DateVector::from(vec![v])), length)
187            }
188            ScalarValue::TimestampSecond(v, _) => {
189                // Timezone is unimplemented now.
190                ConstantVector::new(Arc::new(TimestampSecondVector::from(vec![v])), length)
191            }
192            ScalarValue::TimestampMillisecond(v, _) => {
193                // Timezone is unimplemented now.
194                ConstantVector::new(Arc::new(TimestampMillisecondVector::from(vec![v])), length)
195            }
196            ScalarValue::TimestampMicrosecond(v, _) => {
197                // Timezone is unimplemented now.
198                ConstantVector::new(Arc::new(TimestampMicrosecondVector::from(vec![v])), length)
199            }
200            ScalarValue::TimestampNanosecond(v, _) => {
201                // Timezone is unimplemented now.
202                ConstantVector::new(Arc::new(TimestampNanosecondVector::from(vec![v])), length)
203            }
204            ScalarValue::Time32Second(v) => {
205                ConstantVector::new(Arc::new(TimeSecondVector::from(vec![v])), length)
206            }
207            ScalarValue::Time32Millisecond(v) => {
208                ConstantVector::new(Arc::new(TimeMillisecondVector::from(vec![v])), length)
209            }
210            ScalarValue::Time64Microsecond(v) => {
211                ConstantVector::new(Arc::new(TimeMicrosecondVector::from(vec![v])), length)
212            }
213            ScalarValue::Time64Nanosecond(v) => {
214                ConstantVector::new(Arc::new(TimeNanosecondVector::from(vec![v])), length)
215            }
216            ScalarValue::IntervalYearMonth(v) => {
217                ConstantVector::new(Arc::new(IntervalYearMonthVector::from(vec![v])), length)
218            }
219            ScalarValue::IntervalDayTime(v) => {
220                ConstantVector::new(Arc::new(IntervalDayTimeVector::from(vec![v])), length)
221            }
222            ScalarValue::IntervalMonthDayNano(v) => {
223                ConstantVector::new(Arc::new(IntervalMonthDayNanoVector::from(vec![v])), length)
224            }
225            ScalarValue::DurationSecond(v) => {
226                ConstantVector::new(Arc::new(DurationSecondVector::from(vec![v])), length)
227            }
228            ScalarValue::DurationMillisecond(v) => {
229                ConstantVector::new(Arc::new(DurationMillisecondVector::from(vec![v])), length)
230            }
231            ScalarValue::DurationMicrosecond(v) => {
232                ConstantVector::new(Arc::new(DurationMicrosecondVector::from(vec![v])), length)
233            }
234            ScalarValue::DurationNanosecond(v) => {
235                ConstantVector::new(Arc::new(DurationNanosecondVector::from(vec![v])), length)
236            }
237            ScalarValue::Decimal128(v, p, s) => {
238                let vector = Decimal128Vector::from(vec![v]).with_precision_and_scale(p, s)?;
239                ConstantVector::new(Arc::new(vector), length)
240            }
241            ScalarValue::Struct(v) => {
242                let struct_type = StructType::try_from(v.fields())?;
243                ConstantVector::new(
244                    Arc::new(StructVector::try_new(struct_type, (*v).clone())?),
245                    length,
246                )
247            }
248            ScalarValue::Decimal256(_, _, _)
249            | ScalarValue::FixedSizeList(_)
250            | ScalarValue::LargeList(_)
251            | ScalarValue::Dictionary(_, _)
252            | ScalarValue::Union(_, _, _)
253            | ScalarValue::Utf8View(_)
254            | ScalarValue::BinaryView(_)
255            | ScalarValue::Map(_)
256            | ScalarValue::Date64(_) => {
257                return error::ConversionSnafu {
258                    from: format!("Unsupported scalar value: {value}"),
259                }
260                .fail();
261            }
262        };
263
264        Ok(Arc::new(vector))
265    }
266
267    /// Try to cast an arrow array into vector
268    ///
269    /// # Panics
270    /// Panic if given arrow data type is not supported.
271    pub fn try_into_vector(array: impl AsRef<dyn Array>) -> Result<VectorRef> {
272        Ok(match array.as_ref().data_type() {
273            ArrowDataType::Null => Arc::new(NullVector::try_from_arrow_array(array)?),
274            ArrowDataType::Boolean => Arc::new(BooleanVector::try_from_arrow_array(array)?),
275            ArrowDataType::Binary => Arc::new(BinaryVector::try_from_arrow_array(array)?),
276            ArrowDataType::LargeBinary
277            | ArrowDataType::FixedSizeBinary(_)
278            | ArrowDataType::BinaryView => {
279                let array = arrow::compute::cast(array.as_ref(), &ArrowDataType::Binary)
280                    .context(crate::error::ArrowComputeSnafu)?;
281                Arc::new(BinaryVector::try_from_arrow_array(array)?)
282            }
283            ArrowDataType::Int8 => Arc::new(Int8Vector::try_from_arrow_array(array)?),
284            ArrowDataType::Int16 => Arc::new(Int16Vector::try_from_arrow_array(array)?),
285            ArrowDataType::Int32 => Arc::new(Int32Vector::try_from_arrow_array(array)?),
286            ArrowDataType::Int64 => Arc::new(Int64Vector::try_from_arrow_array(array)?),
287            ArrowDataType::UInt8 => Arc::new(UInt8Vector::try_from_arrow_array(array)?),
288            ArrowDataType::UInt16 => Arc::new(UInt16Vector::try_from_arrow_array(array)?),
289            ArrowDataType::UInt32 => Arc::new(UInt32Vector::try_from_arrow_array(array)?),
290            ArrowDataType::UInt64 => Arc::new(UInt64Vector::try_from_arrow_array(array)?),
291            ArrowDataType::Float32 => Arc::new(Float32Vector::try_from_arrow_array(array)?),
292            ArrowDataType::Float64 => Arc::new(Float64Vector::try_from_arrow_array(array)?),
293            ArrowDataType::Utf8 => Arc::new(StringVector::try_from_arrow_array(array)?),
294            ArrowDataType::LargeUtf8 | ArrowDataType::Utf8View => {
295                let array = arrow::compute::cast(array.as_ref(), &ArrowDataType::Utf8)
296                    .context(crate::error::ArrowComputeSnafu)?;
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)]
465mod tests {
466    use arrow::array::{
467        ArrayRef, BooleanArray, Date32Array, Float32Array, Float64Array, Int8Array, Int16Array,
468        Int32Array, Int64Array, LargeBinaryArray, ListArray, NullArray, Time32MillisecondArray,
469        Time32SecondArray, Time64MicrosecondArray, Time64NanosecondArray,
470        TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,
471        TimestampSecondArray, UInt8Array, UInt16Array, UInt32Array, UInt64Array,
472    };
473    use arrow::buffer::Buffer;
474    use arrow::datatypes::{Int32Type, IntervalMonthDayNano};
475    use arrow_array::{BinaryArray, DictionaryArray, FixedSizeBinaryArray, LargeStringArray};
476    use arrow_schema::DataType;
477    use common_decimal::Decimal128;
478    use common_time::time::Time;
479    use common_time::timestamp::TimeUnit;
480    use common_time::{Date, Duration};
481
482    use super::*;
483    use crate::value::Value;
484    use crate::vectors::ConcreteDataType;
485
486    #[test]
487    fn test_try_into_vectors() {
488        let arrays: Vec<ArrayRef> = vec![
489            Arc::new(Int32Array::from(vec![1])),
490            Arc::new(Int32Array::from(vec![2])),
491            Arc::new(Int32Array::from(vec![3])),
492        ];
493        let vectors = Helper::try_into_vectors(&arrays).unwrap();
494        vectors.iter().for_each(|v| assert_eq!(1, v.len()));
495        assert_eq!(Value::Int32(1), vectors[0].get(0));
496        assert_eq!(Value::Int32(2), vectors[1].get(0));
497        assert_eq!(Value::Int32(3), vectors[2].get(0));
498    }
499
500    #[test]
501    fn test_try_into_date_vector() {
502        let vector = DateVector::from(vec![Some(1), Some(2), None]);
503        let arrow_array = vector.to_arrow_array();
504        assert_eq!(&ArrowDataType::Date32, arrow_array.data_type());
505        let vector_converted = Helper::try_into_vector(arrow_array).unwrap();
506        assert_eq!(vector.len(), vector_converted.len());
507        for i in 0..vector_converted.len() {
508            assert_eq!(vector.get(i), vector_converted.get(i));
509        }
510    }
511
512    #[test]
513    fn test_try_from_scalar_date_value() {
514        let vector = Helper::try_from_scalar_value(ScalarValue::Date32(Some(42)), 3).unwrap();
515        assert_eq!(ConcreteDataType::date_datatype(), vector.data_type());
516        assert_eq!(3, vector.len());
517        for i in 0..vector.len() {
518            assert_eq!(Value::Date(Date::new(42)), vector.get(i));
519        }
520    }
521
522    #[test]
523    fn test_try_from_scalar_duration_value() {
524        let vector =
525            Helper::try_from_scalar_value(ScalarValue::DurationSecond(Some(42)), 3).unwrap();
526        assert_eq!(
527            ConcreteDataType::duration_second_datatype(),
528            vector.data_type()
529        );
530        assert_eq!(3, vector.len());
531        for i in 0..vector.len() {
532            assert_eq!(
533                Value::Duration(Duration::new(42, TimeUnit::Second)),
534                vector.get(i)
535            );
536        }
537    }
538
539    #[test]
540    fn test_try_from_scalar_decimal128_value() {
541        let vector =
542            Helper::try_from_scalar_value(ScalarValue::Decimal128(Some(42), 3, 1), 3).unwrap();
543        assert_eq!(
544            ConcreteDataType::decimal128_datatype(3, 1),
545            vector.data_type()
546        );
547        assert_eq!(3, vector.len());
548        for i in 0..vector.len() {
549            assert_eq!(Value::Decimal128(Decimal128::new(42, 3, 1)), vector.get(i));
550        }
551    }
552
553    #[test]
554    fn test_try_from_list_value() {
555        let value = ScalarValue::List(ScalarValue::new_list(
556            &[ScalarValue::Int32(Some(1)), ScalarValue::Int32(Some(2))],
557            &ArrowDataType::Int32,
558            true,
559        ));
560        let vector = Helper::try_from_scalar_value(value, 3).unwrap();
561        assert_eq!(
562            ConcreteDataType::list_datatype(ConcreteDataType::int32_datatype()),
563            vector.data_type()
564        );
565        assert_eq!(3, vector.len());
566        for i in 0..vector.len() {
567            let v = vector.get(i);
568            let items = v.as_list().unwrap().unwrap().items();
569            assert_eq!(vec![Value::Int32(1), Value::Int32(2)], items);
570        }
571    }
572
573    #[test]
574    fn test_like_utf8() {
575        fn assert_vector(expected: Vec<&str>, actual: &VectorRef) {
576            let actual = actual.as_any().downcast_ref::<StringVector>().unwrap();
577            assert_eq!(*actual, StringVector::from(expected));
578        }
579
580        let names: Vec<String> = vec!["greptime", "hello", "public", "world"]
581            .into_iter()
582            .map(|x| x.to_string())
583            .collect();
584
585        let ret = Helper::like_utf8(names.clone(), "%ll%").unwrap();
586        assert_vector(vec!["hello"], &ret);
587
588        let ret = Helper::like_utf8(names.clone(), "%time").unwrap();
589        assert_vector(vec!["greptime"], &ret);
590
591        let ret = Helper::like_utf8(names.clone(), "%ld").unwrap();
592        assert_vector(vec!["world"], &ret);
593
594        let ret = Helper::like_utf8(names, "%").unwrap();
595        assert_vector(vec!["greptime", "hello", "public", "world"], &ret);
596    }
597
598    #[test]
599    fn test_like_utf8_filter() {
600        fn assert_vector(expected: Vec<&str>, actual: &VectorRef) {
601            let actual = actual.as_any().downcast_ref::<StringVector>().unwrap();
602            assert_eq!(*actual, StringVector::from(expected));
603        }
604
605        fn assert_filter(array: Vec<String>, s: &str, expected_filter: &BooleanVector) {
606            let array = StringArray::from(array);
607            let s = StringArray::new_scalar(s);
608            let actual_filter = comparison::like(&array, &s).unwrap();
609            assert_eq!(BooleanVector::from(actual_filter), *expected_filter);
610        }
611
612        let names: Vec<String> = vec!["greptime", "timeseries", "cloud", "database"]
613            .into_iter()
614            .map(|x| x.to_string())
615            .collect();
616
617        let (table, filter) = Helper::like_utf8_filter(names.clone(), "%ti%").unwrap();
618        assert_vector(vec!["greptime", "timeseries"], &table);
619        assert_filter(names.clone(), "%ti%", &filter);
620
621        let (tables, filter) = Helper::like_utf8_filter(names.clone(), "%lou").unwrap();
622        assert_vector(vec![], &tables);
623        assert_filter(names.clone(), "%lou", &filter);
624
625        let (tables, filter) = Helper::like_utf8_filter(names.clone(), "%d%").unwrap();
626        assert_vector(vec!["cloud", "database"], &tables);
627        assert_filter(names.clone(), "%d%", &filter);
628    }
629
630    fn check_try_into_vector(array: impl Array + 'static) {
631        let array: ArrayRef = Arc::new(array);
632        let vector = Helper::try_into_vector(array.clone()).unwrap();
633        assert_eq!(&array, &vector.to_arrow_array());
634    }
635
636    #[test]
637    fn test_try_into_vector() {
638        check_try_into_vector(NullArray::new(2));
639        check_try_into_vector(BooleanArray::from(vec![true, false]));
640        check_try_into_vector(Int8Array::from(vec![1, 2, 3]));
641        check_try_into_vector(Int16Array::from(vec![1, 2, 3]));
642        check_try_into_vector(Int32Array::from(vec![1, 2, 3]));
643        check_try_into_vector(Int64Array::from(vec![1, 2, 3]));
644        check_try_into_vector(UInt8Array::from(vec![1, 2, 3]));
645        check_try_into_vector(UInt16Array::from(vec![1, 2, 3]));
646        check_try_into_vector(UInt32Array::from(vec![1, 2, 3]));
647        check_try_into_vector(UInt64Array::from(vec![1, 2, 3]));
648        check_try_into_vector(Float32Array::from(vec![1.0, 2.0, 3.0]));
649        check_try_into_vector(Float64Array::from(vec![1.0, 2.0, 3.0]));
650        check_try_into_vector(StringArray::from(vec!["hello", "world"]));
651        check_try_into_vector(Date32Array::from(vec![1, 2, 3]));
652        let data = vec![None, Some(vec![Some(6), Some(7)])];
653        let list_array = ListArray::from_iter_primitive::<Int32Type, _, _>(data);
654        check_try_into_vector(list_array);
655        check_try_into_vector(TimestampSecondArray::from(vec![1, 2, 3]));
656        check_try_into_vector(TimestampMillisecondArray::from(vec![1, 2, 3]));
657        check_try_into_vector(TimestampMicrosecondArray::from(vec![1, 2, 3]));
658        check_try_into_vector(TimestampNanosecondArray::from(vec![1, 2, 3]));
659        check_try_into_vector(Time32SecondArray::from(vec![1, 2, 3]));
660        check_try_into_vector(Time32MillisecondArray::from(vec![1, 2, 3]));
661        check_try_into_vector(Time64MicrosecondArray::from(vec![1, 2, 3]));
662        check_try_into_vector(Time64NanosecondArray::from(vec![1, 2, 3]));
663
664        // Test dictionary arrays with different key types
665        let values = StringArray::from_iter_values(["a", "b", "c"]);
666
667        // Test Int8 keys
668        let keys = Int8Array::from_iter_values([0, 0, 1, 2]);
669        let array: ArrayRef =
670            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
671        Helper::try_into_vector(array).unwrap();
672
673        // Test Int16 keys
674        let keys = Int16Array::from_iter_values([0, 0, 1, 2]);
675        let array: ArrayRef =
676            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
677        Helper::try_into_vector(array).unwrap();
678
679        // Test Int32 keys
680        let keys = Int32Array::from_iter_values([0, 0, 1, 2]);
681        let array: ArrayRef =
682            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
683        Helper::try_into_vector(array).unwrap();
684
685        // Test Int64 keys
686        let keys = Int64Array::from_iter_values([0, 0, 1, 2]);
687        let array: ArrayRef =
688            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
689        Helper::try_into_vector(array).unwrap();
690
691        // Test UInt8 keys
692        let keys = UInt8Array::from_iter_values([0, 0, 1, 2]);
693        let array: ArrayRef =
694            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
695        Helper::try_into_vector(array).unwrap();
696
697        // Test UInt16 keys
698        let keys = UInt16Array::from_iter_values([0, 0, 1, 2]);
699        let array: ArrayRef =
700            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
701        Helper::try_into_vector(array).unwrap();
702
703        // Test UInt32 keys
704        let keys = UInt32Array::from_iter_values([0, 0, 1, 2]);
705        let array: ArrayRef =
706            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
707        Helper::try_into_vector(array).unwrap();
708
709        // Test UInt64 keys
710        let keys = UInt64Array::from_iter_values([0, 0, 1, 2]);
711        let array: ArrayRef = Arc::new(DictionaryArray::try_new(keys, Arc::new(values)).unwrap());
712        Helper::try_into_vector(array).unwrap();
713    }
714
715    #[test]
716    fn test_try_binary_array_into_vector() {
717        let input_vec: Vec<&[u8]> = vec!["hello".as_bytes(), "world".as_bytes()];
718        let assertion_vector = BinaryVector::from(input_vec.clone());
719
720        let input_arrays: Vec<ArrayRef> = vec![
721            Arc::new(LargeBinaryArray::from(input_vec.clone())) as ArrayRef,
722            Arc::new(BinaryArray::from(input_vec.clone())) as ArrayRef,
723            Arc::new(FixedSizeBinaryArray::new(
724                5,
725                Buffer::from_vec("helloworld".as_bytes().to_vec()),
726                None,
727            )) as ArrayRef,
728        ];
729
730        for input_array in input_arrays {
731            let vector = Helper::try_into_vector(input_array).unwrap();
732
733            assert_eq!(2, vector.len());
734            assert_eq!(0, vector.null_count());
735
736            let output_arrow_array: ArrayRef = vector.to_arrow_array();
737            assert_eq!(&DataType::Binary, output_arrow_array.data_type());
738            assert_eq!(&assertion_vector.to_arrow_array(), &output_arrow_array);
739        }
740    }
741
742    #[test]
743    fn test_large_string_array_into_vector() {
744        let input_vec = vec!["a", "b"];
745        let assertion_array = StringArray::from(input_vec.clone());
746
747        let large_string_array: ArrayRef = Arc::new(LargeStringArray::from(input_vec));
748        let vector = Helper::try_into_vector(large_string_array).unwrap();
749        assert_eq!(2, vector.len());
750        assert_eq!(0, vector.null_count());
751
752        let output_arrow_array: StringArray = vector
753            .to_arrow_array()
754            .as_any()
755            .downcast_ref::<StringArray>()
756            .unwrap()
757            .clone();
758        assert_eq!(&assertion_array, &output_arrow_array);
759    }
760
761    #[test]
762    fn test_try_from_scalar_time_value() {
763        let vector = Helper::try_from_scalar_value(ScalarValue::Time32Second(Some(42)), 3).unwrap();
764        assert_eq!(ConcreteDataType::time_second_datatype(), vector.data_type());
765        assert_eq!(3, vector.len());
766        for i in 0..vector.len() {
767            assert_eq!(Value::Time(Time::new_second(42)), vector.get(i));
768        }
769    }
770
771    #[test]
772    fn test_try_from_scalar_interval_value() {
773        let vector = Helper::try_from_scalar_value(
774            ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano::new(1, 1, 2000))),
775            3,
776        )
777        .unwrap();
778
779        assert_eq!(
780            ConcreteDataType::interval_month_day_nano_datatype(),
781            vector.data_type()
782        );
783        assert_eq!(3, vector.len());
784        for i in 0..vector.len() {
785            assert_eq!(
786                Value::IntervalMonthDayNano(IntervalMonthDayNano::new(1, 1, 2000).into()),
787                vector.get(i)
788            );
789        }
790    }
791
792    fn check_try_from_row_to_vector(row: Vec<Value>, dt: &ConcreteDataType) {
793        let vector = Helper::try_from_row_into_vector(&row, dt).unwrap();
794        for (i, item) in row.iter().enumerate().take(vector.len()) {
795            assert_eq!(*item, vector.get(i));
796        }
797    }
798
799    fn check_into_and_from(array: impl Array + 'static) {
800        let array: ArrayRef = Arc::new(array);
801        let vector = Helper::try_into_vector(array.clone()).unwrap();
802        assert_eq!(&array, &vector.to_arrow_array());
803        let row: Vec<Value> = (0..array.len()).map(|i| vector.get(i)).collect();
804        let dt = vector.data_type();
805        check_try_from_row_to_vector(row, &dt);
806    }
807
808    #[test]
809    fn test_try_from_row_to_vector() {
810        check_into_and_from(NullArray::new(2));
811        check_into_and_from(BooleanArray::from(vec![true, false]));
812        check_into_and_from(Int8Array::from(vec![1, 2, 3]));
813        check_into_and_from(Int16Array::from(vec![1, 2, 3]));
814        check_into_and_from(Int32Array::from(vec![1, 2, 3]));
815        check_into_and_from(Int64Array::from(vec![1, 2, 3]));
816        check_into_and_from(UInt8Array::from(vec![1, 2, 3]));
817        check_into_and_from(UInt16Array::from(vec![1, 2, 3]));
818        check_into_and_from(UInt32Array::from(vec![1, 2, 3]));
819        check_into_and_from(UInt64Array::from(vec![1, 2, 3]));
820        check_into_and_from(Float32Array::from(vec![1.0, 2.0, 3.0]));
821        check_into_and_from(Float64Array::from(vec![1.0, 2.0, 3.0]));
822        check_into_and_from(StringArray::from(vec!["hello", "world"]));
823        check_into_and_from(Date32Array::from(vec![1, 2, 3]));
824
825        check_into_and_from(TimestampSecondArray::from(vec![1, 2, 3]));
826        check_into_and_from(TimestampMillisecondArray::from(vec![1, 2, 3]));
827        check_into_and_from(TimestampMicrosecondArray::from(vec![1, 2, 3]));
828        check_into_and_from(TimestampNanosecondArray::from(vec![1, 2, 3]));
829        check_into_and_from(Time32SecondArray::from(vec![1, 2, 3]));
830        check_into_and_from(Time32MillisecondArray::from(vec![1, 2, 3]));
831        check_into_and_from(Time64MicrosecondArray::from(vec![1, 2, 3]));
832        check_into_and_from(Time64NanosecondArray::from(vec![1, 2, 3]));
833    }
834}