Skip to main content

datafusion_functions_json/
json_get_float.rs

1use std::sync::Arc;
2
3use datafusion::arrow::array::{ArrayRef, Float64Array, Float64Builder};
4use datafusion::arrow::datatypes::DataType;
5use datafusion::common::{Result as DataFusionResult, ScalarValue};
6use datafusion::logical_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility};
7use jiter::{NumberAny, Peek};
8
9use crate::common::{get_err, invoke, jiter_json_find, return_type_check, GetError, InvokeResult, JsonPath};
10use crate::common_macros::make_udf_function;
11
12make_udf_function!(
13    JsonGetFloat,
14    json_get_float,
15    json_data path,
16    r#"Get a float value from a JSON string by its "path""#
17);
18
19#[derive(Debug, PartialEq, Eq, Hash)]
20pub(super) struct JsonGetFloat {
21    signature: Signature,
22    aliases: [String; 1],
23}
24
25impl Default for JsonGetFloat {
26    fn default() -> Self {
27        Self {
28            signature: Signature::variadic_any(Volatility::Immutable),
29            aliases: ["json_get_float".to_string()],
30        }
31    }
32}
33
34impl ScalarUDFImpl for JsonGetFloat {
35    fn name(&self) -> &str {
36        self.aliases[0].as_str()
37    }
38
39    fn signature(&self) -> &Signature {
40        &self.signature
41    }
42
43    fn return_type(&self, arg_types: &[DataType]) -> DataFusionResult<DataType> {
44        return_type_check(arg_types, self.name(), DataType::Float64)
45    }
46
47    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DataFusionResult<ColumnarValue> {
48        invoke::<Float64Array>(&args.args, jiter_json_get_float)
49    }
50
51    fn aliases(&self) -> &[String] {
52        &self.aliases
53    }
54
55    fn placement(
56        &self,
57        args: &[datafusion::logical_expr::ExpressionPlacement],
58    ) -> datafusion::logical_expr::ExpressionPlacement {
59        // If the first argument is a column and the remaining arguments are literals (a path)
60        // then we can push this UDF down to the leaf nodes.
61        if args.len() >= 2
62            && matches!(args[0], datafusion::logical_expr::ExpressionPlacement::Column)
63            && args[1..]
64                .iter()
65                .all(|arg| matches!(arg, datafusion::logical_expr::ExpressionPlacement::Literal))
66        {
67            datafusion::logical_expr::ExpressionPlacement::MoveTowardsLeafNodes
68        } else {
69            datafusion::logical_expr::ExpressionPlacement::KeepInPlace
70        }
71    }
72}
73
74impl InvokeResult for Float64Array {
75    type Item = f64;
76
77    type Builder = Float64Builder;
78
79    // Cheaper to produce a float array rather than dict-encoded floats
80    const ACCEPT_DICT_RETURN: bool = false;
81
82    fn builder(capacity: usize) -> Self::Builder {
83        Float64Builder::with_capacity(capacity)
84    }
85
86    fn append_value(builder: &mut Self::Builder, value: Option<Self::Item>) {
87        builder.append_option(value);
88    }
89
90    fn finish(mut builder: Self::Builder) -> DataFusionResult<ArrayRef> {
91        Ok(Arc::new(builder.finish()))
92    }
93
94    fn scalar(value: Option<Self::Item>) -> ScalarValue {
95        ScalarValue::Float64(value)
96    }
97}
98
99fn jiter_json_get_float(json_data: Option<&str>, path: &[JsonPath]) -> Result<f64, GetError> {
100    if let Some((mut jiter, peek)) = jiter_json_find(json_data, path) {
101        match peek {
102            Peek::String => {
103                let s = jiter.known_str()?;
104                s.parse::<f64>().map_err(|_| GetError)
105            }
106            // numbers are represented by everything else in peek, hence doing it this way
107            Peek::Null
108            | Peek::True
109            | Peek::False
110            | Peek::Minus
111            | Peek::Infinity
112            | Peek::NaN
113            | Peek::Array
114            | Peek::Object => get_err!(),
115            _ => match jiter.known_number(peek)? {
116                NumberAny::Float(f) => Ok(f),
117                NumberAny::Int(int) => Ok(int.into()),
118            },
119        }
120    } else {
121        get_err!()
122    }
123}