Skip to main content

datafusion_functions_nested/
array_scale.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_scale function.
6
7use crate::utils::make_scalar_function;
8use arrow::array::{Array, ArrayRef, Float64Array, GenericListArray, OffsetSizeTrait};
9use arrow::buffer::{NullBuffer, OffsetBuffer};
10use arrow::datatypes::{
11    DataType,
12    DataType::{FixedSizeList, LargeList, List, Null},
13    Field,
14};
15use datafusion_common::cast::{as_float64_array, as_generic_list_array};
16use datafusion_common::utils::{
17    ListCoercion, coerced_type_with_base_type_only, offset_span_len,
18};
19use datafusion_common::{Result, internal_err, plan_err, utils::take_function_args};
20use datafusion_expr::{
21    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
22    Volatility,
23};
24use datafusion_macros::user_doc;
25use std::sync::Arc;
26
27make_udf_expr_and_func!(
28    ArrayScale,
29    array_scale,
30    array scalar,
31    "scales each element of a numeric array by a scalar.",
32    array_scale_udf
33);
34
35#[user_doc(
36    doc_section(label = "Array Functions"),
37    description = "Returns a new array with each element of the input array multiplied by a scalar value, computed as `array[i] * scalar`. Returns NULL if the input row is NULL or the scalar is NULL. If a NULL element appears in the input array at position `i`, the result element at position `i` is NULL. Returns an empty array for an empty input array.",
38    syntax_example = "array_scale(array, scalar)",
39    sql_example = r#"```sql
40> select array_scale([1.0, 2.0, 3.0], 2.0);
41+-----------------------------------------------+
42| array_scale(List([1.0,2.0,3.0]),Float64(2.0)) |
43+-----------------------------------------------+
44| [2.0, 4.0, 6.0]                               |
45+-----------------------------------------------+
46```"#,
47    argument(
48        name = "array",
49        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
50    ),
51    argument(
52        name = "scalar",
53        description = "Numeric scalar to multiply each element by. Can be a constant or column expression."
54    )
55)]
56#[derive(Debug, PartialEq, Eq, Hash)]
57pub struct ArrayScale {
58    signature: Signature,
59    aliases: Vec<String>,
60}
61
62impl Default for ArrayScale {
63    fn default() -> Self {
64        Self::new()
65    }
66}
67
68impl ArrayScale {
69    pub fn new() -> Self {
70        Self {
71            signature: Signature::user_defined(Volatility::Immutable),
72            aliases: vec!["list_scale".to_string()],
73        }
74    }
75}
76
77impl ScalarUDFImpl for ArrayScale {
78    fn name(&self) -> &str {
79        "array_scale"
80    }
81
82    fn signature(&self) -> &Signature {
83        &self.signature
84    }
85
86    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
87        // After `coerce_types`, `arg_types[0]` is one of List(Float64) or LargeList(Float64).
88        Ok(arg_types[0].clone())
89    }
90
91    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
92        let [array_type, scalar_type] = take_function_args(self.name(), arg_types)?;
93        let coercion = Some(&ListCoercion::FixedSizedListToList);
94
95        if !matches!(
96            array_type,
97            Null | List(_) | LargeList(_) | FixedSizeList(..)
98        ) {
99            return plan_err!(
100                "{} first argument must be a list type, got {array_type}",
101                self.name()
102            );
103        }
104
105        if !scalar_type.is_numeric() && !matches!(scalar_type, Null) {
106            return plan_err!(
107                "{} second argument must be numeric, got {scalar_type}",
108                self.name()
109            );
110        }
111
112        let coerced_array = if matches!(array_type, Null) {
113            List(Arc::new(Field::new_list_field(DataType::Float64, true)))
114        } else {
115            coerced_type_with_base_type_only(array_type, &DataType::Float64, coercion)
116        };
117
118        Ok(vec![coerced_array, DataType::Float64])
119    }
120
121    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
122        make_scalar_function(array_scale_inner)(&args.args)
123    }
124
125    fn aliases(&self) -> &[String] {
126        &self.aliases
127    }
128
129    fn documentation(&self) -> Option<&Documentation> {
130        self.doc()
131    }
132}
133
134fn array_scale_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
135    let [array, scalar] = take_function_args("array_scale", args)?;
136    match array.data_type() {
137        List(_) => general_array_scale::<i32>(array, scalar),
138        LargeList(_) => general_array_scale::<i64>(array, scalar),
139        arg_type => internal_err!(
140            "array_scale received unexpected type after coercion: {arg_type}"
141        ),
142    }
143}
144
145fn general_array_scale<O: OffsetSizeTrait>(
146    array: &ArrayRef,
147    scalar: &ArrayRef,
148) -> Result<ArrayRef> {
149    let list_array = as_generic_list_array::<O>(array)?;
150    let scalar_array = as_float64_array(scalar)?;
151
152    let values = as_float64_array(list_array.values())?;
153    let offsets = list_array.offsets();
154
155    // A row is null whenever either input row is null. The scalar applies
156    // uniformly across the array, so a null scalar makes the whole row
157    // undefined; union the two row-level null buffers in a single pass
158    // rather than tracking row nulls inside the value loop.
159    let row_nulls = NullBuffer::union(list_array.nulls(), scalar_array.nulls());
160
161    let mut value_builder = Float64Array::builder(offset_span_len(offsets));
162    let mut new_offsets = Vec::<O>::with_capacity(list_array.len() + 1);
163    new_offsets.push(O::zero());
164
165    for row in 0..list_array.len() {
166        if row_nulls.as_ref().is_some_and(|nb| nb.is_null(row)) {
167            new_offsets.push(new_offsets[row]);
168            continue;
169        }
170
171        let start = offsets[row].as_usize();
172        let end = offsets[row + 1].as_usize();
173        let len = end - start;
174        let scalar_val = scalar_array.value(row);
175
176        let slice = values.slice(start, len);
177
178        // Per-element NULL propagation for NULL elements inside the array.
179        for i in 0..len {
180            if slice.is_null(i) {
181                value_builder.append_null();
182            } else {
183                value_builder.append_value(slice.value(i) * scalar_val);
184            }
185        }
186
187        new_offsets.push(new_offsets[row] + O::usize_as(len));
188    }
189
190    let values_array = Arc::new(value_builder.finish());
191
192    // Preserve the inner field from the input array (including any user
193    // metadata). After `coerce_types` the inner type is Float64, but the
194    // input may still carry field-level annotations worth keeping.
195    Ok(Arc::new(GenericListArray::<O>::try_new(
196        Arc::clone(list_array.value_field()),
197        OffsetBuffer::new(new_offsets.into()),
198        values_array,
199        row_nulls,
200    )?))
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn test_sliced_capacity() -> Result<()> {
209        crate::utils::tests::check_sliced_list_behavior(|input| {
210            array_scale_inner(&[
211                Arc::clone(input),
212                Arc::new(Float64Array::from(vec![2.0; input.len()])),
213            ])
214        })
215    }
216}