Skip to main content

vortex_functions/list_transform/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4#[cfg(test)]
5mod tests;
6
7use std::fmt;
8use std::fmt::Display;
9use std::fmt::Formatter;
10use std::sync::Arc;
11
12use itertools::Itertools;
13use vortex_array::ArrayRef;
14use vortex_array::ExecutionCtx;
15use vortex_array::IntoArray;
16use vortex_array::arrays::List;
17use vortex_array::arrays::ListArray;
18use vortex_array::arrays::ListViewArray;
19use vortex_array::arrays::list::ListArrayExt;
20use vortex_array::arrays::list::ListArraySlotsExt;
21use vortex_array::arrays::listview::ListViewArrayExt;
22use vortex_array::arrays::listview::ListViewArraySlotsExt;
23use vortex_array::arrays::listview::ListViewRebuildMode;
24use vortex_array::dtype::DType;
25use vortex_array::dtype::FieldName;
26use vortex_array::scalar_fn::Arity;
27use vortex_array::scalar_fn::ChildName;
28use vortex_array::scalar_fn::ExecutionArgs;
29use vortex_array::scalar_fn::ScalarFnId;
30use vortex_array::scalar_fn::ScalarFnVTable;
31use vortex_array::scalar_fn::display::ExprDisplay;
32use vortex_error::VortexResult;
33use vortex_error::vortex_bail;
34use vortex_error::vortex_ensure;
35use vortex_error::vortex_ensure_eq;
36use vortex_expr::BoundLambda;
37use vortex_expr::Lambda;
38use vortex_session::registry::CachedId;
39
40/// Apply a lambda to every element of each list, keeping each list's length and validity.
41///
42/// The lambda takes one parameter, the element. The only child is the list, of `List` dtype in any
43/// encoding, and the result is a `List` of the same shape. A lambda that can fail runs only on the
44/// elements of valid lists.
45#[derive(Clone)]
46pub struct ListTransform;
47
48/// The lambda of a [`ListTransform`], as written or bound to the element's dtype.
49#[derive(Clone, Debug, PartialEq, Eq, Hash)]
50pub enum ListTransformOptions {
51    /// The lambda as written, in an [`Expression`](vortex_expr::Expression).
52    Lambda(Lambda),
53    /// The lambda bound to the element's dtype, in a
54    /// [`BoundExpression`](vortex_array::expr::BoundExpression) or an array.
55    Bound(BoundLambda),
56}
57
58impl Display for ListTransformOptions {
59    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
60        match self {
61            Self::Lambda(lambda) => lambda.fmt(f),
62            Self::Bound(lambda) => lambda.fmt(f),
63        }
64    }
65}
66
67impl ScalarFnVTable for ListTransform {
68    type Options = ListTransformOptions;
69
70    fn id(&self) -> ScalarFnId {
71        static ID: CachedId = CachedId::new("vortex.list.transform");
72        *ID
73    }
74
75    fn arity(&self, _options: &ListTransformOptions) -> Arity {
76        Arity::Exact(1)
77    }
78
79    fn child_name(&self, _options: &ListTransformOptions, child_idx: usize) -> ChildName {
80        match child_idx {
81            0 => ChildName::from("list"),
82            _ => unreachable!("Invalid child index {child_idx} for list_transform()"),
83        }
84    }
85
86    fn fmt_sql(
87        &self,
88        options: &ListTransformOptions,
89        expr: &dyn ExprDisplay,
90        f: &mut Formatter<'_>,
91    ) -> fmt::Result {
92        write!(f, "{}({}, {options})", self.id(), expr.display_child(0))
93    }
94
95    fn return_dtype(&self, options: &ListTransformOptions, args: &[DType]) -> VortexResult<DType> {
96        let element = match options {
97            ListTransformOptions::Lambda(lambda) => {
98                lambda.return_dtype(&element_dtype(&args[0], lambda.params())?)?
99            }
100            ListTransformOptions::Bound(lambda) => {
101                check_bound_to(lambda, &args[0])?;
102                lambda.dtype().clone()
103            }
104        };
105        Ok(DType::List(Arc::new(element), args[0].nullability()))
106    }
107
108    fn bind_options(
109        &self,
110        options: &ListTransformOptions,
111        args: &[DType],
112    ) -> VortexResult<Option<ListTransformOptions>> {
113        match options {
114            ListTransformOptions::Lambda(lambda) => {
115                let element = element_dtype(&args[0], lambda.params())?;
116                Ok(Some(ListTransformOptions::Bound(lambda.bind(&element)?)))
117            }
118            ListTransformOptions::Bound(lambda) => {
119                check_bound_to(lambda, &args[0])?;
120                Ok(None)
121            }
122        }
123    }
124
125    fn execute(
126        &self,
127        options: &ListTransformOptions,
128        args: &dyn ExecutionArgs,
129        ctx: &mut ExecutionCtx,
130    ) -> VortexResult<ArrayRef> {
131        let ListTransformOptions::Bound(lambda) = options else {
132            vortex_bail!("list_transform()'s lambda is not bound");
133        };
134        match args.get(0)?.try_downcast::<List>() {
135            Ok(list) => transform_list(list, lambda, ctx),
136            Err(list) => transform_list_view(list.execute::<ListViewArray>(ctx)?, lambda, ctx),
137        }
138    }
139
140    fn is_strict(&self, _options: &ListTransformOptions) -> bool {
141        true
142    }
143
144    fn is_infallible(&self, options: &ListTransformOptions) -> bool {
145        match options {
146            ListTransformOptions::Lambda(lambda) => lambda.is_infallible(),
147            ListTransformOptions::Bound(lambda) => lambda.is_infallible(),
148        }
149    }
150}
151
152/// Check that a bound lambda's parameter has the element dtype of a list of this dtype.
153fn check_bound_to(lambda: &BoundLambda, list: &DType) -> VortexResult<()> {
154    let element = element_dtype(list, lambda.params().names().as_ref())?;
155    vortex_ensure!(
156        lambda.is_bound_to(&element),
157        "list_transform()'s lambda {lambda} is bound to element dtype {}, not {}",
158        lambda.params().fields().format(", "),
159        element[0]
160    );
161    Ok(())
162}
163
164/// The dtype of the lambda's one parameter, the element, for a list of this dtype.
165fn element_dtype(list: &DType, params: &[FieldName]) -> VortexResult<[DType; 1]> {
166    let DType::List(element, _) = list else {
167        vortex_bail!("list_transform() takes a List, got {list}");
168    };
169    vortex_ensure!(
170        params.len() == 1,
171        "list_transform() takes a lambda of one parameter, the element, not ({})",
172        params.iter().format(", ")
173    );
174    Ok([element.as_ref().clone()])
175}
176
177/// The lambda over a list's elements, inside the list's offsets and validity.
178///
179/// A lambda that can fail runs only on the elements valid lists reference. One that can't runs on
180/// every element from the first list to the last: results under null lists are never read.
181fn transform_list(
182    list: ListArray,
183    lambda: &BoundLambda,
184    ctx: &mut ExecutionCtx,
185) -> VortexResult<ArrayRef> {
186    let list = if lambda.is_infallible() {
187        trim_ends(list, ctx)?
188    } else {
189        list.compact(ctx)?
190    };
191    let values = lambda.evaluate(vec![list.elements().clone()], list.elements().len())?;
192    vortex_ensure_eq!(values.len(), list.elements().len());
193    // SAFETY: the offsets and validity are the list's, over one value per element.
194    Ok(
195        unsafe { ListArray::new_unchecked(values, list.offsets().clone(), list.list_validity()) }
196            .into_array(),
197    )
198}
199
200/// The lambda over a list view's elements, inside the view's offsets, sizes and validity.
201///
202/// A lambda that can fail runs only on the elements valid lists reference.
203fn transform_list_view(
204    view: ListViewArray,
205    lambda: &BoundLambda,
206    ctx: &mut ExecutionCtx,
207) -> VortexResult<ArrayRef> {
208    let view = if lambda.is_infallible() {
209        view
210    } else {
211        view.rebuild(ListViewRebuildMode::MakeExactWithEmptyNulls, ctx)?
212    };
213    let values = lambda.evaluate(vec![view.elements().clone()], view.elements().len())?;
214    vortex_ensure_eq!(values.len(), view.elements().len());
215    // SAFETY: the offsets, sizes and validity are the view's, over one value per element, so the
216    // views keep their bounds and their layout.
217    Ok(unsafe {
218        ListViewArray::new_unchecked(
219            values,
220            view.offsets().clone(),
221            view.sizes().clone(),
222            view.listview_validity(),
223        )
224        .with_zero_copy_to_list(view.is_zero_copy_to_list())
225    }
226    .into_array())
227}
228
229/// The list without what comes before its first list and after its last.
230fn trim_ends(list: ListArray, ctx: &mut ExecutionCtx) -> VortexResult<ListArray> {
231    if list.offset_at(0, ctx)? == 0 && list.offset_at(list.len(), ctx)? == list.elements().len() {
232        return Ok(list);
233    }
234    list.reset_offsets(false, ctx)
235}