Skip to main content

datafusion_sql/
planner.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
5//! [`SqlToRel`]: SQL Query Planner (produces [`LogicalPlan`] from SQL AST)
6use std::collections::HashMap;
7use std::str::FromStr;
8use std::sync::{Arc, Mutex};
9use std::vec;
10
11use crate::utils::make_decimal_type;
12use arrow::datatypes::*;
13use arrow_schema::extension::{Json, Uuid};
14use datafusion_common::TableReference;
15use datafusion_common::config::SqlParserOptions;
16use datafusion_common::datatype::{DataTypeExt, FieldExt};
17use datafusion_common::error::add_possible_columns_to_diag;
18use datafusion_common::{DFSchema, DataFusionError, Result, not_impl_err, plan_err};
19use datafusion_common::{
20    DFSchemaRef, Diagnostic, SchemaError, field_not_found, internal_err,
21    plan_datafusion_err,
22};
23use datafusion_expr::Expr;
24use datafusion_expr::logical_plan::{LogicalPlan, LogicalPlanBuilder};
25pub use datafusion_expr::planner::ContextProvider;
26use datafusion_expr::utils::find_column_exprs;
27use sqlparser::ast::{ArrayElemTypeDef, ExactNumberInfo, TimezoneInfo};
28use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};
29use sqlparser::ast::{DataType as SQLDataType, Ident, ObjectName, TableAlias};
30
31/// SQL parser options
32#[derive(Debug, Clone, Copy)]
33pub struct ParserOptions {
34    /// Whether to parse float as decimal.
35    pub parse_float_as_decimal: bool,
36    /// Whether to normalize identifiers.
37    pub enable_ident_normalization: bool,
38    /// Whether to support varchar with length.
39    pub support_varchar_with_length: bool,
40    /// Whether to normalize options value.
41    pub enable_options_value_normalization: bool,
42    /// Whether to collect spans
43    pub collect_spans: bool,
44    /// Whether string types (VARCHAR, CHAR, Text, and String) are mapped to `Utf8View` during SQL planning.
45    pub map_string_types_to_utf8view: bool,
46    /// Default null ordering for sorting expressions.
47    pub default_null_ordering: NullOrdering,
48}
49
50impl ParserOptions {
51    /// Creates a new `ParserOptions` instance with default values.
52    ///
53    /// # Examples
54    ///
55    /// ```
56    /// use datafusion_sql::planner::ParserOptions;
57    /// let opts = ParserOptions::new();
58    /// assert_eq!(opts.parse_float_as_decimal, false);
59    /// assert_eq!(opts.enable_ident_normalization, true);
60    /// ```
61    pub fn new() -> Self {
62        Self {
63            parse_float_as_decimal: false,
64            enable_ident_normalization: true,
65            support_varchar_with_length: true,
66            map_string_types_to_utf8view: true,
67            enable_options_value_normalization: false,
68            collect_spans: false,
69            // By default, `nulls_max` is used to follow Postgres's behavior.
70            // postgres rule: https://www.postgresql.org/docs/current/queries-order.html
71            default_null_ordering: NullOrdering::NullsMax,
72        }
73    }
74
75    /// Sets the `parse_float_as_decimal` option.
76    ///
77    /// # Examples
78    ///
79    /// ```
80    /// use datafusion_sql::planner::ParserOptions;
81    /// let opts = ParserOptions::new().with_parse_float_as_decimal(true);
82    /// assert_eq!(opts.parse_float_as_decimal, true);
83    /// ```
84    pub fn with_parse_float_as_decimal(mut self, value: bool) -> Self {
85        self.parse_float_as_decimal = value;
86        self
87    }
88
89    /// Sets the `enable_ident_normalization` option.
90    ///
91    /// # Examples
92    ///
93    /// ```
94    /// use datafusion_sql::planner::ParserOptions;
95    /// let opts = ParserOptions::new().with_enable_ident_normalization(false);
96    /// assert_eq!(opts.enable_ident_normalization, false);
97    /// ```
98    pub fn with_enable_ident_normalization(mut self, value: bool) -> Self {
99        self.enable_ident_normalization = value;
100        self
101    }
102
103    /// Sets the `support_varchar_with_length` option.
104    pub fn with_support_varchar_with_length(mut self, value: bool) -> Self {
105        self.support_varchar_with_length = value;
106        self
107    }
108
109    /// Sets the `map_string_types_to_utf8view` option.
110    pub fn with_map_string_types_to_utf8view(mut self, value: bool) -> Self {
111        self.map_string_types_to_utf8view = value;
112        self
113    }
114
115    /// Sets the `enable_options_value_normalization` option.
116    pub fn with_enable_options_value_normalization(mut self, value: bool) -> Self {
117        self.enable_options_value_normalization = value;
118        self
119    }
120
121    /// Sets the `collect_spans` option.
122    pub fn with_collect_spans(mut self, value: bool) -> Self {
123        self.collect_spans = value;
124        self
125    }
126
127    /// Sets the `default_null_ordering` option.
128    pub fn with_default_null_ordering(mut self, value: NullOrdering) -> Self {
129        self.default_null_ordering = value;
130        self
131    }
132}
133
134impl Default for ParserOptions {
135    fn default() -> Self {
136        Self::new()
137    }
138}
139
140impl From<&SqlParserOptions> for ParserOptions {
141    fn from(options: &SqlParserOptions) -> Self {
142        Self {
143            parse_float_as_decimal: options.parse_float_as_decimal,
144            enable_ident_normalization: options.enable_ident_normalization,
145            support_varchar_with_length: options.support_varchar_with_length,
146            map_string_types_to_utf8view: options.map_string_types_to_utf8view,
147            enable_options_value_normalization: options
148                .enable_options_value_normalization,
149            collect_spans: options.collect_spans,
150            default_null_ordering: options.default_null_ordering.as_str().into(),
151        }
152    }
153}
154
155/// Represents the null ordering for sorting expressions.
156#[derive(Debug, Clone, Copy)]
157pub enum NullOrdering {
158    /// Nulls appear last in ascending order.
159    NullsMax,
160    /// Nulls appear first in descending order.
161    NullsMin,
162    /// Nulls appear first.
163    NullsFirst,
164    /// Nulls appear last.
165    NullsLast,
166}
167
168impl NullOrdering {
169    /// Evaluates the null ordering based on the given ascending flag.
170    ///
171    /// # Returns
172    /// * `true` if nulls should appear first.
173    /// * `false` if nulls should appear last.
174    pub fn nulls_first(&self, asc: bool) -> bool {
175        match self {
176            Self::NullsMax => !asc,
177            Self::NullsMin => asc,
178            Self::NullsFirst => true,
179            Self::NullsLast => false,
180        }
181    }
182}
183
184impl FromStr for NullOrdering {
185    type Err = DataFusionError;
186
187    fn from_str(s: &str) -> Result<Self> {
188        match s {
189            "nulls_max" => Ok(Self::NullsMax),
190            "nulls_min" => Ok(Self::NullsMin),
191            "nulls_first" => Ok(Self::NullsFirst),
192            "nulls_last" => Ok(Self::NullsLast),
193            _ => plan_err!(
194                "Unknown null ordering: Expected one of 'nulls_first', 'nulls_last', 'nulls_min' or 'nulls_max'. Got {s}"
195            ),
196        }
197    }
198}
199
200impl From<&str> for NullOrdering {
201    fn from(s: &str) -> Self {
202        Self::from_str(s).unwrap_or(Self::NullsMax)
203    }
204}
205
206/// Ident Normalizer
207#[derive(Debug)]
208pub struct IdentNormalizer {
209    normalize: bool,
210}
211
212impl Default for IdentNormalizer {
213    fn default() -> Self {
214        Self { normalize: true }
215    }
216}
217
218impl IdentNormalizer {
219    pub fn new(normalize: bool) -> Self {
220        Self { normalize }
221    }
222
223    pub fn normalize(&self, ident: Ident) -> String {
224        if self.normalize {
225            crate::utils::normalize_ident(ident)
226        } else {
227            ident.value
228        }
229    }
230}
231
232/// Struct to store the states used by the Planner. The Planner will leverage the states
233/// to resolve CTEs, Views, subqueries and PREPARE statements. The states include
234/// Common Table Expression (CTE) provided with WITH clause and
235/// Parameter Data Types provided with PREPARE statement and the query schema of the
236/// outer query plan.
237///
238/// # Cloning
239///
240/// Only the `ctes` are truly cloned when the `PlannerContext` is cloned.
241/// This helps resolve scoping issues of CTEs.
242/// By using cloning, a subquery can inherit CTEs from the outer query
243/// and can also define its own private CTEs without affecting the outer query.
244#[derive(Debug, Clone)]
245pub struct PlannerContext {
246    /// Data types for numbered parameters ($1, $2, etc), if supplied
247    /// in `PREPARE` statement
248    prepare_param_data_types: Arc<Vec<Option<FieldRef>>>,
249    /// Map of CTE name to logical plan of the WITH clause.
250    /// Use `Arc<LogicalPlan>` to allow cheap cloning
251    ctes: HashMap<String, Arc<LogicalPlan>>,
252
253    /// The queries schemas of outer query relations, used to resolve the outer referenced
254    /// columns in subquery (recursive aware)
255    outer_queries_schemas_stack: Vec<DFSchemaRef>,
256    /// The joined schemas of all FROM clauses planned so far. When planning LATERAL
257    /// FROM clauses, this should become a suffix of the `outer_query_schema`.
258    outer_from_schema: Option<DFSchemaRef>,
259    /// The query schema defined by the table
260    create_table_schema: Option<DFSchemaRef>,
261    /// When planning non-first queries in a set expression
262    /// (UNION/INTERSECT/EXCEPT), holds the schema of the left-most query.
263    /// Used to alias duplicate expressions to match the left side's field names.
264    set_expr_left_schema: Option<DFSchemaRef>,
265    /// The parameters of all lambdas seen so far
266    lambda_parameters: HashMap<String, FieldRef>,
267}
268
269impl Default for PlannerContext {
270    fn default() -> Self {
271        Self::new()
272    }
273}
274
275impl PlannerContext {
276    /// Create an empty PlannerContext
277    pub fn new() -> Self {
278        Self {
279            prepare_param_data_types: Arc::new(vec![]),
280            ctes: HashMap::new(),
281            outer_queries_schemas_stack: vec![],
282            outer_from_schema: None,
283            create_table_schema: None,
284            set_expr_left_schema: None,
285            lambda_parameters: HashMap::new(),
286        }
287    }
288
289    /// Update the PlannerContext with provided prepare_param_data_types
290    pub fn with_prepare_param_data_types(
291        mut self,
292        prepare_param_data_types: Vec<Option<FieldRef>>,
293    ) -> Self {
294        self.prepare_param_data_types = prepare_param_data_types.into();
295        self
296    }
297
298    /// Return the stack of outer relations' schemas, the outer most
299    /// relation are at the first entry
300    pub fn outer_queries_schemas(&self) -> &[DFSchemaRef] {
301        &self.outer_queries_schemas_stack
302    }
303
304    /// Return an iterator of the subquery relations' schemas, innermost
305    /// relation is returned first.
306    ///
307    /// This order corresponds to the order of resolution when looking up column
308    /// references in subqueries, which start from the innermost relation and
309    /// then look up the outer relations one by one until a match is found or no
310    /// more outer relation exist.
311    ///
312    /// NOTE this is *REVERSED* order of [`Self::outer_queries_schemas`]
313    ///
314    /// This is useful to resolve the column reference in the subquery by
315    /// looking up the outer query schemas one by one.
316    pub fn outer_schemas_iter(&self) -> impl Iterator<Item = &DFSchemaRef> {
317        self.outer_queries_schemas_stack.iter().rev()
318    }
319
320    /// Sets the outer query schema, returning the existing one, if
321    /// any
322    pub fn append_outer_query_schema(&mut self, schema: DFSchemaRef) {
323        self.outer_queries_schemas_stack.push(schema);
324    }
325
326    /// The schema of the adjacent outer relation
327    pub fn latest_outer_query_schema(&self) -> Option<&DFSchemaRef> {
328        self.outer_queries_schemas_stack.last()
329    }
330
331    /// Remove the schema of the adjacent outer relation
332    pub fn pop_outer_query_schema(&mut self) -> Option<DFSchemaRef> {
333        self.outer_queries_schemas_stack.pop()
334    }
335
336    pub fn set_table_schema(
337        &mut self,
338        mut schema: Option<DFSchemaRef>,
339    ) -> Option<DFSchemaRef> {
340        std::mem::swap(&mut self.create_table_schema, &mut schema);
341        schema
342    }
343
344    pub fn table_schema(&self) -> Option<DFSchemaRef> {
345        self.create_table_schema.clone()
346    }
347
348    // Return a clone of the outer FROM schema
349    pub fn outer_from_schema(&self) -> Option<Arc<DFSchema>> {
350        self.outer_from_schema.clone()
351    }
352
353    /// Sets the outer FROM schema, returning the existing one, if any
354    pub fn set_outer_from_schema(
355        &mut self,
356        mut schema: Option<DFSchemaRef>,
357    ) -> Option<DFSchemaRef> {
358        std::mem::swap(&mut self.outer_from_schema, &mut schema);
359        schema
360    }
361
362    /// Extends the FROM schema, returning the existing one, if any
363    pub fn extend_outer_from_schema(&mut self, schema: &DFSchemaRef) -> Result<()> {
364        match self.outer_from_schema.as_mut() {
365            Some(from_schema) => Arc::make_mut(from_schema).merge(schema),
366            None => self.outer_from_schema = Some(Arc::clone(schema)),
367        }
368        Ok(())
369    }
370
371    /// Return the types of parameters (`$1`, `$2`, etc) if known
372    pub fn prepare_param_data_types(&self) -> &[Option<FieldRef>] {
373        &self.prepare_param_data_types
374    }
375
376    /// Returns true if there is a Common Table Expression (CTE) /
377    /// Subquery for the specified name
378    pub fn contains_cte(&self, cte_name: &str) -> bool {
379        self.ctes.contains_key(cte_name)
380    }
381
382    /// Inserts a LogicalPlan for the Common Table Expression (CTE) /
383    /// Subquery for the specified name
384    pub fn insert_cte(&mut self, cte_name: impl Into<String>, plan: LogicalPlan) {
385        let cte_name = cte_name.into();
386        self.ctes.insert(cte_name, Arc::new(plan));
387    }
388
389    /// Return a plan for the Common Table Expression (CTE) / Subquery for the
390    /// specified name
391    pub fn get_cte(&self, cte_name: &str) -> Option<&LogicalPlan> {
392        self.ctes.get(cte_name).map(|cte| cte.as_ref())
393    }
394
395    pub fn lambda_parameters(&self) -> &HashMap<String, FieldRef> {
396        &self.lambda_parameters
397    }
398
399    pub fn with_lambda_parameters(
400        mut self,
401        parameters: impl IntoIterator<Item = FieldRef>,
402    ) -> Self {
403        self.lambda_parameters
404            .extend(parameters.into_iter().map(|f| (f.name().clone(), f)));
405
406        self
407    }
408
409    /// Remove the plan of CTE / Subquery for the specified name
410    pub(super) fn remove_cte(&mut self, cte_name: &str) {
411        self.ctes.remove(cte_name);
412    }
413
414    /// Sets the left-most set expression schema, returning the previous value
415    pub(super) fn set_set_expr_left_schema(
416        &mut self,
417        schema: Option<DFSchemaRef>,
418    ) -> Option<DFSchemaRef> {
419        std::mem::replace(&mut self.set_expr_left_schema, schema)
420    }
421}
422
423/// SQL query planner and binder
424///
425/// This struct is used to convert a SQL AST into a [`LogicalPlan`].
426///
427/// You can control the behavior of the planner by providing [`ParserOptions`].
428///
429/// It performs the following tasks:
430///
431/// 1. Name and type resolution (called "binding" in other systems). This
432///    phase looks up table and column names using the [`ContextProvider`].
433/// 2. Mechanical translation of the AST into a [`LogicalPlan`].
434///
435/// It does not perform type coercion, or perform optimization, which are done
436/// by subsequent passes.
437///
438/// Key interfaces are:
439/// * [`Self::sql_statement_to_plan`]: Convert a statement
440///   (e.g. `SELECT ...`) into a [`LogicalPlan`]
441/// * [`Self::sql_to_expr`]: Convert an expression (e.g. `1 + 2`) into an [`Expr`]
442pub struct SqlToRel<'a, S: ContextProvider> {
443    pub(crate) context_provider: &'a S,
444    pub(crate) options: ParserOptions,
445    pub(crate) ident_normalizer: IdentNormalizer,
446    warnings: Mutex<Vec<Diagnostic>>,
447}
448
449impl<'a, S: ContextProvider> SqlToRel<'a, S> {
450    /// Create a new query planner.
451    ///
452    /// The query planner derives the parser options from the context provider.
453    pub fn new(context_provider: &'a S) -> Self {
454        let parser_options = ParserOptions::from(&context_provider.options().sql_parser);
455        Self::new_with_options(context_provider, parser_options)
456    }
457
458    /// Create a new query planner with the given parser options.
459    ///
460    /// The query planner ignores the parser options from the context provider
461    /// and uses the given parser options instead.
462    pub fn new_with_options(context_provider: &'a S, options: ParserOptions) -> Self {
463        let ident_normalize = options.enable_ident_normalization;
464
465        SqlToRel {
466            context_provider,
467            options,
468            ident_normalizer: IdentNormalizer::new(ident_normalize),
469            warnings: Mutex::new(vec![]),
470        }
471    }
472
473    pub(crate) fn add_warning(&self, warning: Diagnostic) {
474        self.warnings
475            .lock()
476            .expect("warning diagnostic lock poisoned")
477            .push(warning);
478    }
479
480    /// Drain and return non-fatal warnings collected during SQL planning.
481    pub fn take_warnings(&self) -> Vec<Diagnostic> {
482        std::mem::take(
483            &mut self
484                .warnings
485                .lock()
486                .expect("warning diagnostic lock poisoned"),
487        )
488    }
489
490    pub fn build_schema(&self, columns: Vec<SQLColumnDef>) -> Result<Schema> {
491        let mut fields = Vec::with_capacity(columns.len());
492
493        for column in columns {
494            let data_type = self.convert_data_type_to_field(&column.data_type)?;
495            let not_nullable = column
496                .options
497                .iter()
498                .any(|x| x.option == ColumnOption::NotNull);
499            fields.push(
500                data_type
501                    .as_ref()
502                    .clone()
503                    .with_name(self.ident_normalizer.normalize(column.name))
504                    .with_nullable(!not_nullable),
505            );
506        }
507
508        Ok(Schema::new(fields))
509    }
510
511    /// Returns a vector of (column_name, default_expr) pairs
512    pub(super) fn build_column_defaults(
513        &self,
514        columns: &Vec<SQLColumnDef>,
515        planner_context: &mut PlannerContext,
516    ) -> Result<Vec<(String, Expr)>> {
517        let mut column_defaults = vec![];
518        // Default expressions are restricted, column references are not allowed
519        let empty_schema = DFSchema::empty();
520        let error_desc = |e: DataFusionError| match e {
521            DataFusionError::SchemaError(ref err, _)
522                if matches!(**err, SchemaError::FieldNotFound { .. }) =>
523            {
524                plan_datafusion_err!(
525                    "Column reference is not allowed in the DEFAULT expression : {}",
526                    e
527                )
528            }
529            _ => e,
530        };
531
532        for column in columns {
533            if let Some(default_sql_expr) =
534                column.options.iter().find_map(|o| match &o.option {
535                    ColumnOption::Default(expr) => Some(expr),
536                    _ => None,
537                })
538            {
539                let default_expr = self
540                    .sql_to_expr(default_sql_expr.clone(), &empty_schema, planner_context)
541                    .map_err(error_desc)?;
542                column_defaults.push((
543                    self.ident_normalizer.normalize(column.name.clone()),
544                    default_expr,
545                ));
546            }
547        }
548        Ok(column_defaults)
549    }
550
551    /// Apply the given TableAlias to the input plan
552    pub(crate) fn apply_table_alias(
553        &self,
554        plan: LogicalPlan,
555        alias: TableAlias,
556    ) -> Result<LogicalPlan> {
557        let idents = alias.columns.into_iter().map(|c| c.name).collect();
558        let plan = self.apply_expr_alias(plan, idents)?;
559
560        LogicalPlanBuilder::from(plan)
561            .alias(TableReference::bare(
562                self.ident_normalizer.normalize(alias.name),
563            ))?
564            .build()
565    }
566
567    pub(crate) fn apply_expr_alias(
568        &self,
569        plan: LogicalPlan,
570        idents: Vec<Ident>,
571    ) -> Result<LogicalPlan> {
572        if idents.is_empty() {
573            Ok(plan)
574        } else if idents.len() != plan.schema().fields().len() {
575            plan_err!(
576                "Source table contains {} columns but only {} \
577                names given as column alias",
578                plan.schema().fields().len(),
579                idents.len()
580            )
581        } else {
582            let columns = plan.schema().columns();
583            LogicalPlanBuilder::from(plan)
584                .project(columns.into_iter().zip(idents).map(|(col, ident)| {
585                    Expr::Column(col).alias(self.ident_normalizer.normalize(ident))
586                }))?
587                .build()
588        }
589    }
590
591    /// Validate the schema provides all of the columns referenced in the expressions.
592    pub(crate) fn validate_schema_satisfies_exprs(
593        &self,
594        schema: &DFSchema,
595        exprs: &[Expr],
596    ) -> Result<()> {
597        find_column_exprs(exprs)
598            .iter()
599            .try_for_each(|col| match col {
600                Expr::Column(col) => match &col.relation {
601                    Some(r) => schema.field_with_qualified_name(r, &col.name).map(|_| ()),
602                    None => {
603                        if !schema.fields_with_unqualified_name(&col.name).is_empty() {
604                            Ok(())
605                        } else {
606                            Err(field_not_found(
607                                col.relation.clone(),
608                                col.name.as_str(),
609                                schema,
610                            ))
611                        }
612                    }
613                }
614                .map_err(|err: DataFusionError| match &err {
615                    DataFusionError::SchemaError(inner, _)
616                        if matches!(
617                            inner.as_ref(),
618                            SchemaError::FieldNotFound { .. }
619                        ) =>
620                    {
621                        let SchemaError::FieldNotFound {
622                            field,
623                            valid_fields,
624                        } = inner.as_ref()
625                        else {
626                            unreachable!()
627                        };
628                        let mut diagnostic = if let Some(relation) = &col.relation {
629                            Diagnostic::new_error(
630                                format!(
631                                    "column '{}' not found in '{}'",
632                                    col.name, relation
633                                ),
634                                col.spans().first(),
635                            )
636                        } else {
637                            Diagnostic::new_error(
638                                format!("column '{}' not found", col.name),
639                                col.spans().first(),
640                            )
641                        };
642                        add_possible_columns_to_diag(
643                            &mut diagnostic,
644                            field,
645                            valid_fields,
646                        );
647                        err.with_diagnostic(diagnostic)
648                    }
649                    _ => err,
650                }),
651                _ => internal_err!("Not a column"),
652            })
653    }
654
655    pub(crate) fn convert_data_type_to_field(
656        &self,
657        sql_type: &SQLDataType,
658    ) -> Result<FieldRef> {
659        // First check if any of the registered type_planner can handle this type
660        if let Some(type_planner) = self.context_provider.get_type_planner()
661            && let Some(data_type) = type_planner.plan_type_field(sql_type)?
662        {
663            return Ok(data_type);
664        }
665
666        // If no type_planner can handle this type, use the default conversion
667        match sql_type {
668            // Canonical Arrow extension types
669            SQLDataType::Uuid => Ok(Arc::new(
670                Field::new("", DataType::FixedSizeBinary(16), true)
671                    .with_extension_type(Uuid),
672            )),
673            SQLDataType::JSON => Ok(Arc::new(
674                Field::new("", DataType::Utf8, true).with_extension_type(Json::default()),
675            )),
676            SQLDataType::Array(ArrayElemTypeDef::AngleBracket(inner_sql_type)) => {
677                // Arrays may be multi-dimensional.
678                Ok(self.convert_data_type_to_field(inner_sql_type)?.into_list())
679            }
680            SQLDataType::Array(ArrayElemTypeDef::SquareBracket(
681                inner_sql_type,
682                maybe_array_size,
683            )) => {
684                let inner_field = self.convert_data_type_to_field(inner_sql_type)?;
685                if let Some(array_size) = maybe_array_size {
686                    let array_size: i32 = (*array_size).try_into().map_err(|_| {
687                        plan_datafusion_err!(
688                            "Array size must be a positive 32 bit integer, got {array_size}"
689                        )
690                    })?;
691                    Ok(inner_field.into_fixed_size_list(array_size))
692                } else {
693                    Ok(inner_field.into_list())
694                }
695            }
696            SQLDataType::Array(ArrayElemTypeDef::None) => {
697                not_impl_err!("Arrays with unspecified type is not supported")
698            }
699            other => Ok(self
700                .convert_simple_data_type(other)?
701                .into_nullable_field_ref()),
702        }
703    }
704
705    fn convert_simple_data_type(&self, sql_type: &SQLDataType) -> Result<DataType> {
706        match sql_type {
707            SQLDataType::Boolean | SQLDataType::Bool => Ok(DataType::Boolean),
708            SQLDataType::TinyInt(_) => Ok(DataType::Int8),
709            SQLDataType::SmallInt(_) | SQLDataType::Int2(_) => Ok(DataType::Int16),
710            SQLDataType::Int(_) | SQLDataType::Integer(_) | SQLDataType::Int4(_) => {
711                Ok(DataType::Int32)
712            }
713            SQLDataType::BigInt(_) | SQLDataType::Int8(_) => Ok(DataType::Int64),
714            SQLDataType::TinyIntUnsigned(_) | SQLDataType::UTinyInt => Ok(DataType::UInt8),
715            SQLDataType::SmallIntUnsigned(_)
716            | SQLDataType::Int2Unsigned(_)
717            | SQLDataType::USmallInt => {
718                Ok(DataType::UInt16)
719            }
720            SQLDataType::IntUnsigned(_)
721            | SQLDataType::IntegerUnsigned(_)
722            | SQLDataType::Int4Unsigned(_) => Ok(DataType::UInt32),
723            SQLDataType::Varchar(length)
724            | SQLDataType::Nvarchar(length)
725            | SQLDataType::CharacterVarying(length)
726            | SQLDataType::CharVarying(length) => {
727                match (length, self.options.support_varchar_with_length) {
728                    (Some(_), false) => plan_err!(
729                        "does not support Varchar with length, \
730                    please set `support_varchar_with_length` to be true"
731                    ),
732                    _ => {
733                        if self.options.map_string_types_to_utf8view {
734                            Ok(DataType::Utf8View)
735                        } else {
736                            Ok(DataType::Utf8)
737                        }
738                    }
739                }
740            }
741            SQLDataType::BigIntUnsigned(_)
742            | SQLDataType::Int8Unsigned(_)
743            | SQLDataType::UBigInt => {
744                Ok(DataType::UInt64)
745            }
746            SQLDataType::Float(_)
747            | SQLDataType::Real
748            | SQLDataType::Float4 => Ok(DataType::Float32),
749            SQLDataType::Double(ExactNumberInfo::None)
750            | SQLDataType::DoublePrecision
751            | SQLDataType::Float8 => Ok(DataType::Float64),
752            SQLDataType::Double(
753                ExactNumberInfo::Precision(_) | ExactNumberInfo::PrecisionAndScale(_, _),
754            ) => {
755                not_impl_err!(
756                    "Unsupported SQL type (precision/scale not supported) {sql_type}"
757                )
758            }
759            SQLDataType::Char(_) | SQLDataType::Text | SQLDataType::String(_) => {
760                if self.options.map_string_types_to_utf8view {
761                    Ok(DataType::Utf8View)
762                } else {
763                    Ok(DataType::Utf8)
764                }
765            }
766            SQLDataType::Timestamp(precision, tz_info)
767                if precision.is_none() || [0, 3, 6, 9].contains(&precision.unwrap()) =>
768            {
769                let tz = if *tz_info == TimezoneInfo::Tz
770                    || *tz_info == TimezoneInfo::WithTimeZone
771                {
772                    // Timestamp With Time Zone
773                    // INPUT : [SQLDataType]   TimestampTz + [Config] Time Zone
774                    // OUTPUT: [ArrowDataType] Timestamp<TimeUnit, Time Zone>
775                    //
776                    // Note that the configured time zone is an `Option` that is
777                    // unset by default, so by default this yields the
778                    // timezone-naive `Timestamp<TimeUnit, None>`. Whether that
779                    // should remain the behavior is tracked in
780                    // https://github.com/apache/datafusion/issues/25166
781                    self.context_provider
782                        .options()
783                        .execution
784                        .time_zone
785                        .as_ref()
786                        .map(|tz| tz.as_str().to_string())
787                } else {
788                    // Timestamp Without Time zone
789                    None
790                };
791                let precision = match precision {
792                    Some(0) => TimeUnit::Second,
793                    Some(3) => TimeUnit::Millisecond,
794                    Some(6) => TimeUnit::Microsecond,
795                    None | Some(9) => TimeUnit::Nanosecond,
796                    _ => unreachable!(),
797                };
798                Ok(DataType::Timestamp(precision, tz.map(Into::into)))
799            }
800            SQLDataType::Date => Ok(DataType::Date32),
801            SQLDataType::Time(None, tz_info) => {
802                if *tz_info == TimezoneInfo::None
803                    || *tz_info == TimezoneInfo::WithoutTimeZone
804                {
805                    Ok(DataType::Time64(TimeUnit::Nanosecond))
806                } else {
807                    // We don't support TIMETZ and TIME WITH TIME ZONE for now
808                    not_impl_err!("Unsupported SQL type {sql_type}")
809                }
810            }
811            SQLDataType::Numeric(exact_number_info)
812            | SQLDataType::Decimal(exact_number_info) => {
813                let (precision, scale) = match *exact_number_info {
814                    ExactNumberInfo::None => (None, None),
815                    ExactNumberInfo::Precision(precision) => (Some(precision), None),
816                    ExactNumberInfo::PrecisionAndScale(precision, scale) => {
817                        (Some(precision), Some(scale))
818                    }
819                };
820                make_decimal_type(precision, scale.map(|s| s as u64))
821            }
822            SQLDataType::Bytea
823            | SQLDataType::Blob(None)
824            | SQLDataType::Binary(None)
825            | SQLDataType::Varbinary(None)
826            | SQLDataType::Bytes(None) => Ok(DataType::Binary),
827            SQLDataType::Interval { fields, precision } => {
828                if fields.is_some() || precision.is_some() {
829                    return not_impl_err!("Unsupported SQL type {sql_type}");
830                }
831                Ok(DataType::Interval(IntervalUnit::MonthDayNano))
832            }
833            SQLDataType::Struct(fields, _) => {
834                let fields = fields
835                    .iter()
836                    .enumerate()
837                    .map(|(idx, sql_struct_field)| {
838                        let field = self.convert_data_type_to_field(&sql_struct_field.field_type)?;
839                        let field_name = match &sql_struct_field.field_name {
840                            Some(ident) => ident.clone(),
841                            None => Ident::new(format!("c{idx}")),
842                        };
843                        Ok(field.as_ref().clone().with_name(self.ident_normalizer.normalize(field_name)))
844                    })
845                    .collect::<Result<Vec<_>>>()?;
846                Ok(DataType::Struct(Fields::from(fields)))
847            }
848            SQLDataType::Map(key_type, value_type, _) => {
849                let key_field = Arc::new(Field::new(
850                    "key", self.convert_data_type_to_field(key_type)?.data_type().clone(), false
851                ));
852                let value_field = Arc::new(Field::new(
853                    "value", self.convert_data_type_to_field(value_type)?.data_type().clone(), true)
854                );
855                let entries = DataType::Struct(Fields::from([key_field, value_field]));
856                Ok(DataType::Map(Arc::new(Field::new("entries", entries, false)), false))
857            }
858            | SQLDataType::JSON
859            | SQLDataType::Uuid
860            | SQLDataType::Binary(_)
861            | SQLDataType::Varbinary(_)
862            | SQLDataType::Blob(_)
863            | SQLDataType::Datetime(_)
864            | SQLDataType::Regclass
865            | SQLDataType::Custom(_, _)
866            | SQLDataType::Array(_)
867            | SQLDataType::Enum(_, _)
868            | SQLDataType::Set(_)
869            | SQLDataType::MediumInt(_)
870            | SQLDataType::MediumIntUnsigned(_)
871            | SQLDataType::Character(_)
872            | SQLDataType::CharacterLargeObject(_)
873            | SQLDataType::CharLargeObject(_)
874            | SQLDataType::Timestamp(_, _)
875            | SQLDataType::Time(Some(_), _)
876            | SQLDataType::Dec(_)
877            | SQLDataType::BigNumeric(_)
878            | SQLDataType::BigDecimal(_)
879            | SQLDataType::Clob(_)
880            | SQLDataType::Bytes(_)
881            | SQLDataType::Int64
882            | SQLDataType::Float64
883            | SQLDataType::JSONB
884            | SQLDataType::Unspecified
885            | SQLDataType::Int16
886            | SQLDataType::Int32
887            | SQLDataType::Int128
888            | SQLDataType::Int256
889            | SQLDataType::UInt8
890            | SQLDataType::UInt16
891            | SQLDataType::UInt32
892            | SQLDataType::UInt64
893            | SQLDataType::UInt128
894            | SQLDataType::UInt256
895            | SQLDataType::Float32
896            | SQLDataType::Date32
897            | SQLDataType::Datetime64(_, _)
898            | SQLDataType::FixedString(_)
899            | SQLDataType::Tuple(_)
900            | SQLDataType::Nested(_)
901            | SQLDataType::Union(_)
902            | SQLDataType::Nullable(_)
903            | SQLDataType::LowCardinality(_)
904            | SQLDataType::Trigger
905            | SQLDataType::TinyBlob
906            | SQLDataType::MediumBlob
907            | SQLDataType::LongBlob
908            | SQLDataType::TinyText
909            | SQLDataType::MediumText
910            | SQLDataType::LongText
911            | SQLDataType::Bit(_)
912            | SQLDataType::BitVarying(_)
913            | SQLDataType::Signed
914            | SQLDataType::SignedInteger
915            | SQLDataType::Unsigned
916            | SQLDataType::UnsignedInteger
917            | SQLDataType::AnyType
918            | SQLDataType::Table(_)
919            | SQLDataType::VarBit(_)
920            | SQLDataType::HugeInt
921            | SQLDataType::UHugeInt
922            | SQLDataType::TimestampNtz{..}
923            | SQLDataType::NamedTable { .. }
924            | SQLDataType::TsVector
925            | SQLDataType::TsQuery
926            | SQLDataType::GeometricType(_)
927            | SQLDataType::DecimalUnsigned(_) // deprecated mysql type
928            | SQLDataType::FloatUnsigned(_) // deprecated mysql type
929            | SQLDataType::RealUnsigned // deprecated mysql type
930            | SQLDataType::DecUnsigned(_) // deprecated mysql type
931            | SQLDataType::DoubleUnsigned(_) // deprecated mysql type
932            | SQLDataType::DoublePrecisionUnsigned // deprecated mysql type
933            => {
934                not_impl_err!("Unsupported SQL type {sql_type}")
935            }
936        }
937    }
938
939    pub(crate) fn object_name_to_table_reference(
940        &self,
941        object_name: ObjectName,
942    ) -> Result<TableReference> {
943        object_name_to_table_reference(
944            object_name,
945            self.options.enable_ident_normalization,
946        )
947    }
948}
949
950/// Create a [`TableReference`] after normalizing the specified ObjectName
951///
952/// Examples
953/// ```text
954/// ['foo']          -> Bare { table: "foo" }
955/// ['"foo.bar"]]    -> Bare { table: "foo.bar" }
956/// ['foo', 'Bar']   -> Partial { schema: "foo", table: "bar" } <-- note lower case "bar"
957/// ['foo', 'bar']   -> Partial { schema: "foo", table: "bar" }
958/// ['foo', '"Bar"'] -> Partial { schema: "foo", table: "Bar" }
959/// ```
960pub fn object_name_to_table_reference(
961    object_name: ObjectName,
962    enable_normalization: bool,
963) -> Result<TableReference> {
964    // Use destructure to make it clear no fields on ObjectName are ignored
965    let ObjectName(object_name_parts) = object_name;
966    let idents = object_name_parts
967        .into_iter()
968        .map(|object_name_part| {
969            object_name_part.as_ident().cloned().ok_or_else(|| {
970                plan_datafusion_err!(
971                    "Expected identifier, but found: {:?}",
972                    object_name_part
973                )
974            })
975        })
976        .collect::<Result<Vec<_>>>()?;
977    idents_to_table_reference(idents, enable_normalization)
978}
979
980struct IdentTaker {
981    normalizer: IdentNormalizer,
982    idents: Vec<Ident>,
983}
984
985/// Take the next identifier from the back of idents, panic'ing if
986/// there are none left
987impl IdentTaker {
988    fn new(idents: Vec<Ident>, enable_normalization: bool) -> Self {
989        Self {
990            normalizer: IdentNormalizer::new(enable_normalization),
991            idents,
992        }
993    }
994
995    fn take(&mut self) -> String {
996        let ident = self.idents.pop().expect("no more identifiers");
997        self.normalizer.normalize(ident)
998    }
999
1000    /// Returns the number of remaining identifiers
1001    fn len(&self) -> usize {
1002        self.idents.len()
1003    }
1004}
1005
1006// impl Display for a nicer error message
1007impl std::fmt::Display for IdentTaker {
1008    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1009        let mut first = true;
1010        for ident in self.idents.iter() {
1011            if !first {
1012                write!(f, ".")?;
1013            }
1014            write!(f, "{ident}")?;
1015            first = false;
1016        }
1017
1018        Ok(())
1019    }
1020}
1021
1022/// Create a [`TableReference`] after normalizing the specified identifier
1023pub(crate) fn idents_to_table_reference(
1024    idents: Vec<Ident>,
1025    enable_normalization: bool,
1026) -> Result<TableReference> {
1027    let mut taker = IdentTaker::new(idents, enable_normalization);
1028
1029    match taker.len() {
1030        1 => {
1031            let table = taker.take();
1032            Ok(TableReference::bare(table))
1033        }
1034        2 => {
1035            let table = taker.take();
1036            let schema = taker.take();
1037            Ok(TableReference::partial(schema, table))
1038        }
1039        3 => {
1040            let table = taker.take();
1041            let schema = taker.take();
1042            let catalog = taker.take();
1043            Ok(TableReference::full(catalog, schema, table))
1044        }
1045        _ => plan_err!(
1046            "Unsupported compound identifier '{}'. Expected 1, 2 or 3 parts, got {}",
1047            taker,
1048            taker.len()
1049        ),
1050    }
1051}
1052
1053/// Construct a WHERE qualifier suitable for e.g. information_schema filtering
1054/// from the provided object identifiers (catalog, schema and table names).
1055pub fn object_name_to_qualifier(
1056    sql_table_name: &ObjectName,
1057    enable_normalization: bool,
1058) -> Result<String> {
1059    let columns = vec!["table_name", "table_schema", "table_catalog"].into_iter();
1060    let normalizer = IdentNormalizer::new(enable_normalization);
1061    sql_table_name
1062        .0
1063        .iter()
1064        .rev()
1065        .zip(columns)
1066        .map(|(object_name_part, column_name)| {
1067            object_name_part
1068                .as_ident()
1069                .map(|ident| {
1070                    format!(
1071                        r#"{} = '{}'"#,
1072                        column_name,
1073                        normalizer.normalize(ident.clone())
1074                    )
1075                })
1076                .ok_or_else(|| {
1077                    plan_datafusion_err!(
1078                        "Expected identifier, but found: {:?}",
1079                        object_name_part
1080                    )
1081                })
1082        })
1083        .collect::<Result<Vec<_>>>()
1084        .map(|parts| parts.join(" AND "))
1085}