Skip to main content

datafusion_functions_nested/
array_transform.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//! [`datafusion_expr::HigherOrderUDF`] definitions for array_transform function.
6
7use arrow::{
8    array::{Array, ArrayRef, AsArray, LargeListArray, ListArray},
9    compute::take_arrays,
10    datatypes::{DataType, Field, FieldRef},
11};
12use datafusion_common::{
13    Result, exec_err, plan_err,
14    utils::{adjust_offsets_for_slice, list_values_row_number, take_function_args},
15};
16use datafusion_expr::{
17    ColumnarValue, Documentation, HigherOrderFunctionArgs, HigherOrderReturnFieldArgs,
18    HigherOrderSignature, HigherOrderUDFImpl, LambdaParametersProgress, ValueOrLambda,
19    Volatility,
20};
21use datafusion_macros::user_doc;
22use std::sync::Arc;
23
24use crate::lambda_utils::{
25    ListValuesResult, coerce_single_list_arg, extract_list_values,
26    single_list_lambda_parameters,
27};
28
29make_higher_order_function_expr_and_func!(
30    ArrayTransform,
31    array_transform,
32    array lambda,
33    "transforms the values of an array",
34    array_transform_higher_order_function
35);
36
37#[user_doc(
38    doc_section(label = "Array Functions"),
39    description = "transforms the values of an array",
40    syntax_example = "array_transform(array, lambda)",
41    sql_example = r#"```sql
42> select array_transform([1, 2, 3, 4, 5], x -> x*2);
43+--------------------------------------------+
44| array_transform([1, 2, 3, 4, 5], x -> x*2) |
45+--------------------------------------------+
46| [2, 4, 6, 8, 10]                           |
47+--------------------------------------------+
48```"#,
49    argument(
50        name = "array",
51        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
52    ),
53    argument(
54        name = "lambda",
55        description = "The lambda function used to transform each value of the array."
56    )
57)]
58#[derive(Debug, PartialEq, Eq, Hash)]
59pub struct ArrayTransform {
60    signature: HigherOrderSignature,
61    aliases: Vec<String>,
62}
63
64impl Default for ArrayTransform {
65    fn default() -> Self {
66        Self::new()
67    }
68}
69
70impl ArrayTransform {
71    pub fn new() -> Self {
72        Self {
73            signature: HigherOrderSignature::exact(
74                vec![ValueOrLambda::Value(()), ValueOrLambda::Lambda(())],
75                Volatility::Immutable,
76            ),
77            aliases: vec![String::from("list_transform")],
78        }
79    }
80}
81
82impl HigherOrderUDFImpl for ArrayTransform {
83    fn name(&self) -> &str {
84        "array_transform"
85    }
86
87    fn aliases(&self) -> &[String] {
88        &self.aliases
89    }
90
91    fn signature(&self) -> &HigherOrderSignature {
92        &self.signature
93    }
94
95    fn coerce_value_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
96        coerce_single_list_arg(self.name(), arg_types)
97    }
98
99    fn lambda_parameters(
100        &self,
101        _step: usize,
102        fields: &[ValueOrLambda<FieldRef, Option<FieldRef>>],
103    ) -> Result<LambdaParametersProgress> {
104        single_list_lambda_parameters(self.name(), fields)
105    }
106
107    fn return_field_from_args(
108        &self,
109        args: HigherOrderReturnFieldArgs,
110    ) -> Result<Arc<Field>> {
111        let [ValueOrLambda::Value(list), ValueOrLambda::Lambda(lambda)] =
112            take_function_args(self.name(), args.arg_fields)?
113        else {
114            return plan_err!("{} expects a value followed by a lambda", self.name());
115        };
116
117        //TODO: should metadata be copied into the transformed array?
118
119        // lambda is the resulting field of executing the lambda body
120        // with the parameters returned in lambda_parameters
121        let field = Arc::new(Field::new(
122            Field::LIST_FIELD_DEFAULT_NAME,
123            lambda.data_type().clone(),
124            lambda.is_nullable(),
125        ));
126
127        let return_type = match list.data_type() {
128            DataType::List(_) => DataType::List(field),
129            DataType::LargeList(_) => DataType::LargeList(field),
130            other => plan_err!("expected list, got {other}")?,
131        };
132
133        Ok(Arc::new(Field::new("", return_type, list.is_nullable())))
134    }
135
136    fn invoke_with_args(&self, args: HigherOrderFunctionArgs) -> Result<ColumnarValue> {
137        let [list, lambda] = take_function_args(self.name(), &args.args)?;
138        let (ValueOrLambda::Value(list), ValueOrLambda::Lambda(lambda)) = (list, lambda)
139        else {
140            return plan_err!("{} expects a value followed by a lambda", self.name());
141        };
142
143        let list_array = list.to_array(args.number_rows)?;
144
145        let list_values = match extract_list_values(&list_array, args.return_type())? {
146            ListValuesResult::EarlyReturn(v) => return Ok(v),
147            ListValuesResult::Values(v) => v,
148        };
149
150        // by passing closures, lambda.evaluate can evaluate only those actually needed
151        let values_param = || Ok(Arc::clone(&list_values));
152
153        // call the transforming lambda
154        let transformed_values = lambda
155            .evaluate(&[&values_param], |arrays| {
156                // if any column got captured, we need to adjust it to the values arrays,
157                // duplicating values of list with multitple values and removing values of empty lists
158                let indices = list_values_row_number(&list_array)?;
159                Ok(take_arrays(arrays, &indices, None)?)
160            })?
161            .into_array(list_values.len())?;
162
163        let field = match args.return_field.data_type() {
164            DataType::List(field) | DataType::LargeList(field) => Arc::clone(field),
165            _ => {
166                return exec_err!(
167                    "{} expected ScalarFunctionArgs.return_field to be a list, got {}",
168                    self.name(),
169                    args.return_field
170                );
171            }
172        };
173
174        let transformed_list = match list_array.data_type() {
175            DataType::List(_) => {
176                let list = list_array.as_list();
177
178                // since we called list_values above which would return sliced values for
179                // a sliced list, we must adjust the offsets here as otherwise they would be invalid
180                let adjusted_offsets = adjust_offsets_for_slice(list);
181
182                Arc::new(ListArray::new(
183                    field,
184                    adjusted_offsets,
185                    transformed_values,
186                    list.nulls().cloned(),
187                )) as ArrayRef
188            }
189            DataType::LargeList(_) => {
190                let large_list = list_array.as_list();
191
192                // since we called list_values above which would return sliced values for
193                // a sliced list, we must adjust the offsets here as otherwise they would be invalid
194                let adjusted_offsets = adjust_offsets_for_slice(large_list);
195
196                Arc::new(LargeListArray::new(
197                    field,
198                    adjusted_offsets,
199                    transformed_values,
200                    large_list.nulls().cloned(),
201                ))
202            }
203            other => exec_err!("expected list, got {other}")?,
204        };
205
206        Ok(ColumnarValue::Array(transformed_list))
207    }
208
209    fn documentation(&self) -> Option<&Documentation> {
210        self.doc()
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use arrow::{
217        array::{Array, AsArray},
218        buffer::{NullBuffer, OffsetBuffer},
219    };
220
221    use crate::array_transform::array_transform_higher_order_function;
222    use crate::lambda_utils::test_utils::{create_i32_list, eval_hof_on_i32_list, v};
223    use datafusion_expr::lit;
224
225    fn divide_100_by(
226        list: impl Array + Clone + 'static,
227    ) -> datafusion_common::Result<arrow::array::ArrayRef> {
228        eval_hof_on_i32_list(
229            array_transform_higher_order_function(),
230            list,
231            lit(100i32) / v(),
232        )
233    }
234
235    #[test]
236    fn transform_on_sliced_list_should_not_evaluate_on_unreachable_values() {
237        let list = create_i32_list(
238            vec![
239                // Have 0 here so if the expression is called on data that it will fail
240                0, 4, 100, 25, 20, 5, 2, 1, 10,
241            ],
242            OffsetBuffer::<i32>::from_lengths(vec![1, 3, 4, 1]),
243            None,
244        )
245        .slice(1, 3);
246
247        let res = divide_100_by(list).unwrap();
248
249        let actual_list = res.as_list::<i32>();
250
251        let expected_list = create_i32_list(
252            vec![25, 1, 4, 5, 20, 50, 100, 10],
253            OffsetBuffer::<i32>::from_lengths(vec![3, 4, 1]),
254            None,
255        );
256
257        assert_eq!(actual_list, &expected_list);
258    }
259
260    #[test]
261    fn transform_function_should_not_be_evaluated_on_values_underlying_null() {
262        let list = create_i32_list(
263            // 0 here for one of the values behind null, so if it will be evaluated
264            // it will fail due to divide by 0
265            vec![100, 20, 10, 0, 1, 2, 0, 1, 50],
266            OffsetBuffer::<i32>::from_lengths(vec![3, 4, 2]),
267            Some(NullBuffer::from(vec![true, false, true])),
268        );
269
270        let res = divide_100_by(list).unwrap();
271
272        let actual_list = res.as_list::<i32>();
273
274        let expected_list = create_i32_list(
275            vec![1, 5, 10, 100, 2],
276            OffsetBuffer::<i32>::from_lengths(vec![3, 0, 2]),
277            Some(NullBuffer::from(vec![true, false, true])),
278        );
279
280        assert_eq!(actual_list.data_type(), expected_list.data_type());
281        assert_eq!(actual_list, &expected_list);
282    }
283}