Skip to main content

vortex_functions/list_contains/
dict.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_array::ArrayRef;
5use vortex_array::ArrayView;
6use vortex_array::IntoArray;
7use vortex_array::arrays::ConstantArray;
8use vortex_array::arrays::Dict;
9use vortex_array::arrays::DictArray;
10use vortex_array::arrays::dict::DictArrayExt;
11use vortex_array::arrays::dict::DictArraySlotsExt;
12use vortex_array::builtins::ArrayBuiltins;
13use vortex_array::dtype::DType;
14use vortex_array::scalar::Scalar;
15use vortex_error::VortexResult;
16
17use crate::list_contains::ListContains;
18use crate::list_contains::ListContainsElementReduce;
19use crate::list_contains::ListContainsOptions;
20use crate::list_contains::PreparedSet;
21
22/// Pushes `list_contains` of a prepared set into the values of a dictionary of needles.
23impl ListContainsElementReduce for Dict {
24    fn list_contains(
25        list: &ArrayRef,
26        needles: ArrayView<'_, Dict>,
27        options: &ListContainsOptions,
28    ) -> VortexResult<Option<ArrayRef>> {
29        let Some(set) = PreparedSet::set_of(list) else {
30            return Ok(None);
31        };
32        let dtype = DType::Bool(options.result_nullability(list.dtype(), needles.dtype()));
33
34        // Off SQL null semantics an empty list answers `false` for every needle, a null one
35        // included, which the dictionary would answer `null` for from a null code.
36        if set.is_empty() && !options.sql_null_semantics {
37            return Ok(Some(
38                ConstantArray::new(Scalar::bool(false, dtype.nullability()), needles.len())
39                    .into_array(),
40            ));
41        }
42
43        // A sliced dictionary can have more values than code rows. Do not increase the work in
44        // that case.
45        let values = needles.values();
46        let codes = needles.codes();
47        if values.len() > codes.len() {
48            return Ok(None);
49        }
50
51        // A null code answers `null`, as a null needle does against a list with elements.
52        // The optimizer reduces this lazy node when it visits the returned dictionary.
53        let values =
54            ListContains::try_new_opts(list.slice(0..values.len())?, values.clone(), *options)?
55                .into_array();
56
57        // SAFETY: the codes are unchanged, and the values have one result for each value.
58        let dict = unsafe {
59            DictArray::new_unchecked(codes.clone(), values)
60                .set_all_values_referenced(needles.has_all_values_referenced())
61        }
62        .into_array();
63
64        if dict.dtype() == &dtype {
65            Ok(Some(dict))
66        } else {
67            dict.cast(dtype).map(Some)
68        }
69    }
70}