Skip to main content

datafusion_sql/expr/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::ops::ControlFlow;
6use std::sync::Arc;
7
8use arrow::datatypes::{DataType, TimeUnit};
9use datafusion_expr::planner::{
10    PlannerResult, RawBinaryExpr, RawDictionaryExpr, RawFieldAccessExpr,
11};
12use sqlparser::ast::{
13    AccessExpr, BinaryOperator, CastFormat, CastKind, CeilFloorKind,
14    DataType as SQLDataType, DateTimeField, DictionaryField, Expr as SQLExpr,
15    ExprWithAlias as SQLExprWithAlias, JsonPath, JsonPathElem, MapEntry, Spanned,
16    StructField, Subscript, TrimWhereField, TypedString, Value, ValueWithSpan,
17};
18use sqlparser::ast::{Query, Visit, Visitor};
19
20use datafusion_common::{
21    DFSchema, Diagnostic, HashMap, Result, ScalarValue, Span, internal_datafusion_err,
22    internal_err, not_impl_err, plan_err,
23};
24
25use datafusion_expr::expr::ScalarFunction;
26use datafusion_expr::expr::SetQuantifier;
27use datafusion_expr::expr::{InList, WildcardOptions};
28use datafusion_expr::utils::{find_window_exprs, window_function_not_allowed_err};
29use datafusion_expr::{
30    Between, BinaryExpr, Cast, Expr, ExprSchemable, GetFieldAccess, Like, Literal,
31    Operator, TryCast, lit, when,
32};
33
34use crate::planner::{ContextProvider, PlannerContext, SqlToRel};
35use datafusion_functions_nested::expr_fn::{
36    array_has, array_max, array_min, array_position, cardinality,
37};
38
39mod binary_op;
40mod function;
41mod grouping_set;
42mod identifier;
43mod order_by;
44mod subquery;
45mod substring;
46mod unary_op;
47mod value;
48
49/// Returns `None` if `expr` is not a NULL literal, and `Some(span)` where
50/// `span` is the literal's span, if it has one.
51#[expect(
52    clippy::option_option,
53    reason = "The two levels mean different things, see above"
54)]
55fn null_value_span(expr: &SQLExpr) -> Option<Option<Span>> {
56    if let SQLExpr::Value(ValueWithSpan {
57        value: Value::Null,
58        span,
59    }) = expr
60    {
61        Some(Span::try_from_sqlparser_span(*span))
62    } else {
63        None
64    }
65}
66
67fn null_equality_warning(expr: &SQLExpr) -> Option<Diagnostic> {
68    let SQLExpr::BinaryOp { left, op, right } = expr else {
69        return None;
70    };
71
72    let null_span = null_value_span(left).or_else(|| null_value_span(right))?;
73
74    let (message, help) = match op {
75        BinaryOperator::Eq => (
76            "comparison with NULL using `=` always evaluates to NULL",
77            "use `IS NULL` to check for NULL values",
78        ),
79        BinaryOperator::NotEq => (
80            "comparison with NULL using `<>` always evaluates to NULL",
81            "use `IS NOT NULL` to check for non-NULL values",
82        ),
83        _ => return None,
84    };
85
86    Some(
87        Diagnostic::new_warning(message, Span::try_from_sqlparser_span(expr.span()))
88            .with_help(help, null_span),
89    )
90}
91
92struct NullEqualityPredicateVisitor<'a, 'b, S: ContextProvider> {
93    sql_to_rel: &'a SqlToRel<'b, S>,
94    subquery_depth: usize,
95}
96
97impl<'a, 'b, S: ContextProvider> NullEqualityPredicateVisitor<'a, 'b, S> {
98    fn new(sql_to_rel: &'a SqlToRel<'b, S>) -> Self {
99        Self {
100            sql_to_rel,
101            subquery_depth: 0,
102        }
103    }
104}
105
106impl<S: ContextProvider> Visitor for NullEqualityPredicateVisitor<'_, '_, S> {
107    type Break = ();
108
109    fn pre_visit_query(&mut self, _query: &Query) -> ControlFlow<Self::Break> {
110        self.subquery_depth += 1;
111        ControlFlow::Continue(())
112    }
113
114    fn post_visit_query(&mut self, _query: &Query) -> ControlFlow<Self::Break> {
115        self.subquery_depth -= 1;
116        ControlFlow::Continue(())
117    }
118
119    fn pre_visit_expr(&mut self, expr: &SQLExpr) -> ControlFlow<Self::Break> {
120        if self.subquery_depth == 0
121            && let Some(warning) = null_equality_warning(expr)
122        {
123            self.sql_to_rel.add_warning(warning);
124        }
125        ControlFlow::Continue(())
126    }
127}
128
129/// Finds the location of the first window function call in a SQL expression.
130/// An identifier that is an alias of a `SELECT` expression containing a window
131/// function call counts as well, since aliases are resolved before the window
132/// function check (`HAVING total > 0` where `total` is `sum(x) OVER ()`).
133/// Subqueries are skipped: window functions are legal there.
134struct WindowFunctionSpanVisitor<'a, 'b, S: ContextProvider> {
135    sql_to_rel: &'a SqlToRel<'b, S>,
136    aliases: &'a HashMap<String, Expr>,
137    subquery_depth: usize,
138    span: Option<sqlparser::tokenizer::Span>,
139}
140
141impl<S: ContextProvider> Visitor for WindowFunctionSpanVisitor<'_, '_, S> {
142    type Break = ();
143
144    fn pre_visit_query(&mut self, _query: &Query) -> ControlFlow<Self::Break> {
145        self.subquery_depth += 1;
146        ControlFlow::Continue(())
147    }
148
149    fn post_visit_query(&mut self, _query: &Query) -> ControlFlow<Self::Break> {
150        self.subquery_depth -= 1;
151        ControlFlow::Continue(())
152    }
153
154    fn pre_visit_expr(&mut self, expr: &SQLExpr) -> ControlFlow<Self::Break> {
155        if self.subquery_depth > 0 {
156            return ControlFlow::Continue(());
157        }
158        let found = match expr {
159            SQLExpr::Function(function) => function.over.is_some(),
160            SQLExpr::Identifier(ident) => {
161                let name = self.sql_to_rel.ident_normalizer.normalize(ident.clone());
162                self.aliases
163                    .get(&name)
164                    .is_some_and(|aliased| !find_window_exprs([aliased]).is_empty())
165            }
166            _ => false,
167        };
168        if found {
169            self.span = Some(expr.span());
170            ControlFlow::Break(())
171        } else {
172            ControlFlow::Continue(())
173        }
174    }
175}
176
177/// Help for a window function in `WHERE` or `HAVING`: `QUALIFY` is the clause
178/// that filters on window function results.
179pub(crate) const QUALIFY_HELP: &str = "Move the condition that uses this window function to a QUALIFY clause, which is evaluated after window functions are computed";
180
181/// Returns an error if `expr`, planned from a clause where window functions
182/// cannot be evaluated, contains a window function call. `clause` names it in
183/// the message, `help` says how to rewrite the query and `span` is the location
184/// of the call in the SQL text, see [`SqlToRel::window_function_span`].
185///
186/// The physical planner rejects such expressions in every position, but
187/// without a span or a clause-specific hint. This check exists to give a
188/// better error for the common mistakes.
189pub(crate) fn reject_window_functions(
190    expr: &Expr,
191    clause: &str,
192    help: &str,
193    span: Option<Span>,
194) -> Result<()> {
195    match find_window_exprs([expr]).into_iter().next() {
196        None => Ok(()),
197        Some(window) => Err(window_function_not_allowed_err(&window, clause, span, help)),
198    }
199}
200
201impl<S: ContextProvider> SqlToRel<'_, S> {
202    pub(crate) fn warn_on_null_equality_predicate(&self, predicate: &SQLExpr) {
203        let mut visitor = NullEqualityPredicateVisitor::new(self);
204        let _ = predicate.visit(&mut visitor);
205    }
206
207    /// The location in the SQL text of the first window function call in
208    /// `expr`, or of the first identifier that is an alias (in `aliases`) of a
209    /// `SELECT` expression containing one. Falls back to the location of the
210    /// whole of `expr`, and returns `None` only if the parser recorded no
211    /// spans.
212    ///
213    /// Used to point the [`Diagnostic`] for a window function in `WHERE` or
214    /// `HAVING` at the offending call, which the planned [`Expr`] cannot do:
215    /// only columns carry spans there.
216    pub(crate) fn window_function_span(
217        &self,
218        expr: &SQLExpr,
219        aliases: &HashMap<String, Expr>,
220    ) -> Option<Span> {
221        let mut visitor = WindowFunctionSpanVisitor {
222            sql_to_rel: self,
223            aliases,
224            subquery_depth: 0,
225            span: None,
226        };
227        let _ = expr.visit(&mut visitor);
228        Span::try_from_sqlparser_span(visitor.span.unwrap_or_else(|| expr.span()))
229    }
230
231    pub(crate) fn sql_expr_to_logical_expr_with_alias(
232        &self,
233        sql: SQLExprWithAlias,
234        schema: &DFSchema,
235        planner_context: &mut PlannerContext,
236    ) -> Result<Expr> {
237        let mut expr =
238            self.sql_expr_to_logical_expr(sql.expr, schema, planner_context)?;
239        if let Some(alias) = sql.alias {
240            expr = expr.alias(alias.value);
241        }
242        Ok(expr)
243    }
244    pub(crate) fn sql_expr_to_logical_expr(
245        &self,
246        sql: SQLExpr,
247        schema: &DFSchema,
248        planner_context: &mut PlannerContext,
249    ) -> Result<Expr> {
250        enum StackEntry {
251            SQLExpr(Box<SQLExpr>),
252            Operator(BinaryOperator),
253        }
254
255        // Virtual stack machine to convert SQLExpr to Expr
256        // This allows visiting the expr tree in a depth-first manner which
257        // produces expressions in postfix notations, i.e. `a + b` => `a b +`.
258        // See https://github.com/apache/datafusion/issues/1444
259        let mut stack = vec![StackEntry::SQLExpr(Box::new(sql))];
260        let mut eval_stack = vec![];
261
262        while let Some(entry) = stack.pop() {
263            match entry {
264                StackEntry::SQLExpr(sql_expr) => {
265                    match *sql_expr {
266                        SQLExpr::BinaryOp { left, op, right } => {
267                            // Note the order that we push the entries to the stack
268                            // is important. We want to visit the left node first.
269                            stack.push(StackEntry::Operator(op));
270                            stack.push(StackEntry::SQLExpr(right));
271                            stack.push(StackEntry::SQLExpr(left));
272                        }
273                        _ => {
274                            let expr = self.sql_expr_to_logical_expr_internal(
275                                *sql_expr,
276                                schema,
277                                planner_context,
278                            )?;
279                            eval_stack.push(expr);
280                        }
281                    }
282                }
283                StackEntry::Operator(op) => {
284                    let right = eval_stack.pop().unwrap();
285                    let left = eval_stack.pop().unwrap();
286                    let expr = self.build_logical_expr(op, left, right, schema)?;
287                    eval_stack.push(expr);
288                }
289            }
290        }
291
292        assert_eq!(1, eval_stack.len());
293        let expr = eval_stack.pop().unwrap();
294        Ok(expr)
295    }
296
297    fn build_logical_expr(
298        &self,
299        op: BinaryOperator,
300        left: Expr,
301        right: Expr,
302        schema: &DFSchema,
303    ) -> Result<Expr> {
304        let binary_expr = RawBinaryExpr { op, left, right };
305        match self.try_plan_binary_op(binary_expr, schema)? {
306            PlannerResult::Planned(expr) => Ok(expr),
307            PlannerResult::Original(RawBinaryExpr { op, left, right }) => {
308                self.build_binary_expr(&op, left, right)
309            }
310        }
311    }
312
313    fn try_plan_binary_op(
314        &self,
315        mut binary_expr: RawBinaryExpr,
316        schema: &DFSchema,
317    ) -> Result<PlannerResult<RawBinaryExpr>> {
318        for planner in self.context_provider.get_expr_planners() {
319            match planner.plan_binary_op(binary_expr, schema)? {
320                PlannerResult::Planned(expr) => {
321                    return Ok(PlannerResult::Planned(expr));
322                }
323                PlannerResult::Original(expr) => {
324                    binary_expr = expr;
325                }
326            }
327        }
328        Ok(PlannerResult::Original(binary_expr))
329    }
330
331    pub fn sql_to_expr_with_alias(
332        &self,
333        sql: SQLExprWithAlias,
334        schema: &DFSchema,
335        planner_context: &mut PlannerContext,
336    ) -> Result<Expr> {
337        let mut expr =
338            self.sql_expr_to_logical_expr_with_alias(sql, schema, planner_context)?;
339        expr = self.rewrite_partial_qualifier(expr, schema);
340        self.validate_schema_satisfies_exprs(schema, &[expr.clone()])?;
341        let (expr, _) = expr.infer_placeholder_types(schema)?;
342        Ok(expr)
343    }
344
345    /// Generate a relational expression from a SQL expression
346    pub fn sql_to_expr(
347        &self,
348        sql: SQLExpr,
349        schema: &DFSchema,
350        planner_context: &mut PlannerContext,
351    ) -> Result<Expr> {
352        // The location of the original SQL expression in the source code
353        let mut expr = self.sql_expr_to_logical_expr(sql, schema, planner_context)?;
354        expr = self.rewrite_partial_qualifier(expr, schema);
355        self.validate_schema_satisfies_exprs(schema, std::slice::from_ref(&expr))?;
356        let (expr, _) = expr.infer_placeholder_types(schema)?;
357        Ok(expr)
358    }
359
360    /// Rewrite aliases which are not-complete (e.g. ones that only include only table qualifier in a schema.table qualified relation)
361    fn rewrite_partial_qualifier(&self, expr: Expr, schema: &DFSchema) -> Expr {
362        match expr {
363            Expr::Column(col) => match &col.relation {
364                Some(q) => {
365                    match schema.iter().find(|(qualifier, field)| match qualifier {
366                        Some(field_q) => {
367                            field.name() == &col.name
368                                && field_q.to_string().ends_with(&format!(".{q}"))
369                        }
370                        _ => false,
371                    }) {
372                        Some((qualifier, df_field)) => Expr::from((qualifier, df_field)),
373                        None => Expr::Column(col),
374                    }
375                }
376                None => Expr::Column(col),
377            },
378            _ => expr,
379        }
380    }
381
382    /// Internal implementation. Use
383    /// [`Self::sql_expr_to_logical_expr`] to plan exprs.
384    #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
385    fn sql_expr_to_logical_expr_internal(
386        &self,
387        sql: SQLExpr,
388        schema: &DFSchema,
389        planner_context: &mut PlannerContext,
390    ) -> Result<Expr> {
391        // NOTE: This function is called recursively, so each match arm body should be as
392        //       small as possible to decrease stack requirement.
393        //       Follow the common pattern of extracting into a separate function for
394        //       non-trivial arms. See https://github.com/apache/datafusion/pull/12384 for
395        //       more context.
396        match sql {
397            SQLExpr::Value(value) => {
398                self.parse_value(value.into(), planner_context.prepare_param_data_types())
399            }
400            SQLExpr::Extract { field, expr, .. } => {
401                let mut extract_args = vec![
402                    Expr::Literal(ScalarValue::from(format!("{field}")), None),
403                    self.sql_expr_to_logical_expr(*expr, schema, planner_context)?,
404                ];
405
406                for planner in self.context_provider.get_expr_planners() {
407                    match planner.plan_extract(extract_args)? {
408                        PlannerResult::Planned(expr) => return Ok(expr),
409                        PlannerResult::Original(args) => {
410                            extract_args = args;
411                        }
412                    }
413                }
414
415                not_impl_err!("Extract not supported by ExprPlanner: {extract_args:?}")
416            }
417
418            SQLExpr::Array(arr) => self.sql_array_literal(arr.elem, schema),
419            SQLExpr::Interval(interval) => self.sql_interval_to_expr(false, interval),
420            SQLExpr::Identifier(id) => {
421                self.sql_identifier_to_expr(id, schema, planner_context)
422            }
423
424            // <expr>["foo"], <expr>[4] or <expr>[4:5]
425            SQLExpr::CompoundFieldAccess { root, access_chain } => self
426                .sql_compound_field_access_to_expr(
427                    *root,
428                    access_chain,
429                    schema,
430                    planner_context,
431                ),
432
433            SQLExpr::CompoundIdentifier(ids) => {
434                self.sql_compound_identifier_to_expr(ids, schema, planner_context)
435            }
436
437            SQLExpr::Case {
438                operand,
439                conditions,
440                else_result,
441                case_token: _,
442                end_token: _,
443            } => self.sql_case_identifier_to_expr(
444                operand,
445                conditions,
446                else_result,
447                schema,
448                planner_context,
449            ),
450
451            SQLExpr::Cast {
452                kind: CastKind::Cast | CastKind::DoubleColon,
453                expr,
454                data_type,
455                format,
456            } => {
457                self.sql_cast_to_expr(*expr, &data_type, format, schema, planner_context)
458            }
459
460            SQLExpr::Cast {
461                kind: CastKind::TryCast | CastKind::SafeCast,
462                expr,
463                data_type,
464                format,
465            } => {
466                if let Some(format) = format {
467                    return not_impl_err!("CAST with format is not supported: {format}");
468                }
469
470                Ok(Expr::TryCast(TryCast::new_from_field(
471                    Box::new(self.sql_expr_to_logical_expr(
472                        *expr,
473                        schema,
474                        planner_context,
475                    )?),
476                    self.convert_data_type_to_field(&data_type)?,
477                )))
478            }
479
480            SQLExpr::TypedString(TypedString {
481                data_type,
482                value,
483                uses_odbc_syntax: _,
484            }) => {
485                let Some(value) = value.into_string() else {
486                    return plan_err!("Typed literal requires a string payload");
487                };
488
489                Ok(Expr::Cast(Cast::new_from_field(
490                    Box::new(lit(value)),
491                    self.convert_data_type_to_field(&data_type)?,
492                )))
493            }
494
495            SQLExpr::IsNull(expr) => Ok(Expr::IsNull(Box::new(
496                self.sql_expr_to_logical_expr(*expr, schema, planner_context)?,
497            ))),
498
499            SQLExpr::IsNotNull(expr) => Ok(Expr::IsNotNull(Box::new(
500                self.sql_expr_to_logical_expr(*expr, schema, planner_context)?,
501            ))),
502
503            SQLExpr::IsDistinctFrom(left, right) => {
504                Ok(Expr::BinaryExpr(BinaryExpr::new(
505                    Box::new(self.sql_expr_to_logical_expr(
506                        *left,
507                        schema,
508                        planner_context,
509                    )?),
510                    Operator::IsDistinctFrom,
511                    Box::new(self.sql_expr_to_logical_expr(
512                        *right,
513                        schema,
514                        planner_context,
515                    )?),
516                )))
517            }
518
519            SQLExpr::IsNotDistinctFrom(left, right) => {
520                Ok(Expr::BinaryExpr(BinaryExpr::new(
521                    Box::new(self.sql_expr_to_logical_expr(
522                        *left,
523                        schema,
524                        planner_context,
525                    )?),
526                    Operator::IsNotDistinctFrom,
527                    Box::new(self.sql_expr_to_logical_expr(
528                        *right,
529                        schema,
530                        planner_context,
531                    )?),
532                )))
533            }
534
535            SQLExpr::IsTrue(expr) => Ok(Expr::IsTrue(Box::new(
536                self.sql_expr_to_logical_expr(*expr, schema, planner_context)?,
537            ))),
538
539            SQLExpr::IsFalse(expr) => Ok(Expr::IsFalse(Box::new(
540                self.sql_expr_to_logical_expr(*expr, schema, planner_context)?,
541            ))),
542
543            SQLExpr::IsNotTrue(expr) => Ok(Expr::IsNotTrue(Box::new(
544                self.sql_expr_to_logical_expr(*expr, schema, planner_context)?,
545            ))),
546
547            SQLExpr::IsNotFalse(expr) => Ok(Expr::IsNotFalse(Box::new(
548                self.sql_expr_to_logical_expr(*expr, schema, planner_context)?,
549            ))),
550
551            SQLExpr::IsUnknown(expr) => Ok(Expr::IsUnknown(Box::new(
552                self.sql_expr_to_logical_expr(*expr, schema, planner_context)?,
553            ))),
554
555            SQLExpr::IsNotUnknown(expr) => Ok(Expr::IsNotUnknown(Box::new(
556                self.sql_expr_to_logical_expr(*expr, schema, planner_context)?,
557            ))),
558
559            SQLExpr::UnaryOp { op, expr } => {
560                self.parse_sql_unary_op(op, *expr, schema, planner_context)
561            }
562
563            SQLExpr::Between {
564                expr,
565                negated,
566                low,
567                high,
568            } => Ok(Expr::Between(Between::new(
569                Box::new(self.sql_expr_to_logical_expr(
570                    *expr,
571                    schema,
572                    planner_context,
573                )?),
574                negated,
575                Box::new(self.sql_expr_to_logical_expr(*low, schema, planner_context)?),
576                Box::new(self.sql_expr_to_logical_expr(
577                    *high,
578                    schema,
579                    planner_context,
580                )?),
581            ))),
582
583            SQLExpr::InList {
584                expr,
585                list,
586                negated,
587            } => self.sql_in_list_to_expr(*expr, list, negated, schema, planner_context),
588
589            SQLExpr::Like {
590                negated,
591                expr,
592                pattern,
593                escape_char,
594                any,
595            } => self.sql_like_to_expr(
596                negated,
597                *expr,
598                *pattern,
599                escape_char,
600                schema,
601                planner_context,
602                false,
603                any,
604            ),
605
606            SQLExpr::ILike {
607                negated,
608                expr,
609                pattern,
610                escape_char,
611                any,
612            } => self.sql_like_to_expr(
613                negated,
614                *expr,
615                *pattern,
616                escape_char,
617                schema,
618                planner_context,
619                true,
620                any,
621            ),
622
623            SQLExpr::SimilarTo {
624                negated,
625                expr,
626                pattern,
627                escape_char,
628            } => self.sql_similarto_to_expr(
629                negated,
630                *expr,
631                *pattern,
632                escape_char,
633                schema,
634                planner_context,
635            ),
636
637            SQLExpr::BinaryOp { .. } => {
638                internal_err!("binary_op should be handled by sql_expr_to_logical_expr.")
639            }
640
641            #[cfg(feature = "unicode_expressions")]
642            SQLExpr::Substring {
643                expr,
644                substring_from,
645                substring_for,
646                special: _,
647                shorthand: _,
648            } => self.sql_substring_to_expr(
649                expr,
650                substring_from,
651                substring_for,
652                schema,
653                planner_context,
654            ),
655
656            #[cfg(not(feature = "unicode_expressions"))]
657            SQLExpr::Substring { .. } => {
658                internal_err!(
659                    "statement substring requires compilation with feature flag: unicode_expressions."
660                )
661            }
662
663            SQLExpr::Trim {
664                expr,
665                trim_where,
666                trim_what,
667                trim_characters,
668            } => self.sql_trim_to_expr(
669                *expr,
670                trim_where,
671                trim_what,
672                trim_characters,
673                schema,
674                planner_context,
675            ),
676
677            SQLExpr::Function(function) => {
678                self.sql_function_to_expr(function, schema, planner_context)
679            }
680
681            SQLExpr::Rollup(exprs) => {
682                self.sql_rollup_to_expr(exprs, schema, planner_context)
683            }
684            SQLExpr::Cube(exprs) => self.sql_cube_to_expr(exprs, schema, planner_context),
685            SQLExpr::GroupingSets(exprs) => {
686                self.sql_grouping_sets_to_expr(exprs, schema, planner_context)
687            }
688
689            SQLExpr::Floor { expr, field } => match field {
690                CeilFloorKind::DateTimeField(DateTimeField::NoDateTime) => {
691                    self.sql_fn_name_to_expr(*expr, "floor", schema, planner_context)
692                }
693                CeilFloorKind::DateTimeField(_) => {
694                    not_impl_err!("FLOOR with datetime is not supported")
695                }
696                CeilFloorKind::Scale(_) => {
697                    not_impl_err!("FLOOR with scale is not supported")
698                }
699            },
700            SQLExpr::Ceil { expr, field } => match field {
701                CeilFloorKind::DateTimeField(DateTimeField::NoDateTime) => {
702                    self.sql_fn_name_to_expr(*expr, "ceil", schema, planner_context)
703                }
704                CeilFloorKind::DateTimeField(_) => {
705                    not_impl_err!("CEIL with datetime is not supported")
706                }
707                CeilFloorKind::Scale(_) => {
708                    not_impl_err!("CEIL with scale is not supported")
709                }
710            },
711            SQLExpr::Overlay {
712                expr,
713                overlay_what,
714                overlay_from,
715                overlay_for,
716            } => self.sql_overlay_to_expr(
717                *expr,
718                *overlay_what,
719                *overlay_from,
720                overlay_for,
721                schema,
722                planner_context,
723            ),
724            SQLExpr::Nested(e) => {
725                self.sql_expr_to_logical_expr(*e, schema, planner_context)
726            }
727
728            SQLExpr::Exists { subquery, negated } => {
729                self.parse_exists_subquery(*subquery, negated, schema, planner_context)
730            }
731            SQLExpr::InSubquery {
732                expr,
733                subquery,
734                negated,
735            } => {
736                self.parse_in_subquery(*expr, *subquery, negated, schema, planner_context)
737            }
738            SQLExpr::Subquery(subquery) => {
739                self.parse_scalar_subquery(*subquery, schema, planner_context)
740            }
741
742            SQLExpr::Struct { values, fields } => {
743                self.parse_struct(schema, planner_context, values, &fields)
744            }
745            SQLExpr::Position { expr, r#in } => {
746                self.sql_position_to_expr(*expr, *r#in, schema, planner_context)
747            }
748            SQLExpr::AtTimeZone {
749                timestamp,
750                time_zone,
751            } => self.sql_at_time_zone_to_expr(
752                *timestamp,
753                *time_zone,
754                schema,
755                planner_context,
756            ),
757            SQLExpr::Dictionary(fields) => {
758                self.try_plan_dictionary_literal(fields, schema, planner_context)
759            }
760            SQLExpr::Map(map) => {
761                self.try_plan_map_literal(map.entries, schema, planner_context)
762            }
763            SQLExpr::AnyOp {
764                left,
765                compare_op,
766                right,
767                // ANY/SOME are equivalent, this field specifies which the user
768                // specified but it doesn't affect the plan so ignore the field
769                is_some: _,
770            } => match *right {
771                SQLExpr::Subquery(subquery) => self.parse_set_comparison_subquery(
772                    *left,
773                    *subquery,
774                    &compare_op,
775                    SetQuantifier::Any,
776                    schema,
777                    planner_context,
778                ),
779                _ => {
780                    let left_expr = self.sql_to_expr(*left, schema, planner_context)?;
781                    let right_expr = self.sql_to_expr(*right, schema, planner_context)?;
782                    plan_any_op(left_expr, right_expr, &compare_op)
783                }
784            },
785            SQLExpr::AllOp {
786                left,
787                compare_op,
788                right,
789            } => match *right {
790                SQLExpr::Subquery(subquery) => self.parse_set_comparison_subquery(
791                    *left,
792                    *subquery,
793                    &compare_op,
794                    SetQuantifier::All,
795                    schema,
796                    planner_context,
797                ),
798                _ => {
799                    let left_expr = self.sql_to_expr(*left, schema, planner_context)?;
800                    let right_expr = self.sql_to_expr(*right, schema, planner_context)?;
801                    plan_all_op(&left_expr, &right_expr, &compare_op)
802                }
803            },
804            #[expect(deprecated)]
805            SQLExpr::Wildcard(_token) => Ok(Expr::Wildcard {
806                qualifier: None,
807                options: Box::new(WildcardOptions::default()),
808            }),
809            #[expect(deprecated)]
810            SQLExpr::QualifiedWildcard(object_name, _token) => Ok(Expr::Wildcard {
811                qualifier: Some(self.object_name_to_table_reference(object_name)?),
812                options: Box::new(WildcardOptions::default()),
813            }),
814            SQLExpr::Tuple(values) => self.parse_tuple(schema, planner_context, values),
815            SQLExpr::JsonAccess { value, path } => {
816                self.parse_json_access(schema, planner_context, value, &path)
817            }
818            _ => not_impl_err!("Unsupported ast node in sqltorel: {sql:?}"),
819        }
820    }
821
822    fn parse_json_access(
823        &self,
824        schema: &DFSchema,
825        planner_context: &mut PlannerContext,
826        value: Box<SQLExpr>,
827        path: &JsonPath,
828    ) -> Result<Expr> {
829        let value = self.sql_to_expr(*value, schema, planner_context)?;
830        let json_path = path.to_string();
831        let json_path = json_path.strip_prefix(":").unwrap_or(&json_path);
832        let binary_expr = RawBinaryExpr {
833            op: BinaryOperator::Custom(":".to_owned()),
834            left: value,
835            right: Expr::Literal(ScalarValue::Utf8(Some(json_path.to_owned())), None),
836        };
837        let binary_expr = match self.try_plan_binary_op(binary_expr, schema)? {
838            PlannerResult::Planned(expr) => return Ok(expr),
839            PlannerResult::Original(expr) => expr,
840        };
841
842        if !path.path.is_empty()
843            && matches!(&binary_expr.op, BinaryOperator::Custom(op) if op == ":")
844            && is_struct_like(&binary_expr.left.get_type(schema)?)
845            && path
846                .path
847                .iter()
848                .all(|element| struct_field_name_from_json_path_elem(element).is_some())
849        {
850            let mut planned = binary_expr.left.clone();
851            let mut all_fields_planned = true;
852
853            for element in &path.path {
854                let field_name = struct_field_name_from_json_path_elem(element)
855                    .expect("all path elements were checked above");
856                let field_access = RawFieldAccessExpr {
857                    expr: planned,
858                    field_access: GetFieldAccess::NamedStructField {
859                        name: ScalarValue::from(field_name),
860                    },
861                };
862                match self.try_plan_field_access(field_access, schema)? {
863                    PlannerResult::Planned(expr) => planned = expr,
864                    PlannerResult::Original(field_access) => {
865                        planned = field_access.expr;
866                        all_fields_planned = false;
867                        break;
868                    }
869                }
870            }
871
872            if all_fields_planned {
873                return Ok(planned);
874            }
875        }
876
877        let RawBinaryExpr { op, left, right } = binary_expr;
878        self.build_binary_expr(&op, left, right)
879    }
880
881    fn try_plan_field_access(
882        &self,
883        mut field_access_expr: RawFieldAccessExpr,
884        schema: &DFSchema,
885    ) -> Result<PlannerResult<RawFieldAccessExpr>> {
886        for planner in self.context_provider.get_expr_planners() {
887            match planner.plan_field_access(field_access_expr, schema)? {
888                PlannerResult::Planned(expr) => {
889                    return Ok(PlannerResult::Planned(expr));
890                }
891                PlannerResult::Original(expr) => field_access_expr = expr,
892            }
893        }
894        Ok(PlannerResult::Original(field_access_expr))
895    }
896
897    /// Parses a struct(..) expression and plans it creation
898    fn parse_struct(
899        &self,
900        schema: &DFSchema,
901        planner_context: &mut PlannerContext,
902        values: Vec<SQLExpr>,
903        fields: &[StructField],
904    ) -> Result<Expr> {
905        if !fields.is_empty() {
906            return not_impl_err!("Struct fields are not supported yet");
907        }
908        let is_named_struct = values
909            .iter()
910            .any(|value| matches!(value, SQLExpr::Named { .. }));
911
912        let mut create_struct_args = if is_named_struct {
913            self.create_named_struct_expr(values, schema, planner_context)?
914        } else {
915            self.create_struct_expr(values, schema, planner_context)?
916        };
917
918        for planner in self.context_provider.get_expr_planners() {
919            match planner.plan_struct_literal(create_struct_args, is_named_struct)? {
920                PlannerResult::Planned(expr) => return Ok(expr),
921                PlannerResult::Original(args) => create_struct_args = args,
922            }
923        }
924        not_impl_err!("Struct not supported by ExprPlanner: {create_struct_args:?}")
925    }
926
927    fn parse_tuple(
928        &self,
929        schema: &DFSchema,
930        planner_context: &mut PlannerContext,
931        values: Vec<SQLExpr>,
932    ) -> Result<Expr> {
933        match values.first() {
934            Some(SQLExpr::Identifier(_))
935            | Some(SQLExpr::Value(_))
936            | Some(SQLExpr::CompoundIdentifier(_)) => {
937                self.parse_struct(schema, planner_context, values, &[])
938            }
939            None => not_impl_err!("Empty tuple not supported yet"),
940            _ => {
941                not_impl_err!("Only identifiers and literals are supported in tuples")
942            }
943        }
944    }
945
946    /// Plan `<timestamp> AT TIME ZONE '<tz>'`.
947    ///
948    /// The result type depends on whether the input has a timezone *after
949    /// type coercion*, and type coercion runs after this planner. So this
950    /// method only builds `timezone('<tz>', <timestamp>)` through
951    /// [`ExprPlanner::plan_at_time_zone`], and that function decides once the
952    /// type is known. See `TimezoneFunc` in `datafusion-functions` for the
953    /// semantics.
954    ///
955    /// [`ExprPlanner::plan_at_time_zone`]: datafusion_expr::planner::ExprPlanner::plan_at_time_zone
956    fn sql_at_time_zone_to_expr(
957        &self,
958        timestamp: SQLExpr,
959        time_zone: SQLExpr,
960        schema: &DFSchema,
961        planner_context: &mut PlannerContext,
962    ) -> Result<Expr> {
963        let tz: Arc<str> = match time_zone {
964            SQLExpr::Value(ValueWithSpan {
965                value: Value::SingleQuotedString(s),
966                span: _,
967            }) => s.into(),
968            _ => {
969                return not_impl_err!("Unsupported ast node in sqltorel: {time_zone:?}");
970            }
971        };
972
973        let expr =
974            self.sql_expr_to_logical_expr_internal(timestamp, schema, planner_context)?;
975
976        let mut args = vec![lit(tz.as_ref()), expr];
977        for planner in self.context_provider.get_expr_planners() {
978            match planner.plan_at_time_zone(args)? {
979                PlannerResult::Planned(expr) => return Ok(expr),
980                PlannerResult::Original(original) => {
981                    args = original;
982                }
983            }
984        }
985
986        not_impl_err!(
987            "AT TIME ZONE needs an ExprPlanner that implements `plan_at_time_zone`, \
988             such as the `DatetimeFunctionPlanner` of `datafusion-functions`"
989        )
990    }
991
992    fn sql_position_to_expr(
993        &self,
994        substr_expr: SQLExpr,
995        str_expr: SQLExpr,
996        schema: &DFSchema,
997        planner_context: &mut PlannerContext,
998    ) -> Result<Expr> {
999        let substr =
1000            self.sql_expr_to_logical_expr(substr_expr, schema, planner_context)?;
1001        let fullstr = self.sql_expr_to_logical_expr(str_expr, schema, planner_context)?;
1002        let mut position_args = vec![fullstr, substr];
1003        for planner in self.context_provider.get_expr_planners() {
1004            match planner.plan_position(position_args)? {
1005                PlannerResult::Planned(expr) => return Ok(expr),
1006                PlannerResult::Original(args) => {
1007                    position_args = args;
1008                }
1009            }
1010        }
1011
1012        not_impl_err!("Position not supported by ExprPlanner: {position_args:?}")
1013    }
1014
1015    fn try_plan_dictionary_literal(
1016        &self,
1017        fields: Vec<DictionaryField>,
1018        schema: &DFSchema,
1019        planner_context: &mut PlannerContext,
1020    ) -> Result<Expr> {
1021        let mut keys = Vec::with_capacity(fields.len());
1022        let mut values = Vec::with_capacity(fields.len());
1023        for field in fields {
1024            let key = lit(field.key.value);
1025            let value =
1026                self.sql_expr_to_logical_expr(*field.value, schema, planner_context)?;
1027            keys.push(key);
1028            values.push(value);
1029        }
1030
1031        let mut raw_expr = RawDictionaryExpr { keys, values };
1032
1033        for planner in self.context_provider.get_expr_planners() {
1034            match planner.plan_dictionary_literal(raw_expr, schema)? {
1035                PlannerResult::Planned(expr) => {
1036                    return Ok(expr);
1037                }
1038                PlannerResult::Original(expr) => raw_expr = expr,
1039            }
1040        }
1041        not_impl_err!("Dictionary not supported by ExprPlanner: {raw_expr:?}")
1042    }
1043
1044    fn try_plan_map_literal(
1045        &self,
1046        entries: Vec<MapEntry>,
1047        schema: &DFSchema,
1048        planner_context: &mut PlannerContext,
1049    ) -> Result<Expr> {
1050        let mut exprs: Vec<_> = entries
1051            .into_iter()
1052            .flat_map(|entry| [entry.key, entry.value])
1053            .map(|expr| self.sql_expr_to_logical_expr(*expr, schema, planner_context))
1054            .collect::<Result<Vec<_>>>()?;
1055        for planner in self.context_provider.get_expr_planners() {
1056            match planner.plan_make_map(exprs)? {
1057                PlannerResult::Planned(expr) => {
1058                    return Ok(expr);
1059                }
1060                PlannerResult::Original(expr) => exprs = expr,
1061            }
1062        }
1063        not_impl_err!("MAP not supported by ExprPlanner: {exprs:?}")
1064    }
1065
1066    // Handles a call to struct(...) where the arguments are named. For example
1067    // `struct (v as foo, v2 as bar)` by creating a call to the `named_struct` function
1068    fn create_named_struct_expr(
1069        &self,
1070        values: Vec<SQLExpr>,
1071        input_schema: &DFSchema,
1072        planner_context: &mut PlannerContext,
1073    ) -> Result<Vec<Expr>> {
1074        Ok(values
1075            .into_iter()
1076            .enumerate()
1077            .map(|(i, value)| {
1078                let args = if let SQLExpr::Named { expr, name } = value {
1079                    [
1080                        name.value.lit(),
1081                        self.sql_expr_to_logical_expr(
1082                            *expr,
1083                            input_schema,
1084                            planner_context,
1085                        )?,
1086                    ]
1087                } else {
1088                    [
1089                        format!("c{i}").lit(),
1090                        self.sql_expr_to_logical_expr(
1091                            value,
1092                            input_schema,
1093                            planner_context,
1094                        )?,
1095                    ]
1096                };
1097
1098                Ok(args)
1099            })
1100            .collect::<Result<Vec<_>>>()?
1101            .into_iter()
1102            .flatten()
1103            .collect())
1104    }
1105
1106    // Handles a call to struct(...) where the arguments are not named. For example
1107    // `struct (v, v2)` by creating a call to the `struct` function
1108    // which will create a struct with fields named `c0`, `c1`, etc.
1109    fn create_struct_expr(
1110        &self,
1111        values: Vec<SQLExpr>,
1112        input_schema: &DFSchema,
1113        planner_context: &mut PlannerContext,
1114    ) -> Result<Vec<Expr>> {
1115        values
1116            .into_iter()
1117            .map(|value| {
1118                self.sql_expr_to_logical_expr(value, input_schema, planner_context)
1119            })
1120            .collect::<Result<Vec<_>>>()
1121    }
1122
1123    fn sql_in_list_to_expr(
1124        &self,
1125        expr: SQLExpr,
1126        list: Vec<SQLExpr>,
1127        negated: bool,
1128        schema: &DFSchema,
1129        planner_context: &mut PlannerContext,
1130    ) -> Result<Expr> {
1131        let list_expr = list
1132            .into_iter()
1133            .map(|e| self.sql_expr_to_logical_expr(e, schema, planner_context))
1134            .collect::<Result<Vec<_>>>()?;
1135
1136        Ok(Expr::InList(InList::new(
1137            Box::new(self.sql_expr_to_logical_expr(expr, schema, planner_context)?),
1138            list_expr,
1139            negated,
1140        )))
1141    }
1142
1143    #[expect(clippy::too_many_arguments)]
1144    fn sql_like_to_expr(
1145        &self,
1146        negated: bool,
1147        expr: SQLExpr,
1148        pattern: SQLExpr,
1149        escape_char: Option<Box<SQLExpr>>,
1150        schema: &DFSchema,
1151        planner_context: &mut PlannerContext,
1152        case_insensitive: bool,
1153        any: bool,
1154    ) -> Result<Expr> {
1155        if any {
1156            return not_impl_err!("ANY in LIKE expression");
1157        }
1158        let pattern = self.sql_expr_to_logical_expr(pattern, schema, planner_context)?;
1159        let escape_char = match escape_char.map(|e| *e) {
1160            Some(SQLExpr::Value(ValueWithSpan {
1161                value: Value::SingleQuotedString(char),
1162                ..
1163            })) if char.len() == 1 => Some(char.chars().next().unwrap()),
1164            Some(expr) => {
1165                return plan_err!(
1166                    "Invalid escape character in LIKE expression. Expected a single character wrapped with single quotes, got {expr}"
1167                );
1168            }
1169            None => None,
1170        };
1171        Ok(Expr::Like(Like::new(
1172            negated,
1173            Box::new(self.sql_expr_to_logical_expr(expr, schema, planner_context)?),
1174            Box::new(pattern),
1175            escape_char,
1176            case_insensitive,
1177        )))
1178    }
1179
1180    fn sql_similarto_to_expr(
1181        &self,
1182        negated: bool,
1183        expr: SQLExpr,
1184        pattern: SQLExpr,
1185        escape_char: Option<Box<SQLExpr>>,
1186        schema: &DFSchema,
1187        planner_context: &mut PlannerContext,
1188    ) -> Result<Expr> {
1189        let pattern = self.sql_expr_to_logical_expr(pattern, schema, planner_context)?;
1190        let escape_char = match escape_char.map(|e| *e) {
1191            Some(SQLExpr::Value(ValueWithSpan {
1192                value: Value::SingleQuotedString(char),
1193                ..
1194            })) if char.len() == 1 => Some(char.chars().next().unwrap()),
1195            Some(expr) => {
1196                return plan_err!(
1197                    "Invalid escape character in SIMILAR TO expression. Expected a single character wrapped with single quotes, got {expr}"
1198                );
1199            }
1200            None => None,
1201        };
1202        Ok(Expr::SimilarTo(Like::new(
1203            negated,
1204            Box::new(self.sql_expr_to_logical_expr(expr, schema, planner_context)?),
1205            Box::new(pattern),
1206            escape_char,
1207            false,
1208        )))
1209    }
1210
1211    fn sql_trim_to_expr(
1212        &self,
1213        expr: SQLExpr,
1214        trim_where: Option<TrimWhereField>,
1215        trim_what: Option<Box<SQLExpr>>,
1216        trim_characters: Option<Vec<SQLExpr>>,
1217        schema: &DFSchema,
1218        planner_context: &mut PlannerContext,
1219    ) -> Result<Expr> {
1220        let arg = self.sql_expr_to_logical_expr(expr, schema, planner_context)?;
1221        let args = match (trim_what, trim_characters) {
1222            (Some(to_trim), None) => {
1223                let to_trim =
1224                    self.sql_expr_to_logical_expr(*to_trim, schema, planner_context)?;
1225                Ok(vec![arg, to_trim])
1226            }
1227            (None, Some(trim_characters)) => {
1228                if let Some(first) = trim_characters.first() {
1229                    let to_trim = self.sql_expr_to_logical_expr(
1230                        first.clone(),
1231                        schema,
1232                        planner_context,
1233                    )?;
1234                    Ok(vec![arg, to_trim])
1235                } else {
1236                    plan_err!("TRIM CHARACTERS cannot be empty")
1237                }
1238            }
1239            (Some(_), Some(_)) => {
1240                plan_err!("Both TRIM and TRIM CHARACTERS cannot be specified")
1241            }
1242            (None, None) => Ok(vec![arg]),
1243        }?;
1244
1245        let fun_name = match trim_where {
1246            Some(TrimWhereField::Leading) => "ltrim",
1247            Some(TrimWhereField::Trailing) => "rtrim",
1248            Some(TrimWhereField::Both) => "btrim",
1249            None => "trim",
1250        };
1251        let fun = self
1252            .context_provider
1253            .get_function_meta(fun_name)
1254            .ok_or_else(|| {
1255                internal_datafusion_err!("Unable to find expected '{fun_name}' function")
1256            })?;
1257
1258        Ok(Expr::ScalarFunction(ScalarFunction::new_udf(fun, args)))
1259    }
1260
1261    fn sql_overlay_to_expr(
1262        &self,
1263        expr: SQLExpr,
1264        overlay_what: SQLExpr,
1265        overlay_from: SQLExpr,
1266        overlay_for: Option<Box<SQLExpr>>,
1267        schema: &DFSchema,
1268        planner_context: &mut PlannerContext,
1269    ) -> Result<Expr> {
1270        let arg = self.sql_expr_to_logical_expr(expr, schema, planner_context)?;
1271        let what_arg =
1272            self.sql_expr_to_logical_expr(overlay_what, schema, planner_context)?;
1273        let from_arg =
1274            self.sql_expr_to_logical_expr(overlay_from, schema, planner_context)?;
1275        let mut overlay_args = match overlay_for {
1276            Some(for_expr) => {
1277                let for_expr =
1278                    self.sql_expr_to_logical_expr(*for_expr, schema, planner_context)?;
1279                vec![arg, what_arg, from_arg, for_expr]
1280            }
1281            None => vec![arg, what_arg, from_arg],
1282        };
1283        for planner in self.context_provider.get_expr_planners() {
1284            match planner.plan_overlay(overlay_args)? {
1285                PlannerResult::Planned(expr) => return Ok(expr),
1286                PlannerResult::Original(args) => overlay_args = args,
1287            }
1288        }
1289        not_impl_err!("Overlay not supported by ExprPlanner: {overlay_args:?}")
1290    }
1291
1292    fn sql_cast_to_expr(
1293        &self,
1294        expr: SQLExpr,
1295        data_type: &SQLDataType,
1296        format: Option<CastFormat>,
1297        schema: &DFSchema,
1298        planner_context: &mut PlannerContext,
1299    ) -> Result<Expr> {
1300        if let Some(format) = format {
1301            return not_impl_err!("CAST with format is not supported: {format}");
1302        }
1303
1304        let dt = self.convert_data_type_to_field(data_type)?;
1305        let expr = self.sql_expr_to_logical_expr(expr, schema, planner_context)?;
1306
1307        // numeric constants are treated as seconds (rather as nanoseconds)
1308        // to align with postgres / duckdb semantics
1309        let expr = match dt.data_type() {
1310            DataType::Timestamp(TimeUnit::Nanosecond, tz)
1311                if expr.get_type(schema)? == DataType::Int64 =>
1312            {
1313                Expr::Cast(Cast::new(
1314                    Box::new(expr),
1315                    DataType::Timestamp(TimeUnit::Second, tz.clone()),
1316                ))
1317            }
1318            _ => expr,
1319        };
1320
1321        Ok(Expr::Cast(Cast::new_from_field(Box::new(expr), dt)))
1322    }
1323
1324    /// Extracts the root expression and access chain from a compound expression.
1325    ///
1326    /// This function attempts to identify if a compound expression (like `a.b.c`) should be treated
1327    /// as a column reference with a qualifier (like `table.column`) or as a field access expression.
1328    ///
1329    /// # Arguments
1330    ///
1331    /// * `root` - The root SQL expression (e.g., the first part of `a.b.c`)
1332    /// * `access_chain` - Vector of access expressions (e.g., `.b` and `.c` parts)
1333    /// * `schema` - The schema to resolve column references against
1334    /// * `planner_context` - Context for planning expressions
1335    ///
1336    /// # Returns
1337    ///
1338    /// A tuple containing:
1339    /// * The resolved root expression
1340    /// * The remaining access chain that should be processed as field accesses
1341    fn extract_root_and_access_chain(
1342        &self,
1343        root: SQLExpr,
1344        mut access_chain: Vec<AccessExpr>,
1345        schema: &DFSchema,
1346        planner_context: &mut PlannerContext,
1347    ) -> Result<(Expr, Vec<AccessExpr>)> {
1348        let SQLExpr::Identifier(root_ident) = root else {
1349            let root = self.sql_expr_to_logical_expr(root, schema, planner_context)?;
1350            return Ok((root, access_chain));
1351        };
1352
1353        let mut compound_idents = vec![root_ident];
1354        let first_non_ident = access_chain
1355            .iter()
1356            .position(|access| !matches!(access, AccessExpr::Dot(SQLExpr::Identifier(_))))
1357            .unwrap_or(access_chain.len());
1358        for access in access_chain.drain(0..first_non_ident) {
1359            if let AccessExpr::Dot(SQLExpr::Identifier(ident)) = access {
1360                compound_idents.push(ident);
1361            } else {
1362                return internal_err!("Expected identifier in access chain");
1363            }
1364        }
1365
1366        let root = if compound_idents.len() == 1 {
1367            self.sql_identifier_to_expr(
1368                compound_idents.pop().unwrap(),
1369                schema,
1370                planner_context,
1371            )?
1372        } else {
1373            self.sql_compound_identifier_to_expr(
1374                compound_idents,
1375                schema,
1376                planner_context,
1377            )?
1378        };
1379        Ok((root, access_chain))
1380    }
1381
1382    fn sql_compound_field_access_to_expr(
1383        &self,
1384        root: SQLExpr,
1385        access_chain: Vec<AccessExpr>,
1386        schema: &DFSchema,
1387        planner_context: &mut PlannerContext,
1388    ) -> Result<Expr> {
1389        let (root, access_chain) = self.extract_root_and_access_chain(
1390            root,
1391            access_chain,
1392            schema,
1393            planner_context,
1394        )?;
1395        let fields = access_chain
1396            .into_iter()
1397            .map(|field| match field {
1398                AccessExpr::Subscript(subscript) => {
1399                    match subscript {
1400                        Subscript::Index { index } => {
1401                            // index can be a name, in which case it is a named field access
1402                            match index {
1403                                SQLExpr::Value(ValueWithSpan {
1404                                    value:
1405                                        Value::SingleQuotedString(s)
1406                                        | Value::DoubleQuotedString(s),
1407                                    span: _,
1408                                }) => Ok(Some(GetFieldAccess::NamedStructField {
1409                                    name: ScalarValue::from(s),
1410                                })),
1411                                SQLExpr::JsonAccess { .. } => {
1412                                    not_impl_err!("JsonAccess")
1413                                }
1414                                // otherwise treat like a list index
1415                                _ => Ok(Some(GetFieldAccess::ListIndex {
1416                                    key: Box::new(self.sql_expr_to_logical_expr(
1417                                        index,
1418                                        schema,
1419                                        planner_context,
1420                                    )?),
1421                                })),
1422                            }
1423                        }
1424                        Subscript::Slice {
1425                            lower_bound,
1426                            upper_bound,
1427                            stride,
1428                        } => {
1429                            // Means access like [:2]
1430                            let lower_bound = if let Some(lower_bound) = lower_bound {
1431                                self.sql_expr_to_logical_expr(
1432                                    lower_bound,
1433                                    schema,
1434                                    planner_context,
1435                                )
1436                            } else {
1437                                not_impl_err!("Slice subscript requires a lower bound")
1438                            }?;
1439
1440                            // means access like [2:]
1441                            let upper_bound = if let Some(upper_bound) = upper_bound {
1442                                self.sql_expr_to_logical_expr(
1443                                    upper_bound,
1444                                    schema,
1445                                    planner_context,
1446                                )
1447                            } else {
1448                                not_impl_err!("Slice subscript requires an upper bound")
1449                            }?;
1450
1451                            // stride, default to 1
1452                            let stride = if let Some(stride) = stride {
1453                                self.sql_expr_to_logical_expr(
1454                                    stride,
1455                                    schema,
1456                                    planner_context,
1457                                )?
1458                            } else {
1459                                lit(1i64)
1460                            };
1461
1462                            Ok(Some(GetFieldAccess::ListRange {
1463                                start: Box::new(lower_bound),
1464                                stop: Box::new(upper_bound),
1465                                stride: Box::new(stride),
1466                            }))
1467                        }
1468                    }
1469                }
1470                AccessExpr::Dot(expr) => match expr {
1471                    SQLExpr::Value(ValueWithSpan {
1472                        value: Value::SingleQuotedString(s) | Value::DoubleQuotedString(s),
1473                        span    : _
1474                    }) => Ok(Some(GetFieldAccess::NamedStructField {
1475                        name: ScalarValue::from(s),
1476                    })),
1477                    _ => {
1478                        not_impl_err!(
1479                            "Dot access not supported for non-string expr: {expr:?}"
1480                        )
1481                    }
1482                },
1483            })
1484            .collect::<Result<Vec<_>>>()?;
1485
1486        fields
1487            .into_iter()
1488            .flatten()
1489            .try_fold(root, |expr, field_access| {
1490                let field_access_expr = RawFieldAccessExpr { expr, field_access };
1491                match self.try_plan_field_access(field_access_expr, schema)? {
1492                    PlannerResult::Planned(expr) => Ok(expr),
1493                    PlannerResult::Original(field_access_expr) => not_impl_err!(
1494                        "GetFieldAccess not supported by ExprPlanner: {field_access_expr:?}"
1495                    ),
1496                }
1497            })
1498    }
1499}
1500
1501fn is_struct_like(data_type: &DataType) -> bool {
1502    matches!(data_type, DataType::Struct(_))
1503        || matches!(
1504            data_type,
1505            DataType::Dictionary(_, value_type)
1506                if matches!(value_type.as_ref(), DataType::Struct(_))
1507        )
1508}
1509
1510fn struct_field_name_from_json_path_elem(element: &JsonPathElem) -> Option<&str> {
1511    match element {
1512        JsonPathElem::Dot { key, .. } => Some(key),
1513        JsonPathElem::Bracket {
1514            key:
1515                SQLExpr::Value(ValueWithSpan {
1516                    value: Value::SingleQuotedString(key) | Value::DoubleQuotedString(key),
1517                    span: _,
1518                }),
1519        }
1520        | JsonPathElem::ColonBracket {
1521            key:
1522                SQLExpr::Value(ValueWithSpan {
1523                    value: Value::SingleQuotedString(key) | Value::DoubleQuotedString(key),
1524                    span: _,
1525                }),
1526        } => Some(key),
1527        JsonPathElem::Bracket { .. } | JsonPathElem::ColonBracket { .. } => None,
1528    }
1529}
1530
1531/// Builds a CASE expression that handles NULL semantics for `x <op> ANY(arr)`:
1532///
1533/// ```text
1534/// CASE
1535///   WHEN <min_or_max>(arr) IS NOT NULL THEN <comparison>
1536///   WHEN arr IS NOT NULL THEN FALSE          -- empty or all-null array
1537///   ELSE NULL                                -- NULL array
1538/// END
1539/// ```
1540fn any_op_with_null_handling(bound: Expr, comparison: Expr, arr: Expr) -> Result<Expr> {
1541    when(bound.is_not_null(), comparison)
1542        .when(arr.is_not_null(), lit(false))
1543        .otherwise(lit(ScalarValue::Boolean(None)))
1544}
1545
1546/// Plans a `<left> <op> ANY(<right>)` expression for non-subquery operands.
1547fn plan_any_op(
1548    left_expr: Expr,
1549    right_expr: Expr,
1550    compare_op: &BinaryOperator,
1551) -> Result<Expr> {
1552    match compare_op {
1553        BinaryOperator::Eq => Ok(array_has(right_expr, left_expr)),
1554        BinaryOperator::NotEq => {
1555            let min = array_min(right_expr.clone());
1556            let max = array_max(right_expr.clone());
1557            // NOT EQ is true when either bound differs from left
1558            let comparison = min
1559                .not_eq(left_expr.clone())
1560                .or(max.clone().not_eq(left_expr));
1561            any_op_with_null_handling(max, comparison, right_expr)
1562        }
1563        BinaryOperator::Gt => {
1564            let min = array_min(right_expr.clone());
1565            any_op_with_null_handling(min.clone(), min.lt(left_expr), right_expr)
1566        }
1567        BinaryOperator::Lt => {
1568            let max = array_max(right_expr.clone());
1569            any_op_with_null_handling(max.clone(), max.gt(left_expr), right_expr)
1570        }
1571        BinaryOperator::GtEq => {
1572            let min = array_min(right_expr.clone());
1573            any_op_with_null_handling(min.clone(), min.lt_eq(left_expr), right_expr)
1574        }
1575        BinaryOperator::LtEq => {
1576            let max = array_max(right_expr.clone());
1577            any_op_with_null_handling(max.clone(), max.gt_eq(left_expr), right_expr)
1578        }
1579        _ => plan_err!(
1580            "Unsupported AnyOp: '{compare_op}', only '=', '<>', '>', '<', '>=', '<=' are supported"
1581        ),
1582    }
1583}
1584
1585/// Plans `needle <compare_op> ALL(haystack)` with proper SQL NULL semantics.
1586///
1587/// CASE/WHEN structure:
1588///   WHEN arr IS NULL        → NULL
1589///   WHEN empty              → TRUE
1590///   WHEN lhs IS NULL        → NULL
1591///   WHEN decisive_condition → FALSE
1592///   WHEN has_nulls          → NULL
1593///   ELSE                    → TRUE
1594fn plan_all_op(
1595    needle: &Expr,
1596    haystack: &Expr,
1597    compare_op: &BinaryOperator,
1598) -> Result<Expr> {
1599    let null_arr_check = haystack.clone().is_null();
1600    let empty_check = cardinality(haystack.clone()).eq(lit(0u64));
1601    let null_lhs_check = needle.clone().is_null();
1602    // DataFusion's array_position uses is_null() checks internally (not equality),
1603    // so it can locate NULL elements even though NULL = NULL is NULL in standard SQL.
1604    let has_nulls =
1605        array_position(haystack.clone(), lit(ScalarValue::Null), lit(1i64)).is_not_null();
1606
1607    let decisive_condition = match compare_op {
1608        BinaryOperator::NotEq => array_has(haystack.clone(), needle.clone()),
1609        BinaryOperator::Eq => {
1610            let all_equal = array_min(haystack.clone())
1611                .eq(needle.clone())
1612                .and(array_max(haystack.clone()).eq(needle.clone()));
1613            Expr::Not(Box::new(all_equal))
1614        }
1615        BinaryOperator::Gt => {
1616            Expr::Not(Box::new(needle.clone().gt(array_max(haystack.clone()))))
1617        }
1618        BinaryOperator::Lt => {
1619            Expr::Not(Box::new(needle.clone().lt(array_min(haystack.clone()))))
1620        }
1621        BinaryOperator::GtEq => {
1622            Expr::Not(Box::new(needle.clone().gt_eq(array_max(haystack.clone()))))
1623        }
1624        BinaryOperator::LtEq => {
1625            Expr::Not(Box::new(needle.clone().lt_eq(array_min(haystack.clone()))))
1626        }
1627        _ => {
1628            return plan_err!(
1629                "Unsupported AllOp: '{compare_op}', only '=', '<>', '>', '<', '>=', '<=' are supported"
1630            );
1631        }
1632    };
1633
1634    let null_bool = lit(ScalarValue::Boolean(None));
1635    when(null_arr_check, null_bool.clone())
1636        .when(empty_check, lit(true))
1637        .when(null_lhs_check, null_bool.clone())
1638        .when(decisive_condition, lit(false))
1639        .when(has_nulls, null_bool)
1640        .otherwise(lit(true))
1641}
1642
1643#[cfg(test)]
1644mod tests {
1645    use std::collections::HashMap;
1646    use std::sync::Arc;
1647
1648    use arrow::datatypes::{Field, Schema};
1649    use sqlparser::dialect::GenericDialect;
1650    use sqlparser::parser::Parser;
1651
1652    use datafusion_common::TableReference;
1653    use datafusion_common::config::ConfigOptions;
1654    use datafusion_expr::logical_plan::builder::LogicalTableSource;
1655    use datafusion_expr::{
1656        AggregateUDF, HigherOrderUDF, ScalarUDF, TableSource, WindowUDF,
1657    };
1658
1659    use super::*;
1660
1661    struct TestContextProvider {
1662        options: ConfigOptions,
1663        tables: HashMap<String, Arc<dyn TableSource>>,
1664    }
1665
1666    impl TestContextProvider {
1667        pub fn new() -> Self {
1668            let mut tables = HashMap::new();
1669            tables.insert(
1670                "table1".to_string(),
1671                create_table_source(vec![Field::new(
1672                    "column1".to_string(),
1673                    DataType::Utf8,
1674                    false,
1675                )]),
1676            );
1677
1678            Self {
1679                options: Default::default(),
1680                tables,
1681            }
1682        }
1683    }
1684
1685    impl ContextProvider for TestContextProvider {
1686        fn get_table_source(&self, name: TableReference) -> Result<Arc<dyn TableSource>> {
1687            match self.tables.get(name.table()) {
1688                Some(table) => Ok(Arc::clone(table)),
1689                _ => plan_err!("Table not found: {}", name.table()),
1690            }
1691        }
1692
1693        fn get_function_meta(&self, _name: &str) -> Option<Arc<ScalarUDF>> {
1694            None
1695        }
1696
1697        fn get_higher_order_meta(&self, _name: &str) -> Option<Arc<HigherOrderUDF>> {
1698            None
1699        }
1700
1701        fn get_aggregate_meta(&self, name: &str) -> Option<Arc<AggregateUDF>> {
1702            match name {
1703                "sum" => Some(datafusion_functions_aggregate::sum::sum_udaf()),
1704                _ => None,
1705            }
1706        }
1707
1708        fn get_variable_type(&self, _variable_names: &[String]) -> Option<DataType> {
1709            None
1710        }
1711
1712        fn options(&self) -> &ConfigOptions {
1713            &self.options
1714        }
1715
1716        fn get_window_meta(&self, _name: &str) -> Option<Arc<WindowUDF>> {
1717            None
1718        }
1719
1720        fn udf_names(&self) -> Vec<String> {
1721            Vec::new()
1722        }
1723
1724        fn higher_order_function_names(&self) -> Vec<String> {
1725            Vec::new()
1726        }
1727
1728        fn udaf_names(&self) -> Vec<String> {
1729            vec!["sum".to_string()]
1730        }
1731
1732        fn udwf_names(&self) -> Vec<String> {
1733            Vec::new()
1734        }
1735    }
1736
1737    fn create_table_source(fields: Vec<Field>) -> Arc<dyn TableSource> {
1738        Arc::new(LogicalTableSource::new(Arc::new(
1739            Schema::new_with_metadata(fields, HashMap::new()),
1740        )))
1741    }
1742
1743    macro_rules! test_stack_overflow {
1744        ($name:ident, $num_expr:expr) => {
1745            #[test]
1746            fn $name() {
1747                let schema = DFSchema::empty();
1748                let mut planner_context = PlannerContext::default();
1749
1750                let expr_str = (0..$num_expr)
1751                    .map(|i| format!("column1 = 'value{:?}'", i))
1752                    .collect::<Vec<String>>()
1753                    .join(" OR ");
1754
1755                let dialect = GenericDialect {};
1756                let mut parser = Parser::new(&dialect)
1757                    .try_with_sql(expr_str.as_str())
1758                    .unwrap();
1759                let sql_expr = parser.parse_expr().unwrap();
1760
1761                let context_provider = TestContextProvider::new();
1762                let sql_to_rel = SqlToRel::new(&context_provider);
1763
1764                // Should not stack overflow
1765                sql_to_rel
1766                    .sql_expr_to_logical_expr(sql_expr, &schema, &mut planner_context)
1767                    .unwrap();
1768            }
1769        };
1770    }
1771
1772    test_stack_overflow!(test_stack_overflow_64, 64);
1773    test_stack_overflow!(test_stack_overflow_128, 128);
1774    test_stack_overflow!(test_stack_overflow_256, 256);
1775    test_stack_overflow!(test_stack_overflow_512, 512);
1776    test_stack_overflow!(test_stack_overflow_1024, 1024);
1777    test_stack_overflow!(test_stack_overflow_2048, 2048);
1778    test_stack_overflow!(test_stack_overflow_4096, 4096);
1779    test_stack_overflow!(test_stack_overflow_8192, 8192);
1780    #[test]
1781    fn test_sql_to_expr_with_alias() {
1782        let schema = DFSchema::empty();
1783        let mut planner_context = PlannerContext::default();
1784
1785        let expr_str = "SUM(int_col) as sum_int_col";
1786
1787        let dialect = GenericDialect {};
1788        let mut parser = Parser::new(&dialect).try_with_sql(expr_str).unwrap();
1789        // from sqlparser
1790        let sql_expr = parser.parse_expr_with_alias().unwrap();
1791
1792        let context_provider = TestContextProvider::new();
1793        let sql_to_rel = SqlToRel::new(&context_provider);
1794
1795        let expr = sql_to_rel
1796            .sql_expr_to_logical_expr_with_alias(sql_expr, &schema, &mut planner_context)
1797            .unwrap();
1798
1799        assert!(matches!(expr, Expr::Alias(_)));
1800    }
1801
1802    #[test]
1803    fn test_parse_numbers_with_underscores() {
1804        use datafusion_common::ScalarValue::*;
1805
1806        let context_provider = TestContextProvider::new();
1807        let sql_to_rel = SqlToRel::new(&context_provider);
1808
1809        // (input, positive result, negative result)
1810        let test_cases = [
1811            ("1_000", Int64(Some(1000)), Int64(Some(-1000))),
1812            ("100_000", Int64(Some(100000)), Int64(Some(-100000))),
1813            ("1_2_3_4", Int64(Some(1234)), Int64(Some(-1234))),
1814            ("0_0", Int64(Some(0)), Int64(Some(-0))),
1815            ("1_23.4_56", Float64(Some(123.456)), Float64(Some(-123.456))),
1816        ];
1817
1818        for (literal, out_positive, out_negative) in test_cases {
1819            assert_eq!(
1820                sql_to_rel.parse_sql_number(literal, false).unwrap(),
1821                Expr::Literal(out_positive, None)
1822            );
1823            assert_eq!(
1824                sql_to_rel.parse_sql_number(literal, true).unwrap(),
1825                Expr::Literal(out_negative, None)
1826            );
1827        }
1828    }
1829}