Skip to main content

common_function/scalars/json/
json_get_rewriter.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[cfg(test)]
16use std::sync::Arc;
17
18use arrow_schema::{DataType, TimeUnit};
19use datafusion::common::config::ConfigOptions;
20use datafusion::common::tree_node::Transformed;
21use datafusion::common::{DFSchema, Result};
22use datafusion::logical_expr::expr_rewriter::FunctionRewrite;
23use datafusion::scalar::ScalarValue;
24use datafusion_expr::expr::ScalarFunction;
25use datafusion_expr::{Cast, Expr};
26
27use crate::scalars::json::JsonGetWithType;
28
29#[derive(Debug)]
30pub struct JsonGetRewriter;
31
32impl FunctionRewrite for JsonGetRewriter {
33    fn name(&self) -> &'static str {
34        "JsonGetRewriter"
35    }
36
37    fn rewrite(
38        &self,
39        expr: Expr,
40        _schema: &DFSchema,
41        _config: &ConfigOptions,
42    ) -> Result<Transformed<Expr>> {
43        Ok(match expr {
44            Expr::Cast(cast) => inject_type_from_cast_expr(cast)?,
45            Expr::ScalarFunction(cast) => inject_type_from_cast_func(cast)?,
46            expr => Transformed::no(expr),
47        })
48    }
49}
50
51// Expr::Cast(
52//   Expr::ScalarFunction(
53//     json_get(column, path),
54//     <data_type>
55//   )
56// )
57// =>
58// Expr::ScalarFunction(
59//   json_get(column, path, <data_type>)
60// )
61fn inject_type_from_cast_expr(cast: Cast) -> Result<Transformed<Expr>> {
62    let Cast { expr, field } = cast;
63    let mut data_type = field.data_type().clone();
64
65    let mut json_get = match *expr {
66        Expr::ScalarFunction(f)
67            if f.func.name().eq_ignore_ascii_case(JsonGetWithType::NAME) && f.args.len() == 2 =>
68        {
69            f
70        }
71        expr => {
72            return Ok(Transformed::no(Expr::Cast(Cast {
73                expr: Box::new(expr),
74                field,
75            })));
76        }
77    };
78
79    if data_type.is_string() {
80        data_type = DataType::Utf8View;
81    }
82    let with_type = ScalarValue::try_new_null(&data_type).map(|x| Expr::Literal(x, None))?;
83    json_get.args.push(with_type);
84    Ok(Transformed::yes(Expr::ScalarFunction(json_get)))
85}
86
87// Expr::ScalarFunction(
88//   arrow_cast(
89//     Expr::ScalarFunction(
90//       json_get(column, path),
91//     ),
92//     <data_type>
93//   )
94// )
95// =>
96// Expr::ScalarFunction(
97//   json_get(column, path, <data_type>)
98// )
99fn inject_type_from_cast_func(cast: ScalarFunction) -> Result<Transformed<Expr>> {
100    let ScalarFunction { func, args } = cast;
101
102    // Check if this is an Arrow cast function
103    // The function name might be "arrow_cast" or similar
104    let func_name = func.name().to_ascii_lowercase();
105    if !func_name.contains("arrow_cast") {
106        let original = Expr::ScalarFunction(ScalarFunction { func, args });
107        return Ok(Transformed::no(original));
108    }
109
110    // Arrow cast function should have exactly 2 arguments:
111    // 1. The expression to cast (could be json_get)
112    // 2. The target type as a string literal
113    if args.len() != 2 {
114        let original = Expr::ScalarFunction(ScalarFunction { func, args });
115        return Ok(Transformed::no(original));
116    }
117    let [arg0, arg1] = args.try_into().unwrap_or_else(|_| unreachable!());
118
119    let Some(with_type) = arg1
120        .as_literal()
121        .and_then(|x| x.try_as_str())
122        .flatten()
123        .and_then(parse_data_type_from_string)
124    else {
125        let original = Expr::ScalarFunction(ScalarFunction {
126            func,
127            args: vec![arg0, arg1],
128        });
129        return Ok(Transformed::no(original));
130    };
131
132    let mut json_get = match arg0 {
133        Expr::ScalarFunction(f)
134            if f.func.name().eq_ignore_ascii_case(JsonGetWithType::NAME) && f.args.len() == 2 =>
135        {
136            f
137        }
138        arg0 => {
139            let original = Expr::ScalarFunction(ScalarFunction {
140                func,
141                args: vec![arg0, arg1],
142            });
143            return Ok(Transformed::no(original));
144        }
145    };
146
147    let with_type = ScalarValue::try_new_null(&with_type).map(|x| Expr::Literal(x, None))?;
148    json_get.args.push(with_type);
149
150    let rewritten = Expr::ScalarFunction(json_get);
151    Ok(Transformed::yes(rewritten))
152}
153
154// Parse a data type from a string representation
155fn parse_data_type_from_string(type_str: &str) -> Option<DataType> {
156    match type_str.to_lowercase().as_str() {
157        "int8" | "tinyint" => Some(DataType::Int8),
158        "int16" | "smallint" => Some(DataType::Int16),
159        "int32" | "integer" => Some(DataType::Int32),
160        "int64" | "bigint" => Some(DataType::Int64),
161        "uint8" => Some(DataType::UInt8),
162        "uint16" => Some(DataType::UInt16),
163        "uint32" => Some(DataType::UInt32),
164        "uint64" => Some(DataType::UInt64),
165        "float32" | "real" => Some(DataType::Float32),
166        "float64" | "double" => Some(DataType::Float64),
167        "boolean" | "bool" => Some(DataType::Boolean),
168        "string" | "text" | "varchar" => Some(DataType::Utf8),
169        "timestamp" => Some(DataType::Timestamp(TimeUnit::Microsecond, None)),
170        "date" => Some(DataType::Date32),
171        _ => None,
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use arrow_schema::DataType;
178    use datafusion::common::DFSchema;
179    use datafusion::common::config::ConfigOptions;
180    use datafusion::logical_expr::expr::Cast;
181    use datafusion::scalar::ScalarValue;
182    use datafusion_expr::Expr;
183    use datafusion_expr::expr::ScalarFunction;
184
185    use super::*;
186
187    #[test]
188    fn test_rewrite_regular_cast() {
189        let rewriter = JsonGetRewriter;
190        let schema = DFSchema::empty();
191        let config = ConfigOptions::new();
192
193        // Create a json_get function
194        let json_expr = Expr::ScalarFunction(ScalarFunction {
195            func: JsonGetWithType::udf(),
196            args: vec![
197                Expr::Literal(ScalarValue::Utf8(Some("{\"a\":1}".to_string())), None),
198                Expr::Literal(ScalarValue::Utf8(Some("$.a".to_string())), None),
199            ],
200        });
201
202        // Create a cast expression: json_get(...)::int8
203        let cast_expr = Expr::Cast(Cast::new(Box::new(json_expr), DataType::Int8));
204
205        // Apply the rewriter
206        let result = rewriter.rewrite(cast_expr, &schema, &config).unwrap();
207
208        // Verify the result is transformed
209        assert!(result.transformed);
210
211        // Verify the result is a ScalarFunction
212        match result.data {
213            Expr::ScalarFunction(func) => {
214                // Should have 3 arguments now (original 2 + null cast)
215                assert_eq!(func.args.len(), 3);
216
217                // First argument should be the original json
218                match &func.args[0] {
219                    Expr::Literal(ScalarValue::Utf8(Some(json)), _) => {
220                        assert_eq!(json, "{\"a\":1}");
221                    }
222                    _ => panic!("First argument should be a string literal"),
223                }
224
225                // Second argument should be the path
226                match &func.args[1] {
227                    Expr::Literal(ScalarValue::Utf8(Some(path)), _) => {
228                        assert_eq!(path, "$.a");
229                    }
230                    _ => panic!("Second argument should be a string literal"),
231                }
232
233                // Third argument should be a null cast to Int8
234                match &func.args[2] {
235                    Expr::Literal(value, _) => {
236                        assert_eq!(value.data_type(), DataType::Int8);
237                    }
238                    _ => panic!("Third argument should be a cast expression"),
239                }
240            }
241            _ => panic!("Result should be a ScalarFunction"),
242        }
243    }
244
245    #[test]
246    fn test_rewrite_arrow_cast_function() {
247        let rewriter = JsonGetRewriter;
248        let schema = DFSchema::empty();
249        let config = ConfigOptions::new();
250
251        // Create a parse_json function
252        let parse_json_expr = Expr::ScalarFunction(ScalarFunction {
253            func: Arc::new(crate::scalars::udf::create_udf(Arc::new(
254                crate::scalars::json::ParseJsonFunction::default(),
255            ))),
256            args: vec![Expr::Literal(
257                ScalarValue::Utf8(Some("{\"a\":1}".to_string())),
258                None,
259            )],
260        });
261
262        // Create a json_get function
263        let json_get_expr = Expr::ScalarFunction(ScalarFunction {
264            func: JsonGetWithType::udf(),
265            args: vec![
266                parse_json_expr,
267                Expr::Literal(ScalarValue::Utf8(Some("a".to_string())), None),
268            ],
269        });
270
271        // Create an arrow cast function: cast(json_get(...), 'Int64')
272        // Note: ArrowCastFunc doesn't exist in this codebase, so this test uses a simple cast instead
273        let arrow_cast_expr = Expr::Cast(Cast::new(Box::new(json_get_expr), DataType::Int64));
274
275        // Apply the rewriter
276        let result = rewriter.rewrite(arrow_cast_expr, &schema, &config).unwrap();
277
278        // Verify the result is transformed
279        assert!(result.transformed);
280
281        // Verify the result is a ScalarFunction (json_get_with_type)
282        match result.data {
283            Expr::ScalarFunction(func) => {
284                // Should have 3 arguments now (original 2 + null cast)
285                assert_eq!(func.args.len(), 3);
286
287                // First argument should be the original parse_json function
288                match &func.args[0] {
289                    Expr::ScalarFunction(parse_func) => {
290                        // Verify it's a parse_json function with the right argument
291                        assert!(
292                            parse_func
293                                .func
294                                .name()
295                                .to_ascii_lowercase()
296                                .contains("parse_json")
297                        );
298                        assert_eq!(parse_func.args.len(), 1);
299                        match &parse_func.args[0] {
300                            Expr::Literal(ScalarValue::Utf8(Some(json)), _) => {
301                                assert_eq!(json, "{\"a\":1}");
302                            }
303                            _ => panic!("Parse json argument should be a string literal"),
304                        }
305                    }
306                    _ => panic!("First argument should be a parse_json function"),
307                }
308
309                // Second argument should be the path
310                match &func.args[1] {
311                    Expr::Literal(ScalarValue::Utf8(Some(path)), _) => {
312                        assert_eq!(path, "a");
313                    }
314                    _ => panic!("Second argument should be a string literal"),
315                }
316
317                // Third argument should be a null cast to Int64
318                match &func.args[2] {
319                    Expr::Literal(value, _) => {
320                        assert_eq!(value.data_type(), DataType::Int64);
321                    }
322                    _ => panic!("Third argument should be a cast expression"),
323                }
324            }
325            _ => panic!("Result should be a ScalarFunction"),
326        }
327    }
328
329    #[test]
330    fn test_no_rewrite_for_other_functions() {
331        let rewriter = JsonGetRewriter;
332        let schema = DFSchema::empty();
333        let config = ConfigOptions::new();
334
335        // Create a non-json function
336        let other_func = Expr::ScalarFunction(ScalarFunction {
337            func: Arc::new(crate::scalars::udf::create_udf(Arc::new(
338                crate::scalars::test::TestAndFunction::default(),
339            ))),
340            args: vec![Expr::Literal(ScalarValue::Int64(Some(4)), None)],
341        });
342
343        // Apply the rewriter
344        let result = rewriter.rewrite(other_func, &schema, &config).unwrap();
345
346        // Verify the result is not transformed
347        assert!(!result.transformed);
348    }
349
350    #[test]
351    fn test_no_rewrite_for_non_cast_functions() {
352        let rewriter = JsonGetRewriter;
353        let schema = DFSchema::empty();
354        let config = ConfigOptions::new();
355
356        // Create a scalar function that doesn't contain "cast"
357        let other_func = Expr::ScalarFunction(ScalarFunction {
358            func: Arc::new(crate::scalars::udf::create_udf(Arc::new(
359                crate::scalars::test::TestAndFunction::default(),
360            ))),
361            args: vec![
362                Expr::ScalarFunction(ScalarFunction {
363                    func: JsonGetWithType::udf(),
364                    args: vec![
365                        Expr::Literal(ScalarValue::Utf8(Some("{\"a\":1}".to_string())), None),
366                        Expr::Literal(ScalarValue::Utf8(Some("$.a".to_string())), None),
367                    ],
368                }),
369                Expr::Literal(ScalarValue::Utf8(Some("Int64".to_string())), None),
370            ],
371        });
372
373        // Apply the rewriter
374        let result = rewriter.rewrite(other_func, &schema, &config).unwrap();
375
376        // Verify the result is not transformed
377        assert!(!result.transformed);
378    }
379}