datafusion-functions-nested 54.0.0

Nested Type Function packages for the DataFusion query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//! [`datafusion_expr::HigherOrderUDF`] definitions for array_any_match function.

use arrow::{
    array::{Array, AsArray, BooleanArray, BooleanBuilder, new_null_array},
    buffer::NullBuffer,
    compute::take_arrays,
    datatypes::{ArrowNativeType, DataType, Field, FieldRef},
};
use datafusion_common::{
    Result, exec_datafusion_err, exec_err, plan_err,
    utils::{
        adjust_offsets_for_slice, list_values, list_values_row_number, take_function_args,
    },
};
use datafusion_expr::{
    ColumnarValue, Documentation, HigherOrderFunctionArgs, HigherOrderReturnFieldArgs,
    HigherOrderSignature, HigherOrderUDFImpl, LambdaParametersProgress, ValueOrLambda,
    Volatility,
};
use datafusion_macros::user_doc;
use std::{fmt::Debug, sync::Arc};

make_higher_order_function_expr_and_func!(
    ArrayAnyMatch,
    array_any_match,
    array lambda,
    "returns true if any element in the array satisfies the predicate",
    array_any_match_higher_order_function
);

#[user_doc(
    doc_section(label = "Array Functions"),
    description = "Returns whether any elements of an array match the given predicate. Returns true if one or more elements match, false if none match (including empty arrays), and null if the predicate returns null for some elements and false for all others.",
    syntax_example = "any_match(array, predicate)",
    sql_example = r#"```sql
> select any_match([1, 2, 3], x -> x > 2);
+----------------------------------+
| any_match([1, 2, 3], x -> x > 2) |
+----------------------------------+
| true                             |
+----------------------------------+
```"#,
    argument(
        name = "array",
        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
    ),
    argument(
        name = "predicate",
        description = "Lambda predicate that returns a boolean"
    )
)]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct ArrayAnyMatch {
    signature: HigherOrderSignature,
    aliases: Vec<String>,
}

impl Default for ArrayAnyMatch {
    fn default() -> Self {
        Self::new()
    }
}

impl ArrayAnyMatch {
    pub fn new() -> Self {
        Self {
            signature: HigherOrderSignature::exact(
                vec![ValueOrLambda::Value(()), ValueOrLambda::Lambda(())],
                Volatility::Immutable,
            ),
            aliases: vec![String::from("any_match"), String::from("list_any_match")],
        }
    }
}

// Returns Some(true) if any element in [start, end) is true,
// None if no element is true but some are null,
// Some(false) if all are false or range is empty.
fn any_match_for_range(
    predicate: &BooleanArray,
    start: usize,
    end: usize,
) -> Option<bool> {
    let any_true = (start..end).any(|j| predicate.is_valid(j) && predicate.value(j));
    if any_true {
        return Some(true);
    }
    let any_null = (start..end).any(|j| predicate.is_null(j));
    if any_null { None } else { Some(false) }
}

impl HigherOrderUDFImpl for ArrayAnyMatch {
    fn name(&self) -> &str {
        "array_any_match"
    }

    fn aliases(&self) -> &[String] {
        &self.aliases
    }

    fn signature(&self) -> &HigherOrderSignature {
        &self.signature
    }

    fn coerce_value_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
        let [list] = arg_types else {
            return plan_err!(
                "{} function requires 1 value argument, got {}",
                self.name(),
                arg_types.len()
            );
        };

        let coerced = match list {
            DataType::List(_) | DataType::LargeList(_) => list.clone(),
            DataType::ListView(field) | DataType::FixedSizeList(field, _) => {
                DataType::List(Arc::clone(field))
            }
            DataType::LargeListView(field) => DataType::LargeList(Arc::clone(field)),
            _ => {
                return plan_err!(
                    "{} expected a list as first argument, got {}",
                    self.name(),
                    list
                );
            }
        };

        Ok(vec![coerced])
    }

    fn lambda_parameters(
        &self,
        _step: usize,
        fields: &[ValueOrLambda<FieldRef, Option<FieldRef>>],
    ) -> Result<LambdaParametersProgress> {
        let [list, _] = take_function_args(self.name(), fields)?;
        let ValueOrLambda::Value(list) = list else {
            return plan_err!("{} expects a value as first argument", self.name());
        };

        let field = match list.data_type() {
            DataType::List(field) => field,
            DataType::LargeList(field) => field,
            other => return plan_err!("expected list, got {other}"),
        };

        Ok(LambdaParametersProgress::Complete(vec![vec![Arc::clone(
            field,
        )]]))
    }

    fn return_field_from_args(
        &self,
        args: HigherOrderReturnFieldArgs,
    ) -> Result<Arc<Field>> {
        let [ValueOrLambda::Value(list), _] =
            take_function_args(self.name(), args.arg_fields)?
        else {
            return plan_err!("{} expects a value as first argument", self.name());
        };
        let nullable = list.is_nullable();
        Ok(Arc::new(Field::new("", DataType::Boolean, nullable)))
    }

    fn invoke_with_args(&self, args: HigherOrderFunctionArgs) -> Result<ColumnarValue> {
        let [ValueOrLambda::Value(list), ValueOrLambda::Lambda(lambda)] =
            take_function_args(self.name(), &args.args)?
        else {
            return exec_err!("{} expects a value followed by a lambda", self.name());
        };

        let list_array = list.to_array(args.number_rows)?;

        // fast path: fully null input — also required for FixedSizeList which can't be
        // handled by clear_null_values when fully null
        if list_array.null_count() == list_array.len() {
            return Ok(ColumnarValue::Array(new_null_array(
                args.return_type(),
                list_array.len(),
            )));
        }

        let list_values = list_values(&list_array)?;

        let values_param = || Ok(Arc::clone(&list_values));

        let predicate_results = lambda
            .evaluate(&[&values_param], |arrays| {
                let indices = list_values_row_number(&list_array)?;
                Ok(take_arrays(arrays, &indices, None)?)
            })?
            .into_array(list_values.len())?;

        let predicate_bool = predicate_results
            .as_any()
            .downcast_ref::<BooleanArray>()
            .ok_or_else(|| {
                exec_datafusion_err!(
                    "{} predicate must return boolean array",
                    self.name()
                )
            })?;

        let mut values = BooleanBuilder::with_capacity(list_array.len());

        // Maps predicate results (flat over all elements) back to one Boolean per row.
        // Uses adjusted offsets so sliced lists index correctly into the predicate array.
        macro_rules! process_list {
            ($list_typed:expr) => {{
                let offsets = adjust_offsets_for_slice($list_typed);
                for i in 0..$list_typed.len() {
                    let start = offsets[i].as_usize();
                    let end = offsets[i + 1].as_usize();
                    // any_match_for_range returns None when nulls poison the result;
                    // null rows produce an empty range and return Some(false), but their
                    // null bit is preserved by attaching the original null bitmap below.
                    values.append_option(any_match_for_range(predicate_bool, start, end));
                }
            }};
        }

        match list_array.data_type() {
            DataType::List(_) => {
                process_list!(list_array.as_list::<i32>());
            }
            DataType::LargeList(_) => {
                process_list!(list_array.as_list::<i64>());
            }
            other => return exec_err!("expected list, got {other}"),
        }

        let (boolean_buffer, predicate_nulls) = values.finish().into_parts();
        // Merge: a row is null if the input list row was null or the predicate returned null.
        let nulls = NullBuffer::union(list_array.nulls(), predicate_nulls.as_ref());
        Ok(ColumnarValue::Array(Arc::new(BooleanArray::new(
            boolean_buffer,
            nulls,
        ))))
    }

    fn documentation(&self) -> Option<&Documentation> {
        self.doc()
    }
}

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, sync::Arc};

    use arrow::{
        array::{ArrayRef, BooleanArray, Int32Array, ListArray, RecordBatch},
        buffer::{NullBuffer, OffsetBuffer},
        datatypes::{DataType, Field},
    };
    use datafusion_common::{DFSchema, Result};
    use datafusion_expr::{
        Expr, col,
        execution_props::ExecutionProps,
        expr::{HigherOrderFunction, LambdaVariable},
        lambda, lit,
    };
    use datafusion_physical_expr::create_physical_expr;

    use crate::array_any_match::array_any_match_higher_order_function;

    fn run_any_match(
        list: impl arrow::array::Array + Clone + 'static,
    ) -> Result<ArrayRef> {
        let schema = DFSchema::from_unqualified_fields(
            vec![Field::new(
                "list",
                list.data_type().clone(),
                list.is_nullable(),
            )]
            .into(),
            HashMap::new(),
        )?;

        create_physical_expr(
            &Expr::HigherOrderFunction(HigherOrderFunction::new(
                array_any_match_higher_order_function(),
                vec![
                    col("list"),
                    lambda(
                        ["x"],
                        Expr::LambdaVariable(LambdaVariable::new(
                            "x".to_string(),
                            Some(Arc::new(Field::new("x", DataType::Int32, true))),
                        ))
                        .gt(lit(2i32)),
                    ),
                ],
            )),
            &schema,
            &ExecutionProps::new(),
        )?
        .evaluate(&RecordBatch::try_new(
            Arc::clone(schema.inner()),
            vec![Arc::new(list.clone())],
        )?)?
        .into_array(list.len())
    }

    fn run_any_match_div(
        list: impl arrow::array::Array + Clone + 'static,
    ) -> Result<ArrayRef> {
        let schema = DFSchema::from_unqualified_fields(
            vec![Field::new(
                "list",
                list.data_type().clone(),
                list.is_nullable(),
            )]
            .into(),
            HashMap::new(),
        )?;

        let x = Expr::LambdaVariable(LambdaVariable::new(
            "x".to_string(),
            Some(Arc::new(Field::new("x", DataType::Int32, true))),
        ));
        // predicate: (100 / x) > 5 — panics on divide by zero if x == 0 is evaluated
        create_physical_expr(
            &Expr::HigherOrderFunction(HigherOrderFunction::new(
                array_any_match_higher_order_function(),
                vec![col("list"), lambda(["x"], (lit(100i32) / x).gt(lit(5i32)))],
            )),
            &schema,
            &ExecutionProps::new(),
        )?
        .evaluate(&RecordBatch::try_new(
            Arc::clone(schema.inner()),
            vec![Arc::new(list.clone())],
        )?)?
        .into_array(list.len())
    }

    fn make_list(values: Vec<i32>, offsets: OffsetBuffer<i32>) -> ListArray {
        make_list_with_nulls(values, offsets, None)
    }

    fn make_list_with_nulls(
        values: Vec<i32>,
        offsets: OffsetBuffer<i32>,
        nulls: Option<NullBuffer>,
    ) -> ListArray {
        ListArray::new(
            Arc::new(Field::new_list_field(DataType::Int32, true)),
            offsets,
            Arc::new(Int32Array::from(values)),
            nulls,
        )
    }

    #[test]
    fn test_any_match_some_true() -> Result<()> {
        let list = make_list(vec![1, 2, 3], OffsetBuffer::from_lengths(vec![3]));
        let result = run_any_match(list)?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![Some(true)])
        );
        Ok(())
    }

    #[test]
    fn test_any_match_none_true() -> Result<()> {
        let list = make_list(vec![1, 2], OffsetBuffer::from_lengths(vec![2]));
        let result = run_any_match(list)?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![Some(false)])
        );
        Ok(())
    }

    #[test]
    fn test_any_match_empty_array() -> Result<()> {
        let list = make_list(vec![], OffsetBuffer::from_lengths(vec![0]));
        let result = run_any_match(list)?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![Some(false)])
        );
        Ok(())
    }

    #[test]
    fn test_any_match_multiple_rows() -> Result<()> {
        let list = make_list(vec![1, 2, 3, 1, 2], OffsetBuffer::from_lengths(vec![3, 2]));
        let result = run_any_match(list)?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![Some(true), Some(false)])
        );
        Ok(())
    }

    // Predicate must not be evaluated on elements belonging to null rows.
    // The 10 in the null row would satisfy x > 5, but the row result must be None.
    #[test]
    fn test_any_match_should_not_evaluate_predicate_on_values_underlying_null()
    -> Result<()> {
        let list = make_list_with_nulls(
            vec![1, 2, 10, 1, 2],
            OffsetBuffer::from_lengths(vec![3, 2]),
            Some(NullBuffer::from(vec![false, true])),
        );
        let result = run_any_match(list)?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![None, Some(false)])
        );
        Ok(())
    }

    // Predicate must not be evaluated on elements before the slice offset.
    // The 10 before the slice would satisfy x > 5, but it is unreachable.
    #[test]
    fn test_any_match_on_sliced_list_should_not_evaluate_on_unreachable_values()
    -> Result<()> {
        let list = make_list(
            vec![10, 1, 2, 1, 2],
            OffsetBuffer::from_lengths(vec![1, 2, 2]),
        )
        .slice(1, 2);
        let result = run_any_match(list)?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![Some(false), Some(false)])
        );
        Ok(())
    }

    // 0 in the null row would cause divide by zero if the predicate is evaluated on it.
    #[test]
    fn test_any_match_does_not_evaluate_predicate_on_null_row_values() -> Result<()> {
        let list = make_list_with_nulls(
            vec![1, 2, 0, 4, 5],
            OffsetBuffer::from_lengths(vec![3, 2]),
            Some(NullBuffer::from(vec![false, true])),
        );
        let result = run_any_match_div(list)?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![None, Some(true)])
        );
        Ok(())
    }

    // 0 before the slice offset would cause divide by zero if evaluated.
    #[test]
    fn test_any_match_does_not_evaluate_predicate_on_unreachable_values() -> Result<()> {
        let list = make_list(
            vec![0, 4, 5, 50, 100],
            OffsetBuffer::from_lengths(vec![1, 2, 2]),
        )
        .slice(1, 2);
        let result = run_any_match_div(list)?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![Some(true), Some(false)])
        );
        Ok(())
    }
}