Skip to main content

datafusion_functions_nested/
array_has.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`ScalarUDFImpl`] definitions for array_has, array_has_all and array_has_any functions.
6
7use arrow::array::{
8    Array, ArrayRef, ArrowNativeTypeOp, AsArray, BooleanArray, BooleanBufferBuilder,
9    Datum, MAX_INLINE_VIEW_LEN, Scalar, StringArrayType, StringViewArray,
10};
11use arrow::buffer::{BooleanBuffer, NullBuffer, OffsetBuffer};
12use arrow::datatypes::DataType;
13use arrow::downcast_primitive_array;
14use arrow::row::{RowConverter, Rows, SortField};
15use datafusion_common::cast::{as_fixed_size_list_array, as_generic_list_array};
16use datafusion_common::utils::string_utils::string_array_to_vec;
17use datafusion_common::utils::take_function_args;
18use datafusion_common::{DataFusionError, Result, ScalarValue, exec_err};
19use datafusion_expr::expr::ScalarFunction;
20use datafusion_expr::simplify::ExprSimplifyResult;
21use datafusion_expr::{
22    ColumnarValue, Documentation, Expr, ScalarFunctionArgs, ScalarUDFImpl, Signature,
23    Volatility, in_list,
24};
25use datafusion_macros::user_doc;
26use datafusion_physical_expr_common::datum::compare_with_eq;
27use itertools::Itertools;
28
29use crate::make_array::make_array_udf;
30use crate::utils::make_scalar_function;
31
32use hashbrown::HashSet;
33use std::ops::Range;
34use std::sync::Arc;
35
36// Create static instances of ScalarUDFs for each function
37make_udf_expr_and_func!(ArrayHas,
38    array_has,
39    haystack_array element, // arg names
40    "returns true, if the element appears in the first array, otherwise false.", // doc
41    array_has_udf // internal function name
42);
43make_udf_expr_and_func!(ArrayHasAll,
44    array_has_all,
45    haystack_array needle_array, // arg names
46    "returns true if each element of the second array appears in the first array; otherwise, it returns false.", // doc
47    array_has_all_udf // internal function name
48);
49make_udf_expr_and_func!(ArrayHasAny,
50    array_has_any,
51    first_array second_array, // arg names
52    "returns true if at least one element of the second array appears in the first array; otherwise, it returns false.", // doc
53    array_has_any_udf // internal function name
54);
55
56#[user_doc(
57    doc_section(label = "Array Functions"),
58    description = "Returns true if the array contains the element.",
59    syntax_example = "array_has(array, element)",
60    sql_example = r#"```sql
61> select array_has([1, 2, 3], 2);
62+-----------------------------+
63| array_has(List([1,2,3]), 2) |
64+-----------------------------+
65| true                        |
66+-----------------------------+
67```"#,
68    argument(
69        name = "array",
70        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
71    ),
72    argument(
73        name = "element",
74        description = "Scalar or Array expression. Can be a constant, column, or function, and any combination of array operators."
75    )
76)]
77#[derive(Debug, PartialEq, Eq, Hash)]
78pub struct ArrayHas {
79    signature: Signature,
80    aliases: Vec<String>,
81}
82
83impl Default for ArrayHas {
84    fn default() -> Self {
85        Self::new()
86    }
87}
88
89impl ArrayHas {
90    pub fn new() -> Self {
91        Self {
92            signature: Signature::array_and_element(Volatility::Immutable),
93            aliases: vec![
94                String::from("list_has"),
95                String::from("array_contains"),
96                String::from("list_contains"),
97            ],
98        }
99    }
100}
101
102impl ScalarUDFImpl for ArrayHas {
103    fn name(&self) -> &str {
104        "array_has"
105    }
106
107    fn signature(&self) -> &Signature {
108        &self.signature
109    }
110
111    fn return_type(&self, _: &[DataType]) -> Result<DataType> {
112        Ok(DataType::Boolean)
113    }
114
115    fn simplify(
116        &self,
117        mut args: Vec<Expr>,
118        info: &datafusion_expr::simplify::SimplifyContext,
119    ) -> Result<ExprSimplifyResult> {
120        let [haystack, needle] = take_function_args(self.name(), &mut args)?;
121
122        // if the haystack is a constant list, we can use an inlist expression which is more
123        // efficient because the haystack is not varying per-row
124        match haystack {
125            Expr::Literal(scalar, _) if scalar.is_null() => {
126                return Ok(ExprSimplifyResult::Simplified(Expr::Literal(
127                    ScalarValue::Boolean(None),
128                    None,
129                )));
130            }
131            Expr::Literal(
132                // FixedSizeList gets coerced to List
133                scalar @ ScalarValue::List(_) | scalar @ ScalarValue::LargeList(_),
134                _,
135            ) => {
136                if let Ok(scalar_values) =
137                    ScalarValue::convert_array_to_scalar_vec(&scalar.to_array()?)
138                {
139                    assert_eq!(scalar_values.len(), 1);
140                    let values = scalar_values
141                        .into_iter()
142                        .flatten()
143                        .flatten()
144                        .collect::<Vec<_>>();
145
146                    if values.iter().any(ScalarValue::is_null) {
147                        return Ok(ExprSimplifyResult::Original(args));
148                    }
149
150                    let list = values
151                        .into_iter()
152                        .map(|value| Expr::Literal(value, None))
153                        .collect();
154
155                    return Ok(ExprSimplifyResult::Simplified(in_list(
156                        std::mem::take(needle),
157                        list,
158                        false,
159                    )));
160                }
161            }
162            Expr::ScalarFunction(ScalarFunction { func, args })
163                if func == &make_array_udf() =>
164            {
165                let mut has_unsafe_nullable_element = false;
166                for arg in args.iter() {
167                    // `needle IN (needle)` preserves NULL semantics. A different
168                    // nullable element does not: array_has([NULL], value) is false,
169                    // while value IN (NULL) is NULL. Volatile expressions are
170                    // evaluated separately, so syntactic equality is insufficient.
171                    let safe_same_expr = arg == &*needle && !arg.is_volatile();
172                    if info.nullable(arg)? && !safe_same_expr {
173                        has_unsafe_nullable_element = true;
174                        break;
175                    }
176                }
177
178                if !has_unsafe_nullable_element {
179                    // make_array has a static set of arguments, so we can pull the arguments out from it
180                    return Ok(ExprSimplifyResult::Simplified(in_list(
181                        std::mem::take(needle),
182                        std::mem::take(args),
183                        false,
184                    )));
185                }
186            }
187            _ => {}
188        }
189        Ok(ExprSimplifyResult::Original(args))
190    }
191
192    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
193        let [first_arg, second_arg] = take_function_args(self.name(), &args.args)?;
194        if first_arg.data_type().is_null() {
195            // Always return null if the first argument is null
196            // i.e. array_has(null, element) -> null
197            return Ok(ColumnarValue::Scalar(ScalarValue::Boolean(None)));
198        }
199
200        match &second_arg {
201            ColumnarValue::Array(array_needle) => {
202                // the needle is already an array, convert the haystack to an array of the same length
203                let haystack = first_arg.to_array(array_needle.len())?;
204                let array = array_has_inner_for_array(&haystack, array_needle)?;
205                Ok(ColumnarValue::Array(array))
206            }
207            ColumnarValue::Scalar(scalar_needle) => {
208                // Always return null if the second argument is null
209                // i.e. array_has(array, null) -> null
210                if scalar_needle.is_null() {
211                    return Ok(ColumnarValue::Scalar(ScalarValue::Boolean(None)));
212                }
213
214                // since the needle is a scalar, convert it to an array of size 1
215                let haystack = first_arg.to_array(1)?;
216                let needle = scalar_needle.to_array_of_size(1)?;
217                let needle = Scalar::new(needle);
218                let array = array_has_inner_for_scalar(&haystack, &needle)?;
219                if let ColumnarValue::Scalar(_) = &first_arg {
220                    // If both inputs are scalar, keeps output as scalar
221                    let scalar_value = ScalarValue::try_from_array(&array, 0)?;
222                    Ok(ColumnarValue::Scalar(scalar_value))
223                } else {
224                    Ok(ColumnarValue::Array(array))
225                }
226            }
227        }
228    }
229
230    fn aliases(&self) -> &[String] {
231        &self.aliases
232    }
233
234    fn documentation(&self) -> Option<&Documentation> {
235        self.doc()
236    }
237}
238
239fn array_has_inner_for_scalar(
240    haystack: &ArrayRef,
241    needle: &dyn Datum,
242) -> Result<ArrayRef> {
243    let haystack = haystack.as_ref().try_into()?;
244    array_has_dispatch_for_scalar(haystack, needle)
245}
246
247fn array_has_inner_for_array(haystack: &ArrayRef, needle: &ArrayRef) -> Result<ArrayRef> {
248    let haystack = haystack.as_ref().try_into()?;
249    array_has_dispatch_for_array(haystack, needle)
250}
251
252#[derive(Copy, Clone)]
253enum ArrayWrapper<'a> {
254    FixedSizeList(&'a arrow::array::FixedSizeListArray),
255    List(&'a arrow::array::GenericListArray<i32>),
256    LargeList(&'a arrow::array::GenericListArray<i64>),
257}
258
259impl<'a> TryFrom<&'a dyn Array> for ArrayWrapper<'a> {
260    type Error = DataFusionError;
261
262    fn try_from(
263        value: &'a dyn Array,
264    ) -> std::result::Result<ArrayWrapper<'a>, Self::Error> {
265        match value.data_type() {
266            DataType::List(_) => {
267                Ok(ArrayWrapper::List(as_generic_list_array::<i32>(value)?))
268            }
269            DataType::LargeList(_) => Ok(ArrayWrapper::LargeList(
270                as_generic_list_array::<i64>(value)?,
271            )),
272            DataType::FixedSizeList(_, _) => Ok(ArrayWrapper::FixedSizeList(
273                as_fixed_size_list_array(value)?,
274            )),
275            _ => exec_err!("array_has does not support type '{}'.", value.data_type()),
276        }
277    }
278}
279
280impl<'a> ArrayWrapper<'a> {
281    fn len(&self) -> usize {
282        match self {
283            ArrayWrapper::FixedSizeList(arr) => arr.len(),
284            ArrayWrapper::List(arr) => arr.len(),
285            ArrayWrapper::LargeList(arr) => arr.len(),
286        }
287    }
288
289    fn iter(&self) -> Box<dyn Iterator<Item = Option<ArrayRef>> + 'a> {
290        match self {
291            ArrayWrapper::FixedSizeList(arr) => Box::new(arr.iter()),
292            ArrayWrapper::List(arr) => Box::new(arr.iter()),
293            ArrayWrapper::LargeList(arr) => Box::new(arr.iter()),
294        }
295    }
296
297    fn values(&self) -> &ArrayRef {
298        match self {
299            ArrayWrapper::FixedSizeList(arr) => arr.values(),
300            ArrayWrapper::List(arr) => arr.values(),
301            ArrayWrapper::LargeList(arr) => arr.values(),
302        }
303    }
304
305    fn value_type(&self) -> DataType {
306        match self {
307            ArrayWrapper::FixedSizeList(arr) => arr.value_type(),
308            ArrayWrapper::List(arr) => arr.value_type(),
309            ArrayWrapper::LargeList(arr) => arr.value_type(),
310        }
311    }
312
313    fn offsets(&self) -> Box<dyn Iterator<Item = usize> + 'a> {
314        match self {
315            ArrayWrapper::FixedSizeList(arr) => {
316                let value_length = arr.value_length() as usize;
317                Box::new((0..=arr.len()).map(move |i| i * value_length))
318            }
319            ArrayWrapper::List(arr) => {
320                Box::new(arr.offsets().iter().map(|o| (*o) as usize))
321            }
322            ArrayWrapper::LargeList(arr) => {
323                Box::new(arr.offsets().iter().map(|o| (*o) as usize))
324            }
325        }
326    }
327
328    fn nulls(&self) -> Option<&NullBuffer> {
329        match self {
330            ArrayWrapper::FixedSizeList(arr) => arr.nulls(),
331            ArrayWrapper::List(arr) => arr.nulls(),
332            ArrayWrapper::LargeList(arr) => arr.nulls(),
333        }
334    }
335}
336
337/// Evaluate `array_has` with an array (per-row) needle.
338///
339/// Primitive and string element types take a per-type fast path; nested (and any
340/// other) element types fall back to the per-row `eq` kernel, which allocates a
341/// `BooleanArray` per row.
342fn array_has_dispatch_for_array(
343    haystack: ArrayWrapper<'_>,
344    needle: &ArrayRef,
345) -> Result<ArrayRef> {
346    let combined_nulls = NullBuffer::union(haystack.nulls(), needle.nulls());
347    let needle = needle.as_ref();
348
349    // Rebase offsets to 0 with `OffsetBuffer::subtract` so `offsets[i]` indexes
350    // `visible_values` directly (the haystack may be a sliced list).
351    let raw = OffsetBuffer::new(
352        haystack
353            .offsets()
354            .map(|o| o as i64)
355            .collect::<Vec<_>>()
356            .into(),
357    );
358    let first = raw[0];
359    let visible_values = haystack
360        .values()
361        .slice(first as usize, (raw[raw.len() - 1] - first) as usize);
362    let visible_values = visible_values.as_ref();
363    let offsets: Vec<usize> = raw.subtract(first).iter().map(|&o| o as usize).collect();
364
365    // Fast path for primitive/string elements whose (coerced) type matches the
366    // needle; a type mismatch or a nested type falls through to the per-row kernel.
367    let fast_path = if visible_values.data_type() != needle.data_type() {
368        None
369    } else {
370        downcast_primitive_array! {
371            visible_values, needle => {
372                // The element-null path makes several passes over the values, so
373                // past a large average list length the per-row `eq` kernel is
374                // faster -- bail to it. The single-pass all-valid path has no such
375                // crossover, so only bail when elements are null.
376                let num_rows = offsets.len() - 1;
377                if num_rows > 0
378                    && offsets[num_rows] / num_rows > NULL_FAST_PATH_MAX_LEN
379                    && visible_values.null_count() > 0
380                {
381                    None
382                } else {
383                    Some(array_has_array_native(
384                        visible_values.values(),
385                        visible_values.nulls(),
386                        needle.values(),
387                        &offsets,
388                        combined_nulls.as_ref(),
389                    ))
390                }
391            }
392            (DataType::Utf8, _) => Some(array_has_array_string(
393                visible_values.as_string::<i32>(),
394                needle.as_string::<i32>(),
395                &offsets,
396                combined_nulls.as_ref(),
397            )),
398            (DataType::LargeUtf8, _) => Some(array_has_array_string(
399                visible_values.as_string::<i64>(),
400                needle.as_string::<i64>(),
401                &offsets,
402                combined_nulls.as_ref(),
403            )),
404            (DataType::Utf8View, _) => Some(array_has_array_string_view(
405                visible_values.as_string_view(),
406                needle.as_string_view(),
407                &offsets,
408                combined_nulls.as_ref(),
409            )),
410            _ => None,
411        }
412    };
413
414    if let Some(values) = fast_path {
415        return Ok(Arc::new(BooleanArray::new(values, combined_nulls)));
416    }
417
418    // Fallback: per-row `eq` kernel (nested element types, or a type mismatch).
419    let mut result = BooleanBufferBuilder::new(haystack.len());
420    for (i, arr) in haystack.iter().enumerate() {
421        if combined_nulls.as_ref().is_some_and(|n| n.is_null(i)) {
422            result.append(false);
423            continue;
424        }
425        let arr = arr.unwrap();
426        let is_nested = arr.data_type().is_nested();
427        let needle_row = Scalar::new(needle.slice(i, 1));
428        let eq_array = compare_with_eq(&arr, &needle_row, is_nested)?;
429        result.append(eq_array.has_true());
430    }
431
432    Ok(Arc::new(BooleanArray::new(result.finish(), combined_nulls)))
433}
434
435/// Average list length past which the element-null path loses to the per-row
436/// `eq` kernel and bails to it (empirically measured).
437const NULL_FAST_PATH_MAX_LEN: usize = 512;
438
439/// Primitive fast path, two branches on element validity:
440///
441/// 1. No nulls: branchless OR-reduction over the raw slice (auto-vectorizes).
442/// 2. Nulls: AND the equality bitmap with validity (a null slot's value is
443///    arbitrary), then reduce each row to "any bit set". Chunked to bound the
444///    expanded needle.
445///
446/// Generic over the native type alone -- the caller's `downcast_primitive_array!`
447/// peels off the Arrow type -- so `Int32`, `Date32` and `Time32` share a single
448/// instantiation instead of getting one each.
449fn array_has_array_native<N: ArrowNativeTypeOp>(
450    value_slice: &[N],
451    element_nulls: Option<&NullBuffer>,
452    needle_slice: &[N],
453    offsets: &[usize],
454    combined_nulls: Option<&NullBuffer>,
455) -> BooleanBuffer {
456    let num_rows = offsets.len() - 1;
457
458    let Some(element_nulls) = element_nulls else {
459        return BooleanBuffer::collect_bool(num_rows, |i| {
460            if combined_nulls.is_some_and(|n| n.is_null(i)) {
461                return false;
462            }
463            // `needle[i]` is non-null here: combined_nulls covers the needle nulls.
464            let needle_val = needle_slice[i];
465            let start = offsets[i];
466            let end = offsets[i + 1];
467            value_slice[start..end]
468                .iter()
469                .fold(false, |acc, &v| acc | v.is_eq(needle_val))
470        });
471    };
472
473    // Case 2 (see fn doc), chunked like the all/any kernels.
474    let mut result = BooleanBufferBuilder::new(num_rows);
475    let mut needle_expanded: Vec<N> = Vec::new();
476    for chunk_start in (0..num_rows).step_by(ROW_CONVERSION_CHUNK_SIZE) {
477        let chunk_end = (chunk_start + ROW_CONVERSION_CHUNK_SIZE).min(num_rows);
478        let elem_start = offsets[chunk_start];
479        let elem_end = offsets[chunk_end];
480
481        // Expand the per-row needle across this chunk's elements (reused scratch),
482        // then compare in one vectorizable pass and mask out null elements.
483        needle_expanded.clear();
484        for i in chunk_start..chunk_end {
485            needle_expanded.extend(std::iter::repeat_n(
486                needle_slice[i],
487                offsets[i + 1] - offsets[i],
488            ));
489        }
490        let chunk_values = &value_slice[elem_start..elem_end];
491        let eq_bits = BooleanBuffer::collect_bool(chunk_values.len(), |k| {
492            chunk_values[k].is_eq(needle_expanded[k])
493        });
494        let matched = &eq_bits
495            & &element_nulls
496                .inner()
497                .slice(elem_start, elem_end - elem_start);
498
499        for i in chunk_start..chunk_end {
500            if combined_nulls.is_some_and(|n| n.is_null(i)) {
501                result.append(false);
502                continue;
503            }
504            let start = offsets[i] - elem_start;
505            let end = offsets[i + 1] - elem_start;
506            result.append(matched.slice(start, end - start).has_true());
507        }
508    }
509    result.finish()
510}
511
512/// String fast path, generic over the offset width (`Utf8` / `LargeUtf8`).
513fn array_has_array_string<'a, S: StringArrayType<'a> + Copy>(
514    values: S,
515    needle: S,
516    offsets: &[usize],
517    combined_nulls: Option<&NullBuffer>,
518) -> BooleanBuffer {
519    let num_rows = offsets.len() - 1;
520    BooleanBuffer::collect_bool(num_rows, |i| {
521        if combined_nulls.is_some_and(|n| n.is_null(i)) {
522            return false;
523        }
524        // `needle[i]` is non-null here: combined_nulls covers the needle nulls.
525        let needle_val = needle.value(i);
526        let start = offsets[i];
527        let end = offsets[i + 1];
528        // Compare the value first and only consult validity on a match (see the
529        // primitive path for why this is correct and faster on no-match scans).
530        (start..end).any(|k| values.value(k) == needle_val && !values.is_null(k))
531    })
532}
533
534/// `Utf8View` variant of [`array_has_array_string`]: compare the packed 128-bit
535/// views directly so the length + 4-byte prefix reject non-matches without
536/// touching the data buffer, and an inline value matches on the view alone. A
537/// longer view is only materialized to confirm a candidate; validity is
538/// consulted only on a view match.
539fn array_has_array_string_view(
540    values: &StringViewArray,
541    needle: &StringViewArray,
542    offsets: &[usize],
543    combined_nulls: Option<&NullBuffer>,
544) -> BooleanBuffer {
545    let num_rows = offsets.len() - 1;
546    let value_views = values.views();
547    let needle_views = needle.views();
548    BooleanBuffer::collect_bool(num_rows, |i| {
549        if combined_nulls.is_some_and(|n| n.is_null(i)) {
550            return false;
551        }
552        // `needle[i]` is non-null here: combined_nulls covers the needle nulls.
553        let needle_view = needle_views[i];
554        // Low 32 bits are the byte length; the next 32 are the inline prefix.
555        let needle_inline = (needle_view as u32) <= MAX_INLINE_VIEW_LEN;
556        let needle_lo = needle_view as u64;
557        let needle_val = needle.value(i);
558        let start = offsets[i];
559        let end = offsets[i + 1];
560        (start..end).any(|k| {
561            let v = value_views[k];
562            let matched = if needle_inline {
563                // Inline: the whole view is the canonical value (zero padded).
564                v == needle_view
565            } else {
566                // Longer: reject on length + prefix, then confirm the bytes.
567                (v as u64) == needle_lo && values.value(k) == needle_val
568            };
569            matched && !values.is_null(k)
570        })
571    })
572}
573
574fn array_has_dispatch_for_scalar(
575    haystack: ArrayWrapper<'_>,
576    needle: &dyn Datum,
577) -> Result<ArrayRef> {
578    // If first argument is empty list (second argument is non-null), return false
579    // i.e. array_has([], non-null element) -> false
580    if haystack.len() == 0 {
581        return Ok(Arc::new(BooleanArray::new(
582            BooleanBuffer::new_unset(haystack.len()),
583            None,
584        )));
585    }
586
587    // For sliced ListArrays, values() returns the full underlying array but
588    // only elements between the first and last offset are visible.
589    let offsets: Vec<usize> = haystack.offsets().collect();
590    let first_offset = offsets[0];
591    let visible_values = haystack
592        .values()
593        .slice(first_offset, offsets[offsets.len() - 1] - first_offset);
594
595    let is_nested = visible_values.data_type().is_nested();
596    let eq_array = compare_with_eq(&visible_values, needle, is_nested)?;
597
598    // When a haystack element is null, `eq()` returns null (not false).
599    // In Arrow, a null BooleanArray entry has validity=0 but an
600    // undefined value bit that may happen to be 1. Since set_indices()
601    // operates on the raw value buffer and ignores validity, we AND the
602    // values with the validity bitmap to clear any undefined bits at
603    // null positions. This ensures set_indices() only yields positions
604    // where the comparison genuinely returned true.
605    let eq_bits = match eq_array.nulls() {
606        Some(nulls) => eq_array.values() & nulls.inner(),
607        None => eq_array.values().clone(),
608    };
609
610    let validity = match &haystack {
611        ArrayWrapper::FixedSizeList(arr) => arr.nulls(),
612        ArrayWrapper::List(arr) => arr.nulls(),
613        ArrayWrapper::LargeList(arr) => arr.nulls(),
614    };
615    let mut matches = eq_bits.set_indices().peekable();
616    let mut result = BooleanBufferBuilder::new(haystack.len());
617    result.append_n(haystack.len(), false);
618
619    // Match positions are relative to visible_values (0-based), so
620    // subtract first_offset from each offset when comparing.
621    for (i, window) in offsets.windows(2).enumerate() {
622        let end = window[1] - first_offset;
623
624        let has_match = matches.peek().is_some_and(|&p| p < end);
625
626        // Advance past all match positions in this row's range.
627        while matches.peek().is_some_and(|&p| p < end) {
628            matches.next();
629        }
630
631        if has_match && validity.is_none_or(|v| v.is_valid(i)) {
632            result.set_bit(i, true);
633        }
634    }
635
636    // A null haystack row always produces a null output, so we can
637    // reuse the haystack's null buffer directly.
638    Ok(Arc::new(BooleanArray::new(
639        result.finish(),
640        validity.cloned(),
641    )))
642}
643
644fn array_has_all_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
645    array_has_all_and_any_inner(args, ComparisonType::All)
646}
647
648/// Number of rows to process at a time when doing batched row conversion.  This
649/// amortizes the row conversion overhead over more rows, but making this too
650/// large can cause cache pressure for large arrays. See
651/// <https://github.com/apache/datafusion/pull/20588> for context.
652const ROW_CONVERSION_CHUNK_SIZE: usize = 512;
653
654// General row comparison for array_has_all and array_has_any
655fn general_array_has_for_all_and_any<'a>(
656    haystack: ArrayWrapper<'a>,
657    needle: ArrayWrapper<'a>,
658    comparison_type: ComparisonType,
659) -> Result<ArrayRef> {
660    let num_rows = haystack.len();
661    let converter = RowConverter::new(vec![SortField::new(haystack.value_type())])?;
662
663    let h_offsets: Vec<usize> = haystack.offsets().collect();
664    let n_offsets: Vec<usize> = needle.offsets().collect();
665
666    let combined_nulls = NullBuffer::union(haystack.nulls(), needle.nulls());
667    let mut result = BooleanBufferBuilder::new(num_rows);
668
669    for chunk_start in (0..num_rows).step_by(ROW_CONVERSION_CHUNK_SIZE) {
670        let chunk_end = (chunk_start + ROW_CONVERSION_CHUNK_SIZE).min(num_rows);
671
672        // For efficiency with sliced arrays, only process the visible elements,
673        // not the entire underlying buffer.
674        let h_elem_start = h_offsets[chunk_start];
675        let h_elem_end = h_offsets[chunk_end];
676        let n_elem_start = n_offsets[chunk_start];
677        let n_elem_end = n_offsets[chunk_end];
678
679        let h_vals = haystack
680            .values()
681            .slice(h_elem_start, h_elem_end - h_elem_start);
682        let n_vals = needle
683            .values()
684            .slice(n_elem_start, n_elem_end - n_elem_start);
685
686        let chunk_h_rows = converter.convert_columns(&[h_vals])?;
687        let chunk_n_rows = converter.convert_columns(&[n_vals])?;
688
689        for i in chunk_start..chunk_end {
690            if combined_nulls.as_ref().is_some_and(|n| n.is_null(i)) {
691                result.append(false);
692                continue;
693            }
694            result.append(general_array_has_all_and_any_kernel(
695                &chunk_h_rows,
696                (h_offsets[i] - h_elem_start)..(h_offsets[i + 1] - h_elem_start),
697                &chunk_n_rows,
698                (n_offsets[i] - n_elem_start)..(n_offsets[i + 1] - n_elem_start),
699                comparison_type,
700            ));
701        }
702    }
703
704    Ok(Arc::new(BooleanArray::new(result.finish(), combined_nulls)))
705}
706
707// String comparison for array_has_all and array_has_any
708fn array_has_all_and_any_string_internal<'a>(
709    haystack: ArrayWrapper<'a>,
710    needle: ArrayWrapper<'a>,
711    comparison_type: ComparisonType,
712) -> Result<ArrayRef> {
713    let num_rows = haystack.len();
714
715    let h_offsets: Vec<usize> = haystack.offsets().collect();
716    let n_offsets: Vec<usize> = needle.offsets().collect();
717
718    let combined_nulls = NullBuffer::union(haystack.nulls(), needle.nulls());
719    let mut result = BooleanBufferBuilder::new(num_rows);
720
721    for chunk_start in (0..num_rows).step_by(ROW_CONVERSION_CHUNK_SIZE) {
722        let chunk_end = (chunk_start + ROW_CONVERSION_CHUNK_SIZE).min(num_rows);
723
724        let h_elem_start = h_offsets[chunk_start];
725        let h_elem_end = h_offsets[chunk_end];
726        let n_elem_start = n_offsets[chunk_start];
727        let n_elem_end = n_offsets[chunk_end];
728
729        let h_vals = haystack
730            .values()
731            .slice(h_elem_start, h_elem_end - h_elem_start);
732        let n_vals = needle
733            .values()
734            .slice(n_elem_start, n_elem_end - n_elem_start);
735
736        let chunk_h_strings = string_array_to_vec(h_vals.as_ref());
737        let chunk_n_strings = string_array_to_vec(n_vals.as_ref());
738
739        for i in chunk_start..chunk_end {
740            if combined_nulls.as_ref().is_some_and(|n| n.is_null(i)) {
741                result.append(false);
742                continue;
743            }
744            let h_start = h_offsets[i] - h_elem_start;
745            let h_end = h_offsets[i + 1] - h_elem_start;
746            let n_start = n_offsets[i] - n_elem_start;
747            let n_end = n_offsets[i + 1] - n_elem_start;
748            result.append(array_has_string_kernel(
749                &chunk_h_strings[h_start..h_end],
750                &chunk_n_strings[n_start..n_end],
751                comparison_type,
752            ));
753        }
754    }
755
756    Ok(Arc::new(BooleanArray::new(result.finish(), combined_nulls)))
757}
758
759fn array_has_all_and_any_dispatch<'a>(
760    haystack: ArrayWrapper<'a>,
761    needle: ArrayWrapper<'a>,
762    comparison_type: ComparisonType,
763) -> Result<ArrayRef> {
764    if needle.values().is_empty() {
765        let buffer = match comparison_type {
766            ComparisonType::All => BooleanBuffer::new_set(haystack.len()),
767            ComparisonType::Any => BooleanBuffer::new_unset(haystack.len()),
768        };
769        let nulls = NullBuffer::union(haystack.nulls(), needle.nulls());
770        Ok(Arc::new(BooleanArray::new(buffer, nulls)))
771    } else {
772        match needle.value_type() {
773            DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => {
774                array_has_all_and_any_string_internal(haystack, needle, comparison_type)
775            }
776            _ => general_array_has_for_all_and_any(haystack, needle, comparison_type),
777        }
778    }
779}
780
781fn array_has_all_and_any_inner(
782    args: &[ArrayRef],
783    comparison_type: ComparisonType,
784) -> Result<ArrayRef> {
785    let haystack: ArrayWrapper = args[0].as_ref().try_into()?;
786    let needle: ArrayWrapper = args[1].as_ref().try_into()?;
787    array_has_all_and_any_dispatch(haystack, needle, comparison_type)
788}
789
790fn array_has_any_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
791    array_has_all_and_any_inner(args, ComparisonType::Any)
792}
793
794/// Fast path for `array_has_any` when exactly one argument is a scalar.
795fn array_has_any_with_scalar(
796    columnar_arg: &ColumnarValue,
797    scalar_arg: &ScalarValue,
798) -> Result<ColumnarValue> {
799    if scalar_arg.is_null() {
800        return Ok(ColumnarValue::Scalar(ScalarValue::Boolean(None)));
801    }
802
803    // Convert the scalar to a 1-element ListArray, then extract the inner values
804    let scalar_array = scalar_arg.to_array_of_size(1)?;
805    let scalar_list: ArrayWrapper = scalar_array.as_ref().try_into()?;
806    let offsets: Vec<usize> = scalar_list.offsets().collect();
807    let scalar_values = scalar_list
808        .values()
809        .slice(offsets[0], offsets[1] - offsets[0]);
810
811    // If scalar list is empty, result is always false
812    if scalar_values.is_empty() {
813        return Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))));
814    }
815
816    match scalar_values.data_type() {
817        DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => {
818            array_has_any_with_scalar_string(columnar_arg, &scalar_values)
819        }
820        _ => array_has_any_with_scalar_general(columnar_arg, &scalar_values),
821    }
822}
823
824/// When the scalar argument has more elements than this, the scalar fast path
825/// builds a HashSet for O(1) lookups. At or below this threshold, it falls
826/// back to a linear scan, since hashing every columnar element is more
827/// expensive than a linear scan over a short array.
828const SCALAR_SMALL_THRESHOLD: usize = 8;
829
830/// String-specialized scalar fast path for `array_has_any`.
831fn array_has_any_with_scalar_string(
832    columnar_arg: &ColumnarValue,
833    scalar_values: &ArrayRef,
834) -> Result<ColumnarValue> {
835    let (col_arr, is_scalar_output) = match columnar_arg {
836        ColumnarValue::Array(arr) => (Arc::clone(arr), false),
837        ColumnarValue::Scalar(s) => (s.to_array_of_size(1)?, true),
838    };
839
840    let col_list: ArrayWrapper = col_arr.as_ref().try_into()?;
841    let col_values = col_list.values();
842    let col_offsets: Vec<usize> = col_list.offsets().collect();
843    let col_nulls = col_list.nulls();
844
845    let scalar_lookup = ScalarStringLookup::new(scalar_values);
846    let has_null_scalar = scalar_values.null_count() > 0;
847
848    let result = match col_values.data_type() {
849        DataType::Utf8 => array_has_any_string_inner(
850            col_values.as_string::<i32>(),
851            &col_offsets,
852            col_nulls,
853            has_null_scalar,
854            &scalar_lookup,
855        ),
856        DataType::LargeUtf8 => array_has_any_string_inner(
857            col_values.as_string::<i64>(),
858            &col_offsets,
859            col_nulls,
860            has_null_scalar,
861            &scalar_lookup,
862        ),
863        DataType::Utf8View => array_has_any_string_inner(
864            col_values.as_string_view(),
865            &col_offsets,
866            col_nulls,
867            has_null_scalar,
868            &scalar_lookup,
869        ),
870        _ => unreachable!("array_has_any_with_scalar_string called with non-string type"),
871    };
872
873    if is_scalar_output {
874        Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
875            &result, 0,
876        )?))
877    } else {
878        Ok(ColumnarValue::Array(result))
879    }
880}
881
882/// Pre-computed lookup structure for the scalar string fastpath.
883enum ScalarStringLookup<'a> {
884    /// Large scalar: HashSet for O(1) lookups.
885    Set(HashSet<&'a str>),
886    /// Small scalar: Vec for linear scan.
887    List(Vec<Option<&'a str>>),
888}
889
890impl<'a> ScalarStringLookup<'a> {
891    fn new(scalar_values: &'a ArrayRef) -> Self {
892        let strings = string_array_to_vec(scalar_values.as_ref());
893        if strings.len() > SCALAR_SMALL_THRESHOLD {
894            ScalarStringLookup::Set(strings.into_iter().flatten().collect())
895        } else {
896            ScalarStringLookup::List(strings)
897        }
898    }
899
900    fn contains(&self, value: &str) -> bool {
901        match self {
902            ScalarStringLookup::Set(set) => set.contains(value),
903            ScalarStringLookup::List(list) => list.contains(&Some(value)),
904        }
905    }
906}
907
908/// Inner implementation of the string scalar fast path, generic over string
909/// array type to allow direct element access by index.
910fn array_has_any_string_inner<'a, C: StringArrayType<'a> + Copy>(
911    col_strings: C,
912    col_offsets: &[usize],
913    col_nulls: Option<&NullBuffer>,
914    has_null_scalar: bool,
915    scalar_lookup: &ScalarStringLookup<'_>,
916) -> ArrayRef {
917    let num_rows = col_offsets.len() - 1;
918    let mut result = BooleanBufferBuilder::new(num_rows);
919
920    for i in 0..num_rows {
921        if col_nulls.is_some_and(|v| v.is_null(i)) {
922            result.append(false);
923            continue;
924        }
925        let start = col_offsets[i];
926        let end = col_offsets[i + 1];
927        let found = (start..end).any(|j| {
928            if col_strings.is_null(j) {
929                has_null_scalar
930            } else {
931                scalar_lookup.contains(col_strings.value(j))
932            }
933        });
934        result.append(found);
935    }
936
937    Arc::new(BooleanArray::new(result.finish(), col_nulls.cloned()))
938}
939
940/// General scalar fast path for `array_has_any`, using RowConverter for
941/// type-erased comparison.
942fn array_has_any_with_scalar_general(
943    columnar_arg: &ColumnarValue,
944    scalar_values: &ArrayRef,
945) -> Result<ColumnarValue> {
946    let converter =
947        RowConverter::new(vec![SortField::new(scalar_values.data_type().clone())])?;
948    let scalar_rows = converter.convert_columns(&[Arc::clone(scalar_values)])?;
949
950    let (col_arr, is_scalar_output) = match columnar_arg {
951        ColumnarValue::Array(arr) => (Arc::clone(arr), false),
952        ColumnarValue::Scalar(s) => (s.to_array_of_size(1)?, true),
953    };
954
955    let col_list: ArrayWrapper = col_arr.as_ref().try_into()?;
956    let col_offsets: Vec<usize> = col_list.offsets().collect();
957    let col_nulls = col_list.nulls();
958
959    // For efficiency with sliced arrays, only convert the visible elements,
960    // not the entire underlying buffer. Indices into `col_rows` are therefore
961    // relative to `elem_start`.
962    let elem_start = col_offsets[0];
963    let elem_end = col_offsets[col_list.len()];
964    let visible_values = col_list.values().slice(elem_start, elem_end - elem_start);
965    let col_rows = converter.convert_columns(&[visible_values])?;
966
967    let mut result = BooleanBufferBuilder::new(col_list.len());
968    let num_scalar = scalar_rows.num_rows();
969
970    if num_scalar > SCALAR_SMALL_THRESHOLD {
971        // Large scalar: build HashSet for O(1) lookups
972        let scalar_set: HashSet<Box<[u8]>> = (0..num_scalar)
973            .map(|i| Box::from(scalar_rows.row(i).as_ref()))
974            .collect();
975
976        for i in 0..col_list.len() {
977            if col_nulls.is_some_and(|v| v.is_null(i)) {
978                result.append(false);
979                continue;
980            }
981            let start = col_offsets[i] - elem_start;
982            let end = col_offsets[i + 1] - elem_start;
983            let found =
984                (start..end).any(|j| scalar_set.contains(col_rows.row(j).as_ref()));
985            result.append(found);
986        }
987    } else {
988        // Small scalar: linear scan avoids HashSet hashing overhead
989        for i in 0..col_list.len() {
990            if col_nulls.is_some_and(|v| v.is_null(i)) {
991                result.append(false);
992                continue;
993            }
994            let start = col_offsets[i] - elem_start;
995            let end = col_offsets[i + 1] - elem_start;
996            let found = (start..end)
997                .any(|j| (0..num_scalar).any(|k| col_rows.row(j) == scalar_rows.row(k)));
998            result.append(found);
999        }
1000    }
1001
1002    let output: ArrayRef =
1003        Arc::new(BooleanArray::new(result.finish(), col_nulls.cloned()));
1004
1005    if is_scalar_output {
1006        Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
1007            &output, 0,
1008        )?))
1009    } else {
1010        Ok(ColumnarValue::Array(output))
1011    }
1012}
1013
1014#[user_doc(
1015    doc_section(label = "Array Functions"),
1016    description = "Returns true if all elements of sub_array exist in array.",
1017    syntax_example = "array_has_all(array, sub_array)",
1018    sql_example = r#"```sql
1019> select array_has_all([1, 2, 3, 4], [2, 3]);
1020+---------------------------------------------+
1021| array_has_all(List([1,2,3,4]), List([2,3])) |
1022+---------------------------------------------+
1023| true                                        |
1024+---------------------------------------------+
1025```"#,
1026    argument(
1027        name = "array",
1028        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
1029    ),
1030    argument(
1031        name = "sub_array",
1032        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
1033    )
1034)]
1035#[derive(Debug, PartialEq, Eq, Hash)]
1036pub struct ArrayHasAll {
1037    signature: Signature,
1038    aliases: Vec<String>,
1039}
1040
1041impl Default for ArrayHasAll {
1042    fn default() -> Self {
1043        Self::new()
1044    }
1045}
1046
1047impl ArrayHasAll {
1048    pub fn new() -> Self {
1049        Self {
1050            signature: Signature::arrays(2, None, Volatility::Immutable),
1051            aliases: vec![String::from("list_has_all")],
1052        }
1053    }
1054}
1055
1056impl ScalarUDFImpl for ArrayHasAll {
1057    fn name(&self) -> &str {
1058        "array_has_all"
1059    }
1060
1061    fn signature(&self) -> &Signature {
1062        &self.signature
1063    }
1064
1065    fn return_type(&self, _: &[DataType]) -> Result<DataType> {
1066        Ok(DataType::Boolean)
1067    }
1068
1069    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
1070        make_scalar_function(array_has_all_inner)(&args.args)
1071    }
1072
1073    fn aliases(&self) -> &[String] {
1074        &self.aliases
1075    }
1076
1077    fn documentation(&self) -> Option<&Documentation> {
1078        self.doc()
1079    }
1080}
1081
1082#[user_doc(
1083    doc_section(label = "Array Functions"),
1084    description = "Returns true if the arrays have any elements in common.",
1085    syntax_example = "array_has_any(array1, array2)",
1086    sql_example = r#"```sql
1087> select array_has_any([1, 2, 3], [3, 4]);
1088+-------------------------------------------+
1089| array_has_any(List([1,2,3]), List([3,4])) |
1090+-------------------------------------------+
1091| true                                      |
1092+-------------------------------------------+
1093```"#,
1094    argument(
1095        name = "array1",
1096        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
1097    ),
1098    argument(
1099        name = "array2",
1100        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
1101    )
1102)]
1103#[derive(Debug, PartialEq, Eq, Hash)]
1104pub struct ArrayHasAny {
1105    signature: Signature,
1106    aliases: Vec<String>,
1107}
1108
1109impl Default for ArrayHasAny {
1110    fn default() -> Self {
1111        Self::new()
1112    }
1113}
1114
1115impl ArrayHasAny {
1116    pub fn new() -> Self {
1117        Self {
1118            signature: Signature::arrays(2, None, Volatility::Immutable),
1119            aliases: vec![String::from("list_has_any"), String::from("arrays_overlap")],
1120        }
1121    }
1122}
1123
1124impl ScalarUDFImpl for ArrayHasAny {
1125    fn name(&self) -> &str {
1126        "array_has_any"
1127    }
1128
1129    fn signature(&self) -> &Signature {
1130        &self.signature
1131    }
1132
1133    fn return_type(&self, _: &[DataType]) -> Result<DataType> {
1134        Ok(DataType::Boolean)
1135    }
1136
1137    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
1138        let [first_arg, second_arg] = take_function_args(self.name(), &args.args)?;
1139
1140        // If either argument is scalar, use the fast path.
1141        match (&first_arg, &second_arg) {
1142            (cv, ColumnarValue::Scalar(scalar)) | (ColumnarValue::Scalar(scalar), cv) => {
1143                array_has_any_with_scalar(cv, scalar)
1144            }
1145            _ => make_scalar_function(array_has_any_inner)(&args.args),
1146        }
1147    }
1148
1149    fn aliases(&self) -> &[String] {
1150        &self.aliases
1151    }
1152
1153    fn documentation(&self) -> Option<&Documentation> {
1154        self.doc()
1155    }
1156}
1157
1158/// Represents the type of comparison for array_has.
1159#[derive(Debug, PartialEq, Clone, Copy)]
1160enum ComparisonType {
1161    // array_has_all
1162    All,
1163    // array_has_any
1164    Any,
1165}
1166
1167fn array_has_string_kernel(
1168    haystack: &[Option<&str>],
1169    needle: &[Option<&str>],
1170    comparison_type: ComparisonType,
1171) -> bool {
1172    match comparison_type {
1173        ComparisonType::All => needle
1174            .iter()
1175            .dedup()
1176            .all(|x| haystack.iter().dedup().any(|y| y == x)),
1177        ComparisonType::Any => needle
1178            .iter()
1179            .dedup()
1180            .any(|x| haystack.iter().dedup().any(|y| y == x)),
1181    }
1182}
1183
1184fn general_array_has_all_and_any_kernel(
1185    haystack_rows: &Rows,
1186    h_range: Range<usize>,
1187    needle_rows: &Rows,
1188    mut n_range: Range<usize>,
1189    comparison_type: ComparisonType,
1190) -> bool {
1191    let h_start = h_range.start;
1192    let h_end = h_range.end;
1193
1194    match comparison_type {
1195        ComparisonType::All => n_range.all(|ni| {
1196            let needle_row = needle_rows.row(ni);
1197            (h_start..h_end).any(|hi| haystack_rows.row(hi) == needle_row)
1198        }),
1199        ComparisonType::Any => n_range.any(|ni| {
1200            let needle_row = needle_rows.row(ni);
1201            (h_start..h_end).any(|hi| haystack_rows.row(hi) == needle_row)
1202        }),
1203    }
1204}
1205
1206#[cfg(test)]
1207mod tests {
1208    use std::sync::Arc;
1209
1210    use arrow::datatypes::Int32Type;
1211    use arrow::{
1212        array::{
1213            Array, ArrayRef, AsArray, FixedSizeListArray, Int32Array, LargeListArray,
1214            ListArray, create_array,
1215        },
1216        buffer::OffsetBuffer,
1217        datatypes::{DataType, Field, Schema},
1218    };
1219    use datafusion_common::{
1220        DataFusionError, ScalarValue, ToDFSchema, config::ConfigOptions,
1221        utils::SingleRowListArrayBuilder,
1222    };
1223    use datafusion_expr::simplify::SimplifyContext;
1224    use datafusion_expr::{
1225        ColumnarValue, Expr, ScalarFunctionArgs, ScalarUDFImpl, col, lit,
1226        simplify::ExprSimplifyResult,
1227    };
1228
1229    use crate::expr_fn::make_array;
1230
1231    use super::{ArrayHas, ArrayHasAll, ArrayHasAny};
1232
1233    #[test]
1234    fn test_simplify_array_has_to_in_list() {
1235        let haystack = lit(SingleRowListArrayBuilder::new(create_array!(
1236            Int32,
1237            [1, 2, 3]
1238        ))
1239        .build_list_scalar());
1240        let needle = col("c");
1241
1242        let context = SimplifyContext::default();
1243
1244        let Ok(ExprSimplifyResult::Simplified(Expr::InList(in_list))) =
1245            ArrayHas::new().simplify(vec![haystack, needle.clone()], &context)
1246        else {
1247            panic!("Expected simplified expression");
1248        };
1249
1250        assert_eq!(
1251            in_list,
1252            datafusion_expr::expr::InList {
1253                expr: Box::new(needle),
1254                list: vec![lit(1), lit(2), lit(3)],
1255                negated: false,
1256            }
1257        );
1258    }
1259
1260    #[test]
1261    fn test_simplify_array_has_with_make_array_to_in_list() {
1262        let haystack = make_array(vec![lit(1), lit(2), lit(3)]);
1263        let needle = col("c");
1264
1265        let context = SimplifyContext::default();
1266
1267        let Ok(ExprSimplifyResult::Simplified(Expr::InList(in_list))) =
1268            ArrayHas::new().simplify(vec![haystack, needle.clone()], &context)
1269        else {
1270            panic!("Expected simplified expression");
1271        };
1272
1273        assert_eq!(
1274            in_list,
1275            datafusion_expr::expr::InList {
1276                expr: Box::new(needle),
1277                list: vec![lit(1), lit(2), lit(3)],
1278                negated: false,
1279            }
1280        );
1281    }
1282
1283    #[test]
1284    fn test_simplify_array_has_with_nullable_make_array_is_unchanged() {
1285        let haystack = make_array(vec![col("c"), lit(1)]);
1286        let needle = lit(2);
1287        let original = vec![haystack, needle];
1288        let context = SimplifyContext::builder()
1289            .with_schema(
1290                Schema::new(vec![Field::new("c", DataType::Int32, true)])
1291                    .to_dfschema_ref()
1292                    .unwrap(),
1293            )
1294            .build();
1295
1296        let result = ArrayHas::new()
1297            .simplify(original.clone(), &context)
1298            .unwrap();
1299
1300        let ExprSimplifyResult::Original(args) = result else {
1301            panic!("Expected ExprSimplifyResult::Original")
1302        };
1303        assert_eq!(args, original);
1304    }
1305
1306    #[test]
1307    fn test_simplify_array_has_with_same_nullable_element() {
1308        let needle = col("c");
1309        let haystack = make_array(vec![needle.clone()]);
1310        let context = SimplifyContext::builder()
1311            .with_schema(
1312                Schema::new(vec![Field::new("c", DataType::Int32, true)])
1313                    .to_dfschema_ref()
1314                    .unwrap(),
1315            )
1316            .build();
1317
1318        let result = ArrayHas::new()
1319            .simplify(vec![haystack, needle.clone()], &context)
1320            .unwrap();
1321
1322        let ExprSimplifyResult::Simplified(Expr::InList(in_list)) = result else {
1323            panic!("Expected simplified expression")
1324        };
1325        assert_eq!(
1326            in_list,
1327            datafusion_expr::expr::InList {
1328                expr: Box::new(needle.clone()),
1329                list: vec![needle],
1330                negated: false,
1331            }
1332        );
1333    }
1334
1335    #[test]
1336    fn test_simplify_array_has_with_null_list_item_is_unchanged() {
1337        let haystack = lit(SingleRowListArrayBuilder::new(create_array!(
1338            Int32,
1339            [Some(1), None]
1340        ))
1341        .build_list_scalar());
1342        let needle = lit(2);
1343        let original = vec![haystack, needle];
1344
1345        let result = ArrayHas::new()
1346            .simplify(original.clone(), &SimplifyContext::default())
1347            .unwrap();
1348
1349        let ExprSimplifyResult::Original(args) = result else {
1350            panic!("Expected ExprSimplifyResult::Original")
1351        };
1352        assert_eq!(args, original);
1353    }
1354
1355    #[test]
1356    fn test_simplify_array_has_with_null_to_null() {
1357        let haystack = Expr::Literal(ScalarValue::Null, None);
1358        let needle = col("c");
1359
1360        let context = SimplifyContext::default();
1361        let Ok(ExprSimplifyResult::Simplified(simplified)) =
1362            ArrayHas::new().simplify(vec![haystack, needle], &context)
1363        else {
1364            panic!("Expected simplified expression");
1365        };
1366
1367        assert_eq!(simplified, Expr::Literal(ScalarValue::Boolean(None), None));
1368    }
1369
1370    #[test]
1371    fn test_simplify_array_has_with_null_list_to_null() {
1372        let haystack =
1373            ListArray::from_iter_primitive::<Int32Type, [Option<i32>; 0], _>([None]);
1374        let haystack = Expr::Literal(ScalarValue::List(Arc::new(haystack)), None);
1375        let needle = col("c");
1376
1377        let context = SimplifyContext::default();
1378        let Ok(ExprSimplifyResult::Simplified(simplified)) =
1379            ArrayHas::new().simplify(vec![haystack, needle], &context)
1380        else {
1381            panic!("Expected simplified expression");
1382        };
1383
1384        assert_eq!(simplified, Expr::Literal(ScalarValue::Boolean(None), None));
1385    }
1386
1387    #[test]
1388    fn test_array_has_complex_list_not_simplified() {
1389        let haystack = col("c1");
1390        let needle = col("c2");
1391
1392        let context = SimplifyContext::default();
1393
1394        let Ok(ExprSimplifyResult::Original(args)) =
1395            ArrayHas::new().simplify(vec![haystack, needle.clone()], &context)
1396        else {
1397            panic!("Expected simplified expression");
1398        };
1399
1400        assert_eq!(args, vec![col("c1"), col("c2")],);
1401    }
1402
1403    #[test]
1404    fn test_array_has_list_empty_child() -> Result<(), DataFusionError> {
1405        let haystack_field = Arc::new(Field::new_list(
1406            "haystack",
1407            Field::new_list("", Field::new("", DataType::Int32, true), true),
1408            true,
1409        ));
1410
1411        let needle_field = Arc::new(Field::new("needle", DataType::Int32, true));
1412        let return_field = Arc::new(Field::new("return", DataType::Boolean, true));
1413        let haystack = ListArray::new(
1414            Field::new_list_field(DataType::Int32, true).into(),
1415            OffsetBuffer::new(vec![0, 0].into()),
1416            Arc::new(Int32Array::from(Vec::<i32>::new())) as ArrayRef,
1417            Some(vec![false].into()),
1418        );
1419
1420        let haystack = ColumnarValue::Array(Arc::new(haystack));
1421        let needle = ColumnarValue::Scalar(ScalarValue::Int32(Some(1)));
1422        let result = ArrayHas::new().invoke_with_args(ScalarFunctionArgs {
1423            args: vec![haystack, needle],
1424            arg_fields: vec![haystack_field, needle_field],
1425            number_rows: 1,
1426            return_field,
1427            config_options: Arc::new(ConfigOptions::default()),
1428        })?;
1429
1430        let output = result.into_array(1)?;
1431        let output = output.as_boolean();
1432        assert_eq!(output.len(), 1);
1433        assert!(output.is_null(0));
1434
1435        Ok(())
1436    }
1437
1438    #[test]
1439    fn test_array_has_sliced_list() -> Result<(), DataFusionError> {
1440        // [[10, 20], [30, 40], [50, 60], [70, 80]]  →  slice(1,2)  →  [[30, 40], [50, 60]]
1441        let list = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1442            Some(vec![Some(10), Some(20)]),
1443            Some(vec![Some(30), Some(40)]),
1444            Some(vec![Some(50), Some(60)]),
1445            Some(vec![Some(70), Some(80)]),
1446        ]);
1447        let sliced = list.slice(1, 2);
1448        let haystack_field =
1449            Arc::new(Field::new("haystack", sliced.data_type().clone(), true));
1450        let needle_field = Arc::new(Field::new("needle", DataType::Int32, true));
1451        let return_field = Arc::new(Field::new("return", DataType::Boolean, true));
1452
1453        // Search for elements that exist only in sliced-away rows:
1454        // 10 is in the prefix row, 70 is in the suffix row.
1455        let invoke = |needle: i32| -> Result<ArrayRef, DataFusionError> {
1456            ArrayHas::new()
1457                .invoke_with_args(ScalarFunctionArgs {
1458                    args: vec![
1459                        ColumnarValue::Array(Arc::new(sliced.clone())),
1460                        ColumnarValue::Scalar(ScalarValue::Int32(Some(needle))),
1461                    ],
1462                    arg_fields: vec![
1463                        Arc::clone(&haystack_field),
1464                        Arc::clone(&needle_field),
1465                    ],
1466                    number_rows: 2,
1467                    return_field: Arc::clone(&return_field),
1468                    config_options: Arc::new(ConfigOptions::default()),
1469                })?
1470                .into_array(2)
1471        };
1472
1473        let output = invoke(10)?.as_boolean().clone();
1474        assert!(!output.value(0));
1475        assert!(!output.value(1));
1476
1477        let output = invoke(70)?.as_boolean().clone();
1478        assert!(!output.value(0));
1479        assert!(!output.value(1));
1480
1481        Ok(())
1482    }
1483
1484    #[test]
1485    fn test_array_has_list_null_haystack() -> Result<(), DataFusionError> {
1486        let haystack_field = Arc::new(Field::new("haystack", DataType::Null, true));
1487        let needle_field = Arc::new(Field::new("needle", DataType::Int32, true));
1488        let return_field = Arc::new(Field::new("return", DataType::Boolean, true));
1489        let haystack =
1490            ListArray::from_iter_primitive::<Int32Type, [Option<i32>; 0], _>([
1491                None, None, None,
1492            ]);
1493
1494        let haystack = ColumnarValue::Array(Arc::new(haystack));
1495        let needle = ColumnarValue::Scalar(ScalarValue::Int32(Some(1)));
1496        let result = ArrayHas::new().invoke_with_args(ScalarFunctionArgs {
1497            args: vec![haystack, needle],
1498            arg_fields: vec![haystack_field, needle_field],
1499            number_rows: 1,
1500            return_field,
1501            config_options: Arc::new(ConfigOptions::default()),
1502        })?;
1503
1504        let output = result.into_array(1)?;
1505        let output = output.as_boolean();
1506        assert_eq!(output.len(), 3);
1507        for i in 0..3 {
1508            assert!(output.is_null(i));
1509        }
1510
1511        Ok(())
1512    }
1513
1514    /// Invoke a two-argument list UDF with the given arrays and assert the
1515    /// boolean output matches `expected`.
1516    fn invoke_and_assert(
1517        udf: &dyn ScalarUDFImpl,
1518        haystack: &ArrayRef,
1519        needle: ArrayRef,
1520        expected: &[Option<bool>],
1521    ) {
1522        let num_rows = haystack.len();
1523        let list_type = haystack.data_type();
1524        let result = udf
1525            .invoke_with_args(ScalarFunctionArgs {
1526                args: vec![
1527                    ColumnarValue::Array(Arc::clone(haystack)),
1528                    ColumnarValue::Array(needle),
1529                ],
1530                arg_fields: vec![
1531                    Arc::new(Field::new("haystack", list_type.clone(), false)),
1532                    Arc::new(Field::new("needle", list_type.clone(), false)),
1533                ],
1534                number_rows: num_rows,
1535                return_field: Arc::new(Field::new("return", DataType::Boolean, true)),
1536                config_options: Arc::new(ConfigOptions::default()),
1537            })
1538            .unwrap();
1539        let output = result.into_array(num_rows).unwrap();
1540        assert_eq!(output.as_boolean().iter().collect::<Vec<_>>(), expected);
1541    }
1542
1543    #[test]
1544    fn test_sliced_list_offsets() {
1545        // Full rows:
1546        //   row 0: [1, 2]   (not visible after slicing)
1547        //   row 1: [11, 12] (visible row 0)
1548        //   row 2: [21, 22] (visible row 1)
1549        //   row 3: [31, 32] (not visible after slicing)
1550        let field: Arc<Field> = Arc::new(Field::new("item", DataType::Int32, false));
1551        let full_values = Arc::new(Int32Array::from(vec![1, 2, 11, 12, 21, 22, 31, 32]));
1552        let full_offsets = OffsetBuffer::new(vec![0, 2, 4, 6, 8].into());
1553        let full = ListArray::new(Arc::clone(&field), full_offsets, full_values, None);
1554        let sliced_haystack: ArrayRef = Arc::new(full.slice(1, 2));
1555
1556        // array_has_all: needle row 0 = [11], row 1 = [21]
1557        let needle_all: ArrayRef = Arc::new(ListArray::new(
1558            Arc::clone(&field),
1559            OffsetBuffer::new(vec![0, 1, 2].into()),
1560            Arc::new(Int32Array::from(vec![11, 21])),
1561            None,
1562        ));
1563        invoke_and_assert(
1564            &ArrayHasAll::new(),
1565            &sliced_haystack,
1566            needle_all,
1567            &[Some(true), Some(true)],
1568        );
1569
1570        // array_has_any: needle row 0 = [99, 11], row 1 = [99, 21]
1571        let needle_any: ArrayRef = Arc::new(ListArray::new(
1572            field,
1573            OffsetBuffer::new(vec![0, 2, 4].into()),
1574            Arc::new(Int32Array::from(vec![99, 11, 99, 21])),
1575            None,
1576        ));
1577        invoke_and_assert(
1578            &ArrayHasAny::new(),
1579            &sliced_haystack,
1580            needle_any,
1581            &[Some(true), Some(true)],
1582        );
1583    }
1584
1585    #[test]
1586    fn test_sliced_fixed_size_list_offsets() {
1587        // Same logical data as test_sliced_list_offsets, but using FixedSizeListArray.
1588        let field = Arc::new(Field::new("item", DataType::Int32, false));
1589        let full_values = Arc::new(Int32Array::from(vec![1, 2, 11, 12, 21, 22, 31, 32]));
1590        let full = FixedSizeListArray::new(Arc::clone(&field), 2, full_values, None);
1591        let sliced_haystack: ArrayRef = Arc::new(full.slice(1, 2));
1592
1593        // array_has_all: needle row 0 = [11, 12], row 1 = [21, 22]
1594        let needle_all: ArrayRef = Arc::new(FixedSizeListArray::new(
1595            Arc::clone(&field),
1596            2,
1597            Arc::new(Int32Array::from(vec![11, 12, 21, 22])),
1598            None,
1599        ));
1600        invoke_and_assert(
1601            &ArrayHasAll::new(),
1602            &sliced_haystack,
1603            needle_all,
1604            &[Some(true), Some(true)],
1605        );
1606
1607        // array_has_any: needle row 0 = [99, 12], row 1 = [99, 22]
1608        let needle_any: ArrayRef = Arc::new(FixedSizeListArray::new(
1609            field,
1610            2,
1611            Arc::new(Int32Array::from(vec![99, 12, 99, 22])),
1612            None,
1613        ));
1614        invoke_and_assert(
1615            &ArrayHasAny::new(),
1616            &sliced_haystack,
1617            needle_any,
1618            &[Some(true), Some(true)],
1619        );
1620    }
1621
1622    /// Invoke `array_has` with the needle as an array (a column with one value
1623    /// per row). This exercises `array_has_dispatch_for_array` and its fast path.
1624    fn invoke_array_has_array(haystack: ArrayRef, needle: ArrayRef) -> ArrayRef {
1625        let num_rows = haystack.len();
1626        let haystack_type = haystack.data_type().clone();
1627        let needle_type = needle.data_type().clone();
1628        ArrayHas::new()
1629            .invoke_with_args(ScalarFunctionArgs {
1630                args: vec![ColumnarValue::Array(haystack), ColumnarValue::Array(needle)],
1631                arg_fields: vec![
1632                    Arc::new(Field::new("haystack", haystack_type, false)),
1633                    Arc::new(Field::new("needle", needle_type, false)),
1634                ],
1635                number_rows: num_rows,
1636                return_field: Arc::new(Field::new("return", DataType::Boolean, true)),
1637                config_options: Arc::new(ConfigOptions::default()),
1638            })
1639            .unwrap()
1640            .into_array(num_rows)
1641            .unwrap()
1642    }
1643
1644    #[test]
1645    fn test_array_has_array_needle_sliced() {
1646        // Offset normalization for sliced haystacks must keep the element ranges
1647        // and the needle column aligned, for both `List` (offsets from the
1648        // buffer) and `FixedSizeList` (offsets computed as `i * value_length`).
1649        // Slicing is an execution artifact SQL/SLT can't force, so this stays a
1650        // unit test; value-level behavior is covered by `array/array_has.slt`.
1651        let full = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1652            Some(vec![Some(1), Some(2)]),
1653            Some(vec![Some(10), Some(20), Some(30)]), // needle 20 -> true
1654            Some(vec![Some(40)]),                     // needle 41 -> false
1655            Some(vec![Some(50), Some(60)]),           // needle 60 -> true
1656            Some(vec![Some(70)]),
1657        ]);
1658        let sliced_haystack: ArrayRef = Arc::new(full.slice(1, 3));
1659        let sliced_needle: ArrayRef =
1660            Arc::new(Int32Array::from(vec![999, 20, 41, 60, 999]).slice(1, 3));
1661        let result = invoke_array_has_array(sliced_haystack, sliced_needle);
1662        assert_eq!(
1663            result.as_boolean().iter().collect::<Vec<_>>(),
1664            vec![Some(true), Some(false), Some(true)]
1665        );
1666
1667        // Sliced FixedSizeList (width 2; rows 1..=2 of
1668        // [[1,2],[11,12],[21,22],[31,32]] visible) with an aligned needle column.
1669        let field = Arc::new(Field::new("item", DataType::Int32, true));
1670        let fsl_values = Arc::new(Int32Array::from(vec![1, 2, 11, 12, 21, 22, 31, 32]));
1671        let fsl: ArrayRef =
1672            Arc::new(FixedSizeListArray::new(field, 2, fsl_values, None).slice(1, 2));
1673        let needle: ArrayRef = Arc::new(Int32Array::from(vec![11, 99]));
1674        let result = invoke_array_has_array(fsl, needle);
1675        assert_eq!(
1676            result.as_boolean().iter().collect::<Vec<_>>(),
1677            vec![Some(true), Some(false)]
1678        );
1679    }
1680
1681    /// Invoke `array_has_any` with an array haystack and a scalar list of
1682    /// `Int32` elements.
1683    fn invoke_array_has_any_scalar(haystack: ArrayRef, scalar: Vec<i32>) -> ArrayRef {
1684        let num_rows = haystack.len();
1685        let haystack_type = haystack.data_type().clone();
1686        let scalar = SingleRowListArrayBuilder::new(Arc::new(Int32Array::from(scalar)))
1687            .build_list_scalar();
1688        let scalar_type = scalar.data_type();
1689        ArrayHasAny::new()
1690            .invoke_with_args(ScalarFunctionArgs {
1691                args: vec![
1692                    ColumnarValue::Array(haystack),
1693                    ColumnarValue::Scalar(scalar),
1694                ],
1695                arg_fields: vec![
1696                    Arc::new(Field::new("haystack", haystack_type, true)),
1697                    Arc::new(Field::new("scalar", scalar_type, true)),
1698                ],
1699                number_rows: num_rows,
1700                return_field: Arc::new(Field::new("return", DataType::Boolean, true)),
1701                config_options: Arc::new(ConfigOptions::default()),
1702            })
1703            .unwrap()
1704            .into_array(num_rows)
1705            .unwrap()
1706    }
1707
1708    #[test]
1709    fn test_array_has_any_scalar_sliced() {
1710        // The scalar path only row-converts the visible elements of a sliced
1711        // haystack, so its per-row element ranges must be relative to the
1712        // start of the visible range. 1 and 70 appear only in sliced-away rows.
1713        let full = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1714            Some(vec![Some(1), Some(2)]),
1715            Some(vec![Some(10), None, Some(30)]),
1716            None,
1717            Some(vec![]),
1718            Some(vec![Some(50), Some(60)]),
1719            Some(vec![Some(70)]),
1720        ]);
1721        let sliced: ArrayRef = Arc::new(full.slice(1, 4));
1722
1723        // At most `SCALAR_SMALL_THRESHOLD` scalar elements: linear scan.
1724        let result = invoke_array_has_any_scalar(Arc::clone(&sliced), vec![1, 70, 60]);
1725        assert_eq!(
1726            result.as_boolean().iter().collect::<Vec<_>>(),
1727            vec![Some(false), None, Some(false), Some(true)]
1728        );
1729        let result = invoke_array_has_any_scalar(Arc::clone(&sliced), vec![30]);
1730        assert_eq!(
1731            result.as_boolean().iter().collect::<Vec<_>>(),
1732            vec![Some(true), None, Some(false), Some(false)]
1733        );
1734
1735        // More than `SCALAR_SMALL_THRESHOLD` scalar elements: HashSet lookup.
1736        let large_scalar = vec![1, 70, 60, 101, 102, 103, 104, 105, 106, 107];
1737        let result = invoke_array_has_any_scalar(sliced, large_scalar);
1738        assert_eq!(
1739            result.as_boolean().iter().collect::<Vec<_>>(),
1740            vec![Some(false), None, Some(false), Some(true)]
1741        );
1742
1743        // Sliced FixedSizeList (width 2; rows 1..=2 of
1744        // [[1,2],[11,12],[21,22],[31,32]] visible).
1745        let field = Arc::new(Field::new("item", DataType::Int32, true));
1746        let fsl_values = Arc::new(Int32Array::from(vec![1, 2, 11, 12, 21, 22, 31, 32]));
1747        let fsl: ArrayRef =
1748            Arc::new(FixedSizeListArray::new(field, 2, fsl_values, None).slice(1, 2));
1749        let result = invoke_array_has_any_scalar(fsl, vec![1, 22, 31]);
1750        assert_eq!(
1751            result.as_boolean().iter().collect::<Vec<_>>(),
1752            vec![Some(false), Some(true)]
1753        );
1754
1755        // Sliced LargeList; 1 and 70 appear only in sliced-away rows.
1756        let large = LargeListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1757            Some(vec![Some(1), Some(2)]),
1758            Some(vec![Some(10), None, Some(30)]),
1759            Some(vec![Some(50), Some(60)]),
1760            Some(vec![Some(70)]),
1761        ]);
1762        let large: ArrayRef = Arc::new(large.slice(1, 2));
1763        let result = invoke_array_has_any_scalar(large, vec![1, 70, 60]);
1764        assert_eq!(
1765            result.as_boolean().iter().collect::<Vec<_>>(),
1766            vec![Some(false), Some(true)]
1767        );
1768    }
1769}