datafusion_functions_json/
json_length.rs1use std::any::Any;
2use std::sync::Arc;
3
4use datafusion::arrow::array::{ArrayRef, UInt64Array, UInt64Builder};
5use datafusion::arrow::datatypes::DataType;
6use datafusion::common::{Result as DataFusionResult, ScalarValue};
7use datafusion::logical_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility};
8use jiter::Peek;
9
10use crate::common::{get_err, invoke, jiter_json_find, return_type_check, GetError, InvokeResult, JsonPath};
11use crate::common_macros::make_udf_function;
12
13make_udf_function!(
14 JsonLength,
15 json_length,
16 json_data path,
17 r"Get the length of the array or object at the given path."
18);
19
20#[derive(Debug, PartialEq, Eq, Hash)]
21pub(super) struct JsonLength {
22 signature: Signature,
23 aliases: [String; 2],
24}
25
26impl Default for JsonLength {
27 fn default() -> Self {
28 Self {
29 signature: Signature::variadic_any(Volatility::Immutable),
30 aliases: ["json_length".to_string(), "json_len".to_string()],
31 }
32 }
33}
34
35impl ScalarUDFImpl for JsonLength {
36 fn as_any(&self) -> &dyn Any {
37 self
38 }
39
40 fn name(&self) -> &str {
41 self.aliases[0].as_str()
42 }
43
44 fn signature(&self) -> &Signature {
45 &self.signature
46 }
47
48 fn return_type(&self, arg_types: &[DataType]) -> DataFusionResult<DataType> {
49 return_type_check(arg_types, self.name(), DataType::UInt64)
50 }
51
52 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DataFusionResult<ColumnarValue> {
53 invoke::<UInt64Array>(&args.args, jiter_json_length)
54 }
55
56 fn aliases(&self) -> &[String] {
57 &self.aliases
58 }
59}
60
61impl InvokeResult for UInt64Array {
62 type Item = u64;
63
64 type Builder = UInt64Builder;
65
66 const ACCEPT_DICT_RETURN: bool = false;
68
69 fn builder(capacity: usize) -> Self::Builder {
70 UInt64Builder::with_capacity(capacity)
71 }
72
73 fn append_value(builder: &mut Self::Builder, value: Option<Self::Item>) {
74 builder.append_option(value);
75 }
76
77 fn finish(mut builder: Self::Builder) -> DataFusionResult<ArrayRef> {
78 Ok(Arc::new(builder.finish()))
79 }
80
81 fn scalar(value: Option<Self::Item>) -> ScalarValue {
82 ScalarValue::UInt64(value)
83 }
84}
85
86fn jiter_json_length(opt_json: Option<&str>, path: &[JsonPath]) -> Result<u64, GetError> {
87 if let Some((mut jiter, peek)) = jiter_json_find(opt_json, path) {
88 match peek {
89 Peek::Array => {
90 let mut peek_opt = jiter.known_array()?;
91 let mut length: u64 = 0;
92 while let Some(peek) = peek_opt {
93 jiter.known_skip(peek)?;
94 length += 1;
95 peek_opt = jiter.array_step()?;
96 }
97 Ok(length)
98 }
99 Peek::Object => {
100 let mut opt_key = jiter.known_object()?;
101
102 let mut length: u64 = 0;
103 while opt_key.is_some() {
104 jiter.next_skip()?;
105 length += 1;
106 opt_key = jiter.next_key()?;
107 }
108 Ok(length)
109 }
110 _ => get_err!(),
111 }
112 } else {
113 get_err!()
114 }
115}