datafusion-functions-nested 56.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

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

use arrow::{
    array::{Array, BooleanArray, BooleanBuilder},
    buffer::NullBuffer,
    datatypes::{DataType, Field, FieldRef},
};
use datafusion_common::{Result, plan_err, utils::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};

use crate::lambda_utils::{
    SingleListLambdaResult, coerce_single_list_arg, evaluate_single_list_predicate,
};

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>> {
        coerce_single_list_arg(self.name(), arg_types)
    }

    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), ValueOrLambda::Lambda(lambda)] =
            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() || lambda.is_nullable();
        Ok(Arc::new(Field::new("", DataType::Boolean, nullable)))
    }

    fn invoke_with_args(&self, args: HigherOrderFunctionArgs) -> Result<ColumnarValue> {
        let evaluated = match evaluate_single_list_predicate(self.name(), &args)? {
            SingleListLambdaResult::EarlyReturn(v) => return Ok(v),
            SingleListLambdaResult::Ready(v) => v,
        };

        let predicate = evaluated.boolean_predicate(self.name())?;
        let row_offsets = evaluated.row_offsets()?;

        let mut values = BooleanBuilder::with_capacity(evaluated.len());
        for window in row_offsets.windows(2) {
            let (start, end) = (window[0], window[1]);
            // 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, start, end));
        }

        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(evaluated.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, DictionaryArray, Int32Array, ListArray, RecordBatch,
            StringViewArray,
        },
        buffer::{NullBuffer, OffsetBuffer},
        datatypes::{DataType, Field, UInt32Type},
    };
    use datafusion_common::{DFSchema, Result, ScalarValue};
    use datafusion_expr::{
        Expr, HigherOrderReturnFieldArgs, HigherOrderUDFImpl, ValueOrLambda, col,
        execution_props::ExecutionProps,
        expr::{HigherOrderFunction, LambdaVariable},
        lambda, lit,
        physical_planning_context::PhysicalPlanningContext,
    };
    use datafusion_physical_expr::create_physical_expr;

    use crate::array_any_match::{ArrayAnyMatch, array_any_match_higher_order_function};
    use crate::lambda_utils::test_utils::{
        create_i32_large_list, create_i32_list, eval_hof_on_i32_list,
        eval_hof_on_i32_list_with_outer, v,
    };

    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(),
            &PhysicalPlanningContext::default(),
        )?
        .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(),
            &PhysicalPlanningContext::default(),
        )?
        .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(())
    }

    #[test]
    fn test_any_match_return_field_nullability() -> Result<()> {
        for list_nullable in [true, false] {
            for lambda_nullable in [true, false] {
                let list = Arc::new(Field::new(
                    "list",
                    DataType::new_list(DataType::Int32, true),
                    list_nullable,
                ));
                let lambda =
                    Arc::new(Field::new("predicate", DataType::Boolean, lambda_nullable));
                let arg_fields = [
                    ValueOrLambda::Value(Arc::clone(&list)),
                    ValueOrLambda::Lambda(Arc::clone(&lambda)),
                ];
                let scalar_arguments = [None, None];

                let result = ArrayAnyMatch::new().return_field_from_args(
                    HigherOrderReturnFieldArgs {
                        arg_fields: &arg_fields,
                        scalar_arguments: &scalar_arguments,
                    },
                )?;

                assert_eq!(
                    result,
                    Arc::new(Field::new(
                        "",
                        DataType::Boolean,
                        list_nullable || lambda_nullable,
                    ))
                );
            }
        }

        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(())
    }

    #[test]
    fn test_any_match_large_list_parity() -> Result<()> {
        let list = create_i32_large_list(
            vec![1, 2, 3],
            OffsetBuffer::<i64>::from_lengths(vec![3]),
            None,
        );
        let result = eval_hof_on_i32_list(
            array_any_match_higher_order_function(),
            list,
            v().gt(lit(2i32)),
        )?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![Some(true)])
        );
        Ok(())
    }

    #[test]
    fn test_any_match_captured_outer_column() -> Result<()> {
        let list = create_i32_list(
            vec![1, 50, 4, 50, 7, 50],
            OffsetBuffer::<i32>::from_lengths(vec![2, 2, 2]),
            None,
        );
        let number = Int32Array::from(vec![10, 40, 60]);
        let result = eval_hof_on_i32_list_with_outer(
            array_any_match_higher_order_function(),
            list,
            number,
            v().gt(col("number")),
        )?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![Some(true), Some(true), Some(false)])
        );
        Ok(())
    }

    /// Evaluates `any_match(list, x -> x = needle)` over two rows, `[a, b]` and
    /// `[c, a]`, built from `values`, with the lambda variable declared as the element
    /// type. `needle` carries its own type, as these expressions are planned directly
    /// and so are never type coerced.
    fn run_any_match_eq(values: ArrayRef, needle: Expr) -> Result<ArrayRef> {
        let element_type = values.data_type().clone();
        let element_field = Arc::new(Field::new_list_field(element_type.clone(), true));
        let list = ListArray::new(
            Arc::clone(&element_field),
            OffsetBuffer::<i32>::from_lengths(vec![2, 2]),
            values,
            None,
        );

        let schema = DFSchema::from_unqualified_fields(
            vec![Field::new("list", DataType::List(element_field), true)].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", element_type, true))),
                        ))
                        .eq(needle),
                    ),
                ],
            )),
            &schema,
            &ExecutionProps::new(),
            &PhysicalPlanningContext::default(),
        )?
        .evaluate(&RecordBatch::try_new(
            Arc::clone(schema.inner()),
            vec![Arc::new(list)],
        )?)?
        .into_array(2)
    }

    #[test]
    fn test_any_match_on_dictionary_encoded_elements() -> Result<()> {
        let values: ArrayRef = Arc::new(DictionaryArray::<UInt32Type>::from_iter([
            "a", "b", "c", "a",
        ]));
        let result = run_any_match_eq(values, lit("c"))?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![Some(false), Some(true)])
        );
        Ok(())
    }

    #[test]
    fn test_any_match_on_string_view_elements() -> Result<()> {
        let values: ArrayRef = Arc::new(StringViewArray::from(vec!["a", "b", "c", "a"]));
        let needle = lit(ScalarValue::Utf8View(Some("c".to_string())));
        let result = run_any_match_eq(values, needle)?;
        assert_eq!(
            result.as_any().downcast_ref::<BooleanArray>().unwrap(),
            &BooleanArray::from(vec![Some(false), Some(true)])
        );
        Ok(())
    }
}