Skip to main content

datafusion_functions_nested/
except.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`] definition for array_except function.
6
7use crate::set_ops::normalize_visible_values;
8use crate::utils::{check_datatypes, make_scalar_function};
9use arrow::array::new_null_array;
10use arrow::array::{
11    Array, ArrayRef, GenericListArray, OffsetSizeTrait, UInt32Array, UInt64Array,
12    cast::AsArray,
13};
14use arrow::buffer::{NullBuffer, OffsetBuffer};
15use arrow::compute::take;
16use arrow::datatypes::DataType;
17use arrow::row::{RowConverter, SortField};
18use datafusion_common::utils::{ListCoercion, take_function_args};
19use datafusion_common::{HashSet, Result, internal_err};
20use datafusion_expr::{
21    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
22    Volatility,
23};
24use datafusion_macros::user_doc;
25use itertools::Itertools;
26use std::sync::Arc;
27
28make_udf_expr_and_func!(
29    ArrayExcept,
30    array_except,
31    first_array second_array,
32    "returns an array of the elements that appear in the first array but not in the second.",
33    array_except_udf
34);
35
36#[user_doc(
37    doc_section(label = "Array Functions"),
38    description = "Returns an array of the elements that appear in the first array but not in the second.",
39    syntax_example = "array_except(array1, array2)",
40    sql_example = r#"```sql
41> select array_except([1, 2, 3, 4], [5, 6, 3, 4]);
42+-------------------------------------------+
43| array_except([1, 2, 3, 4], [5, 6, 3, 4]); |
44+-------------------------------------------+
45| [1, 2]                                    |
46+-------------------------------------------+
47> select array_except([1, 2, 3, 4], [3, 4, 5, 6]);
48+-------------------------------------------+
49| array_except([1, 2, 3, 4], [3, 4, 5, 6]); |
50+-------------------------------------------+
51| [1, 2]                                    |
52+-------------------------------------------+
53```"#,
54    argument(
55        name = "array1",
56        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
57    ),
58    argument(
59        name = "array2",
60        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
61    )
62)]
63#[derive(Debug, PartialEq, Eq, Hash)]
64pub struct ArrayExcept {
65    signature: Signature,
66    aliases: Vec<String>,
67}
68
69impl Default for ArrayExcept {
70    fn default() -> Self {
71        Self::new()
72    }
73}
74
75impl ArrayExcept {
76    pub fn new() -> Self {
77        Self {
78            signature: Signature::arrays(
79                2,
80                Some(ListCoercion::FixedSizedListToList),
81                Volatility::Immutable,
82            ),
83            aliases: vec!["list_except".to_string()],
84        }
85    }
86}
87
88impl ScalarUDFImpl for ArrayExcept {
89    fn name(&self) -> &str {
90        "array_except"
91    }
92
93    fn signature(&self) -> &Signature {
94        &self.signature
95    }
96
97    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
98        match (&arg_types[0], &arg_types[1]) {
99            (DataType::Null, DataType::Null) => {
100                Ok(DataType::new_list(DataType::Null, true))
101            }
102            (DataType::Null, dt) | (dt, DataType::Null) => Ok(dt.clone()),
103            (dt, _) => Ok(dt.clone()),
104        }
105    }
106
107    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
108        make_scalar_function(array_except_inner)(&args.args)
109    }
110
111    fn aliases(&self) -> &[String] {
112        &self.aliases
113    }
114
115    fn documentation(&self) -> Option<&Documentation> {
116        self.doc()
117    }
118}
119
120fn array_except_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
121    let [array1, array2] = take_function_args("array_except", args)?;
122
123    let len = array1.len();
124    match (array1.data_type(), array2.data_type()) {
125        (DataType::Null, DataType::Null) => Ok(new_null_array(
126            &DataType::new_list(DataType::Null, true),
127            len,
128        )),
129        (DataType::Null, dt @ DataType::List(_))
130        | (DataType::Null, dt @ DataType::LargeList(_))
131        | (dt @ DataType::List(_), DataType::Null)
132        | (dt @ DataType::LargeList(_), DataType::Null) => Ok(new_null_array(dt, len)),
133        (DataType::List(_), DataType::List(_)) => {
134            check_datatypes("array_except", &[array1, array2])?;
135            let list1 = array1.as_list::<i32>();
136            let list2 = array2.as_list::<i32>();
137            let result = general_except::<i32>(list1, list2)?;
138            Ok(Arc::new(result))
139        }
140        (DataType::LargeList(_), DataType::LargeList(_)) => {
141            check_datatypes("array_except", &[array1, array2])?;
142            let list1 = array1.as_list::<i64>();
143            let list2 = array2.as_list::<i64>();
144            let result = general_except::<i64>(list1, list2)?;
145            Ok(Arc::new(result))
146        }
147        (dt1, dt2) => {
148            internal_err!("array_except got unexpected types: {dt1:?} and {dt2:?}")
149        }
150    }
151}
152
153fn general_except<OffsetSize: OffsetSizeTrait>(
154    l: &GenericListArray<OffsetSize>,
155    r: &GenericListArray<OffsetSize>,
156) -> Result<GenericListArray<OffsetSize>> {
157    let converter = RowConverter::new(vec![SortField::new(l.value_type())])?;
158
159    // Normalize -0.0 → +0.0 so RowConverter (IEEE 754 totalOrder) groups
160    // ±0 together for both the rhs lookup set and the lhs probe.
161    let l_first = l.offsets()[0].as_usize();
162    let l_values_norm = normalize_visible_values(l);
163    let l_rows = converter.convert_columns(&[Arc::clone(&l_values_norm)])?;
164
165    let r_first = r.offsets()[0].as_usize();
166    let r_values_norm = normalize_visible_values(r);
167    let r_rows = converter.convert_columns(&[Arc::clone(&r_values_norm)])?;
168
169    let mut offsets = Vec::<OffsetSize>::with_capacity(l.len() + 1);
170    offsets.push(OffsetSize::usize_as(0));
171
172    let mut indices: Vec<usize> = Vec::with_capacity(l_rows.num_rows());
173    let mut dedup = HashSet::new();
174
175    let nulls = NullBuffer::union(l.nulls(), r.nulls());
176
177    let l_offsets_iter = l.offsets().iter().tuple_windows();
178    let r_offsets_iter = r.offsets().iter().tuple_windows();
179    for (list_index, ((l_start, l_end), (r_start, r_end))) in
180        l_offsets_iter.zip(r_offsets_iter).enumerate()
181    {
182        if nulls
183            .as_ref()
184            .is_some_and(|nulls| nulls.is_null(list_index))
185        {
186            offsets.push(OffsetSize::usize_as(indices.len()));
187            continue;
188        }
189
190        for element_index in r_start.as_usize() - r_first..r_end.as_usize() - r_first {
191            let right_row = r_rows.row(element_index);
192            dedup.insert(right_row);
193        }
194        for element_index in l_start.as_usize() - l_first..l_end.as_usize() - l_first {
195            let left_row = l_rows.row(element_index);
196            if dedup.insert(left_row) {
197                indices.push(element_index);
198            }
199        }
200
201        offsets.push(OffsetSize::usize_as(indices.len()));
202        dedup.clear();
203    }
204
205    // Gather distinct left-side values by index.
206    // Use UInt64Array for LargeList to support values arrays exceeding u32::MAX.
207    let values = if indices.is_empty() {
208        arrow::array::new_empty_array(&l.value_type())
209    } else if OffsetSize::IS_LARGE {
210        let indices =
211            UInt64Array::from(indices.into_iter().map(|i| i as u64).collect::<Vec<_>>());
212        take(l_values_norm.as_ref(), &indices, None)?
213    } else {
214        let indices =
215            UInt32Array::from(indices.into_iter().map(|i| i as u32).collect::<Vec<_>>());
216        take(l_values_norm.as_ref(), &indices, None)?
217    };
218
219    Ok(GenericListArray::<OffsetSize>::new(
220        Arc::clone(l.value_field()),
221        OffsetBuffer::new(offsets.into()),
222        values,
223        nulls,
224    ))
225}
226
227#[cfg(test)]
228mod tests {
229    use super::{ArrayExcept, general_except};
230    use arrow::array::{Array, AsArray, Int32Array, LargeListArray, ListArray};
231    use arrow::datatypes::{Field, Float64Type, Int32Type};
232    use datafusion_common::{Result, config::ConfigOptions};
233    use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};
234    use std::sync::Arc;
235
236    #[test]
237    fn test_array_except_sliced_lists() -> Result<()> {
238        // l: [[1,2], [3,4], [5,6], [7,8]]  →  slice(1,2)  →  [[3,4], [5,6]]
239        // r: [[3],   [5],   [6],   [8]]    →  slice(1,2)  →  [[5],   [6]]
240        // except(l, r) should be [[3,4], [5]]
241        let l_full = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
242            Some(vec![Some(1), Some(2)]),
243            Some(vec![Some(3), Some(4)]),
244            Some(vec![Some(5), Some(6)]),
245            Some(vec![Some(7), Some(8)]),
246        ]);
247        let r_full = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
248            Some(vec![Some(3)]),
249            Some(vec![Some(5)]),
250            Some(vec![Some(6)]),
251            Some(vec![Some(8)]),
252        ]);
253        let l_sliced = l_full.slice(1, 2);
254        let r_sliced = r_full.slice(1, 2);
255
256        let list_field = Arc::new(Field::new("item", l_sliced.data_type().clone(), true));
257        let return_field =
258            Arc::new(Field::new("return", l_sliced.data_type().clone(), true));
259
260        let result = ArrayExcept::new().invoke_with_args(ScalarFunctionArgs {
261            args: vec![
262                ColumnarValue::Array(Arc::new(l_sliced)),
263                ColumnarValue::Array(Arc::new(r_sliced)),
264            ],
265            arg_fields: vec![Arc::clone(&list_field), Arc::clone(&list_field)],
266            number_rows: 2,
267            return_field,
268            config_options: Arc::new(ConfigOptions::default()),
269        })?;
270
271        let output = result.into_array(2)?;
272        let output = output.as_list::<i32>();
273
274        // Row 0: [3,4] except [5] = [3,4]
275        let row0 = output.value(0);
276        let row0 = row0.as_any().downcast_ref::<Int32Array>().unwrap();
277        assert_eq!(row0.values().as_ref(), &[3, 4]);
278
279        // Row 1: [5,6] except [6] = [5]
280        let row1 = output.value(1);
281        let row1 = row1.as_any().downcast_ref::<Int32Array>().unwrap();
282        assert_eq!(row1.values().as_ref(), &[5]);
283
284        Ok(())
285    }
286
287    #[test]
288    fn test_array_except_sliced_float_large_lists() -> Result<()> {
289        let l = LargeListArray::from_iter_primitive::<Float64Type, _, _>(vec![
290            Some(vec![Some(99.0)]),
291            Some(vec![Some(-0.0), Some(0.0), Some(1.0), None, None]),
292            Some(vec![Some(-99.0)]),
293        ])
294        .slice(1, 1);
295        let r = LargeListArray::from_iter_primitive::<Float64Type, _, _>(vec![
296            Some(vec![Some(98.0)]),
297            Some(vec![Some(0.0), None]),
298            Some(vec![Some(-98.0)]),
299        ])
300        .slice(1, 1);
301        let result = general_except::<i64>(&l, &r)?;
302        let values = result.value(0);
303        let values = values.as_primitive::<Float64Type>();
304        assert_eq!(values.len(), 1);
305        assert_eq!(values.value(0), 1.0);
306        Ok(())
307    }
308}