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            | ScalarValue::RunEndEncoded(_, _, _) => {
261                return error::ConversionSnafu {
262                    from: format!("Unsupported scalar value: {value}"),
263                }
264                .fail();
265            }
266        };
267
268        Ok(Arc::new(vector))
269    }
270
271    /// Try to cast an arrow array into vector
272    ///
273    /// # Panics
274    /// Panic if given arrow data type is not supported.
275    pub fn try_into_vector(array: impl AsRef<dyn Array>) -> Result<VectorRef> {
276        Ok(match array.as_ref().data_type() {
277            ArrowDataType::Null => Arc::new(NullVector::try_from_arrow_array(array)?),
278            ArrowDataType::Boolean => Arc::new(BooleanVector::try_from_arrow_array(array)?),
279            ArrowDataType::Binary | ArrowDataType::BinaryView => {
280                Arc::new(BinaryVector::try_from_arrow_array(array)?)
281            }
282            ArrowDataType::LargeBinary | ArrowDataType::FixedSizeBinary(_) => {
283                let array = arrow::compute::cast(array.as_ref(), &ArrowDataType::Binary)
284                    .context(crate::error::ArrowComputeSnafu)?;
285                Arc::new(BinaryVector::try_from_arrow_array(array)?)
286            }
287            ArrowDataType::Int8 => Arc::new(Int8Vector::try_from_arrow_array(array)?),
288            ArrowDataType::Int16 => Arc::new(Int16Vector::try_from_arrow_array(array)?),
289            ArrowDataType::Int32 => Arc::new(Int32Vector::try_from_arrow_array(array)?),
290            ArrowDataType::Int64 => Arc::new(Int64Vector::try_from_arrow_array(array)?),
291            ArrowDataType::UInt8 => Arc::new(UInt8Vector::try_from_arrow_array(array)?),
292            ArrowDataType::UInt16 => Arc::new(UInt16Vector::try_from_arrow_array(array)?),
293            ArrowDataType::UInt32 => Arc::new(UInt32Vector::try_from_arrow_array(array)?),
294            ArrowDataType::UInt64 => Arc::new(UInt64Vector::try_from_arrow_array(array)?),
295            ArrowDataType::Float32 => Arc::new(Float32Vector::try_from_arrow_array(array)?),
296            ArrowDataType::Float64 => Arc::new(Float64Vector::try_from_arrow_array(array)?),
297            ArrowDataType::Utf8 | ArrowDataType::LargeUtf8 | ArrowDataType::Utf8View => {
298                Arc::new(StringVector::try_from_arrow_array(array)?)
299            }
300            ArrowDataType::Date32 => Arc::new(DateVector::try_from_arrow_array(array)?),
301            ArrowDataType::List(_) => Arc::new(ListVector::try_from_arrow_array(array)?),
302            ArrowDataType::Timestamp(unit, _) => match unit {
303                TimeUnit::Second => Arc::new(TimestampSecondVector::try_from_arrow_array(array)?),
304                TimeUnit::Millisecond => {
305                    Arc::new(TimestampMillisecondVector::try_from_arrow_array(array)?)
306                }
307                TimeUnit::Microsecond => {
308                    Arc::new(TimestampMicrosecondVector::try_from_arrow_array(array)?)
309                }
310                TimeUnit::Nanosecond => {
311                    Arc::new(TimestampNanosecondVector::try_from_arrow_array(array)?)
312                }
313            },
314            ArrowDataType::Time32(unit) => match unit {
315                TimeUnit::Second => Arc::new(TimeSecondVector::try_from_arrow_array(array)?),
316                TimeUnit::Millisecond => {
317                    Arc::new(TimeMillisecondVector::try_from_arrow_array(array)?)
318                }
319                // Arrow use time32 for second/millisecond.
320                _ => unreachable!(
321                    "unexpected arrow array datatype: {:?}",
322                    array.as_ref().data_type()
323                ),
324            },
325            ArrowDataType::Time64(unit) => match unit {
326                TimeUnit::Microsecond => {
327                    Arc::new(TimeMicrosecondVector::try_from_arrow_array(array)?)
328                }
329                TimeUnit::Nanosecond => {
330                    Arc::new(TimeNanosecondVector::try_from_arrow_array(array)?)
331                }
332                // Arrow use time64 for microsecond/nanosecond.
333                _ => unreachable!(
334                    "unexpected arrow array datatype: {:?}",
335                    array.as_ref().data_type()
336                ),
337            },
338            ArrowDataType::Interval(unit) => match unit {
339                IntervalUnit::YearMonth => {
340                    Arc::new(IntervalYearMonthVector::try_from_arrow_array(array)?)
341                }
342                IntervalUnit::DayTime => {
343                    Arc::new(IntervalDayTimeVector::try_from_arrow_array(array)?)
344                }
345                IntervalUnit::MonthDayNano => {
346                    Arc::new(IntervalMonthDayNanoVector::try_from_arrow_array(array)?)
347                }
348            },
349            ArrowDataType::Duration(unit) => match unit {
350                TimeUnit::Second => Arc::new(DurationSecondVector::try_from_arrow_array(array)?),
351                TimeUnit::Millisecond => {
352                    Arc::new(DurationMillisecondVector::try_from_arrow_array(array)?)
353                }
354                TimeUnit::Microsecond => {
355                    Arc::new(DurationMicrosecondVector::try_from_arrow_array(array)?)
356                }
357                TimeUnit::Nanosecond => {
358                    Arc::new(DurationNanosecondVector::try_from_arrow_array(array)?)
359                }
360            },
361            ArrowDataType::Decimal128(_, _) => {
362                Arc::new(Decimal128Vector::try_from_arrow_array(array)?)
363            }
364            ArrowDataType::Dictionary(key, value) => {
365                macro_rules! handle_dictionary_key_type {
366                    ($key_type:ident) => {{
367                        let array = array
368                            .as_ref()
369                            .as_any()
370                            .downcast_ref::<DictionaryArray<$key_type>>()
371                            .unwrap(); // Safety: the type is guarded by match arm condition
372                        Arc::new(DictionaryVector::new(
373                            array.clone(),
374                            ConcreteDataType::try_from(value.as_ref())?,
375                        )?)
376                    }};
377                }
378
379                match key.as_ref() {
380                    ArrowDataType::Int8 => handle_dictionary_key_type!(Int8Type),
381                    ArrowDataType::Int16 => handle_dictionary_key_type!(Int16Type),
382                    ArrowDataType::Int32 => handle_dictionary_key_type!(Int32Type),
383                    ArrowDataType::Int64 => handle_dictionary_key_type!(Int64Type),
384                    ArrowDataType::UInt8 => handle_dictionary_key_type!(UInt8Type),
385                    ArrowDataType::UInt16 => handle_dictionary_key_type!(UInt16Type),
386                    ArrowDataType::UInt32 => handle_dictionary_key_type!(UInt32Type),
387                    ArrowDataType::UInt64 => handle_dictionary_key_type!(UInt64Type),
388                    _ => {
389                        return error::UnsupportedArrowTypeSnafu {
390                            arrow_type: array.as_ref().data_type().clone(),
391                        }
392                        .fail();
393                    }
394                }
395            }
396
397            ArrowDataType::Struct(fields) => {
398                let array = array
399                    .as_ref()
400                    .as_any()
401                    .downcast_ref::<StructArray>()
402                    .unwrap();
403                Arc::new(StructVector::try_new(
404                    StructType::try_from(fields)?,
405                    array.clone(),
406                )?)
407            }
408            ArrowDataType::Float16
409            | ArrowDataType::LargeList(_)
410            | ArrowDataType::FixedSizeList(_, _)
411            | ArrowDataType::Union(_, _)
412            | ArrowDataType::Decimal256(_, _)
413            | ArrowDataType::Map(_, _)
414            | ArrowDataType::RunEndEncoded(_, _)
415            | ArrowDataType::ListView(_)
416            | ArrowDataType::LargeListView(_)
417            | ArrowDataType::Date64
418            | ArrowDataType::Decimal32(_, _)
419            | ArrowDataType::Decimal64(_, _) => {
420                return error::UnsupportedArrowTypeSnafu {
421                    arrow_type: array.as_ref().data_type().clone(),
422                }
423                .fail();
424            }
425        })
426    }
427
428    /// Try to cast an vec of values into vector, fail if type is not the same across all values.
429    pub fn try_from_row_into_vector(row: &[Value], dt: &ConcreteDataType) -> Result<VectorRef> {
430        let mut builder = dt.create_mutable_vector(row.len());
431        for val in row {
432            builder.try_push_value_ref(&val.as_value_ref())?;
433        }
434        let vector = builder.to_vector();
435        Ok(vector)
436    }
437
438    /// Try to cast slice of `arrays` to vectors.
439    pub fn try_into_vectors(arrays: &[ArrayRef]) -> Result<Vec<VectorRef>> {
440        arrays.iter().map(Self::try_into_vector).collect()
441    }
442
443    /// Perform SQL like operation on `names` and a scalar `s`.
444    pub fn like_utf8(names: Vec<String>, s: &str) -> Result<VectorRef> {
445        let array = StringArray::from(names);
446
447        let s = StringArray::new_scalar(s);
448        let filter = comparison::like(&array, &s).context(error::ArrowComputeSnafu)?;
449
450        let result = compute::filter(&array, &filter).context(error::ArrowComputeSnafu)?;
451        Helper::try_into_vector(result)
452    }
453
454    pub fn like_utf8_filter(names: Vec<String>, s: &str) -> Result<(VectorRef, BooleanVector)> {
455        let array = StringArray::from(names);
456        let s = StringArray::new_scalar(s);
457        let filter = comparison::like(&array, &s).context(error::ArrowComputeSnafu)?;
458        let result = compute::filter(&array, &filter).context(error::ArrowComputeSnafu)?;
459        let vector = Helper::try_into_vector(result)?;
460
461        Ok((vector, BooleanVector::from(filter)))
462    }
463}
464
465#[cfg(test)]
466pub(crate) fn pretty_print(vector: VectorRef) -> String {
467    let array = vector.to_arrow_array();
468    arrow::util::pretty::pretty_format_columns(&vector.vector_type_name(), &[array])
469        .map(|x| x.to_string())
470        .unwrap_or_else(|e| e.to_string())
471}
472
473#[cfg(test)]
474mod tests {
475    use arrow::array::{
476        ArrayRef, BooleanArray, Date32Array, Float32Array, Float64Array, Int8Array, Int16Array,
477        Int32Array, Int64Array, LargeBinaryArray, ListArray, NullArray, Time32MillisecondArray,
478        Time32SecondArray, Time64MicrosecondArray, Time64NanosecondArray,
479        TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,
480        TimestampSecondArray, UInt8Array, UInt16Array, UInt32Array, UInt64Array,
481    };
482    use arrow::buffer::Buffer;
483    use arrow::datatypes::{Int32Type, IntervalMonthDayNano};
484    use arrow_array::{BinaryArray, DictionaryArray, FixedSizeBinaryArray, LargeStringArray};
485    use arrow_schema::DataType;
486    use common_decimal::Decimal128;
487    use common_time::time::Time;
488    use common_time::timestamp::TimeUnit;
489    use common_time::{Date, Duration};
490
491    use super::*;
492    use crate::value::Value;
493    use crate::vectors::ConcreteDataType;
494
495    #[test]
496    fn test_try_into_vectors() {
497        let arrays: Vec<ArrayRef> = vec![
498            Arc::new(Int32Array::from(vec![1])),
499            Arc::new(Int32Array::from(vec![2])),
500            Arc::new(Int32Array::from(vec![3])),
501        ];
502        let vectors = Helper::try_into_vectors(&arrays).unwrap();
503        vectors.iter().for_each(|v| assert_eq!(1, v.len()));
504        assert_eq!(Value::Int32(1), vectors[0].get(0));
505        assert_eq!(Value::Int32(2), vectors[1].get(0));
506        assert_eq!(Value::Int32(3), vectors[2].get(0));
507    }
508
509    #[test]
510    fn test_try_into_date_vector() {
511        let vector = DateVector::from(vec![Some(1), Some(2), None]);
512        let arrow_array = vector.to_arrow_array();
513        assert_eq!(&ArrowDataType::Date32, arrow_array.data_type());
514        let vector_converted = Helper::try_into_vector(arrow_array).unwrap();
515        assert_eq!(vector.len(), vector_converted.len());
516        for i in 0..vector_converted.len() {
517            assert_eq!(vector.get(i), vector_converted.get(i));
518        }
519    }
520
521    #[test]
522    fn test_try_from_scalar_date_value() {
523        let vector = Helper::try_from_scalar_value(ScalarValue::Date32(Some(42)), 3).unwrap();
524        assert_eq!(ConcreteDataType::date_datatype(), vector.data_type());
525        assert_eq!(3, vector.len());
526        for i in 0..vector.len() {
527            assert_eq!(Value::Date(Date::new(42)), vector.get(i));
528        }
529    }
530
531    #[test]
532    fn test_try_from_scalar_duration_value() {
533        let vector =
534            Helper::try_from_scalar_value(ScalarValue::DurationSecond(Some(42)), 3).unwrap();
535        assert_eq!(
536            ConcreteDataType::duration_second_datatype(),
537            vector.data_type()
538        );
539        assert_eq!(3, vector.len());
540        for i in 0..vector.len() {
541            assert_eq!(
542                Value::Duration(Duration::new(42, TimeUnit::Second)),
543                vector.get(i)
544            );
545        }
546    }
547
548    #[test]
549    fn test_try_from_scalar_decimal128_value() {
550        let vector =
551            Helper::try_from_scalar_value(ScalarValue::Decimal128(Some(42), 3, 1), 3).unwrap();
552        assert_eq!(
553            ConcreteDataType::decimal128_datatype(3, 1),
554            vector.data_type()
555        );
556        assert_eq!(3, vector.len());
557        for i in 0..vector.len() {
558            assert_eq!(Value::Decimal128(Decimal128::new(42, 3, 1)), vector.get(i));
559        }
560    }
561
562    #[test]
563    fn test_try_from_list_value() {
564        let value = ScalarValue::List(ScalarValue::new_list(
565            &[ScalarValue::Int32(Some(1)), ScalarValue::Int32(Some(2))],
566            &ArrowDataType::Int32,
567            true,
568        ));
569        let vector = Helper::try_from_scalar_value(value, 3).unwrap();
570        assert_eq!(
571            ConcreteDataType::list_datatype(Arc::new(ConcreteDataType::int32_datatype())),
572            vector.data_type()
573        );
574        assert_eq!(3, vector.len());
575        for i in 0..vector.len() {
576            let v = vector.get(i);
577            let items = v.as_list().unwrap().unwrap().items();
578            assert_eq!(vec![Value::Int32(1), Value::Int32(2)], items);
579        }
580    }
581
582    #[test]
583    fn test_like_utf8() {
584        fn assert_vector(expected: Vec<&str>, actual: &VectorRef) {
585            let actual = actual.as_any().downcast_ref::<StringVector>().unwrap();
586            assert_eq!(*actual, StringVector::from(expected));
587        }
588
589        let names: Vec<String> = vec!["greptime", "hello", "public", "world"]
590            .into_iter()
591            .map(|x| x.to_string())
592            .collect();
593
594        let ret = Helper::like_utf8(names.clone(), "%ll%").unwrap();
595        assert_vector(vec!["hello"], &ret);
596
597        let ret = Helper::like_utf8(names.clone(), "%time").unwrap();
598        assert_vector(vec!["greptime"], &ret);
599
600        let ret = Helper::like_utf8(names.clone(), "%ld").unwrap();
601        assert_vector(vec!["world"], &ret);
602
603        let ret = Helper::like_utf8(names, "%").unwrap();
604        assert_vector(vec!["greptime", "hello", "public", "world"], &ret);
605    }
606
607    #[test]
608    fn test_like_utf8_filter() {
609        fn assert_vector(expected: Vec<&str>, actual: &VectorRef) {
610            let actual = actual.as_any().downcast_ref::<StringVector>().unwrap();
611            assert_eq!(*actual, StringVector::from(expected));
612        }
613
614        fn assert_filter(array: Vec<String>, s: &str, expected_filter: &BooleanVector) {
615            let array = StringArray::from(array);
616            let s = StringArray::new_scalar(s);
617            let actual_filter = comparison::like(&array, &s).unwrap();
618            assert_eq!(BooleanVector::from(actual_filter), *expected_filter);
619        }
620
621        let names: Vec<String> = vec!["greptime", "timeseries", "cloud", "database"]
622            .into_iter()
623            .map(|x| x.to_string())
624            .collect();
625
626        let (table, filter) = Helper::like_utf8_filter(names.clone(), "%ti%").unwrap();
627        assert_vector(vec!["greptime", "timeseries"], &table);
628        assert_filter(names.clone(), "%ti%", &filter);
629
630        let (tables, filter) = Helper::like_utf8_filter(names.clone(), "%lou").unwrap();
631        assert_vector(vec![], &tables);
632        assert_filter(names.clone(), "%lou", &filter);
633
634        let (tables, filter) = Helper::like_utf8_filter(names.clone(), "%d%").unwrap();
635        assert_vector(vec!["cloud", "database"], &tables);
636        assert_filter(names.clone(), "%d%", &filter);
637    }
638
639    fn check_try_into_vector(array: impl Array + 'static) {
640        let array: ArrayRef = Arc::new(array);
641        let vector = Helper::try_into_vector(array.clone()).unwrap();
642        assert_eq!(&array, &vector.to_arrow_array());
643    }
644
645    #[test]
646    fn test_try_into_vector() {
647        check_try_into_vector(NullArray::new(2));
648        check_try_into_vector(BooleanArray::from(vec![true, false]));
649        check_try_into_vector(Int8Array::from(vec![1, 2, 3]));
650        check_try_into_vector(Int16Array::from(vec![1, 2, 3]));
651        check_try_into_vector(Int32Array::from(vec![1, 2, 3]));
652        check_try_into_vector(Int64Array::from(vec![1, 2, 3]));
653        check_try_into_vector(UInt8Array::from(vec![1, 2, 3]));
654        check_try_into_vector(UInt16Array::from(vec![1, 2, 3]));
655        check_try_into_vector(UInt32Array::from(vec![1, 2, 3]));
656        check_try_into_vector(UInt64Array::from(vec![1, 2, 3]));
657        check_try_into_vector(Float32Array::from(vec![1.0, 2.0, 3.0]));
658        check_try_into_vector(Float64Array::from(vec![1.0, 2.0, 3.0]));
659        check_try_into_vector(StringArray::from(vec!["hello", "world"]));
660        check_try_into_vector(Date32Array::from(vec![1, 2, 3]));
661        let data = vec![None, Some(vec![Some(6), Some(7)])];
662        let list_array = ListArray::from_iter_primitive::<Int32Type, _, _>(data);
663        check_try_into_vector(list_array);
664        check_try_into_vector(TimestampSecondArray::from(vec![1, 2, 3]));
665        check_try_into_vector(TimestampMillisecondArray::from(vec![1, 2, 3]));
666        check_try_into_vector(TimestampMicrosecondArray::from(vec![1, 2, 3]));
667        check_try_into_vector(TimestampNanosecondArray::from(vec![1, 2, 3]));
668        check_try_into_vector(Time32SecondArray::from(vec![1, 2, 3]));
669        check_try_into_vector(Time32MillisecondArray::from(vec![1, 2, 3]));
670        check_try_into_vector(Time64MicrosecondArray::from(vec![1, 2, 3]));
671        check_try_into_vector(Time64NanosecondArray::from(vec![1, 2, 3]));
672
673        // Test dictionary arrays with different key types
674        let values = StringArray::from_iter_values(["a", "b", "c"]);
675
676        // Test Int8 keys
677        let keys = Int8Array::from_iter_values([0, 0, 1, 2]);
678        let array: ArrayRef =
679            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
680        Helper::try_into_vector(array).unwrap();
681
682        // Test Int16 keys
683        let keys = Int16Array::from_iter_values([0, 0, 1, 2]);
684        let array: ArrayRef =
685            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
686        Helper::try_into_vector(array).unwrap();
687
688        // Test Int32 keys
689        let keys = Int32Array::from_iter_values([0, 0, 1, 2]);
690        let array: ArrayRef =
691            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
692        Helper::try_into_vector(array).unwrap();
693
694        // Test Int64 keys
695        let keys = Int64Array::from_iter_values([0, 0, 1, 2]);
696        let array: ArrayRef =
697            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
698        Helper::try_into_vector(array).unwrap();
699
700        // Test UInt8 keys
701        let keys = UInt8Array::from_iter_values([0, 0, 1, 2]);
702        let array: ArrayRef =
703            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
704        Helper::try_into_vector(array).unwrap();
705
706        // Test UInt16 keys
707        let keys = UInt16Array::from_iter_values([0, 0, 1, 2]);
708        let array: ArrayRef =
709            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
710        Helper::try_into_vector(array).unwrap();
711
712        // Test UInt32 keys
713        let keys = UInt32Array::from_iter_values([0, 0, 1, 2]);
714        let array: ArrayRef =
715            Arc::new(DictionaryArray::try_new(keys, Arc::new(values.clone())).unwrap());
716        Helper::try_into_vector(array).unwrap();
717
718        // Test UInt64 keys
719        let keys = UInt64Array::from_iter_values([0, 0, 1, 2]);
720        let array: ArrayRef = Arc::new(DictionaryArray::try_new(keys, Arc::new(values)).unwrap());
721        Helper::try_into_vector(array).unwrap();
722    }
723
724    #[test]
725    fn test_try_binary_array_into_vector() {
726        let input_vec: Vec<&[u8]> = vec!["hello".as_bytes(), "world".as_bytes()];
727        let assertion_vector = BinaryVector::from(input_vec.clone());
728
729        let input_arrays: Vec<ArrayRef> = vec![
730            Arc::new(LargeBinaryArray::from(input_vec.clone())) as ArrayRef,
731            Arc::new(BinaryArray::from(input_vec.clone())) as ArrayRef,
732            Arc::new(FixedSizeBinaryArray::new(
733                5,
734                Buffer::from_vec("helloworld".as_bytes().to_vec()),
735                None,
736            )) as ArrayRef,
737        ];
738
739        for input_array in input_arrays {
740            let vector = Helper::try_into_vector(input_array).unwrap();
741
742            assert_eq!(2, vector.len());
743            assert_eq!(0, vector.null_count());
744
745            let output_arrow_array: ArrayRef = vector.to_arrow_array();
746            assert_eq!(&DataType::Binary, output_arrow_array.data_type());
747            assert_eq!(&assertion_vector.to_arrow_array(), &output_arrow_array);
748        }
749    }
750
751    #[test]
752    fn test_large_string_array_into_vector() {
753        let input_vec = vec!["a", "b"];
754        let assertion_array = LargeStringArray::from(input_vec.clone());
755
756        let large_string_array: ArrayRef = Arc::new(LargeStringArray::from(input_vec));
757        let vector = Helper::try_into_vector(large_string_array).unwrap();
758        assert_eq!(2, vector.len());
759        assert_eq!(0, vector.null_count());
760
761        let output_arrow_array: LargeStringArray = vector
762            .to_arrow_array()
763            .as_any()
764            .downcast_ref::<LargeStringArray>()
765            .unwrap()
766            .clone();
767        assert_eq!(&assertion_array, &output_arrow_array);
768    }
769
770    #[test]
771    fn test_try_from_scalar_time_value() {
772        let vector = Helper::try_from_scalar_value(ScalarValue::Time32Second(Some(42)), 3).unwrap();
773        assert_eq!(ConcreteDataType::time_second_datatype(), vector.data_type());
774        assert_eq!(3, vector.len());
775        for i in 0..vector.len() {
776            assert_eq!(Value::Time(Time::new_second(42)), vector.get(i));
777        }
778    }
779
780    #[test]
781    fn test_try_from_scalar_interval_value() {
782        let vector = Helper::try_from_scalar_value(
783            ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano::new(1, 1, 2000))),
784            3,
785        )
786        .unwrap();
787
788        assert_eq!(
789            ConcreteDataType::interval_month_day_nano_datatype(),
790            vector.data_type()
791        );
792        assert_eq!(3, vector.len());
793        for i in 0..vector.len() {
794            assert_eq!(
795                Value::IntervalMonthDayNano(IntervalMonthDayNano::new(1, 1, 2000).into()),
796                vector.get(i)
797            );
798        }
799    }
800
801    fn check_try_from_row_to_vector(row: Vec<Value>, dt: &ConcreteDataType) {
802        let vector = Helper::try_from_row_into_vector(&row, dt).unwrap();
803        for (i, item) in row.iter().enumerate().take(vector.len()) {
804            assert_eq!(*item, vector.get(i));
805        }
806    }
807
808    fn check_into_and_from(array: impl Array + 'static) {
809        let array: ArrayRef = Arc::new(array);
810        let vector = Helper::try_into_vector(array.clone()).unwrap();
811        assert_eq!(&array, &vector.to_arrow_array());
812        let row: Vec<Value> = (0..array.len()).map(|i| vector.get(i)).collect();
813        let dt = vector.data_type();
814        check_try_from_row_to_vector(row, &dt);
815    }
816
817    #[test]
818    fn test_try_from_row_to_vector() {
819        check_into_and_from(NullArray::new(2));
820        check_into_and_from(BooleanArray::from(vec![true, false]));
821        check_into_and_from(Int8Array::from(vec![1, 2, 3]));
822        check_into_and_from(Int16Array::from(vec![1, 2, 3]));
823        check_into_and_from(Int32Array::from(vec![1, 2, 3]));
824        check_into_and_from(Int64Array::from(vec![1, 2, 3]));
825        check_into_and_from(UInt8Array::from(vec![1, 2, 3]));
826        check_into_and_from(UInt16Array::from(vec![1, 2, 3]));
827        check_into_and_from(UInt32Array::from(vec![1, 2, 3]));
828        check_into_and_from(UInt64Array::from(vec![1, 2, 3]));
829        check_into_and_from(Float32Array::from(vec![1.0, 2.0, 3.0]));
830        check_into_and_from(Float64Array::from(vec![1.0, 2.0, 3.0]));
831        check_into_and_from(StringArray::from(vec!["hello", "world"]));
832        check_into_and_from(Date32Array::from(vec![1, 2, 3]));
833
834        check_into_and_from(TimestampSecondArray::from(vec![1, 2, 3]));
835        check_into_and_from(TimestampMillisecondArray::from(vec![1, 2, 3]));
836        check_into_and_from(TimestampMicrosecondArray::from(vec![1, 2, 3]));
837        check_into_and_from(TimestampNanosecondArray::from(vec![1, 2, 3]));
838        check_into_and_from(Time32SecondArray::from(vec![1, 2, 3]));
839        check_into_and_from(Time32MillisecondArray::from(vec![1, 2, 3]));
840        check_into_and_from(Time64MicrosecondArray::from(vec![1, 2, 3]));
841        check_into_and_from(Time64NanosecondArray::from(vec![1, 2, 3]));
842    }
843}