Skip to main content

datafusion_functions_json/
json_get_float.rs

1use std::any::Any;
2use std::sync::Arc;
3
4use datafusion::arrow::array::{ArrayRef, Float64Array, Float64Builder};
5use datafusion::arrow::datatypes::DataType;
6use datafusion::common::{Result as DataFusionResult, ScalarValue};
7use datafusion::logical_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility};
8use jiter::{NumberAny, 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    JsonGetFloat,
15    json_get_float,
16    json_data path,
17    r#"Get a float value from a JSON string by its "path""#
18);
19
20#[derive(Debug, PartialEq, Eq, Hash)]
21pub(super) struct JsonGetFloat {
22    signature: Signature,
23    aliases: [String; 1],
24}
25
26impl Default for JsonGetFloat {
27    fn default() -> Self {
28        Self {
29            signature: Signature::variadic_any(Volatility::Immutable),
30            aliases: ["json_get_float".to_string()],
31        }
32    }
33}
34
35impl ScalarUDFImpl for JsonGetFloat {
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::Float64)
50    }
51
52    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DataFusionResult<ColumnarValue> {
53        invoke::<Float64Array>(&args.args, jiter_json_get_float)
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 Float64Array {
80    type Item = f64;
81
82    type Builder = Float64Builder;
83
84    // Cheaper to produce a float array rather than dict-encoded floats
85    const ACCEPT_DICT_RETURN: bool = false;
86
87    fn builder(capacity: usize) -> Self::Builder {
88        Float64Builder::with_capacity(capacity)
89    }
90
91    fn append_value(builder: &mut Self::Builder, value: Option<Self::Item>) {
92        builder.append_option(value);
93    }
94
95    fn finish(mut builder: Self::Builder) -> DataFusionResult<ArrayRef> {
96        Ok(Arc::new(builder.finish()))
97    }
98
99    fn scalar(value: Option<Self::Item>) -> ScalarValue {
100        ScalarValue::Float64(value)
101    }
102}
103
104fn jiter_json_get_float(json_data: Option<&str>, path: &[JsonPath]) -> Result<f64, GetError> {
105    if let Some((mut jiter, peek)) = jiter_json_find(json_data, path) {
106        match peek {
107            // numbers are represented by everything else in peek, hence doing it this way
108            Peek::Null
109            | Peek::True
110            | Peek::False
111            | Peek::Minus
112            | Peek::Infinity
113            | Peek::NaN
114            | Peek::String
115            | Peek::Array
116            | Peek::Object => get_err!(),
117            _ => match jiter.known_number(peek)? {
118                NumberAny::Float(f) => Ok(f),
119                NumberAny::Int(int) => Ok(int.into()),
120            },
121        }
122    } else {
123        get_err!()
124    }
125}