Skip to main content

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