Skip to main content

datafusion_functions_nested/
map_entries.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_entries function.
6
7use crate::utils::{get_map_entry_field, make_scalar_function};
8use arrow::array::{Array, ArrayRef, ListArray};
9use arrow::datatypes::{DataType, Field, Fields};
10use datafusion_common::utils::take_function_args;
11use datafusion_common::{Result, cast::as_map_array, exec_err};
12use datafusion_expr::{
13    ArrayFunctionSignature, ColumnarValue, Documentation, ScalarFunctionArgs,
14    ScalarUDFImpl, Signature, TypeSignature, Volatility,
15};
16use datafusion_macros::user_doc;
17use std::sync::Arc;
18
19make_udf_expr_and_func!(
20    MapEntriesFunc,
21    map_entries,
22    map,
23    "Return a list of all entries in the map.",
24    map_entries_udf
25);
26
27#[user_doc(
28    doc_section(label = "Map Functions"),
29    description = "Returns a list of all entries in the map.",
30    syntax_example = "map_entries(map)",
31    sql_example = r#"```sql
32SELECT map_entries(MAP {'a': 1, 'b': NULL, 'c': 3});
33----
34[{'key': a, 'value': 1}, {'key': b, 'value': NULL}, {'key': c, 'value': 3}]
35
36SELECT map_entries(map([100, 5], [42, 43]));
37----
38[{'key': 100, 'value': 42}, {'key': 5, 'value': 43}]
39```"#,
40    argument(
41        name = "map",
42        description = "Map expression. Can be a constant, column, or function, and any combination of map operators."
43    )
44)]
45#[derive(Debug, PartialEq, Eq, Hash)]
46pub struct MapEntriesFunc {
47    signature: Signature,
48}
49
50impl Default for MapEntriesFunc {
51    fn default() -> Self {
52        Self::new()
53    }
54}
55
56impl MapEntriesFunc {
57    pub fn new() -> Self {
58        Self {
59            signature: Signature::new(
60                TypeSignature::ArraySignature(ArrayFunctionSignature::MapArray),
61                Volatility::Immutable,
62            ),
63        }
64    }
65}
66
67impl ScalarUDFImpl for MapEntriesFunc {
68    fn name(&self) -> &str {
69        "map_entries"
70    }
71
72    fn signature(&self) -> &Signature {
73        &self.signature
74    }
75
76    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
77        let [map_type] = take_function_args(self.name(), arg_types)?;
78        let map_fields = get_map_entry_field(map_type)?;
79        Ok(DataType::List(Arc::new(Field::new_list_field(
80            DataType::Struct(Fields::from(vec![
81                Field::new(
82                    "key",
83                    map_fields.first().unwrap().data_type().clone(),
84                    false,
85                ),
86                Field::new(
87                    "value",
88                    map_fields.get(1).unwrap().data_type().clone(),
89                    true,
90                ),
91            ])),
92            false,
93        ))))
94    }
95
96    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
97        make_scalar_function(map_entries_inner)(&args.args)
98    }
99
100    fn documentation(&self) -> Option<&Documentation> {
101        self.doc()
102    }
103}
104
105fn map_entries_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
106    let [map_arg] = take_function_args("map_entries", 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_entries should be a map"),
111    };
112
113    Ok(Arc::new(ListArray::new(
114        Arc::new(Field::new_list_field(
115            DataType::Struct(Fields::from(vec![
116                Field::new("key", map_array.key_type().clone(), false),
117                Field::new("value", map_array.value_type().clone(), true),
118            ])),
119            false,
120        )),
121        map_array.offsets().clone(),
122        Arc::new(map_array.entries().clone()),
123        map_array.nulls().cloned(),
124    )))
125}