Skip to main content

datafusion_functions_nested/
array_subtract.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_subtract 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    ArraySubtract,
24    array_subtract,
25    array1 array2,
26    "returns the element-wise difference of two numeric arrays.",
27    array_subtract_udf
28);
29
30#[user_doc(
31    doc_section(label = "Array Functions"),
32    description = "Returns the element-wise difference 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_subtract(array1, array2)",
34    sql_example = r#"```sql
35> select array_subtract([10.0, 20.0, 30.0], [1.0, 2.0, 3.0]);
36+--------------------------------------------------------------+
37| array_subtract(List([10.0,20.0,30.0]),List([1.0,2.0,3.0]))   |
38+--------------------------------------------------------------+
39| [9.0, 18.0, 27.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 ArraySubtract {
53    signature: Signature,
54    aliases: Vec<String>,
55}
56
57impl Default for ArraySubtract {
58    fn default() -> Self {
59        Self::new()
60    }
61}
62
63impl ArraySubtract {
64    pub fn new() -> Self {
65        Self {
66            signature: Signature::user_defined(Volatility::Immutable),
67            aliases: vec!["list_subtract".to_string()],
68        }
69    }
70}
71
72impl ScalarUDFImpl for ArraySubtract {
73    fn name(&self) -> &str {
74        "array_subtract"
75    }
76
77    fn signature(&self) -> &Signature {
78        &self.signature
79    }
80
81    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
82        Ok(arg_types[0].clone())
83    }
84
85    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
86        let [_, _] = take_function_args(self.name(), arg_types)?;
87        coerce_array_math_arg_types(self.name(), arg_types)
88    }
89
90    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
91        make_scalar_function(array_subtract_inner)(&args.args)
92    }
93
94    fn aliases(&self) -> &[String] {
95        &self.aliases
96    }
97
98    fn documentation(&self) -> Option<&Documentation> {
99        self.doc()
100    }
101}
102
103fn array_subtract_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
104    let [array1, array2] = take_function_args("array_subtract", args)?;
105    let sub = |a: f64, b: f64| a - b;
106    match (array1.data_type(), array2.data_type()) {
107        (List(_), List(_)) => {
108            array_math_binary_op::<i32, _>("array_subtract", array1, array2, sub)
109        }
110        (LargeList(_), LargeList(_)) => {
111            array_math_binary_op::<i64, _>("array_subtract", array1, array2, sub)
112        }
113        (arg_type1, arg_type2) => exec_err!(
114            "array_subtract received unexpected types after coercion: {arg_type1} and {arg_type2}"
115        ),
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use std::sync::Arc;
123
124    #[test]
125    fn test_sliced_capacity() -> Result<()> {
126        crate::utils::tests::check_sliced_list_behavior(|input| {
127            array_subtract_inner(&[Arc::clone(input), Arc::clone(input)])
128        })
129    }
130}