Skip to main content

datafusion_functions_nested/
map_values.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 map_values function.
6
7use crate::utils::{get_map_entry_field, make_scalar_function};
8use arrow::array::{Array, ArrayRef, ListArray};
9use arrow::datatypes::{DataType, Field, FieldRef};
10use datafusion_common::utils::take_function_args;
11use datafusion_common::{Result, cast::as_map_array, exec_err, internal_err};
12use datafusion_expr::{
13    ArrayFunctionSignature, ColumnarValue, Documentation, ScalarFunctionArgs,
14    ScalarUDFImpl, Signature, TypeSignature, Volatility,
15};
16use datafusion_macros::user_doc;
17use std::ops::Deref;
18use std::sync::Arc;
19
20make_udf_expr_and_func!(
21    MapValuesFunc,
22    map_values,
23    map,
24    "Return a list of all values in the map.",
25    map_values_udf
26);
27
28#[user_doc(
29    doc_section(label = "Map Functions"),
30    description = "Returns a list of all values in the map.",
31    syntax_example = "map_values(map)",
32    sql_example = r#"```sql
33SELECT map_values(MAP {'a': 1, 'b': NULL, 'c': 3});
34----
35[1, , 3]
36
37SELECT map_values(map([100, 5], [42, 43]));
38----
39[42, 43]
40```"#,
41    argument(
42        name = "map",
43        description = "Map expression. Can be a constant, column, or function, and any combination of map operators."
44    )
45)]
46#[derive(Debug, PartialEq, Eq, Hash)]
47pub(crate) struct MapValuesFunc {
48    signature: Signature,
49}
50
51impl Default for MapValuesFunc {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl MapValuesFunc {
58    pub fn new() -> Self {
59        Self {
60            signature: Signature::new(
61                TypeSignature::ArraySignature(ArrayFunctionSignature::MapArray),
62                Volatility::Immutable,
63            ),
64        }
65    }
66}
67
68impl ScalarUDFImpl for MapValuesFunc {
69    fn name(&self) -> &str {
70        "map_values"
71    }
72
73    fn signature(&self) -> &Signature {
74        &self.signature
75    }
76
77    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
78        internal_err!("return_field_from_args should be used instead")
79    }
80
81    fn return_field_from_args(
82        &self,
83        args: datafusion_expr::ReturnFieldArgs,
84    ) -> Result<FieldRef> {
85        let [map_type] = take_function_args(self.name(), args.arg_fields)?;
86
87        Ok(Field::new(
88            self.name(),
89            DataType::List(get_map_values_field_as_list_field(map_type.data_type())?),
90            // Nullable if the map is nullable
91            args.arg_fields.iter().any(|x| x.is_nullable()),
92        )
93        .into())
94    }
95
96    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
97        make_scalar_function(map_values_inner)(&args.args)
98    }
99
100    fn documentation(&self) -> Option<&Documentation> {
101        self.doc()
102    }
103}
104
105fn map_values_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
106    let [map_arg] = take_function_args("map_values", args)?;
107
108    let map_array = match map_arg.data_type() {
109        DataType::Map(_, _) => as_map_array(&map_arg)?,
110        _ => return exec_err!("Argument for map_values should be a map"),
111    };
112
113    Ok(Arc::new(ListArray::new(
114        get_map_values_field_as_list_field(map_arg.data_type())?,
115        map_array.offsets().clone(),
116        Arc::clone(map_array.values()),
117        map_array.nulls().cloned(),
118    )))
119}
120
121fn get_map_values_field_as_list_field(map_type: &DataType) -> Result<FieldRef> {
122    let map_fields = get_map_entry_field(map_type)?;
123
124    let values_field = map_fields
125        .last()
126        .unwrap()
127        .deref()
128        .clone()
129        .with_name(Field::LIST_FIELD_DEFAULT_NAME);
130
131    Ok(Arc::new(values_field))
132}
133
134#[cfg(test)]
135mod tests {
136    use crate::map_values::MapValuesFunc;
137    use arrow::datatypes::{DataType, Field, FieldRef};
138    use datafusion_common::ScalarValue;
139    use datafusion_expr::ScalarUDFImpl;
140    use std::sync::Arc;
141
142    #[test]
143    fn return_type_field() {
144        fn get_map_field(
145            is_map_nullable: bool,
146            is_keys_nullable: bool,
147            is_values_nullable: bool,
148        ) -> FieldRef {
149            Field::new_map(
150                "something",
151                "entries",
152                Arc::new(Field::new("keys", DataType::Utf8, is_keys_nullable)),
153                Arc::new(Field::new(
154                    "values",
155                    DataType::LargeUtf8,
156                    is_values_nullable,
157                )),
158                false,
159                is_map_nullable,
160            )
161            .into()
162        }
163
164        fn get_list_field(
165            name: &str,
166            is_list_nullable: bool,
167            list_item_type: DataType,
168            is_list_items_nullable: bool,
169        ) -> FieldRef {
170            Field::new_list(
171                name,
172                Arc::new(Field::new_list_field(
173                    list_item_type,
174                    is_list_items_nullable,
175                )),
176                is_list_nullable,
177            )
178            .into()
179        }
180
181        fn get_return_field(field: FieldRef) -> FieldRef {
182            let func = MapValuesFunc::new();
183            let args = datafusion_expr::ReturnFieldArgs {
184                arg_fields: &[field],
185                scalar_arguments: &[None::<&ScalarValue>],
186            };
187
188            func.return_field_from_args(args).unwrap()
189        }
190
191        // Test cases:
192        //
193        // |                      Input Map                         ||                   Expected Output                     |
194        // | ------------------------------------------------------ || ----------------------------------------------------- |
195        // | map nullable | map keys nullable | map values nullable || expected list nullable | expected list items nullable |
196        // | ------------ | ----------------- | ------------------- || ---------------------- | ---------------------------- |
197        // | false        | false             | false               || false                  | false                        |
198        // | false        | false             | true                || false                  | true                         |
199        // | false        | true              | false               || false                  | false                        |
200        // | false        | true              | true                || false                  | true                         |
201        // | true         | false             | false               || true                   | false                        |
202        // | true         | false             | true                || true                   | true                         |
203        // | true         | true              | false               || true                   | false                        |
204        // | true         | true              | true                || true                   | true                         |
205        //
206        // ---------------
207        // We added the key nullability to show that it does not affect the nullability of the list or the list items.
208
209        assert_eq!(
210            get_return_field(get_map_field(false, false, false)),
211            get_list_field("map_values", false, DataType::LargeUtf8, false)
212        );
213
214        assert_eq!(
215            get_return_field(get_map_field(false, false, true)),
216            get_list_field("map_values", false, DataType::LargeUtf8, true)
217        );
218
219        assert_eq!(
220            get_return_field(get_map_field(false, true, false)),
221            get_list_field("map_values", false, DataType::LargeUtf8, false)
222        );
223
224        assert_eq!(
225            get_return_field(get_map_field(false, true, true)),
226            get_list_field("map_values", false, DataType::LargeUtf8, true)
227        );
228
229        assert_eq!(
230            get_return_field(get_map_field(true, false, false)),
231            get_list_field("map_values", true, DataType::LargeUtf8, false)
232        );
233
234        assert_eq!(
235            get_return_field(get_map_field(true, false, true)),
236            get_list_field("map_values", true, DataType::LargeUtf8, true)
237        );
238
239        assert_eq!(
240            get_return_field(get_map_field(true, true, false)),
241            get_list_field("map_values", true, DataType::LargeUtf8, false)
242        );
243
244        assert_eq!(
245            get_return_field(get_map_field(true, true, true)),
246            get_list_field("map_values", true, DataType::LargeUtf8, true)
247        );
248    }
249}