Skip to main content

query/datafusion/
json_expr_planner.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
15use std::sync::Arc;
16
17use arrow_schema::Field;
18use arrow_schema::extension::ExtensionType;
19use common_function::scalars::json::json_get::{JsonGetWithType, parse_json_get_path};
20use datafusion_common::arrow::datatypes::DataType;
21use datafusion_common::{
22    Column, DFSchema, DataFusionError, ExprSchema, Result, ScalarValue, TableReference,
23    plan_datafusion_err,
24};
25use datafusion_expr::expr::{BinaryExpr, ScalarFunction};
26use datafusion_expr::planner::{
27    ExprPlanner, PlannerResult, RawAggregateExpr, RawBinaryExpr, RawFieldAccessExpr, RawScalarExpr,
28    RawWindowExpr,
29};
30use datafusion_expr::type_coercion::functions::{UDFCoercionExt, fields_with_udf};
31use datafusion_expr::{Expr, ExprSchemable, GetFieldAccess, Operator, WindowFunctionDefinition};
32use datatypes::extension::json::{
33    Json2ExtensionType, is_any_json_extension_type, is_json2_extension_type,
34    parse_legacy_json2_settings,
35};
36use datatypes::types::json_type::JsonNativeType;
37use jsonb::jsonpath::Path;
38use sqlparser::ast::BinaryOperator;
39
40/// Rewrites JSON-aware SQL expressions into DataFusion expressions.
41///
42/// This planner handles the following cases:
43/// - Rewrites compound identifiers on JSON extension columns into `json_get` function.
44///   For example, `select a.b.c` => `select json_get(a, '$.b.c')`.
45/// - Extends a JSON path with list indexes and fields following an index.
46///   For example, `select a.b[0].c` => `select json_get(a, '$.b[0].c')`.
47/// - Applies JSON2 path type hints to both compound identifiers and explicit `json_get` calls
48///   before inferring types from their enclosing expressions.
49/// - Pushes an "expected type" argument into the `json_get` function when it participates in a
50///   binary operator. So that `json_get` knows the wanted data type when dealing with variant
51///   JSON values.
52///   For example, `select json_get(a, "b.c") + 1` => `select json_get(a, "b.c", NULL::Int64) + 1`.
53/// - Infers the expected type from scalar, aggregate, and window function signatures.
54///   For example, `select abs(a.b.c)` => `select abs(json_get(a, '$.b.c', NULL::Float64))`.
55#[derive(Debug)]
56pub(crate) struct JsonExprPlanner;
57
58impl ExprPlanner for JsonExprPlanner {
59    fn plan_binary_op(
60        &self,
61        expr: RawBinaryExpr,
62        schema: &DFSchema,
63    ) -> Result<PlannerResult<RawBinaryExpr>> {
64        let RawBinaryExpr {
65            op,
66            mut left,
67            mut right,
68        } = expr;
69
70        if !is_untyped_json_get(&left) && !is_untyped_json_get(&right) {
71            return Ok(PlannerResult::Original(RawBinaryExpr { op, left, right }));
72        }
73
74        let Some(expr_op) = parse_sql_op(&op) else {
75            return Ok(PlannerResult::Original(RawBinaryExpr { op, left, right }));
76        };
77
78        let left_type = left.get_type(schema)?;
79        let right_type = right.get_type(schema)?;
80        let left_changed = push_json_get_type_arg(&mut left, &right_type)?;
81        let right_changed = push_json_get_type_arg(&mut right, &left_type)?;
82        if left_changed || right_changed {
83            Ok(PlannerResult::Planned(Expr::BinaryExpr(BinaryExpr::new(
84                Box::new(left),
85                expr_op,
86                Box::new(right),
87            ))))
88        } else {
89            Ok(PlannerResult::Original(RawBinaryExpr { op, left, right }))
90        }
91    }
92
93    /// Extends the path of an untyped `json_get` with one field access.
94    ///
95    /// For `j.o.l[1].inner.l[2]`, `plan_compound_identifier` first produces
96    /// `json_get(j, '$.o.l')`. DataFusion then calls this method successively
97    /// with a list index, two named fields, and another list index, producing
98    /// the final path `$.o.l[1].inner.l[2]`.
99    fn plan_field_access(
100        &self,
101        mut expr: RawFieldAccessExpr,
102        _schema: &DFSchema,
103    ) -> Result<PlannerResult<RawFieldAccessExpr>> {
104        // See `normalize_field_access_after_subscript` for the reason why we construct the
105        // "suffix" like this.
106        let suffix = match &expr.field_access {
107            GetFieldAccess::ListIndex { key } => {
108                // DataFusion parses ordinary integer literals within the i64 range as Int64.
109                let Expr::Literal(ScalarValue::Int64(Some(index)), _) = key.as_ref() else {
110                    return Ok(PlannerResult::Original(expr));
111                };
112                format!("[{index}]")
113            }
114            GetFieldAccess::NamedStructField { name } => {
115                let Some(name) = name.try_as_str().flatten() else {
116                    return Ok(PlannerResult::Original(expr));
117                };
118                format!(".{}", json_path_field(name)?)
119            }
120            GetFieldAccess::ListRange { .. } => return Ok(PlannerResult::Original(expr)),
121        };
122        let Some(json_get) = extract_untyped_json_get(&mut expr.expr) else {
123            return Ok(PlannerResult::Original(expr));
124        };
125        let Some(Expr::Literal(ScalarValue::Utf8(Some(path)), _)) = json_get.args.get_mut(1) else {
126            return Ok(PlannerResult::Original(expr));
127        };
128
129        path.push_str(&suffix);
130        Ok(PlannerResult::Planned(expr.expr))
131    }
132
133    fn plan_compound_identifier(
134        &self,
135        field: &Field,
136        qualifier: Option<&TableReference>,
137        nested_names: &[String],
138    ) -> Result<PlannerResult<Vec<Expr>>> {
139        if !is_any_json_extension_type(field)
140            // SQL-created JSONB columns use Binary with greptime:type=Json, without an Arrow extension.
141            && field
142                .metadata()
143                .get(datatypes::schema::TYPE_KEY)
144                .is_none_or(|value| value != "Json")
145        {
146            return Ok(PlannerResult::Original(Vec::new()));
147        }
148
149        let mut path = "$".to_string();
150        for name in nested_names {
151            path.push('.');
152            path.push_str(&json_path_field(name)?);
153        }
154
155        let mut args = vec![
156            Expr::Column(Column::from((qualifier, field))),
157            Expr::Literal(ScalarValue::Utf8(Some(path)), None),
158        ];
159        apply_json_type_hint(field, nested_names, &mut args)?;
160
161        Ok(PlannerResult::Planned(Expr::ScalarFunction(
162            ScalarFunction::new_udf(JsonGetWithType::udf(), args),
163        )))
164    }
165
166    /// Rewrites JSON2 arguments without taking over the final function planning.
167    ///
168    /// `Original` carries the possibly modified raw expression to subsequent planners and then
169    /// DataFusion's default function construction. Returning `Planned` would short-circuit both.
170    fn plan_scalar(
171        &self,
172        mut expr: RawScalarExpr,
173        schema: &DFSchema,
174    ) -> Result<PlannerResult<RawScalarExpr>> {
175        if expr.func.name().eq_ignore_ascii_case(JsonGetWithType::NAME) && expr.args.len() == 2 {
176            let field = match &expr.args[0] {
177                // Resolving an unqualified column may require JOIN USING information unavailable
178                // in this schema. Skip hint injection if lookup fails and let DataFusion resolve
179                // the column or report the error later.
180                Expr::Column(column) => schema.field_from_column(column).ok().cloned(),
181                // Outer references carry their field metadata from the outer query's schema.
182                Expr::OuterReferenceColumn(field, _) => Some(Arc::clone(field)),
183                _ => None,
184            };
185            if let Some(field) = field
186                && let Some(path) = json_get_object_path(&expr.args[1])
187            {
188                apply_json_type_hint(&field, &path, &mut expr.args)?;
189            }
190        }
191        push_function_arg_types(expr.func.as_ref(), &mut expr.args)?;
192        Ok(PlannerResult::Original(expr))
193    }
194
195    /// Rewrites JSON2 arguments while preserving subsequent aggregate planning.
196    fn plan_aggregate(
197        &self,
198        mut expr: RawAggregateExpr,
199    ) -> Result<PlannerResult<RawAggregateExpr>> {
200        push_function_arg_types(expr.func.as_ref(), &mut expr.args)?;
201        Ok(PlannerResult::Original(expr))
202    }
203
204    /// Rewrites JSON2 arguments while preserving subsequent window planning.
205    fn plan_window(&self, mut expr: RawWindowExpr) -> Result<PlannerResult<RawWindowExpr>> {
206        match &expr.func_def {
207            WindowFunctionDefinition::AggregateUDF(func) => {
208                push_function_arg_types(func.as_ref(), &mut expr.args)?;
209            }
210            WindowFunctionDefinition::WindowUDF(func) => {
211                push_function_arg_types(func.as_ref(), &mut expr.args)?;
212            }
213        }
214        Ok(PlannerResult::Original(expr))
215    }
216}
217
218/// Sets the native read type for an exact hinted object path. Both SQL syntaxes use this before
219/// an enclosing expression can infer a type or push down a cast.
220fn apply_json_type_hint(field: &Field, path: &[String], args: &mut Vec<Expr>) -> Result<()> {
221    if !is_json2_extension_type(field) || args.len() != 2 {
222        return Ok(());
223    }
224    if let Some(json_type) = json_type_hint(field, path)? {
225        args.push(Expr::Literal(
226            ScalarValue::try_new_null(&json_type.as_arrow_type())?,
227            None,
228        ));
229    }
230    Ok(())
231}
232
233/// Resolves `json_get`'s second argument expression (the path) to object field names for type hint
234/// lookup. For example, the string literal `'$.user.age'` resolves to `["user", "age"]`.
235///
236/// Returns `None` for non-string literals, non-literal expressions, invalid JSONPaths, or paths
237/// containing array indexes, wildcards, or filters.
238/// Returning `None` only skips hint injection; the original `json_get` expression is preserved.
239fn json_get_object_path(expr: &Expr) -> Option<Vec<String>> {
240    let path = expr.as_literal()?.try_as_str().flatten()?;
241    // Invalid paths skip hint lookup here. Later planning still validates the path and reports
242    // the error, preserving the existing JSONPath error behavior.
243    let json_path = parse_json_get_path(path).ok()?;
244    let mut names = Vec::new();
245    for segment in json_path.paths {
246        match segment {
247            Path::Root => {}
248            Path::DotField(name) | Path::ColonField(name) | Path::ObjectField(name) => {
249                names.push(name.into_owned());
250            }
251            // Array indexes, wildcards and filters do not identify a hinted object path.
252            _ => return None,
253        }
254    }
255    Some(names)
256}
257
258/// Returns the configured native type for an exact JSON2 object path.
259fn json_type_hint(field: &Field, path: &[String]) -> Result<Option<JsonNativeType>> {
260    let settings = if field.extension_type_name() == Some(Json2ExtensionType::NAME) {
261        let extension = field
262            .try_extension_type::<Json2ExtensionType>()
263            .map_err(|e| plan_datafusion_err!("invalid JSON2 extension metadata: {e}"))?;
264        Some(extension.metadata().json_settings().clone())
265    } else {
266        parse_legacy_json2_settings(field.metadata())
267            .map_err(|e| plan_datafusion_err!("invalid JSON2 extension metadata: {e}"))?
268    };
269
270    Ok(settings.and_then(|settings| {
271        settings
272            .type_hints()
273            .iter()
274            .find(|hint| hint.path == path)
275            .map(|hint| JsonNativeType::from(&hint.data_type))
276    }))
277}
278
279/// Quotes field names containing JSONPath punctuation, preserving literal keys.
280fn json_path_field(name: &str) -> Result<String> {
281    if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
282        Ok(name.to_string())
283    } else {
284        // Reuse serde_json's string escaping.
285        serde_json::to_string(name).map_err(|e| DataFusionError::External(Box::new(e)))
286    }
287}
288
289enum JsonGetTypeResolution {
290    Fallback,
291    Typed(Vec<(usize, DataType)>),
292}
293
294/// Infers static output types for untyped `json_get` arguments from a function signature.
295///
296/// DataFusion requires every expression to have one Arrow data type during planning. A JSON path
297/// may contain heterogeneous values across rows, but it cannot expose those values as different
298/// Arrow types in one result column. Preserving their runtime types would require a single
299/// Variant-like data type and Variant-aware functions instead. Maybe we can wait for
300/// https://github.com/apache/datafusion/issues/16116
301///
302/// This helper uses the function's coercion rules to select a supported output type, then appends
303/// a typed NULL argument to each relevant `json_get`. The typed argument makes `json_get` project
304/// compatible JSON values to that type and return NULL for incompatible values. Functions that
305/// accept json_get's default `Utf8View` output keep the two-argument form so later rewrites can
306/// still push down an outer cast.
307fn push_function_arg_types<F>(func: &F, args: &mut [Expr]) -> Result<()>
308where
309    F: UDFCoercionExt,
310{
311    if !args.iter().any(is_untyped_json_get) {
312        return Ok(());
313    }
314
315    let fields = args.iter().map(function_arg_field).collect::<Vec<_>>();
316    match infer_json_get_types(func, args, &fields) {
317        JsonGetTypeResolution::Fallback => {
318            let Some(data_type) = fallback_json_get_type(func, args, &fields) else {
319                return Ok(());
320            };
321            for arg in args.iter_mut() {
322                if is_untyped_json_get(arg) {
323                    let _ = push_json_get_type_arg(arg, &data_type)?;
324                }
325            }
326        }
327        JsonGetTypeResolution::Typed(types) => {
328            for (index, data_type) in types {
329                let _ = push_json_get_type_arg(&mut args[index], &data_type)?;
330            }
331        }
332    }
333    Ok(())
334}
335
336fn infer_json_get_types<F>(func: &F, args: &[Expr], fields: &[Arc<Field>]) -> JsonGetTypeResolution
337where
338    F: UDFCoercionExt,
339{
340    // Only untyped json_get arguments use Null placeholders; preserve every other known argument
341    // type. fields_with_udf performs contextual coercion rather than reverse inference from a
342    // signature alone. Numeric signatures may preserve all-Null inputs, while Comparable
343    // signatures may default them to Utf8. For example, retaining the Float64 peer in
344    // coalesce(json_get(...), 1.0) lets DataFusion resolve json_get to Float64 instead of Utf8.
345    //
346    // This is a best-effort probe: a failure does not mean the actual function call is invalid, so
347    // try concrete JSON types before leaving final validation to DataFusion's default planner.
348    let Ok(coerced) = fields_with_udf(fields, func) else {
349        return JsonGetTypeResolution::Fallback;
350    };
351
352    let mut inferred_types = Vec::with_capacity(coerced.len());
353    for (index, (arg, field)) in args.iter().zip(coerced).enumerate() {
354        if !is_untyped_json_get(arg) || field.data_type().is_null() {
355            continue;
356        }
357        let Some(data_type) = json_get_output_type(field.data_type()) else {
358            return JsonGetTypeResolution::Fallback;
359        };
360        inferred_types.push((index, data_type));
361    }
362    if inferred_types.is_empty() {
363        JsonGetTypeResolution::Fallback
364    } else {
365        JsonGetTypeResolution::Typed(inferred_types)
366    }
367}
368
369fn fallback_json_get_type<F>(func: &F, args: &[Expr], fields: &[Arc<Field>]) -> Option<DataType>
370where
371    F: UDFCoercionExt,
372{
373    // Prefer json_get's default Utf8View type. If the function rejects strings but accepts numeric
374    // values, prefer Float64 so both integers and fractions remain usable.
375    let mut candidate_fields = fields.to_vec();
376    for data_type in [
377        DataType::Utf8View,
378        DataType::Float64,
379        DataType::Int64,
380        DataType::Boolean,
381    ] {
382        for (index, arg) in args.iter().enumerate() {
383            if is_untyped_json_get(arg) {
384                candidate_fields[index] = Arc::new(
385                    fields[index]
386                        .as_ref()
387                        .clone()
388                        .with_data_type(data_type.clone()),
389                );
390            }
391        }
392        if fields_with_udf(&candidate_fields, func).is_ok() {
393            return Some(data_type);
394        }
395    }
396    None
397}
398
399fn function_arg_field(expr: &Expr) -> Arc<Field> {
400    let data_type = if is_untyped_json_get(expr) {
401        DataType::Null
402    } else if let Some(data_type) = extract_json_get_type(expr) {
403        data_type
404    } else {
405        // Treat unresolved expressions as untyped NULL. This lets signatures such as `power`
406        // infer a JSON type, while functions such as `coalesce` can leave it untyped for default
407        // planning. This is only best-effort: overloaded or user-defined functions may select a
408        // different signature for NULL than for the expression's actual type.
409        // TODO(LFC): Use the input schema once DataFusion passes it to ExprPlanner::plan_*().
410        expr.get_type(&DFSchema::empty()).unwrap_or(DataType::Null)
411    };
412    Arc::new(Field::new("", data_type, true))
413}
414
415fn json_get_output_type(data_type: &DataType) -> Option<DataType> {
416    let output_type = match data_type {
417        DataType::Boolean => DataType::Boolean,
418        data_type if data_type.is_integer() => DataType::Int64,
419        data_type if data_type.is_floating() => DataType::Float64,
420        DataType::Decimal128(_, _) | DataType::Decimal256(_, _) => DataType::Float64,
421        data_type if data_type.is_string() => DataType::Utf8View,
422        _ => return None,
423    };
424    Some(output_type)
425}
426
427macro_rules! is_untyped_json_get_func {
428    ($func:expr) => {
429        $func
430            .func
431            .name()
432            .eq_ignore_ascii_case(JsonGetWithType::NAME)
433            && $func.args.len() == 2
434    };
435}
436
437macro_rules! is_typed_json_get_func {
438    ($func:expr) => {
439        $func
440            .func
441            .name()
442            .eq_ignore_ascii_case(JsonGetWithType::NAME)
443            && $func.args.len() == 3
444    };
445}
446
447fn extract_untyped_json_get(expr: &mut Expr) -> Option<&mut ScalarFunction> {
448    match expr {
449        Expr::ScalarFunction(f) if is_untyped_json_get_func!(f) => Some(f),
450        _ => None,
451    }
452}
453
454fn extract_json_get_type(expr: &Expr) -> Option<DataType> {
455    match expr {
456        Expr::ScalarFunction(f) if is_typed_json_get_func!(f) => f
457            .args
458            .get(2)
459            .and_then(|x| x.as_literal())
460            .map(|x| x.data_type()),
461        _ => None,
462    }
463}
464
465fn is_untyped_json_get(expr: &Expr) -> bool {
466    matches!(
467        expr,
468        Expr::ScalarFunction(f) if is_untyped_json_get_func!(f)
469    )
470}
471
472fn push_json_get_type_arg(expr: &mut Expr, data_type: &DataType) -> Result<bool> {
473    let Some(json_get) = extract_untyped_json_get(expr) else {
474        return Ok(false);
475    };
476
477    // The two-argument form already returns Utf8View. Keep it so JsonGetRewriter can still absorb
478    // a cast added by subsequent function coercion.
479    if data_type.is_string() {
480        return Ok(false);
481    }
482    let with_type = ScalarValue::try_new_null(data_type).map(|x| Expr::Literal(x, None))?;
483    json_get.args.push(with_type);
484    Ok(true)
485}
486
487fn parse_sql_op(op: &BinaryOperator) -> Option<Operator> {
488    match *op {
489        BinaryOperator::Plus => Some(Operator::Plus),
490        BinaryOperator::Minus => Some(Operator::Minus),
491        BinaryOperator::Multiply => Some(Operator::Multiply),
492        BinaryOperator::Divide => Some(Operator::Divide),
493        BinaryOperator::Modulo => Some(Operator::Modulo),
494        BinaryOperator::Gt => Some(Operator::Gt),
495        BinaryOperator::GtEq => Some(Operator::GtEq),
496        BinaryOperator::Lt => Some(Operator::Lt),
497        BinaryOperator::LtEq => Some(Operator::LtEq),
498        BinaryOperator::Eq => Some(Operator::Eq),
499        BinaryOperator::NotEq => Some(Operator::NotEq),
500        BinaryOperator::And => Some(Operator::And),
501        BinaryOperator::Or => Some(Operator::Or),
502        BinaryOperator::BitwiseAnd => Some(Operator::BitwiseAnd),
503        BinaryOperator::BitwiseOr => Some(Operator::BitwiseOr),
504        BinaryOperator::BitwiseXor => Some(Operator::BitwiseXor),
505        _ => None,
506    }
507}
508
509#[cfg(test)]
510mod tests {
511    use arrow_schema::Fields;
512    use datafusion::functions_aggregate::count::count_udaf;
513    use datafusion::functions_aggregate::sum::sum_udaf;
514    use datafusion_expr::WindowFrame;
515    use datafusion_functions::core::coalesce;
516    use datafusion_functions::math::{abs, power};
517    use datatypes::extension::json::{Json2ExtensionType, JsonExtensionType, JsonMetadata};
518    use datatypes::json::{JsonSettings, JsonTypeHint};
519    use datatypes::prelude::ConcreteDataType;
520    use std::collections::HashMap;
521
522    use super::*;
523
524    fn json_get_expr(base: Expr, path: &str) -> Expr {
525        let json_get = JsonGetWithType::udf();
526        Expr::ScalarFunction(ScalarFunction::new_udf(
527            json_get,
528            vec![
529                base,
530                Expr::Literal(ScalarValue::Utf8(Some(path.to_string())), None),
531            ],
532        ))
533    }
534
535    #[test]
536    fn test_plan_binary_op() -> Result<()> {
537        let planner = JsonExprPlanner;
538        let schema = DFSchema::from_unqualified_fields(
539            Fields::from(vec![Field::new("value", DataType::Int64, true)]),
540            Default::default(),
541        )?;
542
543        let planned = planner.plan_binary_op(
544            RawBinaryExpr {
545                op: BinaryOperator::Eq,
546                left: json_get_expr(
547                    Expr::Literal(ScalarValue::Binary(Some(b"{\"a\": 1}".to_vec())), None),
548                    "a",
549                ),
550                right: Expr::Column(Column::new_unqualified("value")),
551            },
552            &schema,
553        )?;
554
555        match planned {
556            PlannerResult::Planned(Expr::BinaryExpr(expr)) => {
557                assert_eq!(expr.op, Operator::Eq);
558
559                match expr.left.as_ref() {
560                    Expr::ScalarFunction(func) => {
561                        assert_eq!(func.func.name(), JsonGetWithType::NAME);
562                        assert_eq!(func.args.len(), 3);
563                        assert_eq!(func.args[2], Expr::Literal(ScalarValue::Int64(None), None));
564                    }
565                    other => panic!("expected json_get on left side, got {other:?}"),
566                }
567
568                assert_eq!(
569                    expr.right.as_ref(),
570                    &Expr::Column(Column::new_unqualified("value"))
571                );
572            }
573            other => panic!("expected planned binary expression, got {other:?}"),
574        }
575
576        let original = planner.plan_binary_op(
577            RawBinaryExpr {
578                op: BinaryOperator::StringConcat,
579                left: Expr::Column(Column::new_unqualified("value")),
580                right: Expr::Literal(ScalarValue::Utf8(Some("x".to_string())), None),
581            },
582            &schema,
583        )?;
584
585        match original {
586            PlannerResult::Original(expr) => {
587                assert!(matches!(expr.op, BinaryOperator::StringConcat));
588                assert_eq!(expr.left, Expr::Column(Column::new_unqualified("value")));
589                assert_eq!(
590                    expr.right,
591                    Expr::Literal(ScalarValue::Utf8(Some("x".to_string())), None)
592                );
593            }
594            other => panic!(
595                "expected original expression for unsupported operator, got {:?}",
596                other,
597            ),
598        }
599
600        Ok(())
601    }
602
603    #[test]
604    fn test_plan_list_index() -> Result<()> {
605        let planner = JsonExprPlanner;
606        let planned = planner.plan_field_access(
607            RawFieldAccessExpr {
608                field_access: GetFieldAccess::ListIndex {
609                    key: Box::new(Expr::Literal(ScalarValue::Int64(Some(0)), None)),
610                },
611                expr: json_get_expr(Expr::Column(Column::new_unqualified("j")), "list"),
612            },
613            &DFSchema::empty(),
614        )?;
615        let PlannerResult::Planned(Expr::ScalarFunction(func)) = planned else {
616            unreachable!()
617        };
618        assert_eq!(func.func.name(), JsonGetWithType::NAME);
619        assert_eq!(func.args.len(), 2);
620        assert_eq!(
621            func.args[1],
622            Expr::Literal(ScalarValue::Utf8(Some("list[0]".to_string())), None)
623        );
624        Ok(())
625    }
626
627    #[test]
628    fn test_plan_field_after_list_index() -> Result<()> {
629        let planner = JsonExprPlanner;
630        let planned = planner.plan_field_access(
631            RawFieldAccessExpr {
632                field_access: GetFieldAccess::NamedStructField {
633                    name: ScalarValue::Utf8(Some("a.b".to_string())),
634                },
635                expr: json_get_expr(Expr::Column(Column::new_unqualified("j")), "list[0]"),
636            },
637            &DFSchema::empty(),
638        )?;
639        let PlannerResult::Planned(Expr::ScalarFunction(func)) = planned else {
640            unreachable!()
641        };
642        assert_eq!(
643            func.args[1],
644            Expr::Literal(
645                ScalarValue::Utf8(Some(r#"list[0]."a.b""#.to_string())),
646                None
647            )
648        );
649        Ok(())
650    }
651
652    #[test]
653    fn test_plan_compound_identifier() -> Result<()> {
654        let planner = JsonExprPlanner;
655        let qualifier = TableReference::bare("events");
656        let nested_names = vec!["payload".to_string(), "cpu".to_string()];
657
658        for field in [
659            Field::new("labels", DataType::Struct(Fields::empty()), true)
660                .with_extension_type(Json2ExtensionType::default()),
661            Field::new("labels", DataType::Binary, true).with_extension_type(JsonExtensionType),
662            Field::new("labels", DataType::Binary, true).with_metadata(HashMap::from([(
663                datatypes::schema::TYPE_KEY.to_string(),
664                "Json".to_string(),
665            )])),
666        ] {
667            let planned =
668                planner.plan_compound_identifier(&field, Some(&qualifier), &nested_names)?;
669
670            match planned {
671                PlannerResult::Planned(Expr::ScalarFunction(func)) => {
672                    assert_eq!(func.func.name(), JsonGetWithType::NAME);
673                    assert_eq!(func.args.len(), 2);
674                    assert_eq!(
675                        func.args[0],
676                        Expr::Column(Column::new(Some(qualifier.clone()), "labels"))
677                    );
678                    assert_eq!(
679                        func.args[1],
680                        Expr::Literal(ScalarValue::Utf8(Some("$.payload.cpu".to_string())), None)
681                    );
682                }
683                other => panic!("expected json_get scalar function, got {other:?}"),
684            }
685
686            for (key, path) in [
687                ("http.status_code", r#"$."http.status_code""#),
688                ("a\"b", r#"$."a\"b""#),
689                ("a\\b", r#"$."a\\b""#),
690            ] {
691                let planned = planner.plan_compound_identifier(
692                    &field,
693                    Some(&qualifier),
694                    &[key.to_string()],
695                )?;
696                let PlannerResult::Planned(Expr::ScalarFunction(func)) = planned else {
697                    unreachable!()
698                };
699                assert_eq!(
700                    func.args[1],
701                    Expr::Literal(ScalarValue::Utf8(Some(path.to_string())), None)
702                );
703            }
704
705            let PlannerResult::Planned(Expr::ScalarFunction(func)) = planner
706                .plan_compound_identifier(
707                    &field,
708                    Some(&qualifier),
709                    &["resource".to_string(), "http.status_code".to_string()],
710                )?
711            else {
712                unreachable!()
713            };
714            assert_eq!(
715                func.args[1],
716                Expr::Literal(
717                    ScalarValue::Utf8(Some(r#"$.resource."http.status_code""#.to_string())),
718                    None
719                )
720            );
721        }
722
723        for data_type in [DataType::Utf8, DataType::Binary] {
724            let original = planner.plan_compound_identifier(
725                &Field::new("plain", data_type, true),
726                Some(&qualifier),
727                &nested_names,
728            )?;
729
730            match original {
731                PlannerResult::Original(exprs) => assert!(exprs.is_empty()),
732                other => panic!(
733                    "expected original empty result for non-json field, got {:?}",
734                    other,
735                ),
736            }
737        }
738
739        Ok(())
740    }
741
742    #[test]
743    fn test_plan_compound_identifier_applies_json2_type_hint() -> Result<()> {
744        let settings = JsonSettings::try_new(
745            vec![JsonTypeHint {
746                path: vec!["payload".to_string(), "cpu".to_string()],
747                data_type: ConcreteDataType::int64_datatype(),
748                inverted_index: false,
749                skipping_index: None,
750                fulltext_index: None,
751            }],
752            None,
753        )
754        .unwrap();
755        let field = Field::new("labels", DataType::Struct(Fields::empty()), true)
756            .with_extension_type(Json2ExtensionType::new(Arc::new(JsonMetadata::new(
757                settings,
758            ))));
759
760        let PlannerResult::Planned(Expr::ScalarFunction(func)) = JsonExprPlanner
761            .plan_compound_identifier(
762                &field,
763                Some(&TableReference::bare("events")),
764                &["payload".to_string(), "cpu".to_string()],
765            )?
766        else {
767            unreachable!()
768        };
769
770        assert_eq!(
771            Some(DataType::Int64),
772            extract_json_get_type(&Expr::ScalarFunction(func))
773        );
774        Ok(())
775    }
776
777    #[test]
778    fn test_plan_json_get_applies_type_hint() -> Result<()> {
779        let settings = JsonSettings::try_new(
780            vec![
781                JsonTypeHint {
782                    path: vec!["payload".to_string(), "cpu".to_string()],
783                    data_type: ConcreteDataType::int64_datatype(),
784                    inverted_index: false,
785                    skipping_index: None,
786                    fulltext_index: None,
787                },
788                JsonTypeHint {
789                    path: vec!["payload.cpu".to_string()],
790                    data_type: ConcreteDataType::string_datatype(),
791                    inverted_index: false,
792                    skipping_index: None,
793                    fulltext_index: None,
794                },
795            ],
796            None,
797        )
798        .unwrap();
799        let field = Field::new("j", DataType::Struct(Fields::empty()), true).with_extension_type(
800            Json2ExtensionType::new(Arc::new(JsonMetadata::new(settings))),
801        );
802        let relation = TableReference::bare("events");
803        let schema = DFSchema::new_with_metadata(
804            vec![
805                (Some(relation.clone()), Arc::new(field.clone())),
806                (
807                    Some(TableReference::bare("other")),
808                    Arc::new(Field::new("j", DataType::Binary, true)),
809                ),
810            ],
811            Default::default(),
812        )?;
813        let base = Expr::Column(Column::new(Some(relation.clone()), "j"));
814
815        for (path, names, expected) in [
816            ("payload.cpu", vec!["payload", "cpu"], Some(DataType::Int64)),
817            (
818                "$.payload.cpu",
819                vec!["payload", "cpu"],
820                Some(DataType::Int64),
821            ),
822            (
823                r#"$."payload.cpu""#,
824                vec!["payload.cpu"],
825                Some(DataType::Utf8View),
826            ),
827            ("missing", vec!["missing"], None),
828        ] {
829            let Expr::ScalarFunction(function) = json_get_expr(base.clone(), path) else {
830                unreachable!();
831            };
832            let PlannerResult::Original(scalar) = JsonExprPlanner.plan_scalar(
833                RawScalarExpr {
834                    func: function.func,
835                    args: function.args,
836                },
837                &schema,
838            )?
839            else {
840                unreachable!();
841            };
842            let direct = Expr::ScalarFunction(ScalarFunction::new_udf(scalar.func, scalar.args));
843            let names = names.into_iter().map(String::from).collect::<Vec<_>>();
844            let PlannerResult::Planned(dotted) =
845                JsonExprPlanner.plan_compound_identifier(&field, Some(&relation), &names)?
846            else {
847                unreachable!();
848            };
849            assert_eq!(expected, extract_json_get_type(&direct), "{path}");
850            assert_eq!(
851                extract_json_get_type(&dotted),
852                extract_json_get_type(&direct)
853            );
854
855            // Outer function inference must not replace a declared hint.
856            if expected.is_some() {
857                let PlannerResult::Original(outer) = JsonExprPlanner.plan_scalar(
858                    RawScalarExpr {
859                        func: coalesce(),
860                        args: vec![
861                            direct.clone(),
862                            Expr::Literal(ScalarValue::Float64(Some(1.0)), None),
863                        ],
864                    },
865                    &schema,
866                )?
867                else {
868                    unreachable!();
869                };
870                assert_eq!(direct, outer.args[0]);
871            }
872        }
873
874        // Non-object paths cannot match an object type hint. A different table's unhinted
875        // column must not inherit the same-named JSON2 column's hints either.
876        for (base, path) in [
877            (base.clone(), "$"),
878            (base.clone(), "$.payload.*"),
879            (base.clone(), "$.payload.cpu[0]"),
880            (base.clone(), "$.payload["),
881            (Expr::Column(Column::new(Some("other"), "j")), "payload.cpu"),
882        ] {
883            let Expr::ScalarFunction(function) = json_get_expr(base, path) else {
884                unreachable!();
885            };
886            let PlannerResult::Original(scalar) = JsonExprPlanner.plan_scalar(
887                RawScalarExpr {
888                    func: function.func,
889                    args: function.args,
890                },
891                &schema,
892            )?
893            else {
894                unreachable!();
895            };
896            assert_eq!(2, scalar.args.len(), "{path}");
897        }
898        Ok(())
899    }
900
901    #[test]
902    fn test_plan_functions() -> Result<()> {
903        let planner = JsonExprPlanner;
904        let json_get = || json_get_expr(Expr::Column(Column::new_unqualified("j")), "a.b");
905
906        let PlannerResult::Original(scalar) = planner.plan_scalar(
907            RawScalarExpr {
908                func: abs(),
909                args: vec![json_get()],
910            },
911            &DFSchema::empty(),
912        )?
913        else {
914            unreachable!();
915        };
916        assert_eq!(
917            Some(DataType::Float64),
918            extract_json_get_type(&scalar.args[0])
919        );
920
921        let PlannerResult::Original(scalar) = planner.plan_scalar(
922            RawScalarExpr {
923                func: power(),
924                args: vec![
925                    json_get(),
926                    Expr::Column(Column::new_unqualified("exponent")),
927                ],
928            },
929            &DFSchema::empty(),
930        )?
931        else {
932            unreachable!();
933        };
934        assert_eq!(
935            Some(DataType::Float64),
936            extract_json_get_type(&scalar.args[0])
937        );
938
939        let PlannerResult::Original(aggregate) = planner.plan_aggregate(RawAggregateExpr {
940            func: sum_udaf(),
941            args: vec![json_get()],
942            distinct: false,
943            filter: None,
944            order_by: vec![],
945            null_treatment: None,
946        })?
947        else {
948            unreachable!();
949        };
950        assert_eq!(
951            Some(DataType::Float64),
952            extract_json_get_type(&aggregate.args[0])
953        );
954
955        let PlannerResult::Original(count) = planner.plan_aggregate(RawAggregateExpr {
956            func: count_udaf(),
957            args: vec![json_get()],
958            distinct: false,
959            filter: None,
960            order_by: vec![],
961            null_treatment: None,
962        })?
963        else {
964            unreachable!();
965        };
966        assert_eq!(None, extract_json_get_type(&count.args[0]));
967
968        let PlannerResult::Original(window) = planner.plan_window(RawWindowExpr {
969            func_def: WindowFunctionDefinition::AggregateUDF(sum_udaf()),
970            args: vec![json_get()],
971            partition_by: vec![],
972            order_by: vec![],
973            window_frame: WindowFrame::new(None),
974            filter: None,
975            null_treatment: None,
976            distinct: false,
977        })?
978        else {
979            unreachable!();
980        };
981        assert_eq!(
982            Some(DataType::Float64),
983            extract_json_get_type(&window.args[0])
984        );
985        Ok(())
986    }
987
988    #[test]
989    fn test_plan_function_with_mixed_json_get_types() -> Result<()> {
990        let planner = JsonExprPlanner;
991        let json_get = || json_get_expr(Expr::Column(Column::new_unqualified("j")), "a.b");
992        let mut typed = json_get();
993        push_json_get_type_arg(&mut typed, &DataType::Float64)?;
994
995        let PlannerResult::Original(scalar) = planner.plan_scalar(
996            RawScalarExpr {
997                func: coalesce(),
998                args: vec![json_get(), typed],
999            },
1000            &DFSchema::empty(),
1001        )?
1002        else {
1003            unreachable!();
1004        };
1005        assert_eq!(
1006            Some(DataType::Float64),
1007            extract_json_get_type(&scalar.args[0])
1008        );
1009        assert_eq!(
1010            Some(DataType::Float64),
1011            extract_json_get_type(&scalar.args[1])
1012        );
1013        Ok(())
1014    }
1015}