Skip to main content

datafusion_functions_nested/
array_add.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//! [`ScalarUDFImpl`] definitions for array_add function.
6
7use crate::utils::{
8    array_math_binary_op, coerce_array_math_arg_types, make_scalar_function,
9};
10use arrow::array::ArrayRef;
11use arrow::datatypes::{
12    DataType,
13    DataType::{LargeList, List},
14};
15use datafusion_common::{Result, exec_err, utils::take_function_args};
16use datafusion_expr::{
17    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
18    Volatility,
19};
20use datafusion_macros::user_doc;
21
22make_udf_expr_and_func!(
23    ArrayAdd,
24    array_add,
25    array1 array2,
26    "returns the element-wise sum of two numeric arrays.",
27    array_add_udf
28);
29
30#[user_doc(
31    doc_section(label = "Array Functions"),
32    description = "Returns the element-wise sum of two numeric arrays of equal length, computed as `array1[i] + array2[i]` per position. NULL is propagated per element: if either input element at position `i` is NULL, the corresponding output element is NULL (positions are preserved). Returns NULL if either entire input array is NULL. Errors if the per-row lengths differ. Returns an empty array if both inputs are empty.",
33    syntax_example = "array_add(array1, array2)",
34    sql_example = r#"```sql
35> select array_add([1.0, 2.0, 3.0], [10.0, 20.0, 30.0]);
36+---------------------------------------------------------+
37| array_add(List([1.0,2.0,3.0]),List([10.0,20.0,30.0]))   |
38+---------------------------------------------------------+
39| [11.0, 22.0, 33.0]                                      |
40+---------------------------------------------------------+
41```"#,
42    argument(
43        name = "array1",
44        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
45    ),
46    argument(
47        name = "array2",
48        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
49    )
50)]
51#[derive(Debug, PartialEq, Eq, Hash)]
52pub struct ArrayAdd {
53    signature: Signature,
54    aliases: Vec<String>,
55}
56
57impl Default for ArrayAdd {
58    fn default() -> Self {
59        Self::new()
60    }
61}
62
63impl ArrayAdd {
64    pub fn new() -> Self {
65        Self {
66            signature: Signature::user_defined(Volatility::Immutable),
67            aliases: vec!["list_add".to_string()],
68        }
69    }
70}
71
72impl ScalarUDFImpl for ArrayAdd {
73    fn name(&self) -> &str {
74        "array_add"
75    }
76
77    fn signature(&self) -> &Signature {
78        &self.signature
79    }
80
81    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
82        // After `coerce_types`, both args share the same List/LargeList<Float64> shape.
83        Ok(arg_types[0].clone())
84    }
85
86    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
87        let [_, _] = take_function_args(self.name(), arg_types)?;
88        coerce_array_math_arg_types(self.name(), arg_types)
89    }
90
91    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
92        make_scalar_function(array_add_inner)(&args.args)
93    }
94
95    fn aliases(&self) -> &[String] {
96        &self.aliases
97    }
98
99    fn documentation(&self) -> Option<&Documentation> {
100        self.doc()
101    }
102}
103
104fn array_add_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
105    let [array1, array2] = take_function_args("array_add", args)?;
106    let add = |a: f64, b: f64| a + b;
107    match (array1.data_type(), array2.data_type()) {
108        (List(_), List(_)) => {
109            array_math_binary_op::<i32, _>("array_add", array1, array2, add)
110        }
111        (LargeList(_), LargeList(_)) => {
112            array_math_binary_op::<i64, _>("array_add", array1, array2, add)
113        }
114        (arg_type1, arg_type2) => exec_err!(
115            "array_add received unexpected types after coercion: {arg_type1} and {arg_type2}"
116        ),
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use std::sync::Arc;
124
125    #[test]
126    fn test_sliced_capacity() -> Result<()> {
127        crate::utils::tests::check_sliced_list_behavior(|input| {
128            array_add_inner(&[Arc::clone(input), Arc::clone(input)])
129        })
130    }
131}