Skip to main content

datafusion_functions_nested/
array_sum.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_sum function.
6
7use crate::utils::make_scalar_function;
8use arrow::array::{Array, ArrayRef, Float64Array, OffsetSizeTrait};
9use arrow::datatypes::{
10    DataType,
11    DataType::{FixedSizeList, LargeList, List, Null},
12    Field,
13};
14use datafusion_common::cast::{as_float64_array, as_generic_list_array};
15use datafusion_common::utils::{ListCoercion, coerced_type_with_base_type_only};
16use datafusion_common::{Result, internal_err, plan_err, utils::take_function_args};
17use datafusion_expr::{
18    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
19    Volatility,
20};
21use datafusion_macros::user_doc;
22use std::sync::Arc;
23
24make_udf_expr_and_func!(
25    ArraySum,
26    array_sum,
27    array,
28    "returns the sum of elements in a numeric array.",
29    array_sum_udf
30);
31
32#[user_doc(
33    doc_section(label = "Array Functions"),
34    description = "Returns the sum of the elements of the input array, computed as `array[0] + array[1] + ...`. NULL elements are skipped (per SQL aggregate convention). Returns NULL if the input row is NULL, every element is NULL, or the array is empty.",
35    syntax_example = "array_sum(array)",
36    sql_example = r#"```sql
37> select array_sum([1.0, 2.0, 3.0]);
38+--------------------------------+
39| array_sum(List([1.0,2.0,3.0])) |
40+--------------------------------+
41| 6.0                            |
42+--------------------------------+
43```"#,
44    argument(
45        name = "array",
46        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
47    )
48)]
49#[derive(Debug, PartialEq, Eq, Hash)]
50pub struct ArraySum {
51    signature: Signature,
52    aliases: Vec<String>,
53}
54
55impl Default for ArraySum {
56    fn default() -> Self {
57        Self::new()
58    }
59}
60
61impl ArraySum {
62    pub fn new() -> Self {
63        Self {
64            signature: Signature::user_defined(Volatility::Immutable),
65            aliases: vec!["list_sum".to_string()],
66        }
67    }
68}
69
70impl ScalarUDFImpl for ArraySum {
71    fn name(&self) -> &str {
72        "array_sum"
73    }
74
75    fn signature(&self) -> &Signature {
76        &self.signature
77    }
78
79    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
80        Ok(DataType::Float64)
81    }
82
83    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
84        let [arg_type] = take_function_args(self.name(), arg_types)?;
85        let coercion = Some(&ListCoercion::FixedSizedListToList);
86
87        if !matches!(arg_type, Null | List(_) | LargeList(_) | FixedSizeList(..)) {
88            return plan_err!("{} does not support type {arg_type}", self.name());
89        }
90
91        let coerced = if matches!(arg_type, Null) {
92            List(Arc::new(Field::new_list_field(DataType::Float64, true)))
93        } else {
94            coerced_type_with_base_type_only(arg_type, &DataType::Float64, coercion)
95        };
96
97        Ok(vec![coerced])
98    }
99
100    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
101        make_scalar_function(array_sum_inner)(&args.args)
102    }
103
104    fn aliases(&self) -> &[String] {
105        &self.aliases
106    }
107
108    fn documentation(&self) -> Option<&Documentation> {
109        self.doc()
110    }
111}
112
113fn array_sum_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
114    let [array] = take_function_args("array_sum", args)?;
115    match array.data_type() {
116        List(_) => general_array_sum::<i32>(array),
117        LargeList(_) => general_array_sum::<i64>(array),
118        arg_type => {
119            internal_err!("array_sum received unexpected type after coercion: {arg_type}")
120        }
121    }
122}
123
124fn general_array_sum<O: OffsetSizeTrait>(array: &ArrayRef) -> Result<ArrayRef> {
125    let list_array = as_generic_list_array::<O>(array)?;
126    let values = as_float64_array(list_array.values())?;
127    let offsets = list_array.value_offsets();
128
129    let mut builder = Float64Array::builder(list_array.len());
130
131    for row in 0..list_array.len() {
132        if list_array.is_null(row) {
133            builder.append_null();
134            continue;
135        }
136
137        let start = offsets[row].as_usize();
138        let end = offsets[row + 1].as_usize();
139
140        // Skip NULL elements per SQL aggregate convention (matches PostgreSQL
141        // array_sum, DuckDB list_sum, Spark aggregate). Empty arrays and
142        // all-NULL arrays both yield NULL — same behavior as SQL SUM over
143        // an empty set or all-NULL column.
144        let mut sum = 0.0_f64;
145        let mut any_valid = false;
146        for i in start..end {
147            if values.is_valid(i) {
148                sum += values.value(i);
149                any_valid = true;
150            }
151        }
152
153        if any_valid {
154            builder.append_value(sum);
155        } else {
156            builder.append_null();
157        }
158    }
159
160    Ok(Arc::new(builder.finish()))
161}