Skip to main content

datafusion_functions_json/
json_as_text.rs

1use std::any::Any;
2use std::sync::Arc;
3
4use datafusion::arrow::array::{ArrayRef, StringArray, StringBuilder};
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    JsonAsText,
15    json_as_text,
16    json_data path,
17    r#"Get any value from a JSON string by its "path", represented as a string"#
18);
19
20#[derive(Debug, PartialEq, Eq, Hash)]
21pub(super) struct JsonAsText {
22    signature: Signature,
23    aliases: [String; 1],
24}
25
26impl Default for JsonAsText {
27    fn default() -> Self {
28        Self {
29            signature: Signature::variadic_any(Volatility::Immutable),
30            aliases: ["json_as_text".to_string()],
31        }
32    }
33}
34
35impl ScalarUDFImpl for JsonAsText {
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::Utf8)
50    }
51
52    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DataFusionResult<ColumnarValue> {
53        invoke::<StringArray>(&args.args, jiter_json_as_text)
54    }
55
56    fn aliases(&self) -> &[String] {
57        &self.aliases
58    }
59
60    fn placement(
61        &self,
62        args: &[datafusion::logical_expr::ExpressionPlacement],
63    ) -> datafusion::logical_expr::ExpressionPlacement {
64        // If the first argument is a column and the remaining arguments are literals (a path)
65        // then we can push this UDF down to the leaf nodes.
66        if args.len() >= 2
67            && matches!(args[0], datafusion::logical_expr::ExpressionPlacement::Column)
68            && args[1..]
69                .iter()
70                .all(|arg| matches!(arg, datafusion::logical_expr::ExpressionPlacement::Literal))
71        {
72            datafusion::logical_expr::ExpressionPlacement::MoveTowardsLeafNodes
73        } else {
74            datafusion::logical_expr::ExpressionPlacement::KeepInPlace
75        }
76    }
77}
78
79impl InvokeResult for StringArray {
80    type Item = String;
81
82    type Builder = StringBuilder;
83
84    const ACCEPT_DICT_RETURN: bool = true;
85
86    fn builder(capacity: usize) -> Self::Builder {
87        StringBuilder::with_capacity(capacity, 0)
88    }
89
90    fn append_value(builder: &mut Self::Builder, value: Option<Self::Item>) {
91        builder.append_option(value);
92    }
93
94    fn finish(mut builder: Self::Builder) -> DataFusionResult<ArrayRef> {
95        Ok(Arc::new(builder.finish()))
96    }
97
98    fn scalar(value: Option<Self::Item>) -> ScalarValue {
99        ScalarValue::Utf8(value)
100    }
101}
102
103fn jiter_json_as_text(opt_json: Option<&str>, path: &[JsonPath]) -> Result<String, GetError> {
104    if let Some((mut jiter, peek)) = jiter_json_find(opt_json, path) {
105        match peek {
106            Peek::Null => {
107                jiter.known_null()?;
108                get_err!()
109            }
110            Peek::String => Ok(jiter.known_str()?.to_owned()),
111            _ => {
112                let start = jiter.current_index();
113                jiter.known_skip(peek)?;
114                let object_slice = jiter.slice_to_current(start);
115                let object_string = std::str::from_utf8(object_slice)?;
116                Ok(object_string.to_owned())
117            }
118        }
119    } else {
120        get_err!()
121    }
122}