datafusion_functions_nested/
map_keys.rs1use crate::utils::{get_map_entry_field, make_scalar_function};
8use arrow::array::{Array, ArrayRef, ListArray};
9use arrow::datatypes::{DataType, Field};
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 MapKeysFunc,
21 map_keys,
22 map,
23 "Return a list of all keys in the map.",
24 map_keys_udf
25);
26
27#[user_doc(
28 doc_section(label = "Map Functions"),
29 description = "Returns a list of all keys in the map.",
30 syntax_example = "map_keys(map)",
31 sql_example = r#"```sql
32SELECT map_keys(MAP {'a': 1, 'b': NULL, 'c': 3});
33----
34[a, b, c]
35
36SELECT map_keys(map([100, 5], [42, 43]));
37----
38[100, 5]
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 MapKeysFunc {
47 signature: Signature,
48}
49
50impl Default for MapKeysFunc {
51 fn default() -> Self {
52 Self::new()
53 }
54}
55
56impl MapKeysFunc {
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 MapKeysFunc {
68 fn name(&self) -> &str {
69 "map_keys"
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(
81 map_fields.first().unwrap().data_type().clone(),
82 true,
83 ))))
84 }
85
86 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
87 make_scalar_function(map_keys_inner)(&args.args)
88 }
89
90 fn documentation(&self) -> Option<&Documentation> {
91 self.doc()
92 }
93}
94
95fn map_keys_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
96 let [map_arg] = take_function_args("map_keys", args)?;
97
98 let map_array = match map_arg.data_type() {
99 DataType::Map(_, _) => as_map_array(&map_arg)?,
100 _ => return exec_err!("Argument for map_keys should be a map"),
101 };
102
103 Ok(Arc::new(ListArray::new(
104 Arc::new(Field::new_list_field(map_array.key_type().clone(), true)),
106 map_array.offsets().clone(),
107 Arc::clone(map_array.keys()),
108 map_array.nulls().cloned(),
109 )))
110}