Skip to main content

datafusion_sql/unparser/
expr.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 datafusion_common::datatype::DataTypeExt;
6use datafusion_expr::expr::{
7    AggregateFunctionParams, HigherOrderFunction, NullTreatment, WindowFunctionParams,
8};
9use datafusion_expr::expr::{Lambda, Unnest};
10use sqlparser::ast::Value::SingleQuotedString;
11use sqlparser::ast::{
12    self, Array, BinaryOperator, Expr as AstExpr, Function, Ident, Interval, ObjectName,
13    Subscript, TimezoneInfo, UnaryOperator,
14};
15use sqlparser::ast::{CaseWhen, DuplicateTreatment, OrderByOptions, ValueWithSpan};
16use std::sync::Arc;
17use std::vec;
18
19use super::Unparser;
20use super::dialect::{DistinctFromStyle, IntervalStyle};
21use arrow::array::{
22    ArrayRef, Date32Array, Date64Array, PrimitiveArray,
23    types::{
24        ArrowTemporalType, Time32MillisecondType, Time32SecondType,
25        Time64MicrosecondType, Time64NanosecondType, TimestampMicrosecondType,
26        TimestampMillisecondType, TimestampNanosecondType, TimestampSecondType,
27    },
28};
29use arrow::datatypes::{
30    DataType, Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type, DecimalType,
31    FieldRef,
32};
33use arrow::util::display::array_value_to_string;
34use datafusion_common::{
35    Column, Result, ScalarValue, assert_eq_or_internal_err, assert_or_internal_err,
36    internal_datafusion_err, internal_err, not_impl_err, plan_err,
37};
38use datafusion_expr::{
39    Between, BinaryExpr, Case, Cast, Expr, GroupingSet, Like, Operator, TryCast,
40    expr::{Alias, Exists, InList, ScalarFunction, SetQuantifier, Sort, WindowFunction},
41};
42use sqlparser::ast::helpers::attached_token::AttachedToken;
43use sqlparser::tokenizer::Span;
44
45/// Convert a DataFusion [`Expr`] to [`ast::Expr`]
46///
47/// This function is the opposite of [`SqlToRel::sql_to_expr`] and can be used
48/// to, among other things, convert [`Expr`]s to SQL strings. Such strings could
49/// be used to pass filters or other expressions to another SQL engine.
50///
51/// # Errors
52///
53/// Throws an error if [`Expr`] can not be represented by an [`ast::Expr`]
54///
55/// # See Also
56///
57/// * [`Unparser`] for more control over the conversion to SQL
58/// * [`plan_to_sql`] for converting a [`LogicalPlan`] to SQL
59///
60/// # Example
61/// ```
62/// use datafusion_expr::{col, lit};
63/// use datafusion_sql::unparser::expr_to_sql;
64/// let expr = col("a").gt(lit(4)); // form an expression `a > 4`
65/// let sql = expr_to_sql(&expr).unwrap(); // convert to ast::Expr, using
66/// assert_eq!(sql.to_string(), "(a > 4)"); // use Display impl for SQL text
67/// ```
68///
69/// [`SqlToRel::sql_to_expr`]: crate::planner::SqlToRel::sql_to_expr
70/// [`plan_to_sql`]: crate::unparser::plan_to_sql
71/// [`LogicalPlan`]: datafusion_expr::logical_plan::LogicalPlan
72pub fn expr_to_sql(expr: &Expr) -> Result<ast::Expr> {
73    let unparser = Unparser::default();
74    unparser.expr_to_sql(expr)
75}
76
77const LOWEST: &BinaryOperator = &BinaryOperator::Or;
78// Closest precedence we have to IS operator is BitwiseAnd (any other) in PG docs
79// (https://www.postgresql.org/docs/7.2/sql-precedence.html)
80const IS: &BinaryOperator = &BinaryOperator::BitwiseAnd;
81
82fn null_treatment_to_sql(null_treatment: NullTreatment) -> ast::NullTreatment {
83    match null_treatment {
84        NullTreatment::IgnoreNulls => ast::NullTreatment::IgnoreNulls,
85        NullTreatment::RespectNulls => ast::NullTreatment::RespectNulls,
86    }
87}
88
89impl Unparser<'_> {
90    pub fn expr_to_sql(&self, expr: &Expr) -> Result<ast::Expr> {
91        // Unparsing recurses once per nesting level. The function-argument and
92        // dialect scalar-function-override paths cost more per level than the
93        // default `recursive` red zone, so without raising the minimum stack
94        // size the stack-growing trampoline engages too late and the OS stack
95        // overflows on deeply nested expressions (issue #23056). The size
96        // mirrors the planner's stack-growth usage in `query.rs`.
97        crate::stack::maybe_grow(|| self.expr_to_sql_with_nesting(expr))
98    }
99
100    /// Recursive entry point shared by the public [`Self::expr_to_sql`] and the
101    /// internal recursion sites (scalar-function arguments, arrays, maps, and
102    /// dialect scalar-function overrides).
103    ///
104    /// This is a stack-growth checkpoint. Internal recursion must call this
105    /// rather than the public [`Self::expr_to_sql`]: the public entry point
106    /// would re-enter the public stack-growth boundary on every level.
107    pub(crate) fn expr_to_sql_with_nesting(&self, expr: &Expr) -> Result<ast::Expr> {
108        crate::stack::maybe_grow(|| {
109            let mut root_expr = self.expr_to_sql_inner(expr)?;
110            if self.pretty {
111                root_expr = self.remove_unnecessary_nesting(root_expr, LOWEST, LOWEST);
112            }
113            Ok(root_expr)
114        })
115    }
116
117    fn distinct_from_to_sql(
118        &self,
119        left: ast::Expr,
120        right: ast::Expr,
121        is_distinct: bool,
122    ) -> Result<ast::Expr> {
123        match self.dialect.distinct_from_style() {
124            DistinctFromStyle::FullText => {
125                let expr = if is_distinct {
126                    ast::Expr::IsDistinctFrom(Box::new(left), Box::new(right))
127                } else {
128                    ast::Expr::IsNotDistinctFrom(Box::new(left), Box::new(right))
129                };
130                Ok(ast::Expr::Nested(Box::new(expr)))
131            }
132            DistinctFromStyle::Spaceship => {
133                let expr = ast::Expr::Nested(Box::new(ast::Expr::BinaryOp {
134                    left: Box::new(left),
135                    right: Box::new(right),
136                    op: BinaryOperator::Spaceship,
137                }));
138                if is_distinct {
139                    Ok(ast::Expr::Nested(Box::new(ast::Expr::UnaryOp {
140                        op: UnaryOperator::Not,
141                        expr: Box::new(expr),
142                    })))
143                } else {
144                    Ok(expr)
145                }
146            }
147        }
148    }
149
150    fn expr_to_sql_inner(&self, expr: &Expr) -> Result<ast::Expr> {
151        crate::stack::maybe_grow(|| match expr {
152            Expr::InList(InList {
153                expr,
154                list,
155                negated,
156            }) => {
157                let list_expr = list
158                    .iter()
159                    .map(|e| self.expr_to_sql_inner(e))
160                    .collect::<Result<Vec<_>>>()?;
161                Ok(ast::Expr::InList {
162                    expr: Box::new(self.expr_to_sql_inner(expr)?),
163                    list: list_expr,
164                    negated: *negated,
165                })
166            }
167            Expr::ScalarFunction(ScalarFunction { func, args }) => {
168                let func_name = func.name();
169
170                if let Some(expr) = self
171                    .dialect
172                    .scalar_function_to_sql_overrides(self, func_name, args)?
173                {
174                    return Ok(expr);
175                }
176
177                self.scalar_function_to_sql(func_name, args)
178            }
179            Expr::Between(Between {
180                expr,
181                negated,
182                low,
183                high,
184            }) => {
185                let sql_parser_expr = self.expr_to_sql_inner(expr)?;
186                let sql_low = self.expr_to_sql_inner(low)?;
187                let sql_high = self.expr_to_sql_inner(high)?;
188                Ok(ast::Expr::Nested(Box::new(self.between_op_to_sql(
189                    sql_parser_expr,
190                    *negated,
191                    sql_low,
192                    sql_high,
193                ))))
194            }
195            Expr::Column(col) => self.col_to_sql(col),
196            Expr::BinaryExpr(BinaryExpr {
197                left,
198                op: Operator::IsDistinctFrom,
199                right,
200            }) => {
201                let l = self.expr_to_sql_inner(left.as_ref())?;
202                let r = self.expr_to_sql_inner(right.as_ref())?;
203                self.distinct_from_to_sql(l, r, true)
204            }
205            Expr::BinaryExpr(BinaryExpr {
206                left,
207                op: Operator::IsNotDistinctFrom,
208                right,
209            }) => {
210                let l = self.expr_to_sql_inner(left.as_ref())?;
211                let r = self.expr_to_sql_inner(right.as_ref())?;
212                self.distinct_from_to_sql(l, r, false)
213            }
214            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
215                let l = self.expr_to_sql_inner(left.as_ref())?;
216                let r = self.expr_to_sql_inner(right.as_ref())?;
217                let op = self.op_to_sql(op)?;
218
219                Ok(ast::Expr::Nested(Box::new(self.binary_op_to_sql(l, r, op))))
220            }
221            Expr::Case(Case {
222                expr,
223                when_then_expr,
224                else_expr,
225            }) => {
226                let conditions = when_then_expr
227                    .iter()
228                    .map(|(cond, result)| {
229                        Ok(CaseWhen {
230                            condition: self.expr_to_sql_inner(cond)?,
231                            result: self.expr_to_sql_inner(result)?,
232                        })
233                    })
234                    .collect::<Result<Vec<CaseWhen>>>()?;
235
236                let operand = expr
237                    .as_ref()
238                    .map(|e| self.expr_to_sql_inner(e).map(Box::new))
239                    .transpose()?;
240                let else_result = else_expr
241                    .as_ref()
242                    .map(|e| self.expr_to_sql_inner(e).map(Box::new))
243                    .transpose()?;
244
245                Ok(ast::Expr::Case {
246                    operand,
247                    conditions,
248                    else_result,
249                    case_token: AttachedToken::empty(),
250                    end_token: AttachedToken::empty(),
251                })
252            }
253            Expr::Cast(Cast { expr, field }) => Ok(self.cast_to_sql(expr, field)?),
254            Expr::Literal(value, _) => Ok(self.scalar_to_sql(value)?),
255            Expr::Alias(Alias { expr, .. }) => self.expr_to_sql_inner(expr),
256            Expr::WindowFunction(window_fun) => {
257                let WindowFunction {
258                    fun,
259                    params:
260                        WindowFunctionParams {
261                            args,
262                            partition_by,
263                            order_by,
264                            window_frame,
265                            filter,
266                            distinct,
267                            null_treatment,
268                        },
269                } = window_fun.as_ref();
270                let func_name = fun.name();
271
272                let args = self.function_args_to_sql(args)?;
273
274                let units = match window_frame.units {
275                    datafusion_expr::window_frame::WindowFrameUnits::Rows => {
276                        ast::WindowFrameUnits::Rows
277                    }
278                    datafusion_expr::window_frame::WindowFrameUnits::Range => {
279                        ast::WindowFrameUnits::Range
280                    }
281                    datafusion_expr::window_frame::WindowFrameUnits::Groups => {
282                        ast::WindowFrameUnits::Groups
283                    }
284                };
285
286                let order_by = order_by
287                    .iter()
288                    .map(|sort_expr| self.sort_to_sql(sort_expr))
289                    .collect::<Result<Vec<_>>>()?;
290
291                let start_bound = self.convert_bound(&window_frame.start_bound)?;
292                let end_bound = self.convert_bound(&window_frame.end_bound)?;
293
294                let window_frame = if self.dialect.window_func_support_window_frame(
295                    func_name,
296                    &start_bound,
297                    &end_bound,
298                ) {
299                    Some(ast::WindowFrame {
300                        units,
301                        start_bound,
302                        end_bound: Some(end_bound),
303                    })
304                } else {
305                    None
306                };
307
308                let over = Some(ast::WindowType::WindowSpec(ast::WindowSpec {
309                    window_name: None,
310                    partition_by: partition_by
311                        .iter()
312                        .map(|e| self.expr_to_sql_inner(e))
313                        .collect::<Result<Vec<_>>>()?,
314                    order_by,
315                    window_frame,
316                }));
317
318                Ok(ast::Expr::Function(Function {
319                    name: ObjectName::from(vec![Ident {
320                        value: func_name.to_string(),
321                        quote_style: None,
322                        span: Span::empty(),
323                    }]),
324                    args: ast::FunctionArguments::List(ast::FunctionArgumentList {
325                        duplicate_treatment: distinct
326                            .then_some(DuplicateTreatment::Distinct),
327                        args,
328                        clauses: vec![],
329                    }),
330                    filter: filter
331                        .as_ref()
332                        .map(|f| self.expr_to_sql_inner(f).map(Box::new))
333                        .transpose()?,
334                    null_treatment: null_treatment.map(null_treatment_to_sql),
335                    over,
336                    within_group: vec![],
337                    parameters: ast::FunctionArguments::None,
338                    uses_odbc_syntax: false,
339                }))
340            }
341            Expr::SimilarTo(Like {
342                negated,
343                expr,
344                pattern,
345                escape_char,
346                case_insensitive: _,
347            }) => Ok(ast::Expr::Like {
348                negated: *negated,
349                expr: Box::new(self.expr_to_sql_inner(expr)?),
350                pattern: Box::new(self.expr_to_sql_inner(pattern)?),
351                escape_char: escape_char.map(|c| {
352                    Box::new(ast::Expr::Value(SingleQuotedString(c.to_string()).into()))
353                }),
354                any: false,
355            }),
356            Expr::Like(Like {
357                negated,
358                expr,
359                pattern,
360                escape_char,
361                case_insensitive,
362            }) => {
363                let negated = *negated;
364                let expr = Box::new(self.expr_to_sql_inner(expr)?);
365                let pattern = Box::new(self.expr_to_sql_inner(pattern)?);
366                let escape_char = escape_char.map(|c| {
367                    Box::new(ast::Expr::Value(SingleQuotedString(c.to_string()).into()))
368                });
369
370                if *case_insensitive {
371                    Ok(ast::Expr::ILike {
372                        negated,
373                        expr,
374                        pattern,
375                        escape_char,
376                        any: false,
377                    })
378                } else {
379                    Ok(ast::Expr::Like {
380                        negated,
381                        expr,
382                        pattern,
383                        escape_char,
384                        any: false,
385                    })
386                }
387            }
388
389            Expr::AggregateFunction(agg) => {
390                let func_name = agg.func.name();
391                let AggregateFunctionParams {
392                    distinct,
393                    args,
394                    filter,
395                    order_by,
396                    null_treatment,
397                } = &agg.params;
398
399                // An aggregate's `order_by` is spelled one of two ways in SQL:
400                // `WITHIN GROUP (ORDER BY ..)` for ordered-set aggregates, and an
401                // `ORDER BY` clause inside the argument list for every other
402                // aggregate. Both map onto `params.order_by`.
403                let (args_to_use, within_group, clauses) = if order_by.is_empty() {
404                    (self.function_args_to_sql(args)?, vec![], vec![])
405                } else {
406                    let order_by_sql = order_by
407                        .iter()
408                        .map(|sort_expr| self.sort_to_sql(sort_expr))
409                        .collect::<Result<Vec<ast::OrderByExpr>>>()?;
410                    if agg.func.supports_within_group_clause() {
411                        // Ordered-set aggregates carry the ordered value as their
412                        // first argument, so skip it.
413                        (self.function_args_to_sql(&args[1..])?, order_by_sql, vec![])
414                    } else {
415                        (
416                            self.function_args_to_sql(args)?,
417                            vec![],
418                            vec![ast::FunctionArgumentClause::OrderBy(order_by_sql)],
419                        )
420                    }
421                };
422
423                let filter = match filter {
424                    Some(filter) => Some(Box::new(self.expr_to_sql_inner(filter)?)),
425                    None => None,
426                };
427                Ok(ast::Expr::Function(Function {
428                    name: ObjectName::from(vec![Ident {
429                        value: func_name.to_string(),
430                        quote_style: None,
431                        span: Span::empty(),
432                    }]),
433                    args: ast::FunctionArguments::List(ast::FunctionArgumentList {
434                        duplicate_treatment: distinct
435                            .then_some(DuplicateTreatment::Distinct),
436                        args: args_to_use,
437                        clauses,
438                    }),
439                    filter,
440                    null_treatment: null_treatment.map(null_treatment_to_sql),
441                    over: None,
442                    within_group,
443                    parameters: ast::FunctionArguments::None,
444                    uses_odbc_syntax: false,
445                }))
446            }
447            Expr::ScalarSubquery(subq) => {
448                let sub_statement = self.plan_to_sql(subq.subquery.as_ref())?;
449                let ast::Statement::Query(sub_query) = sub_statement else {
450                    return plan_err!(
451                        "Subquery must be a Query, but found {sub_statement:?}"
452                    );
453                };
454                Ok(ast::Expr::Subquery(sub_query))
455            }
456            Expr::InSubquery(insubq) => {
457                let inexpr = Box::new(self.expr_to_sql_inner(insubq.expr.as_ref())?);
458                let sub_statement =
459                    self.plan_to_sql(insubq.subquery.subquery.as_ref())?;
460                let ast::Statement::Query(sub_query) = sub_statement else {
461                    return plan_err!(
462                        "Subquery must be a Query, but found {sub_statement:?}"
463                    );
464                };
465                Ok(ast::Expr::InSubquery {
466                    expr: inexpr,
467                    subquery: sub_query,
468                    negated: insubq.negated,
469                })
470            }
471            Expr::SetComparison(set_cmp) => {
472                let left = Box::new(self.expr_to_sql_inner(set_cmp.expr.as_ref())?);
473                let sub_statement =
474                    self.plan_to_sql(set_cmp.subquery.subquery.as_ref())?;
475                let ast::Statement::Query(sub_query) = sub_statement else {
476                    return plan_err!(
477                        "Subquery must be a Query, but found {sub_statement:?}"
478                    );
479                };
480                let compare_op = self.op_to_sql(&set_cmp.op)?;
481                match set_cmp.quantifier {
482                    SetQuantifier::Any => Ok(ast::Expr::AnyOp {
483                        left,
484                        compare_op,
485                        right: Box::new(ast::Expr::Subquery(sub_query)),
486                        is_some: false,
487                    }),
488                    SetQuantifier::All => Ok(ast::Expr::AllOp {
489                        left,
490                        compare_op,
491                        right: Box::new(ast::Expr::Subquery(sub_query)),
492                    }),
493                }
494            }
495            Expr::Exists(Exists { subquery, negated }) => {
496                let sub_statement = self.plan_to_sql(subquery.subquery.as_ref())?;
497                let ast::Statement::Query(sub_query) = sub_statement else {
498                    return plan_err!(
499                        "Subquery must be a Query, but found {sub_statement:?}"
500                    );
501                };
502                Ok(ast::Expr::Exists {
503                    subquery: sub_query,
504                    negated: *negated,
505                })
506            }
507            Expr::IsNull(expr) => {
508                Ok(ast::Expr::IsNull(Box::new(self.expr_to_sql_inner(expr)?)))
509            }
510            Expr::IsNotNull(expr) => Ok(ast::Expr::IsNotNull(Box::new(
511                self.expr_to_sql_inner(expr)?,
512            ))),
513            Expr::IsTrue(expr) => {
514                Ok(ast::Expr::IsTrue(Box::new(self.expr_to_sql_inner(expr)?)))
515            }
516            Expr::IsNotTrue(expr) => Ok(ast::Expr::IsNotTrue(Box::new(
517                self.expr_to_sql_inner(expr)?,
518            ))),
519            Expr::IsFalse(expr) => {
520                Ok(ast::Expr::IsFalse(Box::new(self.expr_to_sql_inner(expr)?)))
521            }
522            Expr::IsNotFalse(expr) => Ok(ast::Expr::IsNotFalse(Box::new(
523                self.expr_to_sql_inner(expr)?,
524            ))),
525            Expr::IsUnknown(expr) => Ok(ast::Expr::IsUnknown(Box::new(
526                self.expr_to_sql_inner(expr)?,
527            ))),
528            Expr::IsNotUnknown(expr) => Ok(ast::Expr::IsNotUnknown(Box::new(
529                self.expr_to_sql_inner(expr)?,
530            ))),
531            Expr::Not(expr) => {
532                let sql_parser_expr = self.expr_to_sql_inner(expr)?;
533                Ok(AstExpr::UnaryOp {
534                    op: UnaryOperator::Not,
535                    expr: Box::new(sql_parser_expr),
536                })
537            }
538            Expr::Negative(expr) => {
539                let sql_parser_expr = self.expr_to_sql_inner(expr)?;
540                Ok(AstExpr::UnaryOp {
541                    op: UnaryOperator::Minus,
542                    expr: Box::new(sql_parser_expr),
543                })
544            }
545            Expr::ScalarVariable(_, ids) => {
546                assert_or_internal_err!(!ids.is_empty(), "Not a valid ScalarVariable");
547
548                Ok(if ids.len() == 1 {
549                    ast::Expr::Identifier(
550                        self.new_ident_without_quote_style(ids[0].to_string()),
551                    )
552                } else {
553                    ast::Expr::CompoundIdentifier(
554                        ids.iter()
555                            .map(|i| self.new_ident_without_quote_style(i.to_string()))
556                            .collect(),
557                    )
558                })
559            }
560            Expr::TryCast(TryCast { expr, field }) => {
561                let inner_expr = self.expr_to_sql_inner(expr)?;
562                Ok(ast::Expr::Cast {
563                    kind: ast::CastKind::TryCast,
564                    expr: Box::new(inner_expr),
565                    data_type: self.arrow_dtype_to_ast_dtype(field)?,
566                    format: None,
567                })
568            }
569            // TODO: unparsing wildcard addition options
570            #[expect(deprecated)]
571            Expr::Wildcard { qualifier, .. } => {
572                let attached_token = AttachedToken::empty();
573                if let Some(qualifier) = qualifier {
574                    let idents: Vec<Ident> =
575                        qualifier.to_vec().into_iter().map(Ident::new).collect();
576                    Ok(ast::Expr::QualifiedWildcard(
577                        ObjectName::from(idents),
578                        attached_token,
579                    ))
580                } else {
581                    Ok(ast::Expr::Wildcard(attached_token))
582                }
583            }
584            Expr::GroupingSet(grouping_set) => match grouping_set {
585                GroupingSet::GroupingSets(grouping_sets) => {
586                    let expr_ast_sets = grouping_sets
587                        .iter()
588                        .map(|set| {
589                            set.iter()
590                                .map(|e| self.expr_to_sql_inner(e))
591                                .collect::<Result<Vec<_>>>()
592                        })
593                        .collect::<Result<Vec<_>>>()?;
594
595                    Ok(ast::Expr::GroupingSets(expr_ast_sets))
596                }
597                GroupingSet::Cube(cube) => {
598                    let expr_ast_sets = cube
599                        .iter()
600                        .map(|e| {
601                            let sql = self.expr_to_sql_inner(e)?;
602                            Ok(vec![sql])
603                        })
604                        .collect::<Result<Vec<_>>>()?;
605                    Ok(ast::Expr::Cube(expr_ast_sets))
606                }
607                GroupingSet::Rollup(rollup) => {
608                    let expr_ast_sets: Vec<Vec<AstExpr>> = rollup
609                        .iter()
610                        .map(|e| {
611                            let sql = self.expr_to_sql_inner(e)?;
612                            Ok(vec![sql])
613                        })
614                        .collect::<Result<Vec<_>>>()?;
615                    Ok(ast::Expr::Rollup(expr_ast_sets))
616                }
617            },
618            Expr::Placeholder(p) => {
619                Ok(ast::Expr::value(ast::Value::Placeholder(p.id.to_string())))
620            }
621            Expr::OuterReferenceColumn(_, col) => self.col_to_sql(col),
622            Expr::Unnest(unnest) => self.unnest_to_sql(unnest),
623            Expr::HigherOrderFunction(HigherOrderFunction { func, args }) => {
624                let func_name = func.name();
625
626                if let Some(expr) = self
627                    .dialect
628                    .higher_order_function_to_sql_overrides(self, func_name, args)?
629                {
630                    return Ok(expr);
631                }
632
633                self.function_to_sql_internal(func_name, args)
634            }
635            Expr::Lambda(Lambda { params, body }) => {
636                Ok(ast::Expr::Lambda(ast::LambdaFunction {
637                    params: ast::OneOrManyWithParens::Many(
638                        params
639                            .iter()
640                            .map(|param| ast::LambdaFunctionParameter {
641                                name: self.new_ident_quoted_if_needs(param.clone()),
642                                data_type: None,
643                            })
644                            .collect(),
645                    ),
646                    body: Box::new(self.expr_to_sql_inner(body)?),
647                    syntax: ast::LambdaSyntax::Arrow,
648                }))
649            }
650            Expr::LambdaVariable(l) => Ok(ast::Expr::Identifier(
651                self.new_ident_quoted_if_needs(l.name.clone()),
652            )),
653        })
654    }
655
656    pub fn scalar_function_to_sql(
657        &self,
658        func_name: &str,
659        args: &[Expr],
660    ) -> Result<ast::Expr> {
661        match func_name {
662            "make_array" => self.make_array_to_sql(args),
663            "array_element" => self.array_element_to_sql(args),
664            "named_struct" => self.named_struct_to_sql(args),
665            "get_field" => self.get_field_to_sql(args),
666            "map" => self.map_to_sql(args),
667            // TODO: support for the construct and access functions of the `map` type
668            _ => self.function_to_sql_internal(func_name, args),
669        }
670    }
671
672    fn function_to_sql_internal(
673        &self,
674        func_name: &str,
675        args: &[Expr],
676    ) -> Result<ast::Expr> {
677        let args = self.function_args_to_sql(args)?;
678        Ok(ast::Expr::Function(Function {
679            name: ObjectName::from(vec![Ident {
680                value: func_name.to_string(),
681                quote_style: None,
682                span: Span::empty(),
683            }]),
684            args: ast::FunctionArguments::List(ast::FunctionArgumentList {
685                duplicate_treatment: None,
686                args,
687                clauses: vec![],
688            }),
689            filter: None,
690            null_treatment: None,
691            over: None,
692            within_group: vec![],
693            parameters: ast::FunctionArguments::None,
694            uses_odbc_syntax: false,
695        }))
696    }
697
698    fn make_array_to_sql(&self, args: &[Expr]) -> Result<ast::Expr> {
699        let args = args
700            .iter()
701            .map(|e| self.expr_to_sql_with_nesting(e))
702            .collect::<Result<Vec<_>>>()?;
703        Ok(ast::Expr::Array(Array {
704            elem: args,
705            named: self.dialect.use_array_keyword_for_array_literals(),
706        }))
707    }
708
709    fn scalar_value_list_to_sql(&self, array: &ArrayRef) -> Result<ast::Expr> {
710        let mut elem = Vec::with_capacity(array.len());
711        for i in 0..array.len() {
712            let value = ScalarValue::try_from_array(&array, i)?;
713            elem.push(self.scalar_to_sql(&value)?);
714        }
715
716        Ok(ast::Expr::Array(Array {
717            elem,
718            named: self.dialect.use_array_keyword_for_array_literals(),
719        }))
720    }
721
722    fn array_element_to_sql(&self, args: &[Expr]) -> Result<ast::Expr> {
723        assert_eq_or_internal_err!(
724            args.len(),
725            2,
726            "array_element must have exactly 2 arguments"
727        );
728        let array = self.expr_to_sql_with_nesting(&args[0])?;
729        let index = self.expr_to_sql_with_nesting(&args[1])?;
730        Ok(ast::Expr::CompoundFieldAccess {
731            root: Box::new(array),
732            access_chain: vec![ast::AccessExpr::Subscript(Subscript::Index { index })],
733        })
734    }
735
736    fn named_struct_to_sql(&self, args: &[Expr]) -> Result<ast::Expr> {
737        assert_or_internal_err!(
738            args.len().is_multiple_of(2),
739            "named_struct must have an even number of arguments"
740        );
741
742        let args = args
743            .as_chunks::<2>()
744            .0
745            .iter()
746            .map(|[name, value]| {
747                let key = match name {
748                    Expr::Literal(ScalarValue::Utf8(Some(s)), _) => self.new_ident_quoted_if_needs(s.to_string()),
749                    _ => return internal_err!("named_struct expects even arguments to be strings, but received: {name:?}")
750                };
751
752                Ok(ast::DictionaryField {
753                    key,
754                    value: Box::new(self.expr_to_sql_with_nesting(value)?),
755                })
756            })
757            .collect::<Result<Vec<_>>>()?;
758
759        Ok(ast::Expr::Dictionary(args))
760    }
761
762    fn get_field_to_sql(&self, args: &[Expr]) -> Result<ast::Expr> {
763        if args.len() < 2 {
764            return internal_err!(
765                "get_field must have at least 2 arguments, got {}",
766                args.len()
767            );
768        }
769
770        // Extract all field names (args[1..])
771        let mut fields = Vec::with_capacity(args.len() - 1);
772        for arg in &args[1..] {
773            let field = match arg {
774                Expr::Literal(lit, _) => self.new_ident_quoted_if_needs(lit.to_string()),
775                _ => {
776                    return internal_err!(
777                        "get_field expects field arguments to be strings, but received: {:?}",
778                        arg
779                    );
780                }
781            };
782            fields.push(field);
783        }
784
785        match &args[0] {
786            Expr::Column(col) => {
787                let mut id = match self.col_to_sql(col)? {
788                    ast::Expr::Identifier(ident) => vec![ident],
789                    ast::Expr::CompoundIdentifier(idents) => idents,
790                    other => {
791                        return internal_err!(
792                            "expected col_to_sql to return an Identifier or CompoundIdentifier, but received: {:?}",
793                            other
794                        );
795                    }
796                };
797                id.extend(fields);
798                Ok(ast::Expr::CompoundIdentifier(id))
799            }
800            Expr::ScalarFunction(struct_expr) => {
801                let root = self
802                    .scalar_function_to_sql(struct_expr.func.name(), &struct_expr.args)?;
803                let access_chain = fields
804                    .into_iter()
805                    .map(|field| ast::AccessExpr::Dot(ast::Expr::Identifier(field)))
806                    .collect();
807                Ok(ast::Expr::CompoundFieldAccess {
808                    root: Box::new(root),
809                    access_chain,
810                })
811            }
812            _ => {
813                internal_err!(
814                    "get_field expects first argument to be column or scalar function, but received: {:?}",
815                    &args[0]
816                )
817            }
818        }
819    }
820
821    fn map_to_sql(&self, args: &[Expr]) -> Result<ast::Expr> {
822        assert_eq_or_internal_err!(args.len(), 2, "map must have exactly 2 arguments");
823
824        let ast::Expr::Array(Array { elem: keys, .. }) =
825            self.expr_to_sql_with_nesting(&args[0])?
826        else {
827            return internal_err!(
828                "map expects first argument to be an array, but received: {:?}",
829                &args[0]
830            );
831        };
832
833        let ast::Expr::Array(Array { elem: values, .. }) =
834            self.expr_to_sql_with_nesting(&args[1])?
835        else {
836            return internal_err!(
837                "map expects second argument to be an array, but received: {:?}",
838                &args[1]
839            );
840        };
841
842        let entries = keys
843            .into_iter()
844            .zip(values)
845            .map(|(key, value)| ast::MapEntry {
846                key: Box::new(key),
847                value: Box::new(value),
848            })
849            .collect();
850
851        Ok(ast::Expr::Map(ast::Map { entries }))
852    }
853
854    pub fn sort_to_sql(&self, sort: &Sort) -> Result<ast::OrderByExpr> {
855        let Sort {
856            expr,
857            asc,
858            nulls_first,
859        } = sort;
860        let sql_parser_expr = self.expr_to_sql(expr)?;
861
862        let nulls_first = if self.dialect.supports_nulls_first_in_sort() {
863            Some(*nulls_first)
864        } else {
865            None
866        };
867
868        Ok(ast::OrderByExpr {
869            expr: sql_parser_expr,
870            options: OrderByOptions {
871                sort: Some(if *asc {
872                    ast::OrderBySort::Asc
873                } else {
874                    ast::OrderBySort::Desc
875                }),
876                nulls_first,
877            },
878            with_fill: None,
879        })
880    }
881
882    fn ast_type_for_date64_in_cast(&self) -> ast::DataType {
883        if self.dialect.use_timestamp_for_date64() {
884            ast::DataType::Timestamp(None, TimezoneInfo::None)
885        } else {
886            ast::DataType::Datetime(None)
887        }
888    }
889
890    pub fn col_to_sql(&self, col: &Column) -> Result<ast::Expr> {
891        // Replace the column name if the dialect has an override
892        let col_name =
893            if let Some(rewritten_name) = self.dialect.col_alias_overrides(&col.name)? {
894                rewritten_name
895            } else {
896                col.name.to_string()
897            };
898
899        if let Some(table_ref) = &col.relation {
900            let mut id = if self.dialect.full_qualified_col() {
901                table_ref.to_vec()
902            } else {
903                vec![table_ref.table().to_string()]
904            };
905            id.push(col_name);
906            return Ok(ast::Expr::CompoundIdentifier(
907                id.iter()
908                    .map(|i| self.new_ident_quoted_if_needs(i.to_string()))
909                    .collect(),
910            ));
911        }
912        Ok(ast::Expr::Identifier(
913            self.new_ident_quoted_if_needs(col_name),
914        ))
915    }
916
917    fn convert_bound(
918        &self,
919        bound: &datafusion_expr::window_frame::WindowFrameBound,
920    ) -> Result<ast::WindowFrameBound> {
921        match bound {
922            datafusion_expr::window_frame::WindowFrameBound::Preceding(val) => {
923                Ok(ast::WindowFrameBound::Preceding({
924                    let val = self.scalar_to_sql(val)?;
925                    if let ast::Expr::Value(ValueWithSpan {
926                        value: ast::Value::Null,
927                        span: _,
928                    }) = &val
929                    {
930                        None
931                    } else {
932                        Some(Box::new(val))
933                    }
934                }))
935            }
936            datafusion_expr::window_frame::WindowFrameBound::Following(val) => {
937                Ok(ast::WindowFrameBound::Following({
938                    let val = self.scalar_to_sql(val)?;
939                    if let ast::Expr::Value(ValueWithSpan {
940                        value: ast::Value::Null,
941                        span: _,
942                    }) = &val
943                    {
944                        None
945                    } else {
946                        Some(Box::new(val))
947                    }
948                }))
949            }
950            datafusion_expr::window_frame::WindowFrameBound::CurrentRow => {
951                Ok(ast::WindowFrameBound::CurrentRow)
952            }
953        }
954    }
955
956    pub(crate) fn function_args_to_sql(
957        &self,
958        args: &[Expr],
959    ) -> Result<Vec<ast::FunctionArg>> {
960        args.iter()
961            .map(|e| {
962                #[expect(deprecated)]
963                if matches!(
964                    e,
965                    Expr::Wildcard {
966                        qualifier: None,
967                        ..
968                    }
969                ) {
970                    Ok(ast::FunctionArg::Unnamed(ast::FunctionArgExpr::Wildcard))
971                } else {
972                    self.expr_to_sql_with_nesting(e)
973                        .map(|e| ast::FunctionArg::Unnamed(ast::FunctionArgExpr::Expr(e)))
974                }
975            })
976            .collect::<Result<Vec<_>>>()
977    }
978
979    /// This function can create an identifier with or without quotes based on the dialect rules
980    pub(super) fn new_ident_quoted_if_needs(&self, ident: String) -> Ident {
981        let quote_style = self.dialect.identifier_quote_style(&ident);
982        Ident {
983            value: ident,
984            quote_style,
985            span: Span::empty(),
986        }
987    }
988
989    pub(super) fn new_ident_without_quote_style(&self, str: String) -> Ident {
990        Ident {
991            value: str,
992            quote_style: None,
993            span: Span::empty(),
994        }
995    }
996
997    pub(super) fn binary_op_to_sql(
998        &self,
999        lhs: ast::Expr,
1000        rhs: ast::Expr,
1001        op: BinaryOperator,
1002    ) -> ast::Expr {
1003        ast::Expr::BinaryOp {
1004            left: Box::new(lhs),
1005            op,
1006            right: Box::new(rhs),
1007        }
1008    }
1009
1010    /// Given an expression of the form `((a + b) * (c * d))`,
1011    /// the parenthesis is redundant if the precedence of the nested expression is already higher
1012    /// than the surrounding operators' precedence. The above expression would become
1013    /// `(a + b) * c * d`.
1014    ///
1015    /// Also note that when fetching the precedence of a nested expression, we ignore other nested
1016    /// expressions, so precedence of expr `(a * (b + c))` equals `*` and not `+`.
1017    fn remove_unnecessary_nesting(
1018        &self,
1019        expr: ast::Expr,
1020        left_op: &BinaryOperator,
1021        right_op: &BinaryOperator,
1022    ) -> ast::Expr {
1023        crate::stack::maybe_grow(|| match expr {
1024            ast::Expr::Nested(nested) => {
1025                let surrounding_precedence = self
1026                    .sql_op_precedence(left_op)
1027                    .max(self.sql_op_precedence(right_op));
1028
1029                let inner_precedence = self.inner_precedence(&nested);
1030
1031                let not_associative =
1032                    matches!(left_op, BinaryOperator::Minus | BinaryOperator::Divide);
1033
1034                if inner_precedence == surrounding_precedence && not_associative {
1035                    ast::Expr::Nested(Box::new(
1036                        self.remove_unnecessary_nesting(*nested, LOWEST, LOWEST),
1037                    ))
1038                } else if inner_precedence >= surrounding_precedence {
1039                    self.remove_unnecessary_nesting(*nested, left_op, right_op)
1040                } else {
1041                    ast::Expr::Nested(Box::new(
1042                        self.remove_unnecessary_nesting(*nested, LOWEST, LOWEST),
1043                    ))
1044                }
1045            }
1046            ast::Expr::BinaryOp { left, op, right } => ast::Expr::BinaryOp {
1047                left: Box::new(self.remove_unnecessary_nesting(*left, left_op, &op)),
1048                right: Box::new(self.remove_unnecessary_nesting(*right, &op, right_op)),
1049                op,
1050            },
1051            ast::Expr::IsTrue(expr) => ast::Expr::IsTrue(Box::new(
1052                self.remove_unnecessary_nesting(*expr, left_op, IS),
1053            )),
1054            ast::Expr::IsNotTrue(expr) => ast::Expr::IsNotTrue(Box::new(
1055                self.remove_unnecessary_nesting(*expr, left_op, IS),
1056            )),
1057            ast::Expr::IsFalse(expr) => ast::Expr::IsFalse(Box::new(
1058                self.remove_unnecessary_nesting(*expr, left_op, IS),
1059            )),
1060            ast::Expr::IsNotFalse(expr) => ast::Expr::IsNotFalse(Box::new(
1061                self.remove_unnecessary_nesting(*expr, left_op, IS),
1062            )),
1063            ast::Expr::IsNull(expr) => ast::Expr::IsNull(Box::new(
1064                self.remove_unnecessary_nesting(*expr, left_op, IS),
1065            )),
1066            ast::Expr::IsNotNull(expr) => ast::Expr::IsNotNull(Box::new(
1067                self.remove_unnecessary_nesting(*expr, left_op, IS),
1068            )),
1069            ast::Expr::IsUnknown(expr) => ast::Expr::IsUnknown(Box::new(
1070                self.remove_unnecessary_nesting(*expr, left_op, IS),
1071            )),
1072            ast::Expr::IsNotUnknown(expr) => ast::Expr::IsNotUnknown(Box::new(
1073                self.remove_unnecessary_nesting(*expr, left_op, IS),
1074            )),
1075            _ => expr,
1076        })
1077    }
1078
1079    fn inner_precedence(&self, expr: &ast::Expr) -> u8 {
1080        match expr {
1081            ast::Expr::Nested(_) | ast::Expr::Identifier(_) | ast::Expr::Value(_) => 100,
1082            ast::Expr::BinaryOp { op, .. } => self.sql_op_precedence(op),
1083            // Closest precedence we currently have to Between is PGLikeMatch
1084            // (https://www.postgresql.org/docs/7.2/sql-precedence.html)
1085            ast::Expr::Between { .. } => {
1086                self.sql_op_precedence(&BinaryOperator::PGLikeMatch)
1087            }
1088            _ => 0,
1089        }
1090    }
1091
1092    pub(super) fn between_op_to_sql(
1093        &self,
1094        expr: ast::Expr,
1095        negated: bool,
1096        low: ast::Expr,
1097        high: ast::Expr,
1098    ) -> ast::Expr {
1099        ast::Expr::Between {
1100            expr: Box::new(expr),
1101            negated,
1102            low: Box::new(low),
1103            high: Box::new(high),
1104        }
1105    }
1106
1107    fn sql_op_precedence(&self, op: &BinaryOperator) -> u8 {
1108        match self.sql_to_op(op) {
1109            Ok(op) => op.precedence(),
1110            Err(_) => 0,
1111        }
1112    }
1113
1114    fn sql_to_op(&self, op: &BinaryOperator) -> Result<Operator> {
1115        match op {
1116            BinaryOperator::Eq => Ok(Operator::Eq),
1117            BinaryOperator::NotEq => Ok(Operator::NotEq),
1118            BinaryOperator::Lt => Ok(Operator::Lt),
1119            BinaryOperator::LtEq => Ok(Operator::LtEq),
1120            BinaryOperator::Gt => Ok(Operator::Gt),
1121            BinaryOperator::GtEq => Ok(Operator::GtEq),
1122            BinaryOperator::Plus => Ok(Operator::Plus),
1123            BinaryOperator::Minus => Ok(Operator::Minus),
1124            BinaryOperator::Multiply => Ok(Operator::Multiply),
1125            BinaryOperator::Divide => Ok(Operator::Divide),
1126            BinaryOperator::Modulo => Ok(Operator::Modulo),
1127            BinaryOperator::And => Ok(Operator::And),
1128            BinaryOperator::Or => Ok(Operator::Or),
1129            BinaryOperator::PGRegexMatch => Ok(Operator::RegexMatch),
1130            BinaryOperator::PGRegexIMatch => Ok(Operator::RegexIMatch),
1131            BinaryOperator::PGRegexNotMatch => Ok(Operator::RegexNotMatch),
1132            BinaryOperator::PGRegexNotIMatch => Ok(Operator::RegexNotIMatch),
1133            BinaryOperator::PGILikeMatch => Ok(Operator::ILikeMatch),
1134            BinaryOperator::PGNotLikeMatch => Ok(Operator::NotLikeMatch),
1135            BinaryOperator::PGLikeMatch => Ok(Operator::LikeMatch),
1136            BinaryOperator::PGNotILikeMatch => Ok(Operator::NotILikeMatch),
1137            BinaryOperator::BitwiseAnd => Ok(Operator::BitwiseAnd),
1138            BinaryOperator::BitwiseOr => Ok(Operator::BitwiseOr),
1139            BinaryOperator::BitwiseXor => Ok(Operator::BitwiseXor),
1140            BinaryOperator::PGBitwiseShiftRight => Ok(Operator::BitwiseShiftRight),
1141            BinaryOperator::PGBitwiseShiftLeft => Ok(Operator::BitwiseShiftLeft),
1142            BinaryOperator::StringConcat => Ok(Operator::StringConcat),
1143            BinaryOperator::AtArrow => Ok(Operator::AtArrow),
1144            BinaryOperator::ArrowAt => Ok(Operator::ArrowAt),
1145            BinaryOperator::Arrow => Ok(Operator::Arrow),
1146            BinaryOperator::LongArrow => Ok(Operator::LongArrow),
1147            BinaryOperator::HashArrow => Ok(Operator::HashArrow),
1148            BinaryOperator::HashLongArrow => Ok(Operator::HashLongArrow),
1149            BinaryOperator::AtAt => Ok(Operator::AtAt),
1150            BinaryOperator::DuckIntegerDivide | BinaryOperator::MyIntegerDivide => {
1151                Ok(Operator::IntegerDivide)
1152            }
1153            BinaryOperator::HashMinus => Ok(Operator::HashMinus),
1154            BinaryOperator::AtQuestion => Ok(Operator::AtQuestion),
1155            BinaryOperator::Question => Ok(Operator::Question),
1156            BinaryOperator::QuestionAnd => Ok(Operator::QuestionAnd),
1157            BinaryOperator::QuestionPipe => Ok(Operator::QuestionPipe),
1158            _ => not_impl_err!("unsupported operation: {op:?}"),
1159        }
1160    }
1161
1162    fn op_to_sql(&self, op: &Operator) -> Result<BinaryOperator> {
1163        match op {
1164            Operator::Eq => Ok(BinaryOperator::Eq),
1165            Operator::NotEq => Ok(BinaryOperator::NotEq),
1166            Operator::Lt => Ok(BinaryOperator::Lt),
1167            Operator::LtEq => Ok(BinaryOperator::LtEq),
1168            Operator::Gt => Ok(BinaryOperator::Gt),
1169            Operator::GtEq => Ok(BinaryOperator::GtEq),
1170            Operator::Plus => Ok(BinaryOperator::Plus),
1171            Operator::Minus => Ok(BinaryOperator::Minus),
1172            Operator::Multiply => Ok(BinaryOperator::Multiply),
1173            Operator::Divide => Ok(self.dialect.division_operator()),
1174            Operator::Modulo => Ok(BinaryOperator::Modulo),
1175            Operator::And => Ok(BinaryOperator::And),
1176            Operator::Or => Ok(BinaryOperator::Or),
1177            Operator::IsDistinctFrom => not_impl_err!("unsupported operation: {op:?}"),
1178            Operator::IsNotDistinctFrom => not_impl_err!("unsupported operation: {op:?}"),
1179            Operator::RegexMatch => Ok(BinaryOperator::PGRegexMatch),
1180            Operator::RegexIMatch => Ok(BinaryOperator::PGRegexIMatch),
1181            Operator::RegexNotMatch => Ok(BinaryOperator::PGRegexNotMatch),
1182            Operator::RegexNotIMatch => Ok(BinaryOperator::PGRegexNotIMatch),
1183            Operator::ILikeMatch => Ok(BinaryOperator::PGILikeMatch),
1184            Operator::NotLikeMatch => Ok(BinaryOperator::PGNotLikeMatch),
1185            Operator::LikeMatch => Ok(BinaryOperator::PGLikeMatch),
1186            Operator::NotILikeMatch => Ok(BinaryOperator::PGNotILikeMatch),
1187            Operator::BitwiseAnd => Ok(BinaryOperator::BitwiseAnd),
1188            Operator::BitwiseOr => Ok(BinaryOperator::BitwiseOr),
1189            Operator::BitwiseXor => Ok(BinaryOperator::BitwiseXor),
1190            Operator::BitwiseShiftRight => Ok(BinaryOperator::PGBitwiseShiftRight),
1191            Operator::BitwiseShiftLeft => Ok(BinaryOperator::PGBitwiseShiftLeft),
1192            Operator::StringConcat => Ok(BinaryOperator::StringConcat),
1193            Operator::AtArrow => Ok(BinaryOperator::AtArrow),
1194            Operator::ArrowAt => Ok(BinaryOperator::ArrowAt),
1195            Operator::Arrow => Ok(BinaryOperator::Arrow),
1196            Operator::LongArrow => Ok(BinaryOperator::LongArrow),
1197            Operator::HashArrow => Ok(BinaryOperator::HashArrow),
1198            Operator::HashLongArrow => Ok(BinaryOperator::HashLongArrow),
1199            Operator::AtAt => Ok(BinaryOperator::AtAt),
1200            Operator::IntegerDivide => Ok(BinaryOperator::DuckIntegerDivide),
1201            Operator::HashMinus => Ok(BinaryOperator::HashMinus),
1202            Operator::AtQuestion => Ok(BinaryOperator::AtQuestion),
1203            Operator::Question => Ok(BinaryOperator::Question),
1204            Operator::QuestionAnd => Ok(BinaryOperator::QuestionAnd),
1205            Operator::QuestionPipe => Ok(BinaryOperator::QuestionPipe),
1206            Operator::Colon => Ok(BinaryOperator::Custom(":".to_owned())),
1207        }
1208    }
1209
1210    fn handle_timestamp<T: ArrowTemporalType>(
1211        &self,
1212        v: &ScalarValue,
1213        tz: Option<&Arc<str>>,
1214    ) -> Result<ast::Expr>
1215    where
1216        i64: From<T::Native>,
1217    {
1218        let DataType::Timestamp(time_unit, _) = T::DATA_TYPE else {
1219            return Err(internal_datafusion_err!(
1220                "Expected Timestamp, got {:?}",
1221                T::DATA_TYPE
1222            ));
1223        };
1224
1225        let ts = if let Some(tz) = tz {
1226            let dt = v
1227                .to_array()?
1228                .as_any()
1229                .downcast_ref::<PrimitiveArray<T>>()
1230                .ok_or(internal_datafusion_err!(
1231                    "Failed to downcast type {v:?} to arrow array"
1232                ))?
1233                .value_as_datetime_with_tz(0, tz.parse()?)
1234                .ok_or(internal_datafusion_err!(
1235                    "Unable to convert {v:?} to DateTime"
1236                ))?;
1237            self.dialect.timestamp_with_tz_to_string(dt, time_unit)
1238        } else {
1239            v.to_array()?
1240                .as_any()
1241                .downcast_ref::<PrimitiveArray<T>>()
1242                .ok_or(internal_datafusion_err!(
1243                    "Failed to downcast type {v:?} to arrow array"
1244                ))?
1245                .value_as_datetime(0)
1246                .ok_or(internal_datafusion_err!(
1247                    "Unable to convert {v:?} to DateTime"
1248                ))?
1249                .to_string()
1250        };
1251
1252        Ok(ast::Expr::Cast {
1253            kind: ast::CastKind::Cast,
1254            expr: Box::new(ast::Expr::value(SingleQuotedString(ts))),
1255            data_type: self.dialect.timestamp_cast_dtype(&time_unit, &tz.cloned()),
1256            format: None,
1257        })
1258    }
1259
1260    fn handle_time<T: ArrowTemporalType>(&self, v: &ScalarValue) -> Result<ast::Expr>
1261    where
1262        i64: From<T::Native>,
1263    {
1264        let time = v
1265            .to_array()?
1266            .as_any()
1267            .downcast_ref::<PrimitiveArray<T>>()
1268            .ok_or(internal_datafusion_err!(
1269                "Failed to downcast type {v:?} to arrow array"
1270            ))?
1271            .value_as_time(0)
1272            .ok_or(internal_datafusion_err!("Unable to convert {v:?} to Time"))?
1273            .to_string();
1274        Ok(ast::Expr::Cast {
1275            kind: ast::CastKind::Cast,
1276            expr: Box::new(ast::Expr::value(SingleQuotedString(time))),
1277            data_type: ast::DataType::Time(None, TimezoneInfo::None),
1278            format: None,
1279        })
1280    }
1281
1282    // Explicit type cast on ast::Expr::Value is not needed by underlying engine for certain types
1283    // For example: CAST(Utf8("binary_value") AS Binary) and  CAST(Utf8("dictionary_value") AS Dictionary)
1284    fn cast_to_sql(&self, expr: &Expr, field: &FieldRef) -> Result<ast::Expr> {
1285        let inner_expr = self.expr_to_sql_inner(expr)?;
1286        let data_type = field.data_type();
1287        match inner_expr {
1288            ast::Expr::Value(_) => match data_type {
1289                DataType::Dictionary(_, _) | DataType::Binary | DataType::BinaryView
1290                    if field.metadata().is_empty() =>
1291                {
1292                    Ok(inner_expr)
1293                }
1294                _ => Ok(ast::Expr::Cast {
1295                    kind: ast::CastKind::Cast,
1296                    expr: Box::new(inner_expr),
1297                    data_type: self.arrow_dtype_to_ast_dtype(field)?,
1298                    format: None,
1299                }),
1300            },
1301            _ => Ok(ast::Expr::Cast {
1302                kind: ast::CastKind::Cast,
1303                expr: Box::new(inner_expr),
1304                data_type: self.arrow_dtype_to_ast_dtype(field)?,
1305                format: None,
1306            }),
1307        }
1308    }
1309
1310    /// DataFusion ScalarValues sometimes require a ast::Expr to construct.
1311    /// For example ScalarValue::Date32(d) corresponds to the ast::Expr CAST('datestr' as DATE)
1312    fn scalar_to_sql(&self, v: &ScalarValue) -> Result<ast::Expr> {
1313        match v {
1314            ScalarValue::Null => Ok(ast::Expr::value(ast::Value::Null)),
1315            ScalarValue::Boolean(Some(b)) => {
1316                Ok(ast::Expr::value(ast::Value::Boolean(b.to_owned())))
1317            }
1318            ScalarValue::Boolean(None) => Ok(ast::Expr::value(ast::Value::Null)),
1319            ScalarValue::Float16(Some(f)) => {
1320                Ok(ast::Expr::value(ast::Value::Number(f.to_string(), false)))
1321            }
1322            ScalarValue::Float16(None) => Ok(ast::Expr::value(ast::Value::Null)),
1323            ScalarValue::Float32(Some(f)) => {
1324                let f_val = match f.fract() {
1325                    0.0 => format!("{f:.1}"),
1326                    _ => format!("{f}"),
1327                };
1328                Ok(ast::Expr::value(ast::Value::Number(f_val, false)))
1329            }
1330            ScalarValue::Float32(None) => Ok(ast::Expr::value(ast::Value::Null)),
1331            ScalarValue::Float64(Some(f)) => {
1332                let f_val = match f.fract() {
1333                    0.0 => format!("{f:.1}"),
1334                    _ => format!("{f}"),
1335                };
1336                Ok(ast::Expr::value(ast::Value::Number(f_val, false)))
1337            }
1338            ScalarValue::Float64(None) => Ok(ast::Expr::value(ast::Value::Null)),
1339            ScalarValue::Decimal32(Some(value), precision, scale) => {
1340                Ok(ast::Expr::value(ast::Value::Number(
1341                    Decimal32Type::format_decimal(*value, *precision, *scale),
1342                    false,
1343                )))
1344            }
1345            ScalarValue::Decimal32(None, ..) => Ok(ast::Expr::value(ast::Value::Null)),
1346            ScalarValue::Decimal64(Some(value), precision, scale) => {
1347                Ok(ast::Expr::value(ast::Value::Number(
1348                    Decimal64Type::format_decimal(*value, *precision, *scale),
1349                    false,
1350                )))
1351            }
1352            ScalarValue::Decimal64(None, ..) => Ok(ast::Expr::value(ast::Value::Null)),
1353            ScalarValue::Decimal128(Some(value), precision, scale) => {
1354                Ok(ast::Expr::value(ast::Value::Number(
1355                    Decimal128Type::format_decimal(*value, *precision, *scale),
1356                    false,
1357                )))
1358            }
1359            ScalarValue::Decimal128(None, ..) => Ok(ast::Expr::value(ast::Value::Null)),
1360            ScalarValue::Decimal256(Some(value), precision, scale) => {
1361                Ok(ast::Expr::value(ast::Value::Number(
1362                    Decimal256Type::format_decimal(*value, *precision, *scale),
1363                    false,
1364                )))
1365            }
1366            ScalarValue::Decimal256(None, ..) => Ok(ast::Expr::value(ast::Value::Null)),
1367            ScalarValue::Int8(Some(i)) => {
1368                Ok(ast::Expr::value(ast::Value::Number(i.to_string(), false)))
1369            }
1370            ScalarValue::Int8(None) => Ok(ast::Expr::value(ast::Value::Null)),
1371            ScalarValue::Int16(Some(i)) => {
1372                Ok(ast::Expr::value(ast::Value::Number(i.to_string(), false)))
1373            }
1374            ScalarValue::Int16(None) => Ok(ast::Expr::value(ast::Value::Null)),
1375            ScalarValue::Int32(Some(i)) => {
1376                Ok(ast::Expr::value(ast::Value::Number(i.to_string(), false)))
1377            }
1378            ScalarValue::Int32(None) => Ok(ast::Expr::value(ast::Value::Null)),
1379            ScalarValue::Int64(Some(i)) => {
1380                Ok(ast::Expr::value(ast::Value::Number(i.to_string(), false)))
1381            }
1382            ScalarValue::Int64(None) => Ok(ast::Expr::value(ast::Value::Null)),
1383            ScalarValue::UInt8(Some(ui)) => {
1384                Ok(ast::Expr::value(ast::Value::Number(ui.to_string(), false)))
1385            }
1386            ScalarValue::UInt8(None) => Ok(ast::Expr::value(ast::Value::Null)),
1387            ScalarValue::UInt16(Some(ui)) => {
1388                Ok(ast::Expr::value(ast::Value::Number(ui.to_string(), false)))
1389            }
1390            ScalarValue::UInt16(None) => Ok(ast::Expr::value(ast::Value::Null)),
1391            ScalarValue::UInt32(Some(ui)) => {
1392                Ok(ast::Expr::value(ast::Value::Number(ui.to_string(), false)))
1393            }
1394            ScalarValue::UInt32(None) => Ok(ast::Expr::value(ast::Value::Null)),
1395            ScalarValue::UInt64(Some(ui)) => {
1396                Ok(ast::Expr::value(ast::Value::Number(ui.to_string(), false)))
1397            }
1398            ScalarValue::UInt64(None) => Ok(ast::Expr::value(ast::Value::Null)),
1399            ScalarValue::Utf8(Some(str))
1400            | ScalarValue::Utf8View(Some(str))
1401            | ScalarValue::LargeUtf8(Some(str)) => {
1402                if let Some(expr) = self.dialect.string_literal_to_sql(str) {
1403                    return Ok(expr);
1404                }
1405                Ok(ast::Expr::value(SingleQuotedString(str.to_string())))
1406            }
1407            ScalarValue::Utf8(None)
1408            | ScalarValue::Utf8View(None)
1409            | ScalarValue::LargeUtf8(None) => Ok(ast::Expr::value(ast::Value::Null)),
1410            ScalarValue::Binary(Some(bin))
1411            | ScalarValue::BinaryView(Some(bin))
1412            | ScalarValue::LargeBinary(Some(bin))
1413            | ScalarValue::FixedSizeBinary(_, Some(bin)) => {
1414                let hex = bin
1415                    .iter()
1416                    .flat_map(|x| {
1417                        const HEX: [char; 16] = [
1418                            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
1419                            'c', 'd', 'e', 'f',
1420                        ];
1421                        let (hi, lo) = (((*x >> 4) & 0xfu8), (*x & 0xfu8));
1422                        [HEX[hi as usize], HEX[lo as usize]]
1423                    })
1424                    .collect::<String>();
1425                Ok(ast::Expr::value(ast::Value::HexStringLiteral(hex)))
1426            }
1427            ScalarValue::Binary(None)
1428            | ScalarValue::BinaryView(None)
1429            | ScalarValue::FixedSizeBinary(_, None)
1430            | ScalarValue::LargeBinary(None) => Ok(ast::Expr::value(ast::Value::Null)),
1431            ScalarValue::FixedSizeList(a) => self.scalar_value_list_to_sql(a.values()),
1432            ScalarValue::List(a) => self.scalar_value_list_to_sql(a.values()),
1433            ScalarValue::LargeList(a) => self.scalar_value_list_to_sql(a.values()),
1434            ScalarValue::ListView(a) => self.scalar_value_list_to_sql(a.values()),
1435            ScalarValue::LargeListView(a) => self.scalar_value_list_to_sql(a.values()),
1436            ScalarValue::Date32(Some(_)) => {
1437                let date = v
1438                    .to_array()?
1439                    .as_any()
1440                    .downcast_ref::<Date32Array>()
1441                    .ok_or(internal_datafusion_err!(
1442                        "Unable to downcast to Date32 from Date32 scalar"
1443                    ))?
1444                    .value_as_date(0)
1445                    .ok_or(internal_datafusion_err!(
1446                        "Unable to convert Date32 to NaiveDate"
1447                    ))?;
1448
1449                Ok(ast::Expr::Cast {
1450                    kind: ast::CastKind::Cast,
1451                    expr: Box::new(ast::Expr::value(SingleQuotedString(
1452                        date.to_string(),
1453                    ))),
1454                    data_type: ast::DataType::Date,
1455                    format: None,
1456                })
1457            }
1458            ScalarValue::Date32(None) => Ok(ast::Expr::value(ast::Value::Null)),
1459            ScalarValue::Date64(Some(_)) => {
1460                let datetime = v
1461                    .to_array()?
1462                    .as_any()
1463                    .downcast_ref::<Date64Array>()
1464                    .ok_or(internal_datafusion_err!(
1465                        "Unable to downcast to Date64 from Date64 scalar"
1466                    ))?
1467                    .value_as_datetime(0)
1468                    .ok_or(internal_datafusion_err!(
1469                        "Unable to convert Date64 to NaiveDateTime"
1470                    ))?;
1471
1472                Ok(ast::Expr::Cast {
1473                    kind: ast::CastKind::Cast,
1474                    expr: Box::new(ast::Expr::value(SingleQuotedString(
1475                        datetime.to_string(),
1476                    ))),
1477                    data_type: self.ast_type_for_date64_in_cast(),
1478                    format: None,
1479                })
1480            }
1481            ScalarValue::Date64(None) => Ok(ast::Expr::value(ast::Value::Null)),
1482            ScalarValue::Time32Second(Some(_t)) => {
1483                self.handle_time::<Time32SecondType>(v)
1484            }
1485            ScalarValue::Time32Second(None) => Ok(ast::Expr::value(ast::Value::Null)),
1486            ScalarValue::Time32Millisecond(Some(_t)) => {
1487                self.handle_time::<Time32MillisecondType>(v)
1488            }
1489            ScalarValue::Time32Millisecond(None) => {
1490                Ok(ast::Expr::value(ast::Value::Null))
1491            }
1492            ScalarValue::Time64Microsecond(Some(_t)) => {
1493                self.handle_time::<Time64MicrosecondType>(v)
1494            }
1495            ScalarValue::Time64Microsecond(None) => {
1496                Ok(ast::Expr::value(ast::Value::Null))
1497            }
1498            ScalarValue::Time64Nanosecond(Some(_t)) => {
1499                self.handle_time::<Time64NanosecondType>(v)
1500            }
1501            ScalarValue::Time64Nanosecond(None) => Ok(ast::Expr::value(ast::Value::Null)),
1502            ScalarValue::TimestampSecond(Some(_ts), tz) => {
1503                self.handle_timestamp::<TimestampSecondType>(v, tz.as_ref())
1504            }
1505            ScalarValue::TimestampSecond(None, _) => {
1506                Ok(ast::Expr::value(ast::Value::Null))
1507            }
1508            ScalarValue::TimestampMillisecond(Some(_ts), tz) => {
1509                self.handle_timestamp::<TimestampMillisecondType>(v, tz.as_ref())
1510            }
1511            ScalarValue::TimestampMillisecond(None, _) => {
1512                Ok(ast::Expr::value(ast::Value::Null))
1513            }
1514            ScalarValue::TimestampMicrosecond(Some(_ts), tz) => {
1515                self.handle_timestamp::<TimestampMicrosecondType>(v, tz.as_ref())
1516            }
1517            ScalarValue::TimestampMicrosecond(None, _) => {
1518                Ok(ast::Expr::value(ast::Value::Null))
1519            }
1520            ScalarValue::TimestampNanosecond(Some(_ts), tz) => {
1521                self.handle_timestamp::<TimestampNanosecondType>(v, tz.as_ref())
1522            }
1523            ScalarValue::TimestampNanosecond(None, _) => {
1524                Ok(ast::Expr::value(ast::Value::Null))
1525            }
1526            ScalarValue::IntervalYearMonth(Some(_))
1527            | ScalarValue::IntervalDayTime(Some(_))
1528            | ScalarValue::IntervalMonthDayNano(Some(_)) => {
1529                self.interval_scalar_to_sql(v)
1530            }
1531            ScalarValue::IntervalYearMonth(None) => {
1532                Ok(ast::Expr::value(ast::Value::Null))
1533            }
1534            ScalarValue::IntervalDayTime(None) => Ok(ast::Expr::value(ast::Value::Null)),
1535            ScalarValue::IntervalMonthDayNano(None) => {
1536                Ok(ast::Expr::value(ast::Value::Null))
1537            }
1538            ScalarValue::DurationSecond(Some(_d)) => {
1539                not_impl_err!("Unsupported scalar: {v:?}")
1540            }
1541            ScalarValue::DurationSecond(None) => Ok(ast::Expr::value(ast::Value::Null)),
1542            ScalarValue::DurationMillisecond(Some(_d)) => {
1543                not_impl_err!("Unsupported scalar: {v:?}")
1544            }
1545            ScalarValue::DurationMillisecond(None) => {
1546                Ok(ast::Expr::value(ast::Value::Null))
1547            }
1548            ScalarValue::DurationMicrosecond(Some(_d)) => {
1549                not_impl_err!("Unsupported scalar: {v:?}")
1550            }
1551            ScalarValue::DurationMicrosecond(None) => {
1552                Ok(ast::Expr::value(ast::Value::Null))
1553            }
1554            ScalarValue::DurationNanosecond(Some(_d)) => {
1555                not_impl_err!("Unsupported scalar: {v:?}")
1556            }
1557            ScalarValue::DurationNanosecond(None) => {
1558                Ok(ast::Expr::value(ast::Value::Null))
1559            }
1560            ScalarValue::Struct(_) => not_impl_err!("Unsupported scalar: {v:?}"),
1561            ScalarValue::Map(_) => not_impl_err!("Unsupported scalar: {v:?}"),
1562            ScalarValue::Union(..) => not_impl_err!("Unsupported scalar: {v:?}"),
1563            ScalarValue::Dictionary(_k, v) => self.scalar_to_sql(v),
1564            ScalarValue::RunEndEncoded(_, _, v) => self.scalar_to_sql(v),
1565        }
1566    }
1567
1568    /// MySQL requires INTERVAL sql to be in the format: INTERVAL 1 YEAR + INTERVAL 1 MONTH + INTERVAL 1 DAY etc
1569    /// `<https://dev.mysql.com/doc/refman/8.4/en/expressions.html#temporal-intervals>`
1570    /// Interval sequence can't be wrapped in brackets - (INTERVAL 1 YEAR + INTERVAL 1 MONTH ...) so we need to generate
1571    /// a single INTERVAL expression so it works correct for interval subtraction cases
1572    /// MySQL supports the DAY_MICROSECOND unit type (format is DAYS HOURS:MINUTES:SECONDS.MICROSECONDS), but it is not supported by sqlparser
1573    /// so we calculate the best single interval to represent the provided duration
1574    fn interval_to_mysql_expr(
1575        &self,
1576        months: i32,
1577        days: i32,
1578        microseconds: i64,
1579    ) -> Result<ast::Expr> {
1580        // MONTH only
1581        if months != 0 && days == 0 && microseconds == 0 {
1582            let interval = Interval {
1583                value: Box::new(ast::Expr::value(ast::Value::Number(
1584                    months.to_string(),
1585                    false,
1586                ))),
1587                leading_field: Some(ast::DateTimeField::Month),
1588                leading_precision: None,
1589                last_field: None,
1590                fractional_seconds_precision: None,
1591            };
1592            return Ok(ast::Expr::Interval(interval));
1593        } else if months != 0 {
1594            return not_impl_err!(
1595                "Unsupported Interval scalar with both Month and DayTime for IntervalStyle::MySQL"
1596            );
1597        }
1598
1599        // DAY only
1600        if microseconds == 0 {
1601            let interval = Interval {
1602                value: Box::new(ast::Expr::value(ast::Value::Number(
1603                    days.to_string(),
1604                    false,
1605                ))),
1606                leading_field: Some(ast::DateTimeField::Day),
1607                leading_precision: None,
1608                last_field: None,
1609                fractional_seconds_precision: None,
1610            };
1611            return Ok(ast::Expr::Interval(interval));
1612        }
1613
1614        // Calculate the best single interval to represent the provided days and microseconds
1615
1616        let microseconds = microseconds + (days as i64 * 24 * 60 * 60 * 1_000_000);
1617
1618        if microseconds % 1_000_000 != 0 {
1619            let interval = Interval {
1620                value: Box::new(ast::Expr::value(ast::Value::Number(
1621                    microseconds.to_string(),
1622                    false,
1623                ))),
1624                leading_field: Some(ast::DateTimeField::Microsecond),
1625                leading_precision: None,
1626                last_field: None,
1627                fractional_seconds_precision: None,
1628            };
1629            return Ok(ast::Expr::Interval(interval));
1630        }
1631
1632        let secs = microseconds / 1_000_000;
1633
1634        if secs % 60 != 0 {
1635            let interval = Interval {
1636                value: Box::new(ast::Expr::value(ast::Value::Number(
1637                    secs.to_string(),
1638                    false,
1639                ))),
1640                leading_field: Some(ast::DateTimeField::Second),
1641                leading_precision: None,
1642                last_field: None,
1643                fractional_seconds_precision: None,
1644            };
1645            return Ok(ast::Expr::Interval(interval));
1646        }
1647
1648        let mins = secs / 60;
1649
1650        if mins % 60 != 0 {
1651            let interval = Interval {
1652                value: Box::new(ast::Expr::value(ast::Value::Number(
1653                    mins.to_string(),
1654                    false,
1655                ))),
1656                leading_field: Some(ast::DateTimeField::Minute),
1657                leading_precision: None,
1658                last_field: None,
1659                fractional_seconds_precision: None,
1660            };
1661            return Ok(ast::Expr::Interval(interval));
1662        }
1663
1664        let hours = mins / 60;
1665
1666        if hours % 24 != 0 {
1667            let interval = Interval {
1668                value: Box::new(ast::Expr::value(ast::Value::Number(
1669                    hours.to_string(),
1670                    false,
1671                ))),
1672                leading_field: Some(ast::DateTimeField::Hour),
1673                leading_precision: None,
1674                last_field: None,
1675                fractional_seconds_precision: None,
1676            };
1677            return Ok(ast::Expr::Interval(interval));
1678        }
1679
1680        let days = hours / 24;
1681
1682        let interval = Interval {
1683            value: Box::new(ast::Expr::value(ast::Value::Number(
1684                days.to_string(),
1685                false,
1686            ))),
1687            leading_field: Some(ast::DateTimeField::Day),
1688            leading_precision: None,
1689            last_field: None,
1690            fractional_seconds_precision: None,
1691        };
1692        Ok(ast::Expr::Interval(interval))
1693    }
1694
1695    fn interval_scalar_to_sql(&self, v: &ScalarValue) -> Result<ast::Expr> {
1696        match self.dialect.interval_style() {
1697            IntervalStyle::PostgresVerbose => {
1698                let wrap_array = v.to_array()?;
1699                let Some(result) = array_value_to_string(&wrap_array, 0).ok() else {
1700                    return internal_err!(
1701                        "Unable to convert interval scalar value to string"
1702                    );
1703                };
1704                let interval = Interval {
1705                    value: Box::new(ast::Expr::value(SingleQuotedString(
1706                        result.to_uppercase(),
1707                    ))),
1708                    leading_field: None,
1709                    leading_precision: None,
1710                    last_field: None,
1711                    fractional_seconds_precision: None,
1712                };
1713                Ok(ast::Expr::Interval(interval))
1714            }
1715            // If the interval standard is SQLStandard, implement a simple unparse logic
1716            IntervalStyle::SQLStandard => match v {
1717                ScalarValue::IntervalYearMonth(Some(v)) => {
1718                    let interval = Interval {
1719                        value: Box::new(ast::Expr::value(SingleQuotedString(
1720                            v.to_string(),
1721                        ))),
1722                        leading_field: Some(ast::DateTimeField::Month),
1723                        leading_precision: None,
1724                        last_field: None,
1725                        fractional_seconds_precision: None,
1726                    };
1727                    Ok(ast::Expr::Interval(interval))
1728                }
1729                ScalarValue::IntervalDayTime(Some(v)) => {
1730                    let days = v.days;
1731                    let secs = v.milliseconds / 1_000;
1732                    let mins = secs / 60;
1733                    let hours = mins / 60;
1734
1735                    let secs = secs - (mins * 60);
1736                    let mins = mins - (hours * 60);
1737
1738                    let millis = v.milliseconds % 1_000;
1739                    let interval = Interval {
1740                        value: Box::new(ast::Expr::value(SingleQuotedString(format!(
1741                            "{days} {hours}:{mins}:{secs}.{millis:3}"
1742                        )))),
1743                        leading_field: Some(ast::DateTimeField::Day),
1744                        leading_precision: None,
1745                        last_field: Some(ast::DateTimeField::Second),
1746                        fractional_seconds_precision: None,
1747                    };
1748                    Ok(ast::Expr::Interval(interval))
1749                }
1750                ScalarValue::IntervalMonthDayNano(Some(v)) => {
1751                    if v.months >= 0 && v.days == 0 && v.nanoseconds == 0 {
1752                        let interval = Interval {
1753                            value: Box::new(ast::Expr::value(SingleQuotedString(
1754                                v.months.to_string(),
1755                            ))),
1756                            leading_field: Some(ast::DateTimeField::Month),
1757                            leading_precision: None,
1758                            last_field: None,
1759                            fractional_seconds_precision: None,
1760                        };
1761                        Ok(ast::Expr::Interval(interval))
1762                    } else if v.months == 0 && v.nanoseconds % 1_000_000 == 0 {
1763                        let days = v.days;
1764                        let secs = v.nanoseconds / 1_000_000_000;
1765                        let mins = secs / 60;
1766                        let hours = mins / 60;
1767
1768                        let secs = secs - (mins * 60);
1769                        let mins = mins - (hours * 60);
1770
1771                        let millis = (v.nanoseconds % 1_000_000_000) / 1_000_000;
1772
1773                        let interval = Interval {
1774                            value: Box::new(ast::Expr::value(SingleQuotedString(
1775                                format!("{days} {hours}:{mins}:{secs}.{millis:03}"),
1776                            ))),
1777                            leading_field: Some(ast::DateTimeField::Day),
1778                            leading_precision: None,
1779                            last_field: Some(ast::DateTimeField::Second),
1780                            fractional_seconds_precision: None,
1781                        };
1782                        Ok(ast::Expr::Interval(interval))
1783                    } else {
1784                        not_impl_err!(
1785                            "Unsupported IntervalMonthDayNano scalar with both Month and DayTime for IntervalStyle::SQLStandard"
1786                        )
1787                    }
1788                }
1789                _ => not_impl_err!(
1790                    "Unsupported ScalarValue for Interval conversion: {v:?}"
1791                ),
1792            },
1793            IntervalStyle::MySQL => match v {
1794                ScalarValue::IntervalYearMonth(Some(v)) => {
1795                    self.interval_to_mysql_expr(*v, 0, 0)
1796                }
1797                ScalarValue::IntervalDayTime(Some(v)) => {
1798                    self.interval_to_mysql_expr(0, v.days, v.milliseconds as i64 * 1_000)
1799                }
1800                ScalarValue::IntervalMonthDayNano(Some(v)) => {
1801                    if v.nanoseconds % 1_000 != 0 {
1802                        return not_impl_err!(
1803                            "Unsupported IntervalMonthDayNano scalar with nanoseconds precision for IntervalStyle::MySQL"
1804                        );
1805                    }
1806                    self.interval_to_mysql_expr(v.months, v.days, v.nanoseconds / 1_000)
1807                }
1808                _ => not_impl_err!(
1809                    "Unsupported ScalarValue for Interval conversion: {v:?}"
1810                ),
1811            },
1812        }
1813    }
1814
1815    /// Converts an UNNEST operation to an AST expression by wrapping it as a function call,
1816    /// since there is no direct representation for UNNEST in the AST.
1817    fn unnest_to_sql(&self, unnest: &Unnest) -> Result<ast::Expr> {
1818        let args = self.function_args_to_sql(std::slice::from_ref(&unnest.expr))?;
1819
1820        Ok(ast::Expr::Function(Function {
1821            name: ObjectName::from(vec![Ident {
1822                value: "UNNEST".to_string(),
1823                quote_style: None,
1824                span: Span::empty(),
1825            }]),
1826            args: ast::FunctionArguments::List(ast::FunctionArgumentList {
1827                duplicate_treatment: None,
1828                args,
1829                clauses: vec![],
1830            }),
1831            filter: None,
1832            null_treatment: None,
1833            over: None,
1834            within_group: vec![],
1835            parameters: ast::FunctionArguments::None,
1836            uses_odbc_syntax: false,
1837        }))
1838    }
1839
1840    fn arrow_dtype_to_ast_dtype(&self, field: &FieldRef) -> Result<ast::DataType> {
1841        let data_type = field.data_type();
1842        match data_type {
1843            DataType::Null => {
1844                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1845            }
1846            DataType::Boolean => Ok(ast::DataType::Bool),
1847            DataType::Int8 => Ok(self.dialect.int8_cast_dtype()),
1848            DataType::Int16 => Ok(ast::DataType::SmallInt(None)),
1849            DataType::Int32 => Ok(self.dialect.int32_cast_dtype()),
1850            DataType::Int64 => Ok(self.dialect.int64_cast_dtype()),
1851            DataType::UInt8 => Ok(ast::DataType::TinyIntUnsigned(None)),
1852            DataType::UInt16 => Ok(ast::DataType::SmallIntUnsigned(None)),
1853            DataType::UInt32 => Ok(ast::DataType::IntegerUnsigned(None)),
1854            DataType::UInt64 => Ok(ast::DataType::BigIntUnsigned(None)),
1855            DataType::Float16 => {
1856                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1857            }
1858            DataType::Float32 => Ok(ast::DataType::Float(ast::ExactNumberInfo::None)),
1859            DataType::Float64 => Ok(self.dialect.float64_ast_dtype()),
1860            DataType::Timestamp(time_unit, tz) => {
1861                Ok(self.dialect.timestamp_cast_dtype(time_unit, tz))
1862            }
1863            DataType::Date32 => Ok(self.dialect.date32_cast_dtype()),
1864            DataType::Date64 => Ok(self.ast_type_for_date64_in_cast()),
1865            DataType::Time32(_) => {
1866                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1867            }
1868            DataType::Time64(_) => {
1869                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1870            }
1871            DataType::Duration(_) => {
1872                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1873            }
1874            DataType::Interval(_) => Ok(ast::DataType::Interval {
1875                fields: None,
1876                precision: None,
1877            }),
1878            DataType::Binary => {
1879                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1880            }
1881            DataType::FixedSizeBinary(_) => {
1882                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1883            }
1884            DataType::LargeBinary => {
1885                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1886            }
1887            DataType::BinaryView => {
1888                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1889            }
1890            DataType::Utf8 => Ok(self.dialect.utf8_cast_dtype()),
1891            DataType::LargeUtf8 => Ok(self.dialect.large_utf8_cast_dtype()),
1892            DataType::Utf8View => Ok(self.dialect.utf8_cast_dtype()),
1893            DataType::List(_) => {
1894                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1895            }
1896            DataType::FixedSizeList(_, _) => {
1897                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1898            }
1899            DataType::LargeList(_) => {
1900                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1901            }
1902            DataType::ListView(_) => {
1903                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1904            }
1905            DataType::LargeListView(_) => {
1906                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1907            }
1908            DataType::Struct(_) => {
1909                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1910            }
1911            DataType::Union(_, _) => {
1912                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1913            }
1914            DataType::Dictionary(_, val) => {
1915                self.arrow_dtype_to_ast_dtype(&val.clone().into_nullable_field_ref())
1916            }
1917            DataType::RunEndEncoded(_, val) => self.arrow_dtype_to_ast_dtype(val),
1918            DataType::Decimal32(precision, scale)
1919            | DataType::Decimal64(precision, scale)
1920            | DataType::Decimal128(precision, scale)
1921            | DataType::Decimal256(precision, scale) => {
1922                let mut new_precision = *precision as u64;
1923                let mut new_scale = *scale as u64;
1924                if *scale < 0 {
1925                    new_precision = (*precision as i16 - *scale as i16) as u64;
1926                    new_scale = 0
1927                }
1928
1929                Ok(ast::DataType::Decimal(
1930                    ast::ExactNumberInfo::PrecisionAndScale(
1931                        new_precision,
1932                        new_scale as i64,
1933                    ),
1934                ))
1935            }
1936            DataType::Map(_, _) => {
1937                not_impl_err!("Unsupported DataType: conversion: {data_type}")
1938            }
1939        }
1940    }
1941}
1942
1943#[cfg(test)]
1944mod tests {
1945    use std::ops::{Add, Sub};
1946    use std::{sync::Arc, vec};
1947
1948    use crate::unparser::dialect::{MySqlDialect, SnowflakeDialect, SqliteDialect};
1949    use arrow::array::{LargeListArray, LargeListViewArray, ListArray, ListViewArray};
1950    use arrow::datatypes::{DataType::Int8, Field, Int32Type, Schema, TimeUnit};
1951    use ast::ObjectName;
1952    use datafusion_common::datatype::DataTypeExt;
1953    use datafusion_common::{Spans, TableReference};
1954    use datafusion_expr::expr::WildcardOptions;
1955    use datafusion_expr::{
1956        ColumnarValue, HigherOrderUDF, HigherOrderUDFImpl, LambdaParametersProgress,
1957        ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, ValueOrLambda,
1958        Volatility, WindowFrame, WindowFunctionDefinition, case, cast, col, cube, exists,
1959        grouping_set, interval_datetime_lit, interval_year_month_lit, lambda, lambda_var,
1960        lit, not, not_exists, out_ref_col, placeholder, rollup, table_scan, try_cast,
1961        when,
1962    };
1963    use datafusion_expr::{ExprFunctionExt, interval_month_day_nano_lit};
1964    use datafusion_functions::datetime::from_unixtime::FromUnixtimeFunc;
1965    use datafusion_functions::expr_fn::{get_field, named_struct};
1966    use datafusion_functions_aggregate::count::count_udaf;
1967    use datafusion_functions_aggregate::expr_fn::sum;
1968    use datafusion_functions_nested::expr_fn::{array_element, array_has, make_array};
1969    use datafusion_functions_nested::map::map;
1970    use datafusion_functions_window::rank::rank_udwf;
1971    use datafusion_functions_window::row_number::row_number_udwf;
1972    use sqlparser::ast::ExactNumberInfo;
1973
1974    use crate::unparser::dialect::{
1975        BigQueryDialect, CharacterLengthStyle, CustomDialect, CustomDialectBuilder,
1976        DateFieldExtractStyle, DefaultDialect, Dialect, DuckDBDialect, PostgreSqlDialect,
1977        ScalarFnToSqlHandler,
1978    };
1979
1980    use super::*;
1981
1982    /// Mocked UDF
1983    #[derive(Debug, PartialEq, Eq, Hash)]
1984    struct DummyUDF {
1985        signature: Signature,
1986    }
1987
1988    impl DummyUDF {
1989        fn new() -> Self {
1990            Self {
1991                signature: Signature::variadic_any(Volatility::Immutable),
1992            }
1993        }
1994    }
1995
1996    impl ScalarUDFImpl for DummyUDF {
1997        fn name(&self) -> &str {
1998            "dummy_udf"
1999        }
2000
2001        fn signature(&self) -> &Signature {
2002            &self.signature
2003        }
2004
2005        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
2006            Ok(DataType::Int32)
2007        }
2008
2009        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
2010            panic!("dummy - not implemented")
2011        }
2012    }
2013    // See sql::tests for E2E tests.
2014
2015    #[derive(Debug, Hash, Eq, PartialEq)]
2016    struct DummyHigherOrderUDF;
2017
2018    impl HigherOrderUDFImpl for DummyHigherOrderUDF {
2019        fn name(&self) -> &str {
2020            "dummy_higher_order_function"
2021        }
2022
2023        fn signature(&self) -> &datafusion_expr::HigherOrderSignature {
2024            unimplemented!()
2025        }
2026
2027        fn lambda_parameters(
2028            &self,
2029            _step: usize,
2030            _fields: &[ValueOrLambda<FieldRef, Option<FieldRef>>],
2031        ) -> Result<LambdaParametersProgress> {
2032            unimplemented!()
2033        }
2034
2035        fn return_field_from_args(
2036            &self,
2037            _args: datafusion_expr::HigherOrderReturnFieldArgs,
2038        ) -> Result<FieldRef> {
2039            unimplemented!()
2040        }
2041
2042        fn invoke_with_args(
2043            &self,
2044            _args: datafusion_expr::HigherOrderFunctionArgs,
2045        ) -> Result<ColumnarValue> {
2046            unimplemented!()
2047        }
2048    }
2049
2050    #[test]
2051    fn expr_to_sql_ok() -> Result<()> {
2052        let dummy_schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
2053        #[expect(deprecated)]
2054        let dummy_logical_plan = table_scan(Some("t"), &dummy_schema, None)?
2055            .project(vec![Expr::Wildcard {
2056                qualifier: None,
2057                options: Box::new(WildcardOptions::default()),
2058            }])?
2059            .filter(col("a").eq(lit(1)))?
2060            .build()?;
2061
2062        let tests: Vec<(Expr, &str)> = vec![
2063            ((col("a") + col("b")).gt(lit(4)), r#"((a + b) > 4)"#),
2064            (
2065                Expr::Column(Column {
2066                    relation: Some(TableReference::partial("a", "b")),
2067                    name: "c".to_string(),
2068                    spans: Spans::new(),
2069                })
2070                .gt(lit(4)),
2071                r#"(b.c > 4)"#,
2072            ),
2073            (
2074                case(col("a"))
2075                    .when(lit(1), lit(true))
2076                    .when(lit(0), lit(false))
2077                    .otherwise(lit(ScalarValue::Null))?,
2078                r#"CASE a WHEN 1 THEN true WHEN 0 THEN false ELSE NULL END"#,
2079            ),
2080            (
2081                when(col("a").is_null(), lit(true)).otherwise(lit(false))?,
2082                r#"CASE WHEN a IS NULL THEN true ELSE false END"#,
2083            ),
2084            (
2085                when(col("a").is_not_null(), lit(true)).otherwise(lit(false))?,
2086                r#"CASE WHEN a IS NOT NULL THEN true ELSE false END"#,
2087            ),
2088            (
2089                Expr::Cast(Cast::new(Box::new(col("a")), DataType::Date64)),
2090                r#"CAST(a AS DATETIME)"#,
2091            ),
2092            (
2093                Expr::Cast(Cast::new(
2094                    Box::new(col("a")),
2095                    DataType::Timestamp(TimeUnit::Nanosecond, Some("+08:00".into())),
2096                )),
2097                r#"CAST(a AS TIMESTAMP WITH TIME ZONE)"#,
2098            ),
2099            (
2100                Expr::Cast(Cast::new(
2101                    Box::new(col("a")),
2102                    DataType::Timestamp(TimeUnit::Millisecond, None),
2103                )),
2104                r#"CAST(a AS TIMESTAMP)"#,
2105            ),
2106            (
2107                Expr::Cast(Cast::new(Box::new(col("a")), DataType::UInt32)),
2108                r#"CAST(a AS INTEGER UNSIGNED)"#,
2109            ),
2110            (
2111                col("a").in_list(vec![lit(1), lit(2), lit(3)], false),
2112                r#"a IN (1, 2, 3)"#,
2113            ),
2114            (
2115                col("a").in_list(vec![lit(1), lit(2), lit(3)], true),
2116                r#"a NOT IN (1, 2, 3)"#,
2117            ),
2118            (
2119                ScalarUDF::new_from_impl(DummyUDF::new()).call(vec![col("a"), col("b")]),
2120                r#"dummy_udf(a, b)"#,
2121            ),
2122            (
2123                ScalarUDF::new_from_impl(DummyUDF::new())
2124                    .call(vec![col("a"), col("b")])
2125                    .is_null(),
2126                r#"dummy_udf(a, b) IS NULL"#,
2127            ),
2128            (
2129                ScalarUDF::new_from_impl(DummyUDF::new())
2130                    .call(vec![col("a"), col("b")])
2131                    .is_not_null(),
2132                r#"dummy_udf(a, b) IS NOT NULL"#,
2133            ),
2134            (
2135                Expr::HigherOrderFunction(HigherOrderFunction::new(
2136                    Arc::new(HigherOrderUDF::new_from_impl(DummyHigherOrderUDF)),
2137                    vec![col("a"), lambda(["v"], -lambda_var("v"))],
2138                )),
2139                r#"dummy_higher_order_function(a, (v) -> -v)"#,
2140            ),
2141            (
2142                Expr::Like(Like {
2143                    negated: true,
2144                    expr: Box::new(col("a")),
2145                    pattern: Box::new(lit("foo")),
2146                    escape_char: Some('o'),
2147                    case_insensitive: false,
2148                }),
2149                r#"a NOT LIKE 'foo' ESCAPE 'o'"#,
2150            ),
2151            (
2152                Expr::Like(Like {
2153                    negated: true,
2154                    expr: Box::new(col("a")),
2155                    pattern: Box::new(lit("foo")),
2156                    escape_char: Some('o'),
2157                    case_insensitive: true,
2158                }),
2159                r#"a NOT ILIKE 'foo' ESCAPE 'o'"#,
2160            ),
2161            (
2162                Expr::SimilarTo(Like {
2163                    negated: false,
2164                    expr: Box::new(col("a")),
2165                    pattern: Box::new(lit("foo")),
2166                    escape_char: Some('o'),
2167                    case_insensitive: true,
2168                }),
2169                r#"a LIKE 'foo' ESCAPE 'o'"#,
2170            ),
2171            (
2172                Expr::Literal(ScalarValue::Date64(Some(0)), None),
2173                r#"CAST('1970-01-01 00:00:00' AS DATETIME)"#,
2174            ),
2175            (
2176                Expr::Literal(ScalarValue::Date64(Some(10000)), None),
2177                r#"CAST('1970-01-01 00:00:10' AS DATETIME)"#,
2178            ),
2179            (
2180                Expr::Literal(ScalarValue::Date64(Some(-10000)), None),
2181                r#"CAST('1969-12-31 23:59:50' AS DATETIME)"#,
2182            ),
2183            (
2184                Expr::Literal(ScalarValue::Date32(Some(0)), None),
2185                r#"CAST('1970-01-01' AS DATE)"#,
2186            ),
2187            (
2188                Expr::Literal(ScalarValue::Date32(Some(10)), None),
2189                r#"CAST('1970-01-11' AS DATE)"#,
2190            ),
2191            (
2192                Expr::Literal(ScalarValue::Date32(Some(-1)), None),
2193                r#"CAST('1969-12-31' AS DATE)"#,
2194            ),
2195            (
2196                Expr::Literal(ScalarValue::TimestampSecond(Some(10001), None), None),
2197                r#"CAST('1970-01-01 02:46:41' AS TIMESTAMP)"#,
2198            ),
2199            (
2200                Expr::Literal(
2201                    ScalarValue::TimestampSecond(Some(10001), Some("+08:00".into())),
2202                    None,
2203                ),
2204                r#"CAST('1970-01-01T10:46:41+08:00' AS TIMESTAMP WITH TIME ZONE)"#,
2205            ),
2206            (
2207                Expr::Literal(ScalarValue::TimestampMillisecond(Some(10001), None), None),
2208                r#"CAST('1970-01-01 00:00:10.001' AS TIMESTAMP)"#,
2209            ),
2210            (
2211                Expr::Literal(
2212                    ScalarValue::TimestampMillisecond(Some(10001), Some("+08:00".into())),
2213                    None,
2214                ),
2215                r#"CAST('1970-01-01T08:00:10.001+08:00' AS TIMESTAMP WITH TIME ZONE)"#,
2216            ),
2217            (
2218                Expr::Literal(ScalarValue::TimestampMicrosecond(Some(10001), None), None),
2219                r#"CAST('1970-01-01 00:00:00.010001' AS TIMESTAMP)"#,
2220            ),
2221            (
2222                Expr::Literal(
2223                    ScalarValue::TimestampMicrosecond(Some(10001), Some("+08:00".into())),
2224                    None,
2225                ),
2226                r#"CAST('1970-01-01T08:00:00.010001+08:00' AS TIMESTAMP WITH TIME ZONE)"#,
2227            ),
2228            (
2229                Expr::Literal(ScalarValue::TimestampNanosecond(Some(10001), None), None),
2230                r#"CAST('1970-01-01 00:00:00.000010001' AS TIMESTAMP)"#,
2231            ),
2232            (
2233                Expr::Literal(
2234                    ScalarValue::TimestampNanosecond(Some(10001), Some("+08:00".into())),
2235                    None,
2236                ),
2237                r#"CAST('1970-01-01T08:00:00.000010001+08:00' AS TIMESTAMP WITH TIME ZONE)"#,
2238            ),
2239            (
2240                Expr::Literal(ScalarValue::Time32Second(Some(10001)), None),
2241                r#"CAST('02:46:41' AS TIME)"#,
2242            ),
2243            (
2244                Expr::Literal(ScalarValue::Time32Millisecond(Some(10001)), None),
2245                r#"CAST('00:00:10.001' AS TIME)"#,
2246            ),
2247            (
2248                Expr::Literal(ScalarValue::Time64Microsecond(Some(10001)), None),
2249                r#"CAST('00:00:00.010001' AS TIME)"#,
2250            ),
2251            (
2252                Expr::Literal(ScalarValue::Time64Nanosecond(Some(10001)), None),
2253                r#"CAST('00:00:00.000010001' AS TIME)"#,
2254            ),
2255            (sum(col("a")), r#"sum(a)"#),
2256            (
2257                #[expect(deprecated)]
2258                count_udaf()
2259                    .call(vec![Expr::Wildcard {
2260                        qualifier: None,
2261                        options: Box::new(WildcardOptions::default()),
2262                    }])
2263                    .distinct()
2264                    .build()
2265                    .unwrap(),
2266                "count(DISTINCT *)",
2267            ),
2268            (
2269                #[expect(deprecated)]
2270                count_udaf()
2271                    .call(vec![Expr::Wildcard {
2272                        qualifier: None,
2273                        options: Box::new(WildcardOptions::default()),
2274                    }])
2275                    .filter(lit(true))
2276                    .build()
2277                    .unwrap(),
2278                "count(*) FILTER (WHERE true)",
2279            ),
2280            (
2281                Expr::from(WindowFunction {
2282                    fun: WindowFunctionDefinition::WindowUDF(row_number_udwf()),
2283                    params: WindowFunctionParams {
2284                        args: vec![col("col")],
2285                        partition_by: vec![],
2286                        order_by: vec![],
2287                        window_frame: WindowFrame::new(None),
2288                        null_treatment: None,
2289                        distinct: false,
2290                        filter: None,
2291                    },
2292                }),
2293                r#"row_number(col) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)"#,
2294            ),
2295            (
2296                #[expect(deprecated)]
2297                Expr::from(WindowFunction {
2298                    fun: WindowFunctionDefinition::AggregateUDF(count_udaf()),
2299                    params: WindowFunctionParams {
2300                        args: vec![Expr::Wildcard {
2301                            qualifier: None,
2302                            options: Box::new(WildcardOptions::default()),
2303                        }],
2304                        partition_by: vec![],
2305                        order_by: vec![Sort::new(col("a"), false, true)],
2306                        window_frame: WindowFrame::new_bounds(
2307                            datafusion_expr::WindowFrameUnits::Range,
2308                            datafusion_expr::WindowFrameBound::Preceding(
2309                                ScalarValue::UInt32(Some(6)),
2310                            ),
2311                            datafusion_expr::WindowFrameBound::Following(
2312                                ScalarValue::UInt32(Some(2)),
2313                            ),
2314                        ),
2315                        null_treatment: None,
2316                        distinct: false,
2317                        filter: Some(Box::new(col("a").gt(lit(100)))),
2318                    },
2319                }),
2320                r#"count(*) FILTER (WHERE (a > 100)) OVER (ORDER BY a DESC NULLS FIRST RANGE BETWEEN 6 PRECEDING AND 2 FOLLOWING)"#,
2321            ),
2322            (col("a").is_not_null(), r#"a IS NOT NULL"#),
2323            (col("a").is_null(), r#"a IS NULL"#),
2324            (
2325                (col("a") + col("b")).gt(lit(4)).is_true(),
2326                r#"((a + b) > 4) IS TRUE"#,
2327            ),
2328            (
2329                (col("a") + col("b")).gt(lit(4)).is_not_true(),
2330                r#"((a + b) > 4) IS NOT TRUE"#,
2331            ),
2332            (
2333                (col("a") + col("b")).gt(lit(4)).is_false(),
2334                r#"((a + b) > 4) IS FALSE"#,
2335            ),
2336            (
2337                (col("a") + col("b")).gt(lit(4)).is_not_false(),
2338                r#"((a + b) > 4) IS NOT FALSE"#,
2339            ),
2340            (
2341                (col("a") + col("b")).gt(lit(4)).is_unknown(),
2342                r#"((a + b) > 4) IS UNKNOWN"#,
2343            ),
2344            (
2345                (col("a") + col("b")).gt(lit(4)).is_not_unknown(),
2346                r#"((a + b) > 4) IS NOT UNKNOWN"#,
2347            ),
2348            (not(col("a")), r#"NOT a"#),
2349            (
2350                Expr::between(col("a"), lit(1), lit(7)),
2351                r#"(a BETWEEN 1 AND 7)"#,
2352            ),
2353            (Expr::Negative(Box::new(col("a"))), r#"-a"#),
2354            (
2355                exists(Arc::new(dummy_logical_plan.clone())),
2356                r#"EXISTS (SELECT * FROM t WHERE (t.a = 1))"#,
2357            ),
2358            (
2359                not_exists(Arc::new(dummy_logical_plan)),
2360                r#"NOT EXISTS (SELECT * FROM t WHERE (t.a = 1))"#,
2361            ),
2362            (
2363                try_cast(col("a"), DataType::Date64),
2364                r#"TRY_CAST(a AS DATETIME)"#,
2365            ),
2366            (
2367                try_cast(col("a"), DataType::UInt32),
2368                r#"TRY_CAST(a AS INTEGER UNSIGNED)"#,
2369            ),
2370            (
2371                Expr::ScalarVariable(
2372                    Int8.into_nullable_field_ref(),
2373                    vec![String::from("@a")],
2374                ),
2375                r#"@a"#,
2376            ),
2377            (
2378                Expr::ScalarVariable(
2379                    Int8.into_nullable_field_ref(),
2380                    vec![String::from("@root"), String::from("foo")],
2381                ),
2382                r#"@root.foo"#,
2383            ),
2384            (col("x").eq(placeholder("$1")), r#"(x = $1)"#),
2385            (
2386                out_ref_col(DataType::Int32, "t.a").gt(lit(1)),
2387                r#"(t.a > 1)"#,
2388            ),
2389            (
2390                grouping_set(vec![vec![col("a"), col("b")], vec![col("a")]]),
2391                r#"GROUPING SETS ((a, b), (a))"#,
2392            ),
2393            (cube(vec![col("a"), col("b")]), r#"CUBE (a, b)"#),
2394            (rollup(vec![col("a"), col("b")]), r#"ROLLUP (a, b)"#),
2395            (col("table").eq(lit(1)), r#"("table" = 1)"#),
2396            (
2397                col("123_need_quoted").eq(lit(1)),
2398                r#"("123_need_quoted" = 1)"#,
2399            ),
2400            (col("need-quoted").eq(lit(1)), r#"("need-quoted" = 1)"#),
2401            (col("need quoted").eq(lit(1)), r#"("need quoted" = 1)"#),
2402            // See test_interval_scalar_to_expr for interval literals
2403            (
2404                (col("a") + col("b")).gt(Expr::Literal(
2405                    ScalarValue::Decimal32(Some(1123), 4, 3),
2406                    None,
2407                )),
2408                r#"((a + b) > 1.123)"#,
2409            ),
2410            (
2411                (col("a") + col("b")).gt(Expr::Literal(
2412                    ScalarValue::Decimal64(Some(1123), 4, 3),
2413                    None,
2414                )),
2415                r#"((a + b) > 1.123)"#,
2416            ),
2417            (
2418                (col("a") + col("b")).gt(Expr::Literal(
2419                    ScalarValue::Decimal128(Some(100123), 28, 3),
2420                    None,
2421                )),
2422                r#"((a + b) > 100.123)"#,
2423            ),
2424            (
2425                (col("a") + col("b")).gt(Expr::Literal(
2426                    ScalarValue::Decimal256(Some(100123.into()), 28, 3),
2427                    None,
2428                )),
2429                r#"((a + b) > 100.123)"#,
2430            ),
2431            (
2432                Expr::Cast(Cast::new(Box::new(col("a")), DataType::Decimal128(10, -2))),
2433                r#"CAST(a AS DECIMAL(12,0))"#,
2434            ),
2435            (
2436                Expr::Unnest(Unnest {
2437                    expr: Box::new(Expr::Column(Column {
2438                        relation: Some(TableReference::partial("schema", "table")),
2439                        name: "array_col".to_string(),
2440                        spans: Spans::new(),
2441                    })),
2442                    outer: false,
2443                }),
2444                r#"UNNEST("table".array_col)"#,
2445            ),
2446            (make_array(vec![lit(1), lit(2), lit(3)]), "[1, 2, 3]"),
2447            (array_element(col("array_col"), lit(1)), "array_col[1]"),
2448            (
2449                array_element(make_array(vec![lit(1), lit(2), lit(3)]), lit(1)),
2450                "[1, 2, 3][1]",
2451            ),
2452            (
2453                named_struct(vec![lit("a"), lit("1"), lit("b"), lit(2)]),
2454                "{a: '1', b: 2}",
2455            ),
2456            (get_field(col("a.b"), "c"), "a.b.c"),
2457            (
2458                map(vec![lit("a"), lit("b")], vec![lit(1), lit(2)]),
2459                "MAP {'a': 1, 'b': 2}",
2460            ),
2461            (
2462                Expr::Literal(
2463                    ScalarValue::Dictionary(
2464                        Box::new(DataType::Int32),
2465                        Box::new(ScalarValue::Utf8(Some("foo".into()))),
2466                    ),
2467                    None,
2468                ),
2469                "'foo'",
2470            ),
2471            (
2472                Expr::Literal(
2473                    ScalarValue::RunEndEncoded(
2474                        Field::new("run_ends", DataType::Int32, false).into(),
2475                        Field::new("values", DataType::Utf8, true).into(),
2476                        Box::new(ScalarValue::Utf8(Some("foo".into()))),
2477                    ),
2478                    None,
2479                ),
2480                "'foo'",
2481            ),
2482            (
2483                Expr::Literal(
2484                    ScalarValue::List(Arc::new(ListArray::from_iter_primitive::<
2485                        Int32Type,
2486                        _,
2487                        _,
2488                    >(vec![Some(vec![
2489                        Some(1),
2490                        Some(2),
2491                        Some(3),
2492                    ])]))),
2493                    None,
2494                ),
2495                "[1, 2, 3]",
2496            ),
2497            (
2498                Expr::Literal(
2499                    ScalarValue::LargeList(Arc::new(
2500                        LargeListArray::from_iter_primitive::<Int32Type, _, _>(vec![
2501                            Some(vec![Some(1), Some(2), Some(3)]),
2502                        ]),
2503                    )),
2504                    None,
2505                ),
2506                "[1, 2, 3]",
2507            ),
2508            (
2509                Expr::Literal(
2510                    ScalarValue::ListView(Arc::new(
2511                        ListViewArray::from_iter_primitive::<Int32Type, _, _>(vec![
2512                            Some(vec![Some(1), Some(2), Some(3)]),
2513                        ]),
2514                    )),
2515                    None,
2516                ),
2517                "[1, 2, 3]",
2518            ),
2519            (
2520                Expr::Literal(
2521                    ScalarValue::LargeListView(Arc::new(
2522                        LargeListViewArray::from_iter_primitive::<Int32Type, _, _>(vec![
2523                            Some(vec![Some(1), Some(2), Some(3)]),
2524                        ]),
2525                    )),
2526                    None,
2527                ),
2528                "[1, 2, 3]",
2529            ),
2530            (
2531                Expr::BinaryExpr(BinaryExpr {
2532                    left: Box::new(col("a")),
2533                    op: Operator::ArrowAt,
2534                    right: Box::new(col("b")),
2535                }),
2536                "(a <@ b)",
2537            ),
2538            (
2539                Expr::BinaryExpr(BinaryExpr {
2540                    left: Box::new(col("a")),
2541                    op: Operator::AtArrow,
2542                    right: Box::new(col("b")),
2543                }),
2544                "(a @> b)",
2545            ),
2546        ];
2547
2548        for (expr, expected) in tests {
2549            let ast = expr_to_sql(&expr)?;
2550
2551            let actual = format!("{ast}");
2552
2553            assert_eq!(actual, expected);
2554        }
2555
2556        Ok(())
2557    }
2558
2559    #[test]
2560    fn custom_dialect_with_identifier_quote_style() -> Result<()> {
2561        let dialect = CustomDialectBuilder::new()
2562            .with_identifier_quote_style('\'')
2563            .build();
2564        let unparser = Unparser::new(&dialect);
2565
2566        let expr = col("a").gt(lit(4));
2567        let ast = unparser.expr_to_sql(&expr)?;
2568
2569        let actual = format!("{ast}");
2570
2571        let expected = r#"('a' > 4)"#;
2572        assert_eq!(actual, expected);
2573        Ok(())
2574    }
2575
2576    #[test]
2577    fn custom_dialect_without_identifier_quote_style() -> Result<()> {
2578        let dialect = CustomDialect::default();
2579        let unparser = Unparser::new(&dialect);
2580
2581        let expr = col("a").gt(lit(4));
2582        let ast = unparser.expr_to_sql(&expr)?;
2583
2584        let actual = format!("{ast}");
2585
2586        let expected = r#"(a > 4)"#;
2587        assert_eq!(actual, expected);
2588
2589        Ok(())
2590    }
2591
2592    #[test]
2593    fn custom_dialect_use_timestamp_for_date64() -> Result<()> {
2594        for (use_timestamp_for_date64, identifier) in
2595            [(false, "DATETIME"), (true, "TIMESTAMP")]
2596        {
2597            let dialect = CustomDialectBuilder::new()
2598                .with_use_timestamp_for_date64(use_timestamp_for_date64)
2599                .build();
2600            let unparser = Unparser::new(&dialect);
2601
2602            let expr = Expr::Cast(Cast::new(Box::new(col("a")), DataType::Date64));
2603            let ast = unparser.expr_to_sql(&expr)?;
2604
2605            let actual = format!("{ast}");
2606
2607            let expected = format!(r#"CAST(a AS {identifier})"#);
2608            assert_eq!(actual, expected);
2609        }
2610        Ok(())
2611    }
2612
2613    #[test]
2614    fn custom_dialect_float64_ast_dtype() -> Result<()> {
2615        for (float64_ast_dtype, identifier) in [
2616            (ast::DataType::Double(ExactNumberInfo::None), "DOUBLE"),
2617            (ast::DataType::DoublePrecision, "DOUBLE PRECISION"),
2618        ] {
2619            let dialect = CustomDialectBuilder::new()
2620                .with_float64_ast_dtype(float64_ast_dtype)
2621                .build();
2622            let unparser = Unparser::new(&dialect);
2623
2624            let expr = Expr::Cast(Cast::new(Box::new(col("a")), DataType::Float64));
2625            let ast = unparser.expr_to_sql(&expr)?;
2626
2627            let actual = format!("{ast}");
2628
2629            let expected = format!(r#"CAST(a AS {identifier})"#);
2630            assert_eq!(actual, expected);
2631        }
2632        Ok(())
2633    }
2634
2635    #[test]
2636    fn customer_dialect_support_nulls_first_in_ort() -> Result<()> {
2637        let tests: Vec<(Sort, &str, bool)> = vec![
2638            (col("a").sort(true, true), r#"a ASC NULLS FIRST"#, true),
2639            (col("a").sort(true, true), r#"a ASC"#, false),
2640        ];
2641
2642        for (expr, expected, supports_nulls_first_in_sort) in tests {
2643            let dialect = CustomDialectBuilder::new()
2644                .with_supports_nulls_first_in_sort(supports_nulls_first_in_sort)
2645                .build();
2646            let unparser = Unparser::new(&dialect);
2647            let ast = unparser.sort_to_sql(&expr)?;
2648
2649            let actual = format!("{ast}");
2650
2651            assert_eq!(actual, expected);
2652        }
2653
2654        Ok(())
2655    }
2656
2657    #[test]
2658    fn test_character_length_scalar_to_expr() {
2659        let tests = [
2660            (CharacterLengthStyle::Length, "length(x)"),
2661            (CharacterLengthStyle::CharacterLength, "character_length(x)"),
2662        ];
2663
2664        for (style, expected) in tests {
2665            let dialect = CustomDialectBuilder::new()
2666                .with_character_length_style(style)
2667                .build();
2668            let unparser = Unparser::new(&dialect);
2669
2670            let expr = ScalarUDF::new_from_impl(
2671                datafusion_functions::unicode::character_length::CharacterLengthFunc::new(
2672                ),
2673            )
2674            .call(vec![col("x")]);
2675
2676            let ast = unparser.expr_to_sql(&expr).expect("to be unparsed");
2677
2678            let actual = format!("{ast}");
2679
2680            assert_eq!(actual, expected);
2681        }
2682    }
2683
2684    #[test]
2685    fn test_interval_scalar_to_expr() {
2686        let tests = [
2687            (
2688                interval_month_day_nano_lit("1 MONTH"),
2689                IntervalStyle::SQLStandard,
2690                "INTERVAL '1' MONTH",
2691            ),
2692            (
2693                interval_month_day_nano_lit("1.5 DAY"),
2694                IntervalStyle::SQLStandard,
2695                "INTERVAL '1 12:0:0.000' DAY TO SECOND",
2696            ),
2697            (
2698                interval_month_day_nano_lit("-1.5 DAY"),
2699                IntervalStyle::SQLStandard,
2700                "INTERVAL '-1 -12:0:0.000' DAY TO SECOND",
2701            ),
2702            (
2703                interval_month_day_nano_lit("1.51234 DAY"),
2704                IntervalStyle::SQLStandard,
2705                "INTERVAL '1 12:17:46.176' DAY TO SECOND",
2706            ),
2707            (
2708                interval_datetime_lit("1.51234 DAY"),
2709                IntervalStyle::SQLStandard,
2710                "INTERVAL '1 12:17:46.176' DAY TO SECOND",
2711            ),
2712            (
2713                interval_year_month_lit("1 YEAR"),
2714                IntervalStyle::SQLStandard,
2715                "INTERVAL '12' MONTH",
2716            ),
2717            (
2718                interval_month_day_nano_lit(
2719                    "1 YEAR 1 MONTH 1 DAY 3 HOUR 10 MINUTE 20 SECOND",
2720                ),
2721                IntervalStyle::PostgresVerbose,
2722                r#"INTERVAL '13 MONS 1 DAYS 3 HOURS 10 MINS 20.000000000 SECS'"#,
2723            ),
2724            (
2725                interval_month_day_nano_lit("1.5 MONTH"),
2726                IntervalStyle::PostgresVerbose,
2727                r#"INTERVAL '1 MONS 15 DAYS'"#,
2728            ),
2729            (
2730                interval_month_day_nano_lit("-3 MONTH"),
2731                IntervalStyle::PostgresVerbose,
2732                r#"INTERVAL '-3 MONS'"#,
2733            ),
2734            (
2735                interval_month_day_nano_lit("1 MONTH")
2736                    .add(interval_month_day_nano_lit("1 DAY")),
2737                IntervalStyle::PostgresVerbose,
2738                r#"(INTERVAL '1 MONS' + INTERVAL '1 DAYS')"#,
2739            ),
2740            (
2741                interval_month_day_nano_lit("1 MONTH")
2742                    .sub(interval_month_day_nano_lit("1 DAY")),
2743                IntervalStyle::PostgresVerbose,
2744                r#"(INTERVAL '1 MONS' - INTERVAL '1 DAYS')"#,
2745            ),
2746            (
2747                interval_datetime_lit("10 DAY 1 HOUR 10 MINUTE 20 SECOND"),
2748                IntervalStyle::PostgresVerbose,
2749                r#"INTERVAL '10 DAYS 1 HOURS 10 MINS 20.000 SECS'"#,
2750            ),
2751            (
2752                interval_datetime_lit("10 DAY 1.5 HOUR 10 MINUTE 20 SECOND"),
2753                IntervalStyle::PostgresVerbose,
2754                r#"INTERVAL '10 DAYS 1 HOURS 40 MINS 20.000 SECS'"#,
2755            ),
2756            (
2757                interval_year_month_lit("1 YEAR 1 MONTH"),
2758                IntervalStyle::PostgresVerbose,
2759                r#"INTERVAL '1 YEARS 1 MONS'"#,
2760            ),
2761            (
2762                interval_year_month_lit("1.5 YEAR 1 MONTH"),
2763                IntervalStyle::PostgresVerbose,
2764                r#"INTERVAL '1 YEARS 7 MONS'"#,
2765            ),
2766            (
2767                interval_year_month_lit("1 YEAR 1 MONTH"),
2768                IntervalStyle::MySQL,
2769                r#"INTERVAL 13 MONTH"#,
2770            ),
2771            (
2772                interval_month_day_nano_lit("1 YEAR -1 MONTH"),
2773                IntervalStyle::MySQL,
2774                r#"INTERVAL 11 MONTH"#,
2775            ),
2776            (
2777                interval_month_day_nano_lit("15 DAY"),
2778                IntervalStyle::MySQL,
2779                r#"INTERVAL 15 DAY"#,
2780            ),
2781            (
2782                interval_month_day_nano_lit("-40 HOURS"),
2783                IntervalStyle::MySQL,
2784                r#"INTERVAL -40 HOUR"#,
2785            ),
2786            (
2787                interval_datetime_lit("-1.5 DAY 1 HOUR"),
2788                IntervalStyle::MySQL,
2789                "INTERVAL -35 HOUR",
2790            ),
2791            (
2792                interval_datetime_lit("1000000 DAY 1.5 HOUR 10 MINUTE 20 SECOND"),
2793                IntervalStyle::MySQL,
2794                r#"INTERVAL 86400006020 SECOND"#,
2795            ),
2796            (
2797                interval_year_month_lit("0 DAY 0 HOUR"),
2798                IntervalStyle::MySQL,
2799                r#"INTERVAL 0 DAY"#,
2800            ),
2801            (
2802                interval_month_day_nano_lit("-1296000000 SECOND"),
2803                IntervalStyle::MySQL,
2804                r#"INTERVAL -15000 DAY"#,
2805            ),
2806        ];
2807
2808        for (value, style, expected) in tests {
2809            let dialect = CustomDialectBuilder::new()
2810                .with_interval_style(style)
2811                .build();
2812            let unparser = Unparser::new(&dialect);
2813
2814            let ast = unparser.expr_to_sql(&value).expect("to be unparsed");
2815
2816            let actual = format!("{ast}");
2817
2818            assert_eq!(actual, expected);
2819        }
2820    }
2821
2822    #[test]
2823    fn test_float_scalar_to_expr() {
2824        let tests = [
2825            (Expr::Literal(ScalarValue::Float64(Some(3f64)), None), "3.0"),
2826            (
2827                Expr::Literal(ScalarValue::Float64(Some(3.1f64)), None),
2828                "3.1",
2829            ),
2830            (
2831                Expr::Literal(ScalarValue::Float32(Some(-2f32)), None),
2832                "-2.0",
2833            ),
2834            (
2835                Expr::Literal(ScalarValue::Float32(Some(-2.989f32)), None),
2836                "-2.989",
2837            ),
2838        ];
2839        for (value, expected) in tests {
2840            let dialect = CustomDialectBuilder::new().build();
2841            let unparser = Unparser::new(&dialect);
2842
2843            let ast = unparser.expr_to_sql(&value).expect("to be unparsed");
2844            let actual = format!("{ast}");
2845
2846            assert_eq!(actual, expected);
2847        }
2848    }
2849
2850    #[test]
2851    fn test_cast_value_to_binary_expr() {
2852        let tests = [
2853            (
2854                Expr::Cast(Cast::new(
2855                    Box::new(Expr::Literal(
2856                        ScalarValue::Utf8(Some("blah".to_string())),
2857                        None,
2858                    )),
2859                    DataType::Binary,
2860                )),
2861                "'blah'",
2862            ),
2863            (
2864                Expr::Cast(Cast::new(
2865                    Box::new(Expr::Literal(
2866                        ScalarValue::Utf8(Some("blah".to_string())),
2867                        None,
2868                    )),
2869                    DataType::BinaryView,
2870                )),
2871                "'blah'",
2872            ),
2873        ];
2874        for (value, expected) in tests {
2875            let dialect = CustomDialectBuilder::new().build();
2876            let unparser = Unparser::new(&dialect);
2877
2878            let ast = unparser.expr_to_sql(&value).expect("to be unparsed");
2879            let actual = format!("{ast}");
2880
2881            assert_eq!(actual, expected);
2882        }
2883    }
2884
2885    #[test]
2886    fn custom_dialect_use_char_for_utf8_cast() -> Result<()> {
2887        let default_dialect = CustomDialectBuilder::default().build();
2888        let mysql_custom_dialect = CustomDialectBuilder::new()
2889            .with_utf8_cast_dtype(ast::DataType::Char(None))
2890            .with_large_utf8_cast_dtype(ast::DataType::Char(None))
2891            .build();
2892
2893        for (dialect, data_type, identifier) in [
2894            (&default_dialect, DataType::Utf8, "VARCHAR"),
2895            (&default_dialect, DataType::LargeUtf8, "TEXT"),
2896            (&mysql_custom_dialect, DataType::Utf8, "CHAR"),
2897            (&mysql_custom_dialect, DataType::LargeUtf8, "CHAR"),
2898        ] {
2899            let unparser = Unparser::new(dialect);
2900
2901            let expr = Expr::Cast(Cast::new(Box::new(col("a")), data_type));
2902            let ast = unparser.expr_to_sql(&expr)?;
2903
2904            let actual = format!("{ast}");
2905            let expected = format!(r#"CAST(a AS {identifier})"#);
2906
2907            assert_eq!(actual, expected);
2908        }
2909        Ok(())
2910    }
2911
2912    #[test]
2913    fn custom_dialect_with_date_field_extract_style() -> Result<()> {
2914        for (extract_style, unit, expected) in [
2915            (
2916                DateFieldExtractStyle::DatePart,
2917                "YEAR",
2918                "date_part('YEAR', x)",
2919            ),
2920            (
2921                DateFieldExtractStyle::Extract,
2922                "YEAR",
2923                "EXTRACT(YEAR FROM x)",
2924            ),
2925            (DateFieldExtractStyle::Strftime, "YEAR", "strftime('%Y', x)"),
2926            (
2927                DateFieldExtractStyle::DatePart,
2928                "MONTH",
2929                "date_part('MONTH', x)",
2930            ),
2931            (
2932                DateFieldExtractStyle::Extract,
2933                "MONTH",
2934                "EXTRACT(MONTH FROM x)",
2935            ),
2936            (
2937                DateFieldExtractStyle::Extract,
2938                "MONS",
2939                "EXTRACT(MONTH FROM x)",
2940            ),
2941            (
2942                DateFieldExtractStyle::Strftime,
2943                "MONTH",
2944                "strftime('%m', x)",
2945            ),
2946            (DateFieldExtractStyle::Strftime, "YRS", "strftime('%Y', x)"),
2947            (
2948                DateFieldExtractStyle::DatePart,
2949                "DAY",
2950                "date_part('DAY', x)",
2951            ),
2952            (DateFieldExtractStyle::Strftime, "DAY", "strftime('%d', x)"),
2953            (DateFieldExtractStyle::Extract, "DAY", "EXTRACT(DAY FROM x)"),
2954        ] {
2955            let dialect = CustomDialectBuilder::new()
2956                .with_date_field_extract_style(extract_style)
2957                .build();
2958
2959            let unparser = Unparser::new(&dialect);
2960            let expr = ScalarUDF::new_from_impl(
2961                datafusion_functions::datetime::date_part::DatePartFunc::new(),
2962            )
2963            .call(vec![
2964                Expr::Literal(ScalarValue::new_utf8(unit), None),
2965                col("x"),
2966            ]);
2967
2968            let ast = unparser.expr_to_sql(&expr)?;
2969            let actual = format!("{ast}");
2970
2971            assert_eq!(actual, expected);
2972        }
2973        Ok(())
2974    }
2975
2976    #[test]
2977    fn custom_dialect_with_int64_cast_dtype() -> Result<()> {
2978        let default_dialect = CustomDialectBuilder::new().build();
2979        let mysql_dialect = CustomDialectBuilder::new()
2980            .with_int64_cast_dtype(ast::DataType::Custom(
2981                ObjectName::from(vec![Ident::new("SIGNED")]),
2982                vec![],
2983            ))
2984            .build();
2985
2986        for (dialect, identifier) in
2987            [(default_dialect, "BIGINT"), (mysql_dialect, "SIGNED")]
2988        {
2989            let unparser = Unparser::new(&dialect);
2990            let expr = Expr::Cast(Cast::new(Box::new(col("a")), DataType::Int64));
2991            let ast = unparser.expr_to_sql(&expr)?;
2992
2993            let actual = format!("{ast}");
2994            let expected = format!(r#"CAST(a AS {identifier})"#);
2995
2996            assert_eq!(actual, expected);
2997        }
2998        Ok(())
2999    }
3000
3001    #[test]
3002    fn custom_dialect_with_int32_cast_dtype() -> Result<()> {
3003        let default_dialect = CustomDialectBuilder::new().build();
3004        let mysql_dialect = CustomDialectBuilder::new()
3005            .with_int32_cast_dtype(ast::DataType::Custom(
3006                ObjectName::from(vec![Ident::new("SIGNED")]),
3007                vec![],
3008            ))
3009            .build();
3010
3011        for (dialect, identifier) in
3012            [(default_dialect, "INTEGER"), (mysql_dialect, "SIGNED")]
3013        {
3014            let unparser = Unparser::new(&dialect);
3015            let expr = Expr::Cast(Cast::new(Box::new(col("a")), DataType::Int32));
3016            let ast = unparser.expr_to_sql(&expr)?;
3017
3018            let actual = format!("{ast}");
3019            let expected = format!(r#"CAST(a AS {identifier})"#);
3020
3021            assert_eq!(actual, expected);
3022        }
3023        Ok(())
3024    }
3025
3026    #[test]
3027    fn custom_dialect_with_timestamp_cast_dtype() -> Result<()> {
3028        let default_dialect = CustomDialectBuilder::new().build();
3029        let mysql_dialect = CustomDialectBuilder::new()
3030            .with_timestamp_cast_dtype(
3031                ast::DataType::Datetime(None),
3032                ast::DataType::Datetime(None),
3033            )
3034            .build();
3035
3036        let timestamp = DataType::Timestamp(TimeUnit::Nanosecond, None);
3037        let timestamp_with_tz =
3038            DataType::Timestamp(TimeUnit::Nanosecond, Some("+08:00".into()));
3039
3040        for (dialect, data_type, identifier) in [
3041            (&default_dialect, &timestamp, "TIMESTAMP"),
3042            (
3043                &default_dialect,
3044                &timestamp_with_tz,
3045                "TIMESTAMP WITH TIME ZONE",
3046            ),
3047            (&mysql_dialect, &timestamp, "DATETIME"),
3048            (&mysql_dialect, &timestamp_with_tz, "DATETIME"),
3049        ] {
3050            let unparser = Unparser::new(dialect);
3051            let expr = Expr::Cast(Cast::new(Box::new(col("a")), data_type.clone()));
3052            let ast = unparser.expr_to_sql(&expr)?;
3053
3054            let actual = format!("{ast}");
3055            let expected = format!(r#"CAST(a AS {identifier})"#);
3056
3057            assert_eq!(actual, expected);
3058        }
3059        Ok(())
3060    }
3061
3062    #[test]
3063    fn custom_dialect_with_timestamp_cast_dtype_scalar_expr() -> Result<()> {
3064        let default_dialect = CustomDialectBuilder::new().build();
3065        let mysql_dialect = CustomDialectBuilder::new()
3066            .with_timestamp_cast_dtype(
3067                ast::DataType::Datetime(None),
3068                ast::DataType::Datetime(None),
3069            )
3070            .build();
3071
3072        let timestamp = ScalarValue::TimestampMillisecond(Some(1738285549123), None);
3073        let timestamp_with_tz =
3074            ScalarValue::TimestampMillisecond(Some(1738285549123), Some("+08:00".into()));
3075
3076        for (dialect, scalar, expected) in [
3077            (
3078                &default_dialect,
3079                &timestamp,
3080                "CAST('2025-01-31 01:05:49.123' AS TIMESTAMP)",
3081            ),
3082            (
3083                &default_dialect,
3084                &timestamp_with_tz,
3085                "CAST('2025-01-31T09:05:49.123+08:00' AS TIMESTAMP WITH TIME ZONE)",
3086            ),
3087            (
3088                &mysql_dialect,
3089                &timestamp,
3090                "CAST('2025-01-31 01:05:49.123' AS DATETIME)",
3091            ),
3092            (
3093                &mysql_dialect,
3094                &timestamp_with_tz,
3095                "CAST('2025-01-31T09:05:49.123+08:00' AS DATETIME)",
3096            ),
3097        ] {
3098            let unparser = Unparser::new(dialect);
3099            let expr = Expr::Literal(scalar.clone(), None);
3100            let ast = unparser.expr_to_sql(&expr)?;
3101
3102            let actual = format!("{ast}");
3103
3104            assert_eq!(actual, expected);
3105        }
3106        Ok(())
3107    }
3108
3109    // MySQL `DATETIME` without precision is `DATETIME(0)` and rounds the
3110    // literal to whole seconds, which breaks equality and keyset seeks on
3111    // sub-second timestamps. The MySQL dialect must carry the unit's precision.
3112    #[test]
3113    fn mysql_timestamp_cast_keeps_fractional_precision() -> Result<()> {
3114        let unparser = Unparser::new(&MySqlDialect {});
3115
3116        for (scalar, expected) in [
3117            (
3118                ScalarValue::TimestampSecond(Some(1789980940), None),
3119                "CAST('2026-09-21 08:55:40' AS DATETIME)",
3120            ),
3121            (
3122                ScalarValue::TimestampMillisecond(Some(1789980940006), None),
3123                "CAST('2026-09-21 08:55:40.006' AS DATETIME(3))",
3124            ),
3125            (
3126                ScalarValue::TimestampMicrosecond(Some(1789980940006000), None),
3127                "CAST('2026-09-21 08:55:40.006' AS DATETIME(6))",
3128            ),
3129            (
3130                ScalarValue::TimestampNanosecond(Some(1789980940006000000), None),
3131                "CAST('2026-09-21 08:55:40.006' AS DATETIME(6))",
3132            ),
3133        ] {
3134            let ast = unparser.expr_to_sql(&Expr::Literal(scalar, None))?;
3135            assert_eq!(format!("{ast}"), expected);
3136        }
3137
3138        let expr = Expr::Cast(Cast::new(
3139            Box::new(col("a")),
3140            DataType::Timestamp(TimeUnit::Microsecond, None),
3141        ));
3142        let ast = unparser.expr_to_sql(&expr)?;
3143        assert_eq!(format!("{ast}"), "CAST(`a` AS DATETIME(6))");
3144        Ok(())
3145    }
3146
3147    #[test]
3148    fn mysql_int8_cast_uses_signed() -> Result<()> {
3149        let unparser = Unparser::new(&MySqlDialect {});
3150        let expr = Expr::Cast(Cast::new(Box::new(col("a")), Int8));
3151        let ast = unparser.expr_to_sql(&expr)?;
3152        assert_eq!(format!("{ast}"), "CAST(`a` AS SIGNED)");
3153        Ok(())
3154    }
3155
3156    #[test]
3157    fn custom_dialect_date32_ast_dtype() -> Result<()> {
3158        let default_dialect = CustomDialectBuilder::default().build();
3159        let sqlite_custom_dialect = CustomDialectBuilder::new()
3160            .with_date32_cast_dtype(ast::DataType::Text)
3161            .build();
3162
3163        for (dialect, data_type, identifier) in [
3164            (&default_dialect, DataType::Date32, "DATE"),
3165            (&sqlite_custom_dialect, DataType::Date32, "TEXT"),
3166        ] {
3167            let unparser = Unparser::new(dialect);
3168
3169            let expr = Expr::Cast(Cast::new(Box::new(col("a")), data_type));
3170            let ast = unparser.expr_to_sql(&expr)?;
3171
3172            let actual = format!("{ast}");
3173            let expected = format!(r#"CAST(a AS {identifier})"#);
3174
3175            assert_eq!(actual, expected);
3176        }
3177        Ok(())
3178    }
3179
3180    #[test]
3181    fn custom_dialect_division_operator() -> Result<()> {
3182        let default_dialect = CustomDialectBuilder::new().build();
3183        let duckdb_dialect = CustomDialectBuilder::new()
3184            .with_division_operator(BinaryOperator::DuckIntegerDivide)
3185            .build();
3186
3187        for (dialect, expected) in
3188            [(default_dialect, "(a / b)"), (duckdb_dialect, "(a // b)")]
3189        {
3190            let unparser = Unparser::new(&dialect);
3191            let expr = Expr::BinaryExpr(BinaryExpr {
3192                left: Box::new(col("a")),
3193                op: Operator::Divide,
3194                right: Box::new(col("b")),
3195            });
3196            let ast = unparser.expr_to_sql(&expr)?;
3197
3198            let actual = format!("{ast}");
3199            let expected = expected.to_string();
3200
3201            assert_eq!(actual, expected);
3202        }
3203        Ok(())
3204    }
3205
3206    #[test]
3207    fn test_mssql_dialect_national_literal() -> Result<()> {
3208        struct MsSqlDialect;
3209
3210        impl Dialect for MsSqlDialect {
3211            fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
3212                Some('[')
3213            }
3214
3215            fn string_literal_to_sql(&self, s: &str) -> Option<ast::Expr> {
3216                if !s.is_ascii() {
3217                    Some(ast::Expr::value(ast::Value::NationalStringLiteral(
3218                        s.to_string(),
3219                    )))
3220                } else {
3221                    None
3222                }
3223            }
3224        }
3225
3226        let dialect = MsSqlDialect;
3227        let unparser = Unparser::new(&dialect);
3228
3229        // Get nation string literal for the custom mssql dialect
3230        for (s, expected) in [
3231            ("national string", "'national string'"),
3232            ("datafusion資料融合", "N'datafusion資料融合'"),
3233        ] {
3234            let expr = Expr::Literal(ScalarValue::Utf8(Some(s.to_string())), None);
3235            let ast = unparser.expr_to_sql(&expr)?;
3236            assert_eq!(ast.to_string(), expected);
3237
3238            let expr = Expr::Literal(ScalarValue::Utf8View(Some(s.to_string())), None);
3239            let ast = unparser.expr_to_sql(&expr)?;
3240            assert_eq!(ast.to_string(), expected);
3241
3242            let expr = Expr::Literal(ScalarValue::LargeUtf8(Some(s.to_string())), None);
3243            let ast = unparser.expr_to_sql(&expr)?;
3244            assert_eq!(ast.to_string(), expected);
3245        }
3246
3247        let dialect = DefaultDialect {};
3248        let unparser = Unparser::new(&dialect);
3249
3250        // Get normal string literal for default dialect
3251        for (s, expected) in [
3252            ("national string", "'national string'"),
3253            ("datafusion資料融合", "'datafusion資料融合'"),
3254        ] {
3255            let expr = Expr::Literal(ScalarValue::Utf8(Some(s.to_string())), None);
3256            let ast = unparser.expr_to_sql(&expr)?;
3257            assert_eq!(ast.to_string(), expected);
3258
3259            let expr = Expr::Literal(ScalarValue::Utf8View(Some(s.to_string())), None);
3260            let ast = unparser.expr_to_sql(&expr)?;
3261            assert_eq!(ast.to_string(), expected);
3262
3263            let expr = Expr::Literal(ScalarValue::LargeUtf8(Some(s.to_string())), None);
3264            let ast = unparser.expr_to_sql(&expr)?;
3265            assert_eq!(ast.to_string(), expected);
3266        }
3267        Ok(())
3268    }
3269
3270    #[test]
3271    fn test_cast_value_to_dict_expr() {
3272        let tests = [(
3273            Expr::Cast(Cast::new(
3274                Box::new(Expr::Literal(
3275                    ScalarValue::Utf8(Some("variation".to_string())),
3276                    None,
3277                )),
3278                DataType::Dictionary(Box::new(Int8), Box::new(DataType::Utf8)),
3279            )),
3280            "'variation'",
3281        )];
3282        for (value, expected) in tests {
3283            let dialect = CustomDialectBuilder::new().build();
3284            let unparser = Unparser::new(&dialect);
3285
3286            let ast = unparser.expr_to_sql(&value).expect("to be unparsed");
3287            let actual = format!("{ast}");
3288
3289            assert_eq!(actual, expected);
3290        }
3291    }
3292
3293    #[test]
3294    fn test_array_literal_scalar_value_to_sql_postgres() -> Result<()> {
3295        let dialect: Arc<dyn Dialect> = Arc::new(PostgreSqlDialect {});
3296        let unparser = Unparser::new(dialect.as_ref());
3297
3298        let expr = Expr::Literal(
3299            ScalarValue::List(ScalarValue::new_list_nullable(
3300                &[
3301                    ScalarValue::Int32(Some(1)),
3302                    ScalarValue::Int32(Some(2)),
3303                    ScalarValue::Int32(Some(3)),
3304                ],
3305                &DataType::Int32,
3306            )),
3307            None,
3308        );
3309
3310        let ast = unparser.expr_to_sql(&expr)?;
3311        assert_eq!(ast.to_string(), "ARRAY[1, 2, 3]");
3312
3313        Ok(())
3314    }
3315
3316    #[test]
3317    fn test_nested_array_literal_scalar_value_to_sql_postgres() -> Result<()> {
3318        let dialect: Arc<dyn Dialect> = Arc::new(PostgreSqlDialect {});
3319        let unparser = Unparser::new(dialect.as_ref());
3320
3321        let inner_type = DataType::Int32;
3322        let nested_type =
3323            DataType::List(Arc::new(Field::new_list_field(inner_type.clone(), true)));
3324
3325        let expr = Expr::Literal(
3326            ScalarValue::List(ScalarValue::new_list_nullable(
3327                &[
3328                    ScalarValue::List(ScalarValue::new_list_nullable(
3329                        &[ScalarValue::Int32(Some(1)), ScalarValue::Int32(Some(2))],
3330                        &inner_type,
3331                    )),
3332                    ScalarValue::List(ScalarValue::new_list_nullable(
3333                        &[ScalarValue::Int32(Some(3)), ScalarValue::Int32(Some(4))],
3334                        &inner_type,
3335                    )),
3336                ],
3337                &nested_type,
3338            )),
3339            None,
3340        );
3341
3342        let ast = unparser.expr_to_sql(&expr)?;
3343        assert_eq!(ast.to_string(), "ARRAY[ARRAY[1, 2], ARRAY[3, 4]]");
3344
3345        Ok(())
3346    }
3347
3348    #[test]
3349    fn test_round_scalar_fn_to_expr() -> Result<()> {
3350        let default_dialect: Arc<dyn Dialect> = Arc::new(
3351            CustomDialectBuilder::new()
3352                .with_identifier_quote_style('"')
3353                .build(),
3354        );
3355        let postgres_dialect: Arc<dyn Dialect> = Arc::new(PostgreSqlDialect {});
3356
3357        for (dialect, identifier) in
3358            [(default_dialect, "DOUBLE"), (postgres_dialect, "NUMERIC")]
3359        {
3360            let unparser = Unparser::new(dialect.as_ref());
3361            let expr = Expr::ScalarFunction(ScalarFunction {
3362                func: Arc::new(ScalarUDF::from(
3363                    datafusion_functions::math::round::RoundFunc::new(),
3364                )),
3365                args: vec![
3366                    Expr::Cast(Cast::new(Box::new(col("a")), DataType::Float64)),
3367                    Expr::Literal(ScalarValue::Int64(Some(2)), None),
3368                ],
3369            });
3370            let ast = unparser.expr_to_sql(&expr)?;
3371
3372            let actual = format!("{ast}");
3373            let expected = format!(r#"round(CAST("a" AS {identifier}), 2)"#);
3374
3375            assert_eq!(actual, expected);
3376        }
3377        Ok(())
3378    }
3379
3380    #[test]
3381    fn test_postgres_array_has_to_any() -> Result<()> {
3382        let default_dialect: Arc<dyn Dialect> = Arc::new(DefaultDialect {});
3383        let postgres_dialect: Arc<dyn Dialect> = Arc::new(PostgreSqlDialect {});
3384        let expr = array_has(col("items"), lit(1));
3385
3386        for (dialect, expected) in [
3387            (default_dialect, "array_has(\"items\", 1)"),
3388            (postgres_dialect, "1 = ANY(\"items\")"),
3389        ] {
3390            let unparser = Unparser::new(dialect.as_ref());
3391            let actual = format!("{}", unparser.expr_to_sql(&expr)?);
3392            assert_eq!(actual, expected);
3393        }
3394
3395        Ok(())
3396    }
3397
3398    /// Regression test for https://github.com/apache/datafusion/issues/23056
3399    ///
3400    /// Deeply-nested expressions whose unparse path routes through scalar
3401    /// function arguments and dialect scalar-function overrides used to
3402    /// overflow the OS stack even with `recursive_protection` enabled,
3403    /// because the per-level stack cost of those paths exceeds the default
3404    /// `recursive` red zone and the unparser installed no [`StackGuard`].
3405    ///
3406    /// This test only asserts the protected behavior, so it is gated on the
3407    /// `recursive_protection` feature. Without that feature the unparser is
3408    /// not stack-safe by design and a deep enough expression will overflow.
3409    #[cfg(feature = "recursive_protection")]
3410    #[test]
3411    fn test_deeply_nested_expr_does_not_overflow_stack() {
3412        // Far deeper than the ~60 levels that overflow without protection, but
3413        // bounded so the trampoline's heap stacks stay reasonable in debug.
3414        const DEPTH: usize = 2_000;
3415
3416        // Run on an explicit, realistically-sized thread stack. The work is
3417        // performed on a spawned thread so an overflow (in the unfixed code)
3418        // aborts the process and fails the test deterministically rather than
3419        // depending on the harness thread's stack size.
3420        let handle = std::thread::Builder::new()
3421            .stack_size(2 * 1024 * 1024)
3422            .spawn(|| {
3423                // 1. Linear chain through a dialect scalar-function override:
3424                //    array_has(array_has(... array_has(col, 'x') ...), 'x').
3425                //    PostgreSqlDialect unparses array_has via array_has_to_sql_any,
3426                //    which recurses back into the unparser for each argument.
3427                let mut nested_fn: Expr = col("c");
3428                for _ in 0..DEPTH {
3429                    nested_fn = array_has(nested_fn, lit("x"));
3430                }
3431                let pg = PostgreSqlDialect {};
3432                Unparser::new(&pg)
3433                    .expr_to_sql(&nested_fn)
3434                    .expect("deeply nested scalar function should unparse");
3435
3436                // 2. Linear chain of plain binary operators, exercising the
3437                //    inner -> inner recursion on the default dialect.
3438                let mut nested_binary: Expr = col("c");
3439                for _ in 0..DEPTH {
3440                    nested_binary = nested_binary + lit(1);
3441                }
3442                Unparser::default()
3443                    .expr_to_sql(&nested_binary)
3444                    .expect("deeply nested binary expression should unparse");
3445
3446                // 3. Same binary chain in pretty mode. Pretty mode runs
3447                //    `remove_unnecessary_nesting` at every level, which recurses
3448                //    alongside the unparse itself; this locks down that second
3449                //    recursion site fixed by this PR.
3450                Unparser::default()
3451                    .with_pretty(true)
3452                    .expr_to_sql(&nested_binary)
3453                    .expect(
3454                        "deeply nested binary expression should unparse in pretty mode",
3455                    );
3456            })
3457            .unwrap();
3458
3459        // If the unparser overflows, the process aborts and this join is never
3460        // reached; otherwise the spawned thread returns cleanly.
3461        handle.join().expect("unparsing thread should not panic");
3462    }
3463
3464    #[cfg(feature = "recursive_protection")]
3465    #[test]
3466    fn test_expr_to_sql_does_not_mutate_recursive_minimum_stack_size() -> Result<()> {
3467        const DEFAULT_RECURSIVE_RED_ZONE: usize = 128 * 1024;
3468
3469        let previous_minimum = recursive::get_minimum_stack_size();
3470        recursive::set_minimum_stack_size(DEFAULT_RECURSIVE_RED_ZONE);
3471
3472        let observed_minimum = Arc::new(std::sync::atomic::AtomicUsize::new(usize::MAX));
3473        let dialect = DuckDBDialect::new().with_custom_scalar_overrides(vec![(
3474            "dummy_udf",
3475            Box::new({
3476                let observed_minimum = Arc::clone(&observed_minimum);
3477                move |unparser: &Unparser, args: &[Expr]| {
3478                    observed_minimum.store(
3479                        recursive::get_minimum_stack_size(),
3480                        std::sync::atomic::Ordering::Relaxed,
3481                    );
3482                    unparser.scalar_function_to_sql("dummy_udf", args).map(Some)
3483                }
3484            }) as ScalarFnToSqlHandler,
3485        )]);
3486        let expr = ScalarUDF::new_from_impl(DummyUDF::new()).call(vec![col("a")]);
3487
3488        let result = Unparser::new(&dialect).expr_to_sql(&expr);
3489        let final_minimum = recursive::get_minimum_stack_size();
3490        recursive::set_minimum_stack_size(previous_minimum);
3491
3492        result?;
3493        assert_eq!(
3494            observed_minimum.load(std::sync::atomic::Ordering::Relaxed),
3495            DEFAULT_RECURSIVE_RED_ZONE
3496        );
3497        assert_eq!(final_minimum, DEFAULT_RECURSIVE_RED_ZONE);
3498
3499        Ok(())
3500    }
3501
3502    #[test]
3503    fn case_propagates_operand_and_else_errors() {
3504        let unsupported = Expr::Literal(ScalarValue::DurationSecond(Some(1)), None);
3505        let expressions = [
3506            Expr::Case(Case::new(
3507                Some(Box::new(unsupported.clone())),
3508                vec![(Box::new(lit(1)), Box::new(lit(2)))],
3509                None,
3510            )),
3511            Expr::Case(Case::new(
3512                None,
3513                vec![(Box::new(lit(true)), Box::new(lit(1)))],
3514                Some(Box::new(unsupported)),
3515            )),
3516        ];
3517
3518        for expr in expressions {
3519            let error = expr_to_sql(&expr).expect_err("unsupported CASE child");
3520            assert!(error.to_string().contains("Unsupported scalar"));
3521        }
3522    }
3523
3524    #[test]
3525    fn test_window_func_support_window_frame() -> Result<()> {
3526        let default_dialect: Arc<dyn Dialect> =
3527            Arc::new(CustomDialectBuilder::new().build());
3528
3529        let test_dialect: Arc<dyn Dialect> = Arc::new(
3530            CustomDialectBuilder::new()
3531                .with_window_func_support_window_frame(false)
3532                .build(),
3533        );
3534
3535        for (dialect, expected) in [
3536            (
3537                default_dialect,
3538                "rank() OVER (ORDER BY a ASC NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)",
3539            ),
3540            (test_dialect, "rank() OVER (ORDER BY a ASC NULLS FIRST)"),
3541        ] {
3542            let unparser = Unparser::new(dialect.as_ref());
3543            let func = WindowFunctionDefinition::WindowUDF(rank_udwf());
3544            let mut window_func = WindowFunction::new(func, vec![]);
3545            window_func.params.order_by = vec![Sort::new(col("a"), true, true)];
3546            let expr = Expr::from(window_func);
3547            let ast = unparser.expr_to_sql(&expr)?;
3548
3549            let actual = ast.to_string();
3550            let expected = expected.to_string();
3551
3552            assert_eq!(actual, expected);
3553        }
3554        Ok(())
3555    }
3556
3557    #[test]
3558    fn test_from_unixtime() -> Result<()> {
3559        let default_dialect: Arc<dyn Dialect> = Arc::new(DefaultDialect {});
3560        let sqlite_dialect: Arc<dyn Dialect> = Arc::new(SqliteDialect {});
3561
3562        for (dialect, expected) in [
3563            (default_dialect, "from_unixtime(date_col)"),
3564            (sqlite_dialect, "datetime(`date_col`, 'unixepoch')"),
3565        ] {
3566            let unparser = Unparser::new(dialect.as_ref());
3567            let expr = Expr::ScalarFunction(ScalarFunction {
3568                func: Arc::new(ScalarUDF::from(FromUnixtimeFunc::default())),
3569                args: vec![col("date_col")],
3570            });
3571
3572            let ast = unparser.expr_to_sql(&expr)?;
3573
3574            let actual = ast.to_string();
3575            let expected = expected.to_string();
3576
3577            assert_eq!(actual, expected);
3578        }
3579        Ok(())
3580    }
3581
3582    #[test]
3583    fn test_date_trunc() -> Result<()> {
3584        let default_dialect: Arc<dyn Dialect> = Arc::new(DefaultDialect {});
3585        let sqlite_dialect: Arc<dyn Dialect> = Arc::new(SqliteDialect {});
3586
3587        for (dialect, precision, expected) in [
3588            (
3589                Arc::clone(&default_dialect),
3590                "YEAR",
3591                "date_trunc('YEAR', date_col)",
3592            ),
3593            (
3594                Arc::clone(&sqlite_dialect),
3595                "YEAR",
3596                "strftime('%Y', `date_col`)",
3597            ),
3598            (
3599                Arc::clone(&default_dialect),
3600                "MONTH",
3601                "date_trunc('MONTH', date_col)",
3602            ),
3603            (
3604                Arc::clone(&sqlite_dialect),
3605                "MONTH",
3606                "strftime('%Y-%m', `date_col`)",
3607            ),
3608            (
3609                Arc::clone(&default_dialect),
3610                "DAY",
3611                "date_trunc('DAY', date_col)",
3612            ),
3613            (
3614                Arc::clone(&sqlite_dialect),
3615                "DAY",
3616                "strftime('%Y-%m-%d', `date_col`)",
3617            ),
3618            (
3619                Arc::clone(&default_dialect),
3620                "HOUR",
3621                "date_trunc('HOUR', date_col)",
3622            ),
3623            (
3624                Arc::clone(&sqlite_dialect),
3625                "HOUR",
3626                "strftime('%Y-%m-%d %H', `date_col`)",
3627            ),
3628            (
3629                Arc::clone(&default_dialect),
3630                "MINUTE",
3631                "date_trunc('MINUTE', date_col)",
3632            ),
3633            (
3634                Arc::clone(&sqlite_dialect),
3635                "MINUTE",
3636                "strftime('%Y-%m-%d %H:%M', `date_col`)",
3637            ),
3638            (default_dialect, "SECOND", "date_trunc('SECOND', date_col)"),
3639            (
3640                sqlite_dialect,
3641                "SECOND",
3642                "strftime('%Y-%m-%d %H:%M:%S', `date_col`)",
3643            ),
3644        ] {
3645            let unparser = Unparser::new(dialect.as_ref());
3646            let expr = Expr::ScalarFunction(ScalarFunction {
3647                func: Arc::new(ScalarUDF::from(
3648                    datafusion_functions::datetime::date_trunc::DateTruncFunc::new(),
3649                )),
3650                args: vec![
3651                    Expr::Literal(ScalarValue::Utf8(Some(precision.to_string())), None),
3652                    col("date_col"),
3653                ],
3654            });
3655
3656            let ast = unparser.expr_to_sql(&expr)?;
3657
3658            let actual = ast.to_string();
3659            let expected = expected.to_string();
3660
3661            assert_eq!(actual, expected);
3662        }
3663        Ok(())
3664    }
3665
3666    #[test]
3667    fn test_dictionary_to_sql() -> Result<()> {
3668        let dialect = CustomDialectBuilder::new().build();
3669
3670        let unparser = Unparser::new(&dialect);
3671
3672        let arrow_field = Arc::new(Field::new(
3673            "",
3674            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
3675            true,
3676        ));
3677        let ast_dtype = unparser.arrow_dtype_to_ast_dtype(&arrow_field)?;
3678
3679        assert_eq!(ast_dtype, ast::DataType::Varchar(None));
3680
3681        Ok(())
3682    }
3683
3684    #[test]
3685    fn test_run_end_encoded_to_sql() -> Result<()> {
3686        let dialect = CustomDialectBuilder::new().build();
3687
3688        let unparser = Unparser::new(&dialect);
3689
3690        let ast_dtype = unparser.arrow_dtype_to_ast_dtype(
3691            &DataType::RunEndEncoded(
3692                Field::new("run_ends", DataType::Int32, false).into(),
3693                Field::new("values", DataType::Utf8, true).into(),
3694            )
3695            .into_nullable_field_ref(),
3696        )?;
3697
3698        assert_eq!(ast_dtype, ast::DataType::Varchar(None));
3699
3700        Ok(())
3701    }
3702
3703    #[test]
3704    fn test_utf8_view_to_sql() -> Result<()> {
3705        let dialect = CustomDialectBuilder::new()
3706            .with_utf8_cast_dtype(ast::DataType::Char(None))
3707            .build();
3708        let unparser = Unparser::new(&dialect);
3709
3710        let arrow_field = Arc::new(Field::new("", DataType::Utf8View, true));
3711        let ast_dtype = unparser.arrow_dtype_to_ast_dtype(&arrow_field)?;
3712
3713        assert_eq!(ast_dtype, ast::DataType::Char(None));
3714
3715        let expr = cast(col("a"), DataType::Utf8View);
3716        let ast = unparser.expr_to_sql(&expr)?;
3717
3718        let actual = format!("{ast}");
3719        let expected = r#"CAST(a AS CHAR)"#.to_string();
3720
3721        assert_eq!(actual, expected);
3722
3723        let expr = col("a").eq(lit(ScalarValue::Utf8View(Some("hello".to_string()))));
3724        let ast = unparser.expr_to_sql(&expr)?;
3725
3726        let actual = format!("{ast}");
3727        let expected = r#"(a = 'hello')"#.to_string();
3728
3729        assert_eq!(actual, expected);
3730
3731        let expr = col("a").is_not_null();
3732
3733        let ast = unparser.expr_to_sql(&expr)?;
3734        let actual = format!("{ast}");
3735        let expected = r#"a IS NOT NULL"#.to_string();
3736
3737        assert_eq!(actual, expected);
3738
3739        let expr = col("a").is_null();
3740
3741        let ast = unparser.expr_to_sql(&expr)?;
3742        let actual = format!("{ast}");
3743        let expected = r#"a IS NULL"#.to_string();
3744
3745        assert_eq!(actual, expected);
3746
3747        Ok(())
3748    }
3749
3750    #[test]
3751    fn test_custom_scalar_overrides_duckdb() -> Result<()> {
3752        let duckdb_default = DuckDBDialect::new();
3753        let duckdb_extended = DuckDBDialect::new().with_custom_scalar_overrides(vec![(
3754            "dummy_udf",
3755            Box::new(|unparser: &Unparser, args: &[Expr]| {
3756                unparser.scalar_function_to_sql("smart_udf", args).map(Some)
3757            }) as ScalarFnToSqlHandler,
3758        )]);
3759
3760        for (dialect, expected) in [
3761            (duckdb_default, r#"dummy_udf("a", "b")"#),
3762            (duckdb_extended, r#"smart_udf("a", "b")"#),
3763        ] {
3764            let unparser = Unparser::new(&dialect);
3765            let expr =
3766                ScalarUDF::new_from_impl(DummyUDF::new()).call(vec![col("a"), col("b")]);
3767            let actual = format!("{}", unparser.expr_to_sql(&expr)?);
3768            assert_eq!(actual, expected);
3769        }
3770
3771        Ok(())
3772    }
3773
3774    #[test]
3775    fn test_cast_timestamp_sqlite() -> Result<()> {
3776        let dialect: Arc<dyn Dialect> = Arc::new(SqliteDialect {});
3777
3778        let unparser = Unparser::new(dialect.as_ref());
3779        let expr = Expr::Cast(Cast::new(
3780            Box::new(col("a")),
3781            DataType::Timestamp(TimeUnit::Nanosecond, None),
3782        ));
3783
3784        let ast = unparser.expr_to_sql(&expr)?;
3785
3786        let actual = ast.to_string();
3787        let expected = "CAST(`a` AS TEXT)".to_string();
3788
3789        assert_eq!(actual, expected);
3790
3791        Ok(())
3792    }
3793
3794    #[test]
3795    fn test_timestamp_with_tz_format() -> Result<()> {
3796        let default_dialect: Arc<dyn Dialect> =
3797            Arc::new(CustomDialectBuilder::new().build());
3798
3799        let duckdb_dialect: Arc<dyn Dialect> = Arc::new(DuckDBDialect::new());
3800        let bigquery_dialect: Arc<dyn Dialect> = Arc::new(BigQueryDialect::new());
3801        let snowflake_dialect: Arc<dyn Dialect> = Arc::new(SnowflakeDialect::new());
3802
3803        for (dialect, scalar, expected) in [
3804            (
3805                Arc::clone(&default_dialect),
3806                ScalarValue::TimestampSecond(Some(1757934000), Some("+00:00".into())),
3807                "CAST('2025-09-15T11:00:00+00:00' AS TIMESTAMP WITH TIME ZONE)",
3808            ),
3809            (
3810                Arc::clone(&default_dialect),
3811                ScalarValue::TimestampMillisecond(
3812                    Some(1757934000123),
3813                    Some("+01:00".into()),
3814                ),
3815                "CAST('2025-09-15T12:00:00.123+01:00' AS TIMESTAMP WITH TIME ZONE)",
3816            ),
3817            (
3818                Arc::clone(&default_dialect),
3819                ScalarValue::TimestampMicrosecond(
3820                    Some(1757934000123456),
3821                    Some("-01:00".into()),
3822                ),
3823                "CAST('2025-09-15T10:00:00.123456-01:00' AS TIMESTAMP WITH TIME ZONE)",
3824            ),
3825            (
3826                Arc::clone(&default_dialect),
3827                ScalarValue::TimestampNanosecond(
3828                    Some(1757934000123456789),
3829                    Some("+00:00".into()),
3830                ),
3831                "CAST('2025-09-15T11:00:00.123456789+00:00' AS TIMESTAMP WITH TIME ZONE)",
3832            ),
3833            (
3834                Arc::clone(&duckdb_dialect),
3835                ScalarValue::TimestampSecond(Some(1757934000), Some("+00:00".into())),
3836                "CAST('2025-09-15T11:00:00+00:00' AS TIMESTAMP WITH TIME ZONE)",
3837            ),
3838            (
3839                Arc::clone(&duckdb_dialect),
3840                ScalarValue::TimestampMillisecond(
3841                    Some(1757934000123),
3842                    Some("+01:00".into()),
3843                ),
3844                "CAST('2025-09-15T12:00:00.123+01:00' AS TIMESTAMP WITH TIME ZONE)",
3845            ),
3846            (
3847                Arc::clone(&duckdb_dialect),
3848                ScalarValue::TimestampMicrosecond(
3849                    Some(1757934000123456),
3850                    Some("-01:00".into()),
3851                ),
3852                "CAST('2025-09-15T10:00:00.123456-01:00' AS TIMESTAMP WITH TIME ZONE)",
3853            ),
3854            (
3855                Arc::clone(&duckdb_dialect),
3856                ScalarValue::TimestampNanosecond(
3857                    Some(1757934000123456789),
3858                    Some("+00:00".into()),
3859                ),
3860                "CAST('2025-09-15T11:00:00.123456789+00:00' AS TIMESTAMP WITH TIME ZONE)",
3861            ),
3862            (
3863                Arc::clone(&bigquery_dialect),
3864                ScalarValue::TimestampSecond(Some(1757934000), Some("+00:00".into())),
3865                "CAST('2025-09-15T11:00:00+00:00' AS TIMESTAMP)",
3866            ),
3867            (
3868                Arc::clone(&bigquery_dialect),
3869                ScalarValue::TimestampMillisecond(
3870                    Some(1757934000123),
3871                    Some("+01:00".into()),
3872                ),
3873                "CAST('2025-09-15T12:00:00.123+01:00' AS TIMESTAMP)",
3874            ),
3875            (
3876                Arc::clone(&bigquery_dialect),
3877                ScalarValue::TimestampMicrosecond(
3878                    Some(1757934000123456),
3879                    Some("-01:00".into()),
3880                ),
3881                "CAST('2025-09-15T10:00:00.123456-01:00' AS TIMESTAMP)",
3882            ),
3883            (
3884                Arc::clone(&bigquery_dialect),
3885                ScalarValue::TimestampNanosecond(
3886                    Some(1757934000123456789),
3887                    Some("+00:00".into()),
3888                ),
3889                "CAST('2025-09-15T11:00:00.123456789+00:00' AS TIMESTAMP)",
3890            ),
3891            (
3892                Arc::clone(&snowflake_dialect),
3893                ScalarValue::TimestampMillisecond(
3894                    Some(1757934000123),
3895                    Some("+01:00".into()),
3896                ),
3897                "CAST('2025-09-15T12:00:00.123+01:00' AS TIMESTAMP WITH TIME ZONE)",
3898            ),
3899        ] {
3900            let unparser = Unparser::new(dialect.as_ref());
3901
3902            let expr = Expr::Literal(scalar, None);
3903
3904            let actual = format!("{}", unparser.expr_to_sql(&expr)?);
3905            assert_eq!(actual, expected);
3906        }
3907        Ok(())
3908    }
3909
3910    #[test]
3911    fn test_timestamp_literal_passes_tz_to_dialect() -> Result<()> {
3912        // Puts the time zone it receives into the cast type, so the generated
3913        // SQL shows which zone the unparser passed to the dialect.
3914        struct TzEchoDialect;
3915
3916        impl Dialect for TzEchoDialect {
3917            fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
3918                None
3919            }
3920
3921            fn timestamp_cast_dtype(
3922                &self,
3923                _time_unit: &TimeUnit,
3924                tz: &Option<Arc<str>>,
3925            ) -> ast::DataType {
3926                match tz {
3927                    Some(tz) => ast::DataType::Custom(
3928                        ObjectName::from(vec![Ident::new("TIMESTAMPTZ")]),
3929                        vec![tz.to_string()],
3930                    ),
3931                    None => ast::DataType::Timestamp(None, TimezoneInfo::None),
3932                }
3933            }
3934        }
3935
3936        let unparser = Unparser::new(&TzEchoDialect);
3937
3938        let literal = Expr::Literal(
3939            ScalarValue::TimestampSecond(Some(1704078000), Some("Asia/Tokyo".into())),
3940            None,
3941        );
3942        let cast_expr = cast(
3943            col("a"),
3944            DataType::Timestamp(TimeUnit::Second, Some("Asia/Tokyo".into())),
3945        );
3946
3947        for (expr, expected) in [
3948            (
3949                literal,
3950                "CAST('2024-01-01T12:00:00+09:00' AS TIMESTAMPTZ(Asia/Tokyo))",
3951            ),
3952            (cast_expr, "CAST(a AS TIMESTAMPTZ(Asia/Tokyo))"),
3953        ] {
3954            let actual = format!("{}", unparser.expr_to_sql(&expr)?);
3955            assert_eq!(actual, expected);
3956        }
3957        Ok(())
3958    }
3959
3960    #[test]
3961    fn test_bigquery_dialect_overrides() -> Result<()> {
3962        let bigquery_dialect: Arc<dyn Dialect> = Arc::new(BigQueryDialect::new());
3963        let unparser = Unparser::new(bigquery_dialect.as_ref());
3964
3965        // date_field_extract_style: EXTRACT instead of date_part
3966        let expr = Expr::ScalarFunction(ScalarFunction {
3967            func: Arc::new(ScalarUDF::new_from_impl(
3968                datafusion_functions::datetime::date_part::DatePartFunc::new(),
3969            )),
3970            args: vec![lit("YEAR"), col("date_col")],
3971        });
3972        let actual = format!("{}", unparser.expr_to_sql(&expr)?);
3973        assert_eq!(actual, "EXTRACT(YEAR FROM `date_col`)");
3974
3975        // interval_style: SQL standard instead of PostgresVerbose
3976        let expr = interval_year_month_lit("3 months");
3977        let actual = format!("{}", unparser.expr_to_sql(&expr)?);
3978        assert_eq!(actual, "INTERVAL '3' MONTH");
3979
3980        // float64_ast_dtype: FLOAT64 instead of DOUBLE
3981        let expr = cast(col("a"), DataType::Float64);
3982        let actual = format!("{}", unparser.expr_to_sql(&expr)?);
3983        assert_eq!(actual, "CAST(`a` AS FLOAT64)");
3984
3985        // supports_column_alias_in_table_alias: false
3986        assert!(!bigquery_dialect.supports_column_alias_in_table_alias());
3987
3988        // utf8_cast_dtype: STRING instead of VARCHAR
3989        let expr = cast(col("a"), DataType::Utf8);
3990        let actual = format!("{}", unparser.expr_to_sql(&expr)?);
3991        assert_eq!(actual, "CAST(`a` AS STRING)");
3992
3993        // large_utf8_cast_dtype: STRING instead of TEXT
3994        let expr = cast(col("a"), DataType::LargeUtf8);
3995        let actual = format!("{}", unparser.expr_to_sql(&expr)?);
3996        assert_eq!(actual, "CAST(`a` AS STRING)");
3997
3998        // timestamp_cast_dtype: TIMESTAMP (no WITH TIME ZONE)
3999        let expr = cast(
4000            col("a"),
4001            DataType::Timestamp(TimeUnit::Microsecond, Some("+00:00".into())),
4002        );
4003        let actual = format!("{}", unparser.expr_to_sql(&expr)?);
4004        assert_eq!(actual, "CAST(`a` AS TIMESTAMP)");
4005
4006        Ok(())
4007    }
4008
4009    #[test]
4010    fn test_is_distinct_from() {
4011        let mysql_unparser = Unparser::new(&MySqlDialect {});
4012
4013        let expr = Expr::BinaryExpr(BinaryExpr::new(
4014            Box::new(col("c1")),
4015            Operator::IsDistinctFrom,
4016            Box::new(lit(true)),
4017        ));
4018
4019        let sql = expr_to_sql(&expr).unwrap().to_string();
4020        assert_eq!(sql, "(c1 IS DISTINCT FROM true)");
4021        let sql = mysql_unparser.expr_to_sql(&expr).unwrap().to_string();
4022        assert_eq!(sql, "(NOT (`c1` <=> true))");
4023
4024        let expr = Expr::BinaryExpr(BinaryExpr::new(
4025            Box::new(col("c1")),
4026            Operator::IsNotDistinctFrom,
4027            Box::new(lit(true)),
4028        ));
4029
4030        let sql = expr_to_sql(&expr).unwrap().to_string();
4031        assert_eq!(sql, "(c1 IS NOT DISTINCT FROM true)");
4032        let sql = mysql_unparser.expr_to_sql(&expr).unwrap().to_string();
4033        assert_eq!(sql, "(`c1` <=> true)");
4034    }
4035
4036    #[test]
4037    fn test_binary_literal() {
4038        let value = vec![0xDEu8, 0xAD, 0xBE, 0xEF];
4039        let expected_hex = "X'deadbeef'";
4040
4041        assert_eq!(
4042            expr_to_sql(&Expr::Literal(
4043                ScalarValue::Binary(Some(value.clone())),
4044                None
4045            ))
4046            .unwrap()
4047            .to_string(),
4048            expected_hex
4049        );
4050        assert_eq!(
4051            expr_to_sql(&Expr::Literal(
4052                ScalarValue::BinaryView(Some(value.clone())),
4053                None
4054            ))
4055            .unwrap()
4056            .to_string(),
4057            expected_hex
4058        );
4059        assert_eq!(
4060            expr_to_sql(&Expr::Literal(
4061                ScalarValue::FixedSizeBinary(4, Some(value.clone())),
4062                None
4063            ))
4064            .unwrap()
4065            .to_string(),
4066            expected_hex
4067        );
4068        assert_eq!(
4069            expr_to_sql(&Expr::Literal(
4070                ScalarValue::LargeBinary(Some(value.clone())),
4071                None
4072            ))
4073            .unwrap()
4074            .to_string(),
4075            expected_hex
4076        );
4077
4078        assert_eq!(
4079            expr_to_sql(&Expr::Literal(ScalarValue::Binary(None), None))
4080                .unwrap()
4081                .to_string(),
4082            "NULL"
4083        );
4084        assert_eq!(
4085            expr_to_sql(&Expr::Literal(ScalarValue::BinaryView(None), None))
4086                .unwrap()
4087                .to_string(),
4088            "NULL"
4089        );
4090        assert_eq!(
4091            expr_to_sql(&Expr::Literal(ScalarValue::FixedSizeBinary(1, None), None))
4092                .unwrap()
4093                .to_string(),
4094            "NULL"
4095        );
4096        assert_eq!(
4097            expr_to_sql(&Expr::Literal(ScalarValue::LargeBinary(None), None))
4098                .unwrap()
4099                .to_string(),
4100            "NULL"
4101        );
4102    }
4103
4104    #[test]
4105    fn test_random_function() -> Result<()> {
4106        let duckdb_dialect = DuckDBDialect::new();
4107        let dialects = vec![
4108            (Unparser::new(&DefaultDialect {}), "random()"),
4109            (Unparser::new(&PostgreSqlDialect {}), "random()"),
4110            (Unparser::new(&duckdb_dialect), "random()"),
4111            (Unparser::new(&MySqlDialect {}), "rand()"),
4112            (Unparser::new(&SqliteDialect {}), "random()"),
4113            (Unparser::new(&BigQueryDialect {}), "rand()"),
4114            (Unparser::new(&SnowflakeDialect {}), "random()"),
4115        ];
4116
4117        let expr = Expr::ScalarFunction(ScalarFunction {
4118            func: Arc::new(ScalarUDF::from(
4119                datafusion_functions::math::random::RandomFunc::new(),
4120            )),
4121            args: vec![],
4122        });
4123
4124        for (unparser, result) in dialects {
4125            assert_eq!(unparser.expr_to_sql(&expr)?.to_string(), result);
4126        }
4127
4128        Ok(())
4129    }
4130
4131    #[test]
4132    fn test_unparse_null_treatment_window_and_aggregate() -> Result<()> {
4133        use datafusion_expr::expr::NullTreatment;
4134        use datafusion_functions_aggregate::first_last::first_value_udaf;
4135        use datafusion_functions_window::nth_value::first_value_udwf;
4136
4137        // Window function with IgnoreNulls
4138        let window_ignore = Expr::from(WindowFunction {
4139            fun: WindowFunctionDefinition::WindowUDF(first_value_udwf()),
4140            params: WindowFunctionParams {
4141                args: vec![col("a")],
4142                partition_by: vec![],
4143                order_by: vec![Sort::new(col("b"), true, true)],
4144                window_frame: WindowFrame::new(None),
4145                null_treatment: Some(NullTreatment::IgnoreNulls),
4146                distinct: false,
4147                filter: None,
4148            },
4149        });
4150
4151        // Window function with RespectNulls
4152        let window_respect = Expr::from(WindowFunction {
4153            fun: WindowFunctionDefinition::WindowUDF(first_value_udwf()),
4154            params: WindowFunctionParams {
4155                args: vec![col("a")],
4156                partition_by: vec![],
4157                order_by: vec![Sort::new(col("b"), true, true)],
4158                window_frame: WindowFrame::new(None),
4159                null_treatment: Some(NullTreatment::RespectNulls),
4160                distinct: false,
4161                filter: None,
4162            },
4163        });
4164
4165        // Window function with None (Control)
4166        let window_none = Expr::from(WindowFunction {
4167            fun: WindowFunctionDefinition::WindowUDF(first_value_udwf()),
4168            params: WindowFunctionParams {
4169                args: vec![col("a")],
4170                partition_by: vec![],
4171                order_by: vec![Sort::new(col("b"), true, true)],
4172                window_frame: WindowFrame::new(None),
4173                null_treatment: None,
4174                distinct: false,
4175                filter: None,
4176            },
4177        });
4178
4179        // Aggregate function with IgnoreNulls
4180        let agg_ignore =
4181            Expr::AggregateFunction(datafusion_expr::expr::AggregateFunction::new_udf(
4182                first_value_udaf(),
4183                vec![col("a")],
4184                false,
4185                None,
4186                vec![],
4187                Some(NullTreatment::IgnoreNulls),
4188            ));
4189
4190        // Aggregate function with RespectNulls
4191        let agg_respect =
4192            Expr::AggregateFunction(datafusion_expr::expr::AggregateFunction::new_udf(
4193                first_value_udaf(),
4194                vec![col("a")],
4195                false,
4196                None,
4197                vec![],
4198                Some(NullTreatment::RespectNulls),
4199            ));
4200
4201        // Aggregate function with None (Control)
4202        let agg_none =
4203            Expr::AggregateFunction(datafusion_expr::expr::AggregateFunction::new_udf(
4204                first_value_udaf(),
4205                vec![col("a")],
4206                false,
4207                None,
4208                vec![],
4209                None,
4210            ));
4211
4212        let actual_window_ignore = expr_to_sql(&window_ignore)?.to_string();
4213        let actual_window_respect = expr_to_sql(&window_respect)?.to_string();
4214        let actual_window_none = expr_to_sql(&window_none)?.to_string();
4215        let actual_agg_ignore = expr_to_sql(&agg_ignore)?.to_string();
4216        let actual_agg_respect = expr_to_sql(&agg_respect)?.to_string();
4217        let actual_agg_none = expr_to_sql(&agg_none)?.to_string();
4218
4219        assert_eq!(
4220            actual_window_ignore,
4221            "first_value(a) IGNORE NULLS OVER (ORDER BY b ASC NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)"
4222        );
4223        assert_eq!(
4224            actual_window_respect,
4225            "first_value(a) RESPECT NULLS OVER (ORDER BY b ASC NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)"
4226        );
4227        assert_eq!(
4228            actual_window_none,
4229            "first_value(a) OVER (ORDER BY b ASC NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)"
4230        );
4231        assert_eq!(actual_agg_ignore, "first_value(a) IGNORE NULLS");
4232        assert_eq!(actual_agg_respect, "first_value(a) RESPECT NULLS");
4233        assert_eq!(actual_agg_none, "first_value(a)");
4234
4235        Ok(())
4236    }
4237}