Skip to main content

vortex_functions/list_contains/prepared/
function.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Formatter;
5
6use prost::Message;
7use vortex_array::ArrayRef;
8use vortex_array::ExecutionCtx;
9use vortex_array::IntoArray;
10use vortex_array::arrays::ConstantArray;
11use vortex_array::arrays::ScalarFn;
12use vortex_array::arrays::ScalarFnArray;
13use vortex_array::dtype::DType;
14use vortex_array::proto::scalar as pb;
15use vortex_array::scalar::Scalar;
16use vortex_array::scalar_fn::Arity;
17use vortex_array::scalar_fn::ChildName;
18use vortex_array::scalar_fn::ExecutionArgs;
19use vortex_array::scalar_fn::ReduceNode;
20use vortex_array::scalar_fn::ReduceNodeValidity;
21use vortex_array::scalar_fn::ScalarFnId;
22use vortex_array::scalar_fn::ScalarFnVTable;
23use vortex_array::scalar_fn::ScalarFnVTableExt;
24use vortex_array::scalar_fn::display::ExprDisplay;
25use vortex_error::VortexExpect;
26use vortex_error::VortexResult;
27use vortex_session::VortexSession;
28use vortex_session::registry::CachedId;
29
30use super::PreparedSetData;
31
32/// A constant, non-null list whose elements are prepared as a set for membership lookups.
33///
34/// [`ListContains`] puts this in place of a literal list when an expression is optimized, so that
35/// every batch the expression is applied to looks up its needles in one shared
36/// [`PreparedSetData`]: the list is materialized, sorted and hashed once per expression rather
37/// than once per batch. In an array tree, the constant list of a [`ListContains`] node becomes
38/// this function with no children.
39///
40/// Every row of such an array holds the list. A slice or a filter of it keeps the options, so it
41/// looks up in the same set. A [`ListContainsElementReduce`] rule of the needle encoding can push
42/// the function into the needle's parts with slices of the array, so that the chunks of a chunked
43/// needle or the values of a dictionary all look up in one set, and a
44/// [`ListContainsElementKernel`] of the needle encoding gets the set through
45/// [`PreparedSet::set_of`].
46///
47/// It serializes as the list, and deserializes into a set prepared again.
48///
49/// [`ListContains`]: crate::list_contains::ListContains
50/// [`ListContainsElementKernel`]: crate::list_contains::ListContainsElementKernel
51/// [`ListContainsElementReduce`]: crate::list_contains::ListContainsElementReduce
52#[derive(Clone, Debug)]
53pub struct PreparedSet;
54
55impl PreparedSet {
56    /// Prepares the non-null list scalar `list` as a set repeated `len` times.
57    ///
58    /// [`ListContains`] prepares a constant list itself. A kernel crate can use this to test its
59    /// [`ListContainsElementKernel`] against a prepared set.
60    ///
61    /// [`ListContains`]: crate::list_contains::ListContains
62    /// [`ListContainsElementKernel`]: crate::list_contains::ListContainsElementKernel
63    ///
64    /// # Errors
65    ///
66    /// Fails when `list` is not a list, or is null.
67    pub fn try_new_array(list: Scalar, len: usize) -> VortexResult<ArrayRef> {
68        Ok(Self::new_array(PreparedSetData::try_new(list)?, len))
69    }
70
71    /// An array of `len` rows that share the prepared set `set`.
72    pub(crate) fn new_array(set: PreparedSetData, len: usize) -> ArrayRef {
73        ScalarFnArray::try_new_with_len(Self.bind(set), [], len)
74            .vortex_expect("A prepared set has no children, and its dtype is the list dtype")
75            .into_array()
76    }
77
78    /// The prepared set that every row of `array` holds, when `array` is a [`PreparedSet`].
79    pub fn set_of(array: &ArrayRef) -> Option<&PreparedSetData> {
80        array
81            .as_opt::<ScalarFn>()?
82            .data()
83            .scalar_fn()
84            .as_opt::<Self>()
85    }
86}
87
88impl ScalarFnVTable for PreparedSet {
89    type Options = PreparedSetData;
90
91    fn id(&self) -> ScalarFnId {
92        static ID: CachedId = CachedId::new("vortex.list.prepared_set");
93        *ID
94    }
95
96    fn serialize(&self, set: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
97        Ok(Some(set.list().to_proto()?.encode_to_vec()))
98    }
99
100    fn deserialize(&self, metadata: &[u8], session: &VortexSession) -> VortexResult<Self::Options> {
101        let list = Scalar::from_proto(&pb::Scalar::decode(metadata)?, session)?;
102        PreparedSetData::try_new(list)
103    }
104
105    fn arity(&self, _options: &Self::Options) -> Arity {
106        Arity::Exact(0)
107    }
108
109    fn child_name(&self, _options: &Self::Options, _child_idx: usize) -> ChildName {
110        unreachable!()
111    }
112
113    fn fmt_sql(
114        &self,
115        set: &Self::Options,
116        _expr: &dyn ExprDisplay,
117        f: &mut Formatter<'_>,
118    ) -> std::fmt::Result {
119        write!(f, "{}", set.list())
120    }
121
122    fn return_dtype(&self, set: &Self::Options, _arg_dtypes: &[DType]) -> VortexResult<DType> {
123        Ok(set.list().dtype().clone())
124    }
125
126    fn execute(
127        &self,
128        set: &Self::Options,
129        args: &dyn ExecutionArgs,
130        _ctx: &mut ExecutionCtx,
131    ) -> VortexResult<ArrayRef> {
132        // The rows hold the list only. The haystack is of no use to the canonical form.
133        Ok(ConstantArray::new(set.list().clone(), args.row_count()).into_array())
134    }
135
136    fn validity<T: ReduceNode>(
137        &self,
138        _set: &Self::Options,
139        node: &T,
140    ) -> VortexResult<ReduceNodeValidity<T>> {
141        // The list is never null.
142        Ok(ReduceNodeValidity::Reduced(node.new_constant(true.into())))
143    }
144
145    fn is_strict(&self, _options: &Self::Options) -> bool {
146        true
147    }
148
149    fn is_infallible(&self, _options: &Self::Options) -> bool {
150        true
151    }
152}