Skip to main content

datafusion_common/
dfschema.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//! DFSchema is an extended schema struct that DataFusion uses to provide support for
6//! fields with optional relation names.
7
8use std::collections::{BTreeSet, HashSet};
9use std::fmt::Write as _;
10use std::fmt::{Display, Formatter};
11use std::hash::Hash;
12use std::sync::{Arc, LazyLock};
13
14use crate::error::{_plan_err, _schema_err, DataFusionError, Result};
15use crate::{
16    Column, FunctionalDependencies, SchemaError, TableReference, field_not_found,
17    unqualified_field_not_found,
18};
19
20use arrow::compute::can_cast_types;
21use arrow::datatypes::{
22    DataType, Field, FieldRef, Fields, Metadata, Schema, SchemaBuilder, SchemaRef,
23};
24
25/// A reference-counted reference to a [DFSchema].
26pub type DFSchemaRef = Arc<DFSchema>;
27
28/// DFSchema wraps an Arrow schema and add a relation (table) name.
29///
30/// The schema may hold the fields across multiple tables. Some fields may be
31/// qualified and some unqualified. A qualified field is a field that has a
32/// relation name associated with it.
33///
34/// Unqualified fields must be unique not only amongst themselves, but also must
35/// have a distinct name from any qualified field names. This allows finding a
36/// qualified field by name to be possible, so long as there aren't multiple
37/// qualified fields with the same name.
38///]
39/// # See Also
40/// * [DFSchemaRef], an alias to `Arc<DFSchema>`
41/// * [DataTypeExt], common methods for working with Arrow [DataType]s
42/// * [FieldExt], extension methods for working with Arrow [Field]s
43///
44/// [DataTypeExt]: crate::datatype::DataTypeExt
45/// [FieldExt]: crate::datatype::FieldExt
46///
47/// # Creating qualified schemas
48///
49/// Use [DFSchema::try_from_qualified_schema] to create a qualified schema from
50/// an Arrow schema.
51///
52/// ```rust
53/// use arrow::datatypes::{DataType, Field, Schema};
54/// use datafusion_common::{Column, DFSchema};
55///
56/// let arrow_schema = Schema::new(vec![Field::new("c1", DataType::Int32, false)]);
57///
58/// let df_schema = DFSchema::try_from_qualified_schema("t1", &arrow_schema).unwrap();
59/// let column = Column::from_qualified_name("t1.c1");
60/// assert!(df_schema.has_column(&column));
61///
62/// // Can also access qualified fields with unqualified name, if it's unambiguous
63/// let column = Column::from_qualified_name("c1");
64/// assert!(df_schema.has_column(&column));
65/// ```
66///
67/// # Creating unqualified schemas
68///
69/// Create an unqualified schema using TryFrom:
70///
71/// ```rust
72/// use arrow::datatypes::{DataType, Field, Schema};
73/// use datafusion_common::{Column, DFSchema};
74///
75/// let arrow_schema = Schema::new(vec![Field::new("c1", DataType::Int32, false)]);
76///
77/// let df_schema = DFSchema::try_from(arrow_schema).unwrap();
78/// let column = Column::new_unqualified("c1");
79/// assert!(df_schema.has_column(&column));
80/// ```
81///
82/// # Converting back to Arrow schema
83///
84/// Use the `Into` trait to convert `DFSchema` into an Arrow schema:
85///
86/// ```rust
87/// use arrow::datatypes::{Field, Schema};
88/// use datafusion_common::DFSchema;
89/// use std::collections::HashMap;
90///
91/// let df_schema = DFSchema::from_unqualified_fields(
92///     vec![Field::new("c1", arrow::datatypes::DataType::Int32, false)].into(),
93///     HashMap::new(),
94/// )
95/// .unwrap();
96/// let schema: &Schema = df_schema.as_arrow();
97/// assert_eq!(schema.fields().len(), 1);
98/// ```
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct DFSchema {
101    /// Inner Arrow schema reference.
102    inner: SchemaRef,
103    /// Optional qualifiers for each column in this schema. In the same order as
104    /// the `self.inner.fields()`
105    field_qualifiers: Vec<Option<TableReference>>,
106    /// Stores functional dependencies in the schema.
107    functional_dependencies: FunctionalDependencies,
108}
109
110impl DFSchema {
111    /// Creates an empty `DFSchema`
112    pub fn empty() -> Self {
113        Self {
114            inner: Arc::new(Schema::new([])),
115            field_qualifiers: vec![],
116            functional_dependencies: FunctionalDependencies::empty(),
117        }
118    }
119
120    /// Returns a reference to a shared empty [`DFSchema`].
121    pub fn empty_ref() -> &'static DFSchemaRef {
122        static EMPTY: LazyLock<DFSchemaRef> =
123            LazyLock::new(|| Arc::new(DFSchema::empty()));
124        &EMPTY
125    }
126
127    /// Return a reference to the inner Arrow [`Schema`]
128    ///
129    /// Note this does not have the qualifier information
130    pub fn as_arrow(&self) -> &Schema {
131        self.inner.as_ref()
132    }
133
134    /// Return a reference to the inner Arrow [`SchemaRef`]
135    ///
136    /// Note this does not have the qualifier information
137    pub fn inner(&self) -> &SchemaRef {
138        &self.inner
139    }
140
141    /// Create a `DFSchema` from an Arrow schema where all the fields have a given qualifier
142    pub fn new_with_metadata(
143        qualified_fields: Vec<(Option<TableReference>, Arc<Field>)>,
144        metadata: impl Into<Metadata>,
145    ) -> Result<Self> {
146        let (qualifiers, fields): (Vec<Option<TableReference>>, Vec<Arc<Field>>) =
147            qualified_fields.into_iter().unzip();
148
149        let schema = Arc::new(Schema::new_with_metadata(fields, metadata));
150
151        let dfschema = Self {
152            inner: schema,
153            field_qualifiers: qualifiers,
154            functional_dependencies: FunctionalDependencies::empty(),
155        };
156        dfschema.check_names()?;
157        Ok(dfschema)
158    }
159
160    /// Create a new `DFSchema` from a list of Arrow [Field]s
161    pub fn from_unqualified_fields(
162        fields: Fields,
163        metadata: impl Into<Metadata>,
164    ) -> Result<Self> {
165        let field_count = fields.len();
166        let schema = Arc::new(Schema::new_with_metadata(fields, metadata));
167        let dfschema = Self {
168            inner: schema,
169            field_qualifiers: vec![None; field_count],
170            functional_dependencies: FunctionalDependencies::empty(),
171        };
172        dfschema.check_names()?;
173        Ok(dfschema)
174    }
175
176    /// Create a `DFSchema` from an Arrow schema and a given qualifier
177    ///
178    /// To create a schema from an Arrow schema without a qualifier, use
179    /// `DFSchema::try_from`.
180    pub fn try_from_qualified_schema(
181        qualifier: impl Into<TableReference>,
182        schema: &Schema,
183    ) -> Result<Self> {
184        let qualifier = qualifier.into();
185        let schema = DFSchema {
186            inner: schema.clone().into(),
187            field_qualifiers: vec![Some(qualifier); schema.fields.len()],
188            functional_dependencies: FunctionalDependencies::empty(),
189        };
190        schema.check_names()?;
191        Ok(schema)
192    }
193
194    /// Create a `DFSchema` from an Arrow schema where all the fields have a given qualifier
195    pub fn from_field_specific_qualified_schema(
196        qualifiers: Vec<Option<TableReference>>,
197        schema: &SchemaRef,
198    ) -> Result<Self> {
199        let dfschema = Self {
200            inner: Arc::clone(schema),
201            field_qualifiers: qualifiers,
202            functional_dependencies: FunctionalDependencies::empty(),
203        };
204        dfschema.check_names()?;
205        Ok(dfschema)
206    }
207
208    /// Return the same schema, where all fields have a given qualifier.
209    pub fn with_field_specific_qualified_schema(
210        &self,
211        qualifiers: Vec<Option<TableReference>>,
212    ) -> Result<Self> {
213        if qualifiers.len() != self.fields().len() {
214            return _plan_err!(
215                "Number of qualifiers must match number of fields. Expected {}, got {}",
216                self.fields().len(),
217                qualifiers.len()
218            );
219        }
220        Ok(DFSchema {
221            inner: Arc::clone(&self.inner),
222            field_qualifiers: qualifiers,
223            functional_dependencies: self.functional_dependencies.clone(),
224        })
225    }
226
227    /// Check if the schema have some fields with the same name
228    pub fn check_names(&self) -> Result<()> {
229        let mut qualified_names = BTreeSet::new();
230        let mut unqualified_names = BTreeSet::new();
231
232        for (field, qualifier) in self.inner.fields().iter().zip(&self.field_qualifiers) {
233            if let Some(qualifier) = qualifier {
234                if !qualified_names.insert((qualifier, field.name())) {
235                    return _schema_err!(SchemaError::DuplicateQualifiedField {
236                        qualifier: Box::new(qualifier.clone()),
237                        name: field.name().to_string(),
238                    });
239                }
240            } else if !unqualified_names.insert(field.name()) {
241                return _schema_err!(SchemaError::DuplicateUnqualifiedField {
242                    name: field.name().to_string()
243                });
244            }
245        }
246
247        for (qualifier, name) in qualified_names {
248            if unqualified_names.contains(name) {
249                return _schema_err!(SchemaError::AmbiguousReference {
250                    field: Box::new(Column::new(Some(qualifier.clone()), name))
251                });
252            }
253        }
254        Ok(())
255    }
256
257    /// Assigns functional dependencies.
258    pub fn with_functional_dependencies(
259        mut self,
260        functional_dependencies: FunctionalDependencies,
261    ) -> Result<Self> {
262        if functional_dependencies.is_valid(self.inner.fields.len()) {
263            self.functional_dependencies = functional_dependencies;
264            Ok(self)
265        } else {
266            _plan_err!(
267                "Invalid functional dependency: {:?}",
268                functional_dependencies
269            )
270        }
271    }
272
273    /// Create a new schema that contains the fields from this schema followed by the fields
274    /// from the supplied schema. An error will be returned if there are duplicate field names.
275    pub fn join(&self, schema: &DFSchema) -> Result<Self> {
276        let mut schema_builder = SchemaBuilder::with_capacity(
277            self.inner.fields().len() + schema.fields().len(),
278        );
279        schema_builder.extend(self.inner.fields().iter().cloned());
280        schema_builder.extend(schema.fields().iter().cloned());
281        let new_schema = schema_builder.finish();
282
283        let mut new_metadata = self.inner.metadata.clone();
284        new_metadata.extend(schema.inner.metadata.clone());
285        let new_schema_with_metadata = new_schema.with_metadata(new_metadata);
286
287        let mut new_qualifiers = self.field_qualifiers.clone();
288        new_qualifiers.extend_from_slice(schema.field_qualifiers.as_slice());
289
290        let new_self = Self {
291            inner: Arc::new(new_schema_with_metadata),
292            field_qualifiers: new_qualifiers,
293            functional_dependencies: FunctionalDependencies::empty(),
294        };
295        new_self.check_names()?;
296        Ok(new_self)
297    }
298
299    /// Modify this schema by appending the fields from the supplied schema, ignoring any
300    /// duplicate fields.
301    ///
302    /// ## Merge Precedence
303    ///
304    /// **Schema-level metadata**: Metadata from both schemas is merged.
305    /// If both schemas have the same metadata key, the value from the `other_schema` parameter takes precedence.
306    ///
307    /// **Field-level merging**: Only non-duplicate fields are added. This means that the
308    /// `self` fields will always take precedence over the `other_schema` fields.
309    /// Duplicate field detection is based on:
310    /// - For qualified fields: both qualifier and field name must match
311    /// - For unqualified fields: only field name needs to match
312    ///
313    /// Take note how the precedence for fields & metadata merging differs;
314    /// merging prefers fields from `self` but prefers metadata from `other_schema`.
315    pub fn merge(&mut self, other_schema: &DFSchema) {
316        if other_schema.inner.fields.is_empty() {
317            return;
318        }
319
320        let self_fields: HashSet<(Option<&TableReference>, &FieldRef)> =
321            self.iter().collect();
322        let self_unqualified_names: HashSet<&str> = self
323            .inner
324            .fields
325            .iter()
326            .map(|field| field.name().as_str())
327            .collect();
328
329        let mut schema_builder = SchemaBuilder::from(self.inner.fields.clone());
330        let mut qualifiers = Vec::with_capacity(other_schema.inner.fields.len());
331        for (qualifier, field) in other_schema.iter() {
332            // skip duplicate columns
333            let duplicated_field = match qualifier {
334                Some(q) => self_fields.contains(&(Some(q), field)),
335                // for unqualified columns, check as unqualified name
336                None => self_unqualified_names.contains(field.name().as_str()),
337            };
338            if !duplicated_field {
339                schema_builder.push(Arc::clone(field));
340                qualifiers.push(qualifier.cloned());
341            }
342        }
343        let mut metadata = self.inner.metadata.clone();
344        metadata.extend(other_schema.inner.metadata.clone());
345
346        let finished = schema_builder.finish();
347        let finished_with_metadata = finished.with_metadata(metadata);
348        self.inner = finished_with_metadata.into();
349        self.field_qualifiers.extend(qualifiers);
350    }
351
352    /// Get a list of fields for this schema
353    pub fn fields(&self) -> &Fields {
354        &self.inner.fields
355    }
356
357    /// Returns a reference to [`FieldRef`] for a column at specific index
358    /// within the schema.
359    ///
360    /// See also [Self::qualified_field] to get both qualifier and field
361    pub fn field(&self, i: usize) -> &FieldRef {
362        &self.inner.fields[i]
363    }
364
365    /// Returns the qualifier (if any) and [`FieldRef`] for a column at specific
366    /// index within the schema.
367    pub fn qualified_field(&self, i: usize) -> (Option<&TableReference>, &FieldRef) {
368        (self.field_qualifiers[i].as_ref(), self.field(i))
369    }
370
371    pub fn index_of_column_by_name(
372        &self,
373        qualifier: Option<&TableReference>,
374        name: &str,
375    ) -> Option<usize> {
376        let mut matches = self
377            .iter()
378            .enumerate()
379            .filter(|(_, (q, f))| match (qualifier, q) {
380                // field to lookup is qualified.
381                // current field is qualified and not shared between relations, compare both
382                // qualifier and name.
383                (Some(q), Some(field_q)) => q.resolved_eq(field_q) && f.name() == name,
384                // field to lookup is qualified but current field is unqualified.
385                (Some(_), None) => false,
386                // field to lookup is unqualified, no need to compare qualifier
387                (None, Some(_)) | (None, None) => f.name() == name,
388            })
389            .map(|(idx, _)| idx);
390        matches.next()
391    }
392
393    /// Find the index of the column with the given qualifier and name,
394    /// returning `None` if not found
395    ///
396    /// See [Self::index_of_column] for a version that returns an error if the
397    /// column is not found
398    pub fn maybe_index_of_column(&self, col: &Column) -> Option<usize> {
399        self.index_of_column_by_name(col.relation.as_ref(), &col.name)
400    }
401
402    /// Find the index of the column with the given qualifier and name,
403    /// returning `Err` if not found
404    ///
405    /// See [Self::maybe_index_of_column] for a version that returns `None` if
406    /// the column is not found
407    pub fn index_of_column(&self, col: &Column) -> Result<usize> {
408        self.maybe_index_of_column(col)
409            .ok_or_else(|| field_not_found(col.relation.clone(), &col.name, self))
410    }
411
412    /// Check if the column is in the current schema
413    pub fn is_column_from_schema(&self, col: &Column) -> bool {
414        self.index_of_column_by_name(col.relation.as_ref(), &col.name)
415            .is_some()
416    }
417
418    /// Find the [`FieldRef`] with the given name and optional qualifier
419    pub fn field_with_name(
420        &self,
421        qualifier: Option<&TableReference>,
422        name: &str,
423    ) -> Result<&FieldRef> {
424        if let Some(qualifier) = qualifier {
425            self.field_with_qualified_name(qualifier, name)
426        } else {
427            self.field_with_unqualified_name(name)
428        }
429    }
430
431    /// Find the qualified field with the given name
432    pub fn qualified_field_with_name(
433        &self,
434        qualifier: Option<&TableReference>,
435        name: &str,
436    ) -> Result<(Option<&TableReference>, &FieldRef)> {
437        if let Some(qualifier) = qualifier {
438            let idx = self
439                .index_of_column_by_name(Some(qualifier), name)
440                .ok_or_else(|| field_not_found(Some(qualifier.clone()), name, self))?;
441            Ok((self.field_qualifiers[idx].as_ref(), self.field(idx)))
442        } else {
443            self.qualified_field_with_unqualified_name(name)
444        }
445    }
446
447    /// Find all fields having the given qualifier
448    pub fn fields_with_qualified(&self, qualifier: &TableReference) -> Vec<&FieldRef> {
449        self.iter()
450            .filter(|(q, _)| q.map(|q| q.eq(qualifier)).unwrap_or(false))
451            .map(|(_, f)| f)
452            .collect()
453    }
454
455    /// Find all fields indices having the given qualifier
456    pub fn fields_indices_with_qualified(
457        &self,
458        qualifier: &TableReference,
459    ) -> Vec<usize> {
460        self.iter()
461            .enumerate()
462            .filter_map(|(idx, (q, _))| q.and_then(|q| q.eq(qualifier).then_some(idx)))
463            .collect()
464    }
465
466    /// Find all fields that match the given name
467    pub fn fields_with_unqualified_name(&self, name: &str) -> Vec<&FieldRef> {
468        self.fields()
469            .iter()
470            .filter(|field| field.name() == name)
471            .collect()
472    }
473
474    /// Find all fields that match the given name and return them with their qualifier
475    pub fn qualified_fields_with_unqualified_name(
476        &self,
477        name: &str,
478    ) -> Vec<(Option<&TableReference>, &FieldRef)> {
479        self.iter()
480            .filter(|(_, field)| field.name() == name)
481            .collect()
482    }
483
484    /// Find all fields that match the given name and convert to column
485    pub fn columns_with_unqualified_name(&self, name: &str) -> Vec<Column> {
486        self.iter()
487            .filter(|(_, field)| field.name() == name)
488            .map(|(qualifier, field)| Column::new(qualifier.cloned(), field.name()))
489            .collect()
490    }
491
492    /// Return all `Column`s for the schema
493    pub fn columns(&self) -> Vec<Column> {
494        self.iter()
495            .map(|(qualifier, field)| {
496                Column::new(qualifier.cloned(), field.name().clone())
497            })
498            .collect()
499    }
500
501    /// Find the qualified field with the given unqualified name
502    pub fn qualified_field_with_unqualified_name(
503        &self,
504        name: &str,
505    ) -> Result<(Option<&TableReference>, &FieldRef)> {
506        let matches = self.qualified_fields_with_unqualified_name(name);
507        match matches.len() {
508            0 => Err(unqualified_field_not_found(name, self)),
509            1 => Ok((matches[0].0, matches[0].1)),
510            _ => {
511                // When `matches` size > 1, it doesn't necessarily mean an `ambiguous name` problem.
512                // Because name may generate from Alias/... . It means that it don't own qualifier.
513                // For example:
514                //             Join on id = b.id
515                // Project a.id as id   TableScan b id
516                // In this case, there isn't `ambiguous name` problem. When `matches` just contains
517                // one field without qualifier, we should return it.
518                let fields_without_qualifier = matches
519                    .iter()
520                    .filter(|(q, _)| q.is_none())
521                    .collect::<Vec<_>>();
522                if fields_without_qualifier.len() == 1 {
523                    Ok((fields_without_qualifier[0].0, fields_without_qualifier[0].1))
524                } else {
525                    _schema_err!(SchemaError::AmbiguousReference {
526                        field: Box::new(Column::new_unqualified(name.to_string()))
527                    })
528                }
529            }
530        }
531    }
532
533    /// Find the field with the given name
534    pub fn field_with_unqualified_name(&self, name: &str) -> Result<&FieldRef> {
535        self.qualified_field_with_unqualified_name(name)
536            .map(|(_, field)| field)
537    }
538
539    /// Find the field with the given qualified name
540    pub fn field_with_qualified_name(
541        &self,
542        qualifier: &TableReference,
543        name: &str,
544    ) -> Result<&FieldRef> {
545        let idx = self
546            .index_of_column_by_name(Some(qualifier), name)
547            .ok_or_else(|| field_not_found(Some(qualifier.clone()), name, self))?;
548
549        Ok(self.field(idx))
550    }
551
552    /// Find the field with the given qualified column
553    pub fn qualified_field_from_column(
554        &self,
555        column: &Column,
556    ) -> Result<(Option<&TableReference>, &FieldRef)> {
557        self.qualified_field_with_name(column.relation.as_ref(), &column.name)
558    }
559
560    /// Find if the field exists with the given name
561    pub fn has_column_with_unqualified_name(&self, name: &str) -> bool {
562        self.fields().iter().any(|field| field.name() == name)
563    }
564
565    /// Find if the field exists with the given qualified name
566    pub fn has_column_with_qualified_name(
567        &self,
568        qualifier: &TableReference,
569        name: &str,
570    ) -> bool {
571        self.iter()
572            .any(|(q, f)| q.map(|q| q.eq(qualifier)).unwrap_or(false) && f.name() == name)
573    }
574
575    /// Find if the field exists with the given qualified column
576    pub fn has_column(&self, column: &Column) -> bool {
577        match &column.relation {
578            Some(r) => self.has_column_with_qualified_name(r, &column.name),
579            None => self.has_column_with_unqualified_name(&column.name),
580        }
581    }
582
583    /// Check to see if unqualified field names matches field names in Arrow schema
584    pub fn matches_arrow_schema(&self, arrow_schema: &Schema) -> bool {
585        self.inner
586            .fields
587            .iter()
588            .zip(arrow_schema.fields().iter())
589            .all(|(dffield, arrowfield)| dffield.name() == arrowfield.name())
590    }
591
592    /// Returns true if the two schemas have the same qualified named
593    /// fields with logically equivalent data types. Returns false otherwise.
594    ///
595    /// Use [DFSchema]::equivalent_names_and_types for stricter semantic type
596    /// equivalence checking.
597    pub fn logically_equivalent_names_and_types(&self, other: &Self) -> bool {
598        if self.fields().len() != other.fields().len() {
599            return false;
600        }
601        let self_fields = self.iter();
602        let other_fields = other.iter();
603        self_fields.zip(other_fields).all(|((q1, f1), (q2, f2))| {
604            q1 == q2
605                && f1.name() == f2.name()
606                && Self::datatype_is_logically_equal(f1.data_type(), f2.data_type())
607        })
608    }
609
610    /// Returns Ok if the two schemas have the same qualified named
611    /// fields with the compatible data types.
612    ///
613    /// Returns an `Err` with a message otherwise.
614    ///
615    /// This is a specialized version of Eq that ignores differences in
616    /// nullability and metadata.
617    ///
618    /// Use [DFSchema]::logically_equivalent_names_and_types for a weaker
619    /// logical type checking, which for example would consider a dictionary
620    /// encoded UTF8 array to be equivalent to a plain UTF8 array.
621    pub fn has_equivalent_names_and_types(&self, other: &Self) -> Result<()> {
622        // case 1 : schema length mismatch
623        if self.fields().len() != other.fields().len() {
624            _plan_err!(
625                "Schema mismatch: the schema length are not same \
626            Expected schema length: {}, got: {}",
627                self.fields().len(),
628                other.fields().len()
629            )
630        } else {
631            // case 2 : schema length match, but fields mismatch
632            // check if the fields name are the same and have the same data types
633            self.fields()
634                .iter()
635                .zip(other.fields().iter())
636                .try_for_each(|(f1, f2)| {
637                    if f1.name() != f2.name()
638                        || (!DFSchema::datatype_is_semantically_equal(
639                            f1.data_type(),
640                            f2.data_type(),
641                        ))
642                    {
643                        _plan_err!(
644                            "Schema mismatch: Expected field '{}' with type {}, \
645                            but got '{}' with type {}.",
646                            f1.name(),
647                            f1.data_type(),
648                            f2.name(),
649                            f2.data_type()
650                        )
651                    } else {
652                        Ok(())
653                    }
654                })
655        }
656    }
657
658    /// Checks if two [`DataType`]s are logically equal. This is a notably weaker constraint
659    /// than datatype_is_semantically_equal in that different representations of same data can be
660    /// logically but not semantically equivalent. Semantically equivalent types are always also
661    /// logically equivalent. For example:
662    /// - a Dictionary<K,V> type is logically equal to a plain V type
663    /// - a Dictionary<K1, V1> is also logically equal to Dictionary<K2, V1>
664    /// - a RunEndEncoded<K,V> type is logically equal to a plain V type
665    /// - a RunEndEncoded<K1, V1> is also logically equal to RunEndEncoded<K2, V1>
666    /// - Utf8 and Utf8View are logically equal
667    pub fn datatype_is_logically_equal(dt1: &DataType, dt2: &DataType) -> bool {
668        // check nested fields
669        match (dt1, dt2) {
670            (DataType::Dictionary(_, v1), DataType::Dictionary(_, v2)) => {
671                Self::datatype_is_logically_equal(v1.as_ref(), v2.as_ref())
672            }
673            (DataType::Dictionary(_, v1), othertype)
674            | (othertype, DataType::Dictionary(_, v1)) => {
675                Self::datatype_is_logically_equal(v1.as_ref(), othertype)
676            }
677            (DataType::RunEndEncoded(_, v1), DataType::RunEndEncoded(_, v2)) => {
678                Self::datatype_is_logically_equal(v1.data_type(), v2.data_type())
679            }
680            (DataType::RunEndEncoded(_, v1), othertype)
681            | (othertype, DataType::RunEndEncoded(_, v1)) => {
682                Self::datatype_is_logically_equal(v1.data_type(), othertype)
683            }
684            (DataType::List(f1), DataType::List(f2))
685            | (DataType::LargeList(f1), DataType::LargeList(f2))
686            | (DataType::ListView(f1), DataType::ListView(f2))
687            | (DataType::LargeListView(f1), DataType::LargeListView(f2))
688            | (DataType::FixedSizeList(f1, _), DataType::FixedSizeList(f2, _)) => {
689                // Don't compare the names of the technical inner field
690                // Usually "item" but that's not mandated
691                Self::datatype_is_logically_equal(f1.data_type(), f2.data_type())
692            }
693            (DataType::Map(f1, _), DataType::Map(f2, _)) => {
694                // Don't compare the names of the technical inner fields
695                // Usually "entries", "key", "value" but that's not mandated
696                match (f1.data_type(), f2.data_type()) {
697                    (DataType::Struct(f1_inner), DataType::Struct(f2_inner)) => {
698                        f1_inner.len() == f2_inner.len()
699                            && f1_inner.iter().zip(f2_inner.iter()).all(|(f1, f2)| {
700                                Self::datatype_is_logically_equal(
701                                    f1.data_type(),
702                                    f2.data_type(),
703                                )
704                            })
705                    }
706                    _ => panic!("Map type should have an inner struct field"),
707                }
708            }
709            (DataType::Struct(fields1), DataType::Struct(fields2)) => {
710                let iter1 = fields1.iter();
711                let iter2 = fields2.iter();
712                fields1.len() == fields2.len() &&
713                        // all fields have to be the same
714                    iter1
715                    .zip(iter2)
716                        .all(|(f1, f2)| Self::field_is_logically_equal(f1, f2))
717            }
718            (DataType::Union(fields1, _), DataType::Union(fields2, _)) => {
719                let iter1 = fields1.iter();
720                let iter2 = fields2.iter();
721                fields1.len() == fields2.len() &&
722                    // all fields have to be the same
723                    iter1
724                        .zip(iter2)
725                        .all(|((t1, f1), (t2, f2))| t1 == t2 && Self::field_is_logically_equal(f1, f2))
726            }
727            // Utf8 and Utf8View are logically equivalent
728            (DataType::Utf8, DataType::Utf8View) => true,
729            (DataType::Utf8View, DataType::Utf8) => true,
730            _ => Self::datatype_is_semantically_equal(dt1, dt2),
731        }
732    }
733
734    /// Returns true of two [`DataType`]s are semantically equal (same
735    /// name and type), ignoring both metadata and nullability, decimal precision/scale,
736    /// and timezone time units/timezones.
737    ///
738    /// request to upstream: <https://github.com/apache/arrow-rs/issues/3199>
739    pub fn datatype_is_semantically_equal(dt1: &DataType, dt2: &DataType) -> bool {
740        // check nested fields
741        match (dt1, dt2) {
742            (DataType::Dictionary(k1, v1), DataType::Dictionary(k2, v2)) => {
743                Self::datatype_is_semantically_equal(k1.as_ref(), k2.as_ref())
744                    && Self::datatype_is_semantically_equal(v1.as_ref(), v2.as_ref())
745            }
746            (DataType::RunEndEncoded(k1, v1), DataType::RunEndEncoded(k2, v2)) => {
747                Self::datatype_is_semantically_equal(k1.data_type(), k2.data_type())
748                    && Self::datatype_is_semantically_equal(
749                        v1.data_type(),
750                        v2.data_type(),
751                    )
752            }
753            (DataType::List(f1), DataType::List(f2))
754            | (DataType::LargeList(f1), DataType::LargeList(f2))
755            | (DataType::ListView(f1), DataType::ListView(f2))
756            | (DataType::LargeListView(f1), DataType::LargeListView(f2))
757            | (DataType::FixedSizeList(f1, _), DataType::FixedSizeList(f2, _)) => {
758                // Don't compare the names of the technical inner field
759                // Usually "item" but that's not mandated
760                Self::datatype_is_semantically_equal(f1.data_type(), f2.data_type())
761            }
762            (DataType::Map(f1, _), DataType::Map(f2, _)) => {
763                // Don't compare the names of the technical inner fields
764                // Usually "entries", "key", "value" but that's not mandated
765                match (f1.data_type(), f2.data_type()) {
766                    (DataType::Struct(f1_inner), DataType::Struct(f2_inner)) => {
767                        f1_inner.len() == f2_inner.len()
768                            && f1_inner.iter().zip(f2_inner.iter()).all(|(f1, f2)| {
769                                Self::datatype_is_semantically_equal(
770                                    f1.data_type(),
771                                    f2.data_type(),
772                                )
773                            })
774                    }
775                    _ => panic!("Map type should have an inner struct field"),
776                }
777            }
778            (DataType::Struct(fields1), DataType::Struct(fields2)) => {
779                let iter1 = fields1.iter();
780                let iter2 = fields2.iter();
781                fields1.len() == fields2.len() &&
782                        // all fields have to be the same
783                    iter1
784                    .zip(iter2)
785                        .all(|(f1, f2)| Self::field_is_semantically_equal(f1, f2))
786            }
787            (DataType::Union(fields1, _), DataType::Union(fields2, _)) => {
788                let iter1 = fields1.iter();
789                let iter2 = fields2.iter();
790                fields1.len() == fields2.len() &&
791                    // all fields have to be the same
792                    iter1
793                        .zip(iter2)
794                        .all(|((t1, f1), (t2, f2))| t1 == t2 && Self::field_is_semantically_equal(f1, f2))
795            }
796            (
797                DataType::Decimal32(_l_precision, _l_scale),
798                DataType::Decimal32(_r_precision, _r_scale),
799            ) => true,
800            (
801                DataType::Decimal64(_l_precision, _l_scale),
802                DataType::Decimal64(_r_precision, _r_scale),
803            ) => true,
804            (
805                DataType::Decimal128(_l_precision, _l_scale),
806                DataType::Decimal128(_r_precision, _r_scale),
807            ) => true,
808            (
809                DataType::Decimal256(_l_precision, _l_scale),
810                DataType::Decimal256(_r_precision, _r_scale),
811            ) => true,
812            (
813                DataType::Timestamp(_l_time_unit, _l_timezone),
814                DataType::Timestamp(_r_time_unit, _r_timezone),
815            ) => true,
816            _ => dt1 == dt2,
817        }
818    }
819
820    fn field_is_logically_equal(f1: &Field, f2: &Field) -> bool {
821        f1.name() == f2.name()
822            && Self::datatype_is_logically_equal(f1.data_type(), f2.data_type())
823    }
824
825    fn field_is_semantically_equal(f1: &Field, f2: &Field) -> bool {
826        f1.name() == f2.name()
827            && Self::datatype_is_semantically_equal(f1.data_type(), f2.data_type())
828    }
829
830    /// Strip all field qualifier in schema
831    pub fn strip_qualifiers(self) -> Self {
832        DFSchema {
833            field_qualifiers: vec![None; self.inner.fields.len()],
834            inner: self.inner,
835            functional_dependencies: self.functional_dependencies,
836        }
837    }
838
839    /// Replace all field qualifier with new value in schema
840    pub fn replace_qualifier(self, qualifier: impl Into<TableReference>) -> Self {
841        let qualifier = qualifier.into();
842        DFSchema {
843            field_qualifiers: vec![Some(qualifier); self.inner.fields.len()],
844            inner: self.inner,
845            functional_dependencies: self.functional_dependencies,
846        }
847    }
848
849    /// Get list of fully-qualified field names in this schema
850    pub fn field_names(&self) -> Vec<String> {
851        self.iter()
852            .map(|(qualifier, field)| qualified_name(qualifier, field.name()))
853            .collect::<Vec<_>>()
854    }
855
856    /// Get metadata of this schema
857    pub fn metadata(&self) -> &Metadata {
858        &self.inner.metadata
859    }
860
861    /// Get functional dependencies
862    pub fn functional_dependencies(&self) -> &FunctionalDependencies {
863        &self.functional_dependencies
864    }
865
866    /// Iterate over the qualifiers and fields in the DFSchema
867    pub fn iter(&self) -> impl Iterator<Item = (Option<&TableReference>, &FieldRef)> {
868        self.field_qualifiers
869            .iter()
870            .zip(self.inner.fields().iter())
871            .map(|(qualifier, field)| (qualifier.as_ref(), field))
872    }
873    /// Returns a tree-like string representation of the schema.
874    ///
875    /// This method formats the schema
876    /// with a tree-like structure showing field names, types, and nullability.
877    ///
878    /// # Example
879    ///
880    /// ```
881    /// use arrow::datatypes::{DataType, Field, Schema};
882    /// use datafusion_common::DFSchema;
883    /// use std::collections::HashMap;
884    ///
885    /// let schema = DFSchema::from_unqualified_fields(
886    ///     vec![
887    ///         Field::new("id", DataType::Int32, false),
888    ///         Field::new("name", DataType::Utf8, true),
889    ///     ]
890    ///     .into(),
891    ///     HashMap::new(),
892    /// )
893    /// .unwrap();
894    ///
895    /// assert_eq!(
896    ///     schema.tree_string().to_string(),
897    ///     r#"root
898    ///  |-- id: int32 (nullable = false)
899    ///  |-- name: utf8 (nullable = true)"#
900    /// );
901    /// ```
902    pub fn tree_string(&self) -> impl Display + '_ {
903        let mut result = String::from("root\n");
904
905        for (qualifier, field) in self.iter() {
906            let field_name = match qualifier {
907                Some(q) => format!("{}.{}", q, field.name()),
908                None => field.name().to_string(),
909            };
910
911            format_field_with_indent(
912                &mut result,
913                &field_name,
914                field.data_type(),
915                field.is_nullable(),
916                " ",
917            );
918        }
919
920        // Remove the trailing newline
921        if result.ends_with('\n') {
922            result.pop();
923        }
924
925        result
926    }
927}
928
929/// Format field with proper nested indentation for complex types
930fn format_field_with_indent(
931    result: &mut String,
932    field_name: &str,
933    data_type: &DataType,
934    nullable: bool,
935    indent: &str,
936) {
937    let nullable_str = nullable.to_string().to_lowercase();
938    let child_indent = format!("{indent}|    ");
939
940    match data_type {
941        DataType::List(field) => {
942            writeln!(
943                result,
944                "{indent}|-- {field_name}: list (nullable = {nullable_str})"
945            )
946            .ok();
947            format_field_with_indent(
948                result,
949                field.name(),
950                field.data_type(),
951                field.is_nullable(),
952                &child_indent,
953            );
954        }
955        DataType::LargeList(field) => {
956            writeln!(
957                result,
958                "{indent}|-- {field_name}: large list (nullable = {nullable_str})"
959            )
960            .ok();
961            format_field_with_indent(
962                result,
963                field.name(),
964                field.data_type(),
965                field.is_nullable(),
966                &child_indent,
967            );
968        }
969        DataType::FixedSizeList(field, _size) => {
970            writeln!(
971                result,
972                "{indent}|-- {field_name}: fixed size list (nullable = {nullable_str})"
973            )
974            .ok();
975            format_field_with_indent(
976                result,
977                field.name(),
978                field.data_type(),
979                field.is_nullable(),
980                &child_indent,
981            );
982        }
983        DataType::Map(field, _) => {
984            writeln!(
985                result,
986                "{indent}|-- {field_name}: map (nullable = {nullable_str})"
987            )
988            .ok();
989            if let DataType::Struct(inner_fields) = field.data_type()
990                && inner_fields.len() == 2
991            {
992                format_field_with_indent(
993                    result,
994                    "key",
995                    inner_fields[0].data_type(),
996                    inner_fields[0].is_nullable(),
997                    &child_indent,
998                );
999                let value_contains_null = field.is_nullable().to_string().to_lowercase();
1000                // Handle complex value types properly
1001                match inner_fields[1].data_type() {
1002                    DataType::Struct(_)
1003                    | DataType::List(_)
1004                    | DataType::LargeList(_)
1005                    | DataType::FixedSizeList(_, _)
1006                    | DataType::Map(_, _) => {
1007                        format_field_with_indent(
1008                            result,
1009                            "value",
1010                            inner_fields[1].data_type(),
1011                            inner_fields[1].is_nullable(),
1012                            &child_indent,
1013                        );
1014                    }
1015                    _ => {
1016                        writeln!(result, "{child_indent}|-- value: {} (nullable = {value_contains_null})",
1017                                format_simple_data_type(inner_fields[1].data_type())).ok();
1018                    }
1019                }
1020            }
1021        }
1022        DataType::Struct(fields) => {
1023            writeln!(
1024                result,
1025                "{indent}|-- {field_name}: struct (nullable = {nullable_str})"
1026            )
1027            .ok();
1028            for struct_field in fields {
1029                format_field_with_indent(
1030                    result,
1031                    struct_field.name(),
1032                    struct_field.data_type(),
1033                    struct_field.is_nullable(),
1034                    &child_indent,
1035                );
1036            }
1037        }
1038        _ => {
1039            let type_str = format_simple_data_type(data_type);
1040            writeln!(
1041                result,
1042                "{indent}|-- {field_name}: {type_str} (nullable = {nullable_str})"
1043            )
1044            .ok();
1045        }
1046    }
1047}
1048
1049/// Format simple DataType in lowercase format (for leaf nodes)
1050fn format_simple_data_type(data_type: &DataType) -> String {
1051    match data_type {
1052        DataType::Boolean => "boolean".to_string(),
1053        DataType::Int8 => "int8".to_string(),
1054        DataType::Int16 => "int16".to_string(),
1055        DataType::Int32 => "int32".to_string(),
1056        DataType::Int64 => "int64".to_string(),
1057        DataType::UInt8 => "uint8".to_string(),
1058        DataType::UInt16 => "uint16".to_string(),
1059        DataType::UInt32 => "uint32".to_string(),
1060        DataType::UInt64 => "uint64".to_string(),
1061        DataType::Float16 => "float16".to_string(),
1062        DataType::Float32 => "float32".to_string(),
1063        DataType::Float64 => "float64".to_string(),
1064        DataType::Utf8 => "utf8".to_string(),
1065        DataType::LargeUtf8 => "large_utf8".to_string(),
1066        DataType::Binary => "binary".to_string(),
1067        DataType::LargeBinary => "large_binary".to_string(),
1068        DataType::FixedSizeBinary(_) => "fixed_size_binary".to_string(),
1069        DataType::Date32 => "date32".to_string(),
1070        DataType::Date64 => "date64".to_string(),
1071        DataType::Time32(_) => "time32".to_string(),
1072        DataType::Time64(_) => "time64".to_string(),
1073        DataType::Timestamp(_, tz) => match tz {
1074            Some(tz_str) => format!("timestamp ({tz_str})"),
1075            None => "timestamp".to_string(),
1076        },
1077        DataType::Interval(_) => "interval".to_string(),
1078        DataType::Dictionary(_, value_type) => {
1079            format_simple_data_type(value_type.as_ref())
1080        }
1081        DataType::Decimal32(precision, scale) => {
1082            format!("decimal32({precision}, {scale})")
1083        }
1084        DataType::Decimal64(precision, scale) => {
1085            format!("decimal64({precision}, {scale})")
1086        }
1087        DataType::Decimal128(precision, scale) => {
1088            format!("decimal128({precision}, {scale})")
1089        }
1090        DataType::Decimal256(precision, scale) => {
1091            format!("decimal256({precision}, {scale})")
1092        }
1093        DataType::Null => "null".to_string(),
1094        _ => format!("{data_type}").to_lowercase(),
1095    }
1096}
1097
1098/// Allow DFSchema to be converted into an Arrow `&Schema`
1099impl AsRef<Schema> for DFSchema {
1100    fn as_ref(&self) -> &Schema {
1101        self.as_arrow()
1102    }
1103}
1104
1105/// Allow DFSchema to be converted into an Arrow `&SchemaRef` (to clone, for
1106/// example)
1107impl AsRef<SchemaRef> for DFSchema {
1108    fn as_ref(&self) -> &SchemaRef {
1109        self.inner()
1110    }
1111}
1112
1113/// Create a `DFSchema` from an Arrow schema
1114impl TryFrom<Schema> for DFSchema {
1115    type Error = DataFusionError;
1116    fn try_from(schema: Schema) -> Result<Self, Self::Error> {
1117        Self::try_from(Arc::new(schema))
1118    }
1119}
1120
1121impl TryFrom<SchemaRef> for DFSchema {
1122    type Error = DataFusionError;
1123    fn try_from(schema: SchemaRef) -> Result<Self, Self::Error> {
1124        let field_count = schema.fields.len();
1125        let dfschema = Self {
1126            inner: schema,
1127            field_qualifiers: vec![None; field_count],
1128            functional_dependencies: FunctionalDependencies::empty(),
1129        };
1130        dfschema.check_names()?;
1131        Ok(dfschema)
1132    }
1133}
1134
1135impl From<DFSchema> for SchemaRef {
1136    fn from(dfschema: DFSchema) -> Self {
1137        Arc::clone(&dfschema.inner)
1138    }
1139}
1140
1141// Hashing refers to a subset of fields considered in PartialEq.
1142impl Hash for DFSchema {
1143    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1144        self.inner.fields.hash(state);
1145        self.inner.metadata.len().hash(state); // HashMap is not hashable
1146    }
1147}
1148
1149/// Convenience trait to convert Schema like things to DFSchema and DFSchemaRef with fewer keystrokes
1150pub trait ToDFSchema
1151where
1152    Self: Sized,
1153{
1154    /// Attempt to create a DSSchema
1155    fn to_dfschema(self) -> Result<DFSchema>;
1156
1157    /// Attempt to create a DSSchemaRef
1158    fn to_dfschema_ref(self) -> Result<DFSchemaRef> {
1159        Ok(Arc::new(self.to_dfschema()?))
1160    }
1161}
1162
1163impl ToDFSchema for Schema {
1164    fn to_dfschema(self) -> Result<DFSchema> {
1165        DFSchema::try_from(self)
1166    }
1167}
1168
1169impl ToDFSchema for SchemaRef {
1170    fn to_dfschema(self) -> Result<DFSchema> {
1171        DFSchema::try_from(self)
1172    }
1173}
1174
1175impl ToDFSchema for Vec<Field> {
1176    fn to_dfschema(self) -> Result<DFSchema> {
1177        let field_count = self.len();
1178        let schema = Schema {
1179            fields: self.into(),
1180            metadata: Metadata::new(),
1181        };
1182        let dfschema = DFSchema {
1183            inner: schema.into(),
1184            field_qualifiers: vec![None; field_count],
1185            functional_dependencies: FunctionalDependencies::empty(),
1186        };
1187        Ok(dfschema)
1188    }
1189}
1190
1191impl Display for DFSchema {
1192    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
1193        write!(
1194            f,
1195            "fields:[{}], metadata:{:?}",
1196            self.iter()
1197                .map(|(q, f)| qualified_name(q, f.name()))
1198                .collect::<Vec<String>>()
1199                .join(", "),
1200            self.inner.metadata
1201        )
1202    }
1203}
1204
1205/// Provides schema information needed by certain methods of `Expr`
1206/// (defined in the datafusion-common crate).
1207///
1208/// Note that this trait is implemented for &[DFSchema] which is
1209/// widely used in the DataFusion codebase.
1210pub trait ExprSchema: std::fmt::Debug {
1211    /// Is this column reference nullable?
1212    fn nullable(&self, col: &Column) -> Result<bool> {
1213        Ok(self.field_from_column(col)?.is_nullable())
1214    }
1215
1216    /// What is the datatype of this column?
1217    fn data_type(&self, col: &Column) -> Result<&DataType> {
1218        Ok(self.field_from_column(col)?.data_type())
1219    }
1220
1221    /// Returns the column's optional metadata.
1222    fn metadata(&self, col: &Column) -> Result<&Metadata> {
1223        Ok(self.field_from_column(col)?.metadata())
1224    }
1225
1226    /// Return the column's datatype and nullability
1227    fn data_type_and_nullable(&self, col: &Column) -> Result<(&DataType, bool)> {
1228        let field = self.field_from_column(col)?;
1229        Ok((field.data_type(), field.is_nullable()))
1230    }
1231
1232    // Return the column's field
1233    fn field_from_column(&self, col: &Column) -> Result<&FieldRef>;
1234}
1235
1236// Implement `ExprSchema` for `Arc<DFSchema>`
1237impl<P: AsRef<DFSchema> + std::fmt::Debug> ExprSchema for P {
1238    fn nullable(&self, col: &Column) -> Result<bool> {
1239        self.as_ref().nullable(col)
1240    }
1241
1242    fn data_type(&self, col: &Column) -> Result<&DataType> {
1243        self.as_ref().data_type(col)
1244    }
1245
1246    fn metadata(&self, col: &Column) -> Result<&Metadata> {
1247        ExprSchema::metadata(self.as_ref(), col)
1248    }
1249
1250    fn data_type_and_nullable(&self, col: &Column) -> Result<(&DataType, bool)> {
1251        self.as_ref().data_type_and_nullable(col)
1252    }
1253
1254    fn field_from_column(&self, col: &Column) -> Result<&FieldRef> {
1255        self.as_ref().field_from_column(col)
1256    }
1257}
1258
1259impl ExprSchema for DFSchema {
1260    fn field_from_column(&self, col: &Column) -> Result<&FieldRef> {
1261        match &col.relation {
1262            Some(r) => self.field_with_qualified_name(r, &col.name),
1263            None => self.field_with_unqualified_name(&col.name),
1264        }
1265    }
1266}
1267
1268/// DataFusion-specific extensions to [`Schema`].
1269pub trait SchemaExt {
1270    /// This is a specialized version of Eq that ignores differences
1271    /// in nullability and metadata.
1272    ///
1273    /// It works the same as [`DFSchema::has_equivalent_names_and_types`].
1274    fn equivalent_names_and_types(&self, other: &Self) -> bool;
1275
1276    /// Returns nothing if the two schemas have the same qualified named
1277    /// fields with logically equivalent data types. Returns internal error otherwise.
1278    ///
1279    /// Use [DFSchema]::has_equivalent_names_and_types for stricter semantic type
1280    /// equivalence checking.
1281    ///
1282    /// It is only used by insert into cases.
1283    fn logically_equivalent_names_and_types(&self, other: &Self) -> Result<()>;
1284}
1285
1286impl SchemaExt for Schema {
1287    fn equivalent_names_and_types(&self, other: &Self) -> bool {
1288        if self.fields().len() != other.fields().len() {
1289            return false;
1290        }
1291
1292        self.fields()
1293            .iter()
1294            .zip(other.fields().iter())
1295            .all(|(f1, f2)| {
1296                f1.name() == f2.name()
1297                    && DFSchema::datatype_is_semantically_equal(
1298                        f1.data_type(),
1299                        f2.data_type(),
1300                    )
1301            })
1302    }
1303
1304    // It is only used by insert into cases.
1305    fn logically_equivalent_names_and_types(&self, other: &Self) -> Result<()> {
1306        // case 1 : schema length mismatch
1307        if self.fields().len() != other.fields().len() {
1308            _plan_err!(
1309                "Inserting query must have the same schema length as the table. \
1310            Expected table schema length: {}, got: {}",
1311                self.fields().len(),
1312                other.fields().len()
1313            )
1314        } else {
1315            // case 2 : schema length match, but fields mismatch
1316            // check if the fields name are the same and have the same data types
1317            self.fields()
1318                .iter()
1319                .zip(other.fields().iter())
1320                .try_for_each(|(f1, f2)| {
1321                    if f1.name() != f2.name() || (!DFSchema::datatype_is_logically_equal(f1.data_type(), f2.data_type()) && !can_cast_types(f2.data_type(), f1.data_type())) {
1322                        _plan_err!(
1323                            "Inserting query schema mismatch: Expected table field '{}' with type {}, \
1324                            but got '{}' with type {}.",
1325                            f1.name(),
1326                            f1.data_type(),
1327                            f2.name(),
1328                            f2.data_type())
1329                    } else {
1330                        Ok(())
1331                    }
1332                })
1333        }
1334    }
1335}
1336
1337/// Build a fully-qualified field name string. This is equivalent to
1338/// `format!("{q}.{name}")` when `qualifier` is `Some`, or just `name` when
1339/// `None`. We avoid going through the `fmt` machinery for performance reasons.
1340pub fn qualified_name(qualifier: Option<&TableReference>, name: &str) -> String {
1341    let Some(qualifier) = qualifier else {
1342        return name.to_string();
1343    };
1344    let (first, second, third) = match qualifier {
1345        TableReference::Bare { table } => (table.as_ref(), None, None),
1346        TableReference::Partial { schema, table } => {
1347            (schema.as_ref(), Some(table.as_ref()), None)
1348        }
1349        TableReference::Full {
1350            catalog,
1351            schema,
1352            table,
1353        } => (
1354            catalog.as_ref(),
1355            Some(schema.as_ref()),
1356            Some(table.as_ref()),
1357        ),
1358    };
1359
1360    let extra = second.map_or(0, str::len) + third.map_or(0, str::len);
1361    let mut s = String::with_capacity(first.len() + extra + 3 + name.len());
1362    s.push_str(first);
1363    if let Some(second) = second {
1364        s.push('.');
1365        s.push_str(second);
1366    }
1367    if let Some(third) = third {
1368        s.push('.');
1369        s.push_str(third);
1370    }
1371    s.push('.');
1372    s.push_str(name);
1373    s
1374}
1375
1376#[cfg(test)]
1377mod tests {
1378    use crate::assert_contains;
1379    use std::collections::HashMap;
1380
1381    use super::*;
1382
1383    /// `qualified_name` doesn't use `TableReference::Display` for performance
1384    /// reasons, but check that the output is consistent.
1385    #[test]
1386    fn qualified_name_agrees_with_display() {
1387        let cases: &[(Option<TableReference>, &str)] = &[
1388            (None, "col"),
1389            (Some(TableReference::bare("t")), "c0"),
1390            (Some(TableReference::partial("s", "t")), "c0"),
1391            (Some(TableReference::full("c", "s", "t")), "c0"),
1392            (Some(TableReference::bare("mytable")), "some_column_name"),
1393            // Empty segments must be preserved so that distinct qualified
1394            // fields don't collide in `DFSchema::field_names()`.
1395            (Some(TableReference::bare("")), "col"),
1396            (Some(TableReference::partial("s", "")), "col"),
1397            (Some(TableReference::partial("", "t")), "col"),
1398            (Some(TableReference::full("c", "", "t")), "col"),
1399            (Some(TableReference::full("", "s", "t")), "col"),
1400            (Some(TableReference::full("c", "s", "")), "col"),
1401            (Some(TableReference::full("", "", "")), "col"),
1402        ];
1403        for (qualifier, name) in cases {
1404            let actual = qualified_name(qualifier.as_ref(), name);
1405            let expected = match qualifier {
1406                Some(q) => format!("{q}.{name}"),
1407                None => name.to_string(),
1408            };
1409            assert_eq!(actual, expected, "qualifier={qualifier:?} name={name}");
1410        }
1411    }
1412
1413    #[test]
1414    fn qualifier_in_name() -> Result<()> {
1415        let col = Column::from_name("t1.c0");
1416        let schema = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1417        // lookup with unqualified name "t1.c0"
1418        let err = schema.index_of_column(&col).unwrap_err();
1419        let expected = "Schema error: No field named \"t1.c0\". Did you mean 't1.c0'?\n\
1420            Valid fields are t1.c0, t1.c1.";
1421        assert_eq!(err.strip_backtrace(), expected);
1422        Ok(())
1423    }
1424
1425    #[test]
1426    fn quoted_qualifiers_in_name() -> Result<()> {
1427        let col = Column::from_name("t1.c0");
1428        let schema = DFSchema::try_from_qualified_schema(
1429            "t1",
1430            &Schema::new(vec![
1431                Field::new("CapitalColumn", DataType::Boolean, true),
1432                Field::new("field.with.period", DataType::Boolean, true),
1433            ]),
1434        )?;
1435
1436        // lookup with unqualified name "t1.c0"
1437        let err = schema.index_of_column(&col).unwrap_err();
1438        let expected = "Schema error: No field named \"t1.c0\".\n\
1439            Valid fields are t1.\"CapitalColumn\", t1.\"field.with.period\".";
1440        assert_eq!(err.strip_backtrace(), expected);
1441        Ok(())
1442    }
1443
1444    #[test]
1445    fn field_not_found_suggests_closest_field_name() -> Result<()> {
1446        let schema = DFSchema::try_from(Schema::new(vec![
1447            Field::new("abzz", DataType::Boolean, true),
1448            Field::new("abcd", DataType::Boolean, true),
1449        ]))?;
1450
1451        let err = schema.field_with_unqualified_name("abc").unwrap_err();
1452        let expected = "Schema error: No field named abc. Did you mean 'abcd'?\n\
1453            Valid fields are abzz, abcd.";
1454        assert_eq!(err.strip_backtrace(), expected);
1455        Ok(())
1456    }
1457
1458    #[test]
1459    fn field_not_found_suggests_case_sensitive_qualified_field() -> Result<()> {
1460        let schema = DFSchema::try_from_qualified_schema(
1461            "hits",
1462            &Schema::new(vec![
1463                Field::new("WatchID", DataType::Boolean, true),
1464                Field::new("URL", DataType::Boolean, true),
1465                Field::new("URLHash", DataType::Boolean, true),
1466            ]),
1467        )?;
1468
1469        let err = schema.field_with_unqualified_name("url").unwrap_err();
1470        let expected = "Schema error: No field named url. Did you mean 'hits.\"URL\"'?\n\
1471            Column names are case sensitive. \
1472            You can use double quotes to refer to the hits.\"URL\" column \
1473            or disable the datafusion.sql_parser.enable_ident_normalization configuration.\n\
1474            Valid fields are hits.\"WatchID\", hits.\"URL\", hits.\"URLHash\".";
1475        assert_eq!(err.strip_backtrace(), expected);
1476        Ok(())
1477    }
1478
1479    #[test]
1480    fn from_unqualified_schema() -> Result<()> {
1481        let schema = DFSchema::try_from(test_schema_1())?;
1482        assert_eq!("fields:[c0, c1], metadata:{}", schema.to_string());
1483        Ok(())
1484    }
1485
1486    #[test]
1487    fn from_qualified_schema() -> Result<()> {
1488        let schema = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1489        assert_eq!("fields:[t1.c0, t1.c1], metadata:{}", schema.to_string());
1490        Ok(())
1491    }
1492
1493    #[test]
1494    fn test_from_field_specific_qualified_schema() -> Result<()> {
1495        let schema = DFSchema::from_field_specific_qualified_schema(
1496            vec![Some("t1".into()), None],
1497            &Arc::new(Schema::new(vec![
1498                Field::new("c0", DataType::Boolean, true),
1499                Field::new("c1", DataType::Boolean, true),
1500            ])),
1501        )?;
1502        assert_eq!("fields:[t1.c0, c1], metadata:{}", schema.to_string());
1503        Ok(())
1504    }
1505
1506    #[test]
1507    fn test_from_qualified_fields() -> Result<()> {
1508        let schema = DFSchema::new_with_metadata(
1509            vec![
1510                (
1511                    Some("t0".into()),
1512                    Arc::new(Field::new("c0", DataType::Boolean, true)),
1513                ),
1514                (None, Arc::new(Field::new("c1", DataType::Boolean, true))),
1515            ],
1516            HashMap::new(),
1517        )?;
1518        assert_eq!("fields:[t0.c0, c1], metadata:{}", schema.to_string());
1519        Ok(())
1520    }
1521
1522    #[test]
1523    fn from_qualified_schema_into_arrow_schema() -> Result<()> {
1524        let schema = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1525        let arrow_schema = schema.as_arrow();
1526        insta::assert_snapshot!(arrow_schema.to_string(), @r#"Field { "c0": nullable Boolean }, Field { "c1": nullable Boolean }"#);
1527        Ok(())
1528    }
1529
1530    #[test]
1531    fn join_qualified() -> Result<()> {
1532        let left = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1533        let right = DFSchema::try_from_qualified_schema("t2", &test_schema_1())?;
1534        let join = left.join(&right)?;
1535        assert_eq!(
1536            "fields:[t1.c0, t1.c1, t2.c0, t2.c1], metadata:{}",
1537            join.to_string()
1538        );
1539        // test valid access
1540        assert!(
1541            join.field_with_qualified_name(&TableReference::bare("t1"), "c0")
1542                .is_ok()
1543        );
1544        assert!(
1545            join.field_with_qualified_name(&TableReference::bare("t2"), "c0")
1546                .is_ok()
1547        );
1548        // test invalid access
1549        assert!(join.field_with_unqualified_name("c0").is_err());
1550        assert!(join.field_with_unqualified_name("t1.c0").is_err());
1551        assert!(join.field_with_unqualified_name("t2.c0").is_err());
1552        Ok(())
1553    }
1554
1555    #[test]
1556    fn join_qualified_duplicate() -> Result<()> {
1557        let left = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1558        let right = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1559        let join = left.join(&right);
1560        assert_eq!(
1561            join.unwrap_err().strip_backtrace(),
1562            "Schema error: Schema contains duplicate qualified field name t1.c0",
1563        );
1564        Ok(())
1565    }
1566
1567    #[test]
1568    fn join_unqualified_duplicate() -> Result<()> {
1569        let left = DFSchema::try_from(test_schema_1())?;
1570        let right = DFSchema::try_from(test_schema_1())?;
1571        let join = left.join(&right);
1572        assert_eq!(
1573            join.unwrap_err().strip_backtrace(),
1574            "Schema error: Schema contains duplicate unqualified field name c0"
1575        );
1576        Ok(())
1577    }
1578
1579    #[test]
1580    fn join_mixed() -> Result<()> {
1581        let left = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1582        let right = DFSchema::try_from(test_schema_2())?;
1583        let join = left.join(&right)?;
1584        assert_eq!(
1585            "fields:[t1.c0, t1.c1, c100, c101], metadata:{}",
1586            join.to_string()
1587        );
1588        // test valid access
1589        assert!(
1590            join.field_with_qualified_name(&TableReference::bare("t1"), "c0")
1591                .is_ok()
1592        );
1593        assert!(join.field_with_unqualified_name("c0").is_ok());
1594        assert!(join.field_with_unqualified_name("c100").is_ok());
1595        assert!(join.field_with_name(None, "c100").is_ok());
1596        // test invalid access
1597        assert!(join.field_with_unqualified_name("t1.c0").is_err());
1598        assert!(join.field_with_unqualified_name("t1.c100").is_err());
1599        assert!(
1600            join.field_with_qualified_name(&TableReference::bare(""), "c100")
1601                .is_err()
1602        );
1603        Ok(())
1604    }
1605
1606    #[test]
1607    fn join_mixed_duplicate() -> Result<()> {
1608        let left = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1609        let right = DFSchema::try_from(test_schema_1())?;
1610        let join = left.join(&right);
1611        assert_contains!(
1612            join.unwrap_err().to_string(),
1613            "Schema error: Schema contains qualified \
1614                          field name t1.c0 and unqualified field name c0 which would be ambiguous"
1615        );
1616        Ok(())
1617    }
1618
1619    #[test]
1620    fn helpful_error_messages() -> Result<()> {
1621        let schema = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1622        let expected_help = "Valid fields are t1.c0, t1.c1.";
1623        assert_contains!(
1624            schema
1625                .field_with_qualified_name(&TableReference::bare("x"), "y")
1626                .unwrap_err()
1627                .to_string(),
1628            expected_help
1629        );
1630        assert_contains!(
1631            schema
1632                .field_with_unqualified_name("y")
1633                .unwrap_err()
1634                .to_string(),
1635            expected_help
1636        );
1637        assert!(schema.index_of_column_by_name(None, "y").is_none());
1638        assert!(schema.index_of_column_by_name(None, "t1.c0").is_none());
1639
1640        Ok(())
1641    }
1642
1643    #[test]
1644    fn select_without_valid_fields() {
1645        let schema = DFSchema::empty();
1646
1647        let col = Column::from_qualified_name("t1.c0");
1648        let err = schema.index_of_column(&col).unwrap_err();
1649        let expected = "Schema error: No field named t1.c0.";
1650        assert_eq!(err.strip_backtrace(), expected);
1651
1652        // the same check without qualifier
1653        let col = Column::from_name("c0");
1654        let err = schema.index_of_column(&col).err().unwrap();
1655        let expected = "Schema error: No field named c0.";
1656        assert_eq!(err.strip_backtrace(), expected);
1657    }
1658
1659    #[test]
1660    fn into() {
1661        // Demonstrate how to convert back and forth between Schema, SchemaRef, DFSchema, and DFSchemaRef
1662        let arrow_schema = Schema::new_with_metadata(
1663            vec![Field::new("c0", DataType::Int64, true)],
1664            test_metadata(),
1665        );
1666        let arrow_schema_ref = Arc::new(arrow_schema.clone());
1667
1668        let df_schema = DFSchema {
1669            inner: Arc::clone(&arrow_schema_ref),
1670            field_qualifiers: vec![None; arrow_schema_ref.fields.len()],
1671            functional_dependencies: FunctionalDependencies::empty(),
1672        };
1673        let df_schema_ref = Arc::new(df_schema.clone());
1674
1675        {
1676            let arrow_schema = arrow_schema.clone();
1677            let arrow_schema_ref = Arc::clone(&arrow_schema_ref);
1678
1679            assert_eq!(df_schema, arrow_schema.to_dfschema().unwrap());
1680            assert_eq!(df_schema, arrow_schema_ref.to_dfschema().unwrap());
1681        }
1682
1683        {
1684            let arrow_schema = arrow_schema.clone();
1685            let arrow_schema_ref = Arc::clone(&arrow_schema_ref);
1686
1687            assert_eq!(df_schema_ref, arrow_schema.to_dfschema_ref().unwrap());
1688            assert_eq!(df_schema_ref, arrow_schema_ref.to_dfschema_ref().unwrap());
1689        }
1690
1691        // Now, consume the refs
1692        assert_eq!(df_schema_ref, arrow_schema.to_dfschema_ref().unwrap());
1693        assert_eq!(df_schema_ref, arrow_schema_ref.to_dfschema_ref().unwrap());
1694    }
1695
1696    fn test_schema_1() -> Schema {
1697        Schema::new(vec![
1698            Field::new("c0", DataType::Boolean, true),
1699            Field::new("c1", DataType::Boolean, true),
1700        ])
1701    }
1702    #[test]
1703    fn test_dfschema_to_schema_conversion() {
1704        let mut a_metadata = HashMap::new();
1705        a_metadata.insert("key".to_string(), "value".to_string());
1706        let a_field = Field::new("a", DataType::Int64, false).with_metadata(a_metadata);
1707
1708        let mut b_metadata = HashMap::new();
1709        b_metadata.insert("key".to_string(), "value".to_string());
1710        let b_field = Field::new("b", DataType::Int64, false).with_metadata(b_metadata);
1711
1712        let schema = Arc::new(Schema::new(vec![a_field, b_field]));
1713
1714        let df_schema = DFSchema {
1715            inner: Arc::clone(&schema),
1716            field_qualifiers: vec![None; schema.fields.len()],
1717            functional_dependencies: FunctionalDependencies::empty(),
1718        };
1719
1720        assert_eq!(df_schema.inner.metadata(), schema.metadata())
1721    }
1722
1723    #[test]
1724    fn test_contain_column() -> Result<()> {
1725        // qualified exists
1726        {
1727            let col = Column::from_qualified_name("t1.c0");
1728            let schema = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1729            assert!(schema.is_column_from_schema(&col));
1730        }
1731
1732        // qualified not exists
1733        {
1734            let col = Column::from_qualified_name("t1.c2");
1735            let schema = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1736            assert!(!schema.is_column_from_schema(&col));
1737        }
1738
1739        // unqualified exists
1740        {
1741            let col = Column::from_name("c0");
1742            let schema = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1743            assert!(schema.is_column_from_schema(&col));
1744        }
1745
1746        // unqualified not exists
1747        {
1748            let col = Column::from_name("c2");
1749            let schema = DFSchema::try_from_qualified_schema("t1", &test_schema_1())?;
1750            assert!(!schema.is_column_from_schema(&col));
1751        }
1752
1753        Ok(())
1754    }
1755
1756    #[test]
1757    fn test_datatype_is_logically_equal() {
1758        assert!(DFSchema::datatype_is_logically_equal(
1759            &DataType::Int8,
1760            &DataType::Int8
1761        ));
1762
1763        assert!(!DFSchema::datatype_is_logically_equal(
1764            &DataType::Int8,
1765            &DataType::Int16
1766        ));
1767
1768        // Test lists
1769
1770        // Succeeds if both have the same element type, disregards names and nullability
1771        assert!(DFSchema::datatype_is_logically_equal(
1772            &DataType::List(Field::new_list_field(DataType::Int8, true).into()),
1773            &DataType::List(Field::new("element", DataType::Int8, false).into())
1774        ));
1775        assert!(DFSchema::datatype_is_logically_equal(
1776            &DataType::ListView(Field::new_list_field(DataType::Int8, true).into()),
1777            &DataType::ListView(Field::new("element", DataType::Int8, false).into())
1778        ));
1779
1780        // Fails if element type is different
1781        assert!(!DFSchema::datatype_is_logically_equal(
1782            &DataType::List(Field::new_list_field(DataType::Int8, true).into()),
1783            &DataType::List(Field::new_list_field(DataType::Int16, true).into())
1784        ));
1785        assert!(!DFSchema::datatype_is_logically_equal(
1786            &DataType::ListView(Field::new_list_field(DataType::Int8, true).into()),
1787            &DataType::ListView(Field::new_list_field(DataType::Int16, true).into())
1788        ));
1789
1790        // Test maps
1791        let map_field = DataType::Map(
1792            Field::new(
1793                "entries",
1794                DataType::Struct(Fields::from(vec![
1795                    Field::new("key", DataType::Int8, false),
1796                    Field::new("value", DataType::Int8, true),
1797                ])),
1798                true,
1799            )
1800            .into(),
1801            true,
1802        );
1803
1804        // Succeeds if both maps have the same key and value types, disregards names and nullability
1805        assert!(DFSchema::datatype_is_logically_equal(
1806            &map_field,
1807            &DataType::Map(
1808                Field::new(
1809                    "pairs",
1810                    DataType::Struct(Fields::from(vec![
1811                        Field::new("one", DataType::Int8, false),
1812                        Field::new("two", DataType::Int8, false)
1813                    ])),
1814                    true
1815                )
1816                .into(),
1817                true
1818            )
1819        ));
1820        // Fails if value type is different
1821        assert!(!DFSchema::datatype_is_logically_equal(
1822            &map_field,
1823            &DataType::Map(
1824                Field::new(
1825                    "entries",
1826                    DataType::Struct(Fields::from(vec![
1827                        Field::new("key", DataType::Int8, false),
1828                        Field::new("value", DataType::Int16, true)
1829                    ])),
1830                    true
1831                )
1832                .into(),
1833                true
1834            )
1835        ));
1836
1837        // Fails if key type is different
1838        assert!(!DFSchema::datatype_is_logically_equal(
1839            &map_field,
1840            &DataType::Map(
1841                Field::new(
1842                    "entries",
1843                    DataType::Struct(Fields::from(vec![
1844                        Field::new("key", DataType::Int16, false),
1845                        Field::new("value", DataType::Int8, true)
1846                    ])),
1847                    true
1848                )
1849                .into(),
1850                true
1851            )
1852        ));
1853
1854        // Test structs
1855
1856        let struct_field = DataType::Struct(Fields::from(vec![
1857            Field::new("a", DataType::Int8, true),
1858            Field::new("b", DataType::Int8, true),
1859        ]));
1860
1861        // Succeeds if both have same names and datatypes, ignores nullability
1862        assert!(DFSchema::datatype_is_logically_equal(
1863            &struct_field,
1864            &DataType::Struct(Fields::from(vec![
1865                Field::new("a", DataType::Int8, false),
1866                Field::new("b", DataType::Int8, true),
1867            ]))
1868        ));
1869
1870        // Fails if field names are different
1871        assert!(!DFSchema::datatype_is_logically_equal(
1872            &struct_field,
1873            &DataType::Struct(Fields::from(vec![
1874                Field::new("x", DataType::Int8, true),
1875                Field::new("y", DataType::Int8, true),
1876            ]))
1877        ));
1878
1879        // Fails if types are different
1880        assert!(!DFSchema::datatype_is_logically_equal(
1881            &struct_field,
1882            &DataType::Struct(Fields::from(vec![
1883                Field::new("a", DataType::Int16, true),
1884                Field::new("b", DataType::Int8, true),
1885            ]))
1886        ));
1887
1888        // Fails if more or less fields
1889        assert!(!DFSchema::datatype_is_logically_equal(
1890            &struct_field,
1891            &DataType::Struct(Fields::from(vec![Field::new("a", DataType::Int8, true),]))
1892        ));
1893    }
1894
1895    #[test]
1896    fn test_datatype_is_logically_equivalent_to_dictionary() {
1897        // Dictionary is logically equal to its value type
1898        assert!(DFSchema::datatype_is_logically_equal(
1899            &DataType::Utf8,
1900            &DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8))
1901        ));
1902
1903        // Dictionary is logically equal to the logically equivalent value type
1904        assert!(DFSchema::datatype_is_logically_equal(
1905            &DataType::Utf8View,
1906            &DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8))
1907        ));
1908
1909        assert!(DFSchema::datatype_is_logically_equal(
1910            &DataType::Dictionary(
1911                Box::new(DataType::Int32),
1912                Box::new(DataType::List(
1913                    Field::new("element", DataType::Utf8, false).into()
1914                ))
1915            ),
1916            &DataType::Dictionary(
1917                Box::new(DataType::Int32),
1918                Box::new(DataType::List(
1919                    Field::new("element", DataType::Utf8View, false).into()
1920                ))
1921            )
1922        ));
1923    }
1924
1925    #[test]
1926    fn test_datatype_is_logically_equivalent_to_ree() {
1927        // RunEndEncoded is logically equal to its value type
1928        assert!(DFSchema::datatype_is_logically_equal(
1929            &DataType::Utf8,
1930            &DataType::RunEndEncoded(
1931                Field::new("run", DataType::Int32, false).into(),
1932                Field::new("val", DataType::Utf8, true).into(),
1933            )
1934        ));
1935
1936        // Dictionary is logically equal to the logically equivalent value type
1937        assert!(DFSchema::datatype_is_logically_equal(
1938            &DataType::Utf8View,
1939            &DataType::RunEndEncoded(
1940                Field::new("run", DataType::Int32, false).into(),
1941                Field::new("val", DataType::Utf8, true).into(),
1942            )
1943        ));
1944
1945        assert!(DFSchema::datatype_is_logically_equal(
1946            &DataType::RunEndEncoded(
1947                Field::new("run", DataType::Int32, false).into(),
1948                Field::new(
1949                    "val",
1950                    DataType::List(Field::new("element", DataType::Utf8, false).into()),
1951                    true
1952                )
1953                .into(),
1954            ),
1955            &DataType::RunEndEncoded(
1956                Field::new("run", DataType::Int64, false).into(),
1957                Field::new(
1958                    "val",
1959                    DataType::List(
1960                        Field::new("element", DataType::Utf8View, false).into()
1961                    ),
1962                    true
1963                )
1964                .into(),
1965            ),
1966        ));
1967    }
1968
1969    #[test]
1970    fn test_datatype_is_semantically_equal() {
1971        assert!(DFSchema::datatype_is_semantically_equal(
1972            &DataType::Int8,
1973            &DataType::Int8
1974        ));
1975
1976        assert!(!DFSchema::datatype_is_semantically_equal(
1977            &DataType::Int8,
1978            &DataType::Int16
1979        ));
1980
1981        // Succeeds if decimal precision and scale are different
1982        assert!(DFSchema::datatype_is_semantically_equal(
1983            &DataType::Decimal32(1, 2),
1984            &DataType::Decimal32(2, 1),
1985        ));
1986
1987        assert!(DFSchema::datatype_is_semantically_equal(
1988            &DataType::Decimal64(1, 2),
1989            &DataType::Decimal64(2, 1),
1990        ));
1991
1992        assert!(DFSchema::datatype_is_semantically_equal(
1993            &DataType::Decimal128(1, 2),
1994            &DataType::Decimal128(2, 1),
1995        ));
1996
1997        assert!(DFSchema::datatype_is_semantically_equal(
1998            &DataType::Decimal256(1, 2),
1999            &DataType::Decimal256(2, 1),
2000        ));
2001
2002        // Any two timestamp types should match
2003        assert!(DFSchema::datatype_is_semantically_equal(
2004            &DataType::Timestamp(
2005                arrow::datatypes::TimeUnit::Microsecond,
2006                Some("UTC".into())
2007            ),
2008            &DataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
2009        ));
2010
2011        // Test lists
2012
2013        // Succeeds if both have the same element type, disregards names and nullability
2014        assert!(DFSchema::datatype_is_semantically_equal(
2015            &DataType::List(Field::new_list_field(DataType::Int8, true).into()),
2016            &DataType::List(Field::new("element", DataType::Int8, false).into())
2017        ));
2018        assert!(DFSchema::datatype_is_semantically_equal(
2019            &DataType::ListView(Field::new_list_field(DataType::Int8, true).into()),
2020            &DataType::ListView(Field::new("element", DataType::Int8, false).into())
2021        ));
2022
2023        // Fails if element type is different
2024        assert!(!DFSchema::datatype_is_semantically_equal(
2025            &DataType::List(Field::new_list_field(DataType::Int8, true).into()),
2026            &DataType::List(Field::new_list_field(DataType::Int16, true).into())
2027        ));
2028        assert!(!DFSchema::datatype_is_semantically_equal(
2029            &DataType::ListView(Field::new_list_field(DataType::Int8, true).into()),
2030            &DataType::ListView(Field::new_list_field(DataType::Int16, true).into())
2031        ));
2032
2033        // Test maps
2034        let map_field = DataType::Map(
2035            Field::new(
2036                "entries",
2037                DataType::Struct(Fields::from(vec![
2038                    Field::new("key", DataType::Int8, false),
2039                    Field::new("value", DataType::Int8, true),
2040                ])),
2041                true,
2042            )
2043            .into(),
2044            true,
2045        );
2046
2047        // Succeeds if both maps have the same key and value types, disregards names and nullability
2048        assert!(DFSchema::datatype_is_semantically_equal(
2049            &map_field,
2050            &DataType::Map(
2051                Field::new(
2052                    "pairs",
2053                    DataType::Struct(Fields::from(vec![
2054                        Field::new("one", DataType::Int8, false),
2055                        Field::new("two", DataType::Int8, false)
2056                    ])),
2057                    true
2058                )
2059                .into(),
2060                true
2061            )
2062        ));
2063        // Fails if value type is different
2064        assert!(!DFSchema::datatype_is_semantically_equal(
2065            &map_field,
2066            &DataType::Map(
2067                Field::new(
2068                    "entries",
2069                    DataType::Struct(Fields::from(vec![
2070                        Field::new("key", DataType::Int8, false),
2071                        Field::new("value", DataType::Int16, true)
2072                    ])),
2073                    true
2074                )
2075                .into(),
2076                true
2077            )
2078        ));
2079
2080        // Fails if key type is different
2081        assert!(!DFSchema::datatype_is_semantically_equal(
2082            &map_field,
2083            &DataType::Map(
2084                Field::new(
2085                    "entries",
2086                    DataType::Struct(Fields::from(vec![
2087                        Field::new("key", DataType::Int16, false),
2088                        Field::new("value", DataType::Int8, true)
2089                    ])),
2090                    true
2091                )
2092                .into(),
2093                true
2094            )
2095        ));
2096
2097        // Test structs
2098
2099        let struct_field = DataType::Struct(Fields::from(vec![
2100            Field::new("a", DataType::Int8, true),
2101            Field::new("b", DataType::Int8, true),
2102        ]));
2103
2104        // Succeeds if both have same names and datatypes, ignores nullability
2105        assert!(DFSchema::datatype_is_logically_equal(
2106            &struct_field,
2107            &DataType::Struct(Fields::from(vec![
2108                Field::new("a", DataType::Int8, false),
2109                Field::new("b", DataType::Int8, true),
2110            ]))
2111        ));
2112
2113        // Fails if field names are different
2114        assert!(!DFSchema::datatype_is_logically_equal(
2115            &struct_field,
2116            &DataType::Struct(Fields::from(vec![
2117                Field::new("x", DataType::Int8, true),
2118                Field::new("y", DataType::Int8, true),
2119            ]))
2120        ));
2121
2122        // Fails if types are different
2123        assert!(!DFSchema::datatype_is_logically_equal(
2124            &struct_field,
2125            &DataType::Struct(Fields::from(vec![
2126                Field::new("a", DataType::Int16, true),
2127                Field::new("b", DataType::Int8, true),
2128            ]))
2129        ));
2130
2131        // Fails if more or less fields
2132        assert!(!DFSchema::datatype_is_logically_equal(
2133            &struct_field,
2134            &DataType::Struct(Fields::from(vec![Field::new("a", DataType::Int8, true),]))
2135        ));
2136    }
2137
2138    #[test]
2139    fn test_datatype_is_not_semantically_equivalent_to_dictionary() {
2140        // Dictionary is not semantically equal to its value type
2141        assert!(!DFSchema::datatype_is_semantically_equal(
2142            &DataType::Utf8,
2143            &DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8))
2144        ));
2145    }
2146
2147    #[test]
2148    fn test_datatype_is_not_semantically_equivalent_to_ree() {
2149        // RunEndEncoded is not semantically equal to its value type
2150        assert!(!DFSchema::datatype_is_semantically_equal(
2151            &DataType::Utf8,
2152            &DataType::RunEndEncoded(
2153                Field::new("run", DataType::Int32, false).into(),
2154                Field::new("val", DataType::Utf8, true).into(),
2155            )
2156        ));
2157    }
2158
2159    fn test_schema_2() -> Schema {
2160        Schema::new(vec![
2161            Field::new("c100", DataType::Boolean, true),
2162            Field::new("c101", DataType::Boolean, true),
2163        ])
2164    }
2165
2166    fn test_metadata() -> HashMap<String, String> {
2167        test_metadata_n(2)
2168    }
2169
2170    fn test_metadata_n(n: usize) -> HashMap<String, String> {
2171        (0..n).map(|i| (format!("k{i}"), format!("v{i}"))).collect()
2172    }
2173
2174    #[test]
2175    fn test_print_schema_unqualified() {
2176        let schema = DFSchema::from_unqualified_fields(
2177            vec![
2178                Field::new("id", DataType::Int32, false),
2179                Field::new("name", DataType::Utf8, true),
2180                Field::new("age", DataType::Int64, true),
2181                Field::new("active", DataType::Boolean, false),
2182            ]
2183            .into(),
2184            HashMap::new(),
2185        )
2186        .unwrap();
2187
2188        let output = schema.tree_string();
2189
2190        insta::assert_snapshot!(output, @r"
2191        root
2192         |-- id: int32 (nullable = false)
2193         |-- name: utf8 (nullable = true)
2194         |-- age: int64 (nullable = true)
2195         |-- active: boolean (nullable = false)
2196        ");
2197    }
2198
2199    #[test]
2200    fn test_print_schema_qualified() {
2201        let schema = DFSchema::try_from_qualified_schema(
2202            "table1",
2203            &Schema::new(vec![
2204                Field::new("id", DataType::Int32, false),
2205                Field::new("name", DataType::Utf8, true),
2206            ]),
2207        )
2208        .unwrap();
2209
2210        let output = schema.tree_string();
2211
2212        insta::assert_snapshot!(output, @r"
2213        root
2214         |-- table1.id: int32 (nullable = false)
2215         |-- table1.name: utf8 (nullable = true)
2216        ");
2217    }
2218
2219    #[test]
2220    fn test_print_schema_complex_types() {
2221        let struct_field = Field::new(
2222            "address",
2223            DataType::Struct(Fields::from(vec![
2224                Field::new("street", DataType::Utf8, true),
2225                Field::new("city", DataType::Utf8, true),
2226            ])),
2227            true,
2228        );
2229
2230        let list_field = Field::new(
2231            "tags",
2232            DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
2233            true,
2234        );
2235
2236        let schema = DFSchema::from_unqualified_fields(
2237            vec![
2238                Field::new("id", DataType::Int32, false),
2239                struct_field,
2240                list_field,
2241                Field::new("score", DataType::Decimal128(10, 2), true),
2242            ]
2243            .into(),
2244            HashMap::new(),
2245        )
2246        .unwrap();
2247
2248        let output = schema.tree_string();
2249        insta::assert_snapshot!(output, @r"
2250        root
2251         |-- id: int32 (nullable = false)
2252         |-- address: struct (nullable = true)
2253         |    |-- street: utf8 (nullable = true)
2254         |    |-- city: utf8 (nullable = true)
2255         |-- tags: list (nullable = true)
2256         |    |-- item: utf8 (nullable = true)
2257         |-- score: decimal128(10, 2) (nullable = true)
2258        ");
2259    }
2260
2261    #[test]
2262    fn test_print_schema_empty() {
2263        let schema = DFSchema::empty();
2264        let output = schema.tree_string();
2265        insta::assert_snapshot!(output, @"root");
2266    }
2267
2268    #[test]
2269    fn test_print_schema_deeply_nested_types() {
2270        // Create a deeply nested structure to test indentation and complex type formatting
2271        let inner_struct = Field::new(
2272            "inner",
2273            DataType::Struct(Fields::from(vec![
2274                Field::new("level1", DataType::Utf8, true),
2275                Field::new("level2", DataType::Int32, false),
2276            ])),
2277            true,
2278        );
2279
2280        let nested_list = Field::new(
2281            "nested_list",
2282            DataType::List(Arc::new(Field::new(
2283                "item",
2284                DataType::Struct(Fields::from(vec![
2285                    Field::new("id", DataType::Int64, false),
2286                    Field::new("value", DataType::Float64, true),
2287                ])),
2288                true,
2289            ))),
2290            true,
2291        );
2292
2293        let map_field = Field::new(
2294            "map_data",
2295            DataType::Map(
2296                Arc::new(Field::new(
2297                    "entries",
2298                    DataType::Struct(Fields::from(vec![
2299                        Field::new("key", DataType::Utf8, false),
2300                        Field::new(
2301                            "value",
2302                            DataType::List(Arc::new(Field::new(
2303                                "item",
2304                                DataType::Int32,
2305                                true,
2306                            ))),
2307                            true,
2308                        ),
2309                    ])),
2310                    false,
2311                )),
2312                false,
2313            ),
2314            true,
2315        );
2316
2317        let schema = DFSchema::from_unqualified_fields(
2318            vec![
2319                Field::new("simple_field", DataType::Utf8, true),
2320                inner_struct,
2321                nested_list,
2322                map_field,
2323                Field::new(
2324                    "timestamp_field",
2325                    DataType::Timestamp(
2326                        arrow::datatypes::TimeUnit::Microsecond,
2327                        Some("UTC".into()),
2328                    ),
2329                    false,
2330                ),
2331            ]
2332            .into(),
2333            HashMap::new(),
2334        )
2335        .unwrap();
2336
2337        let output = schema.tree_string();
2338
2339        insta::assert_snapshot!(output, @r"
2340        root
2341         |-- simple_field: utf8 (nullable = true)
2342         |-- inner: struct (nullable = true)
2343         |    |-- level1: utf8 (nullable = true)
2344         |    |-- level2: int32 (nullable = false)
2345         |-- nested_list: list (nullable = true)
2346         |    |-- item: struct (nullable = true)
2347         |    |    |-- id: int64 (nullable = false)
2348         |    |    |-- value: float64 (nullable = true)
2349         |-- map_data: map (nullable = true)
2350         |    |-- key: utf8 (nullable = false)
2351         |    |-- value: list (nullable = true)
2352         |    |    |-- item: int32 (nullable = true)
2353         |-- timestamp_field: timestamp (UTC) (nullable = false)
2354        ");
2355    }
2356
2357    #[test]
2358    fn test_print_schema_mixed_qualified_unqualified() {
2359        // Test a schema with mixed qualified and unqualified fields
2360        let schema = DFSchema::new_with_metadata(
2361            vec![
2362                (
2363                    Some("table1".into()),
2364                    Arc::new(Field::new("id", DataType::Int32, false)),
2365                ),
2366                (None, Arc::new(Field::new("name", DataType::Utf8, true))),
2367                (
2368                    Some("table2".into()),
2369                    Arc::new(Field::new("score", DataType::Float64, true)),
2370                ),
2371                (
2372                    None,
2373                    Arc::new(Field::new("active", DataType::Boolean, false)),
2374                ),
2375            ],
2376            HashMap::new(),
2377        )
2378        .unwrap();
2379
2380        let output = schema.tree_string();
2381
2382        insta::assert_snapshot!(output, @r"
2383        root
2384         |-- table1.id: int32 (nullable = false)
2385         |-- name: utf8 (nullable = true)
2386         |-- table2.score: float64 (nullable = true)
2387         |-- active: boolean (nullable = false)
2388        ");
2389    }
2390
2391    #[test]
2392    fn test_print_schema_array_of_map() {
2393        // Test the specific example from user feedback: array of map
2394        let map_field = Field::new(
2395            "entries",
2396            DataType::Struct(Fields::from(vec![
2397                Field::new("key", DataType::Utf8, false),
2398                Field::new("value", DataType::Utf8, false),
2399            ])),
2400            false,
2401        );
2402
2403        let array_of_map_field = Field::new(
2404            "array_map_field",
2405            DataType::List(Arc::new(Field::new(
2406                "item",
2407                DataType::Map(Arc::new(map_field), false),
2408                false,
2409            ))),
2410            false,
2411        );
2412
2413        let schema = DFSchema::from_unqualified_fields(
2414            vec![array_of_map_field].into(),
2415            HashMap::new(),
2416        )
2417        .unwrap();
2418
2419        let output = schema.tree_string();
2420
2421        insta::assert_snapshot!(output, @r"
2422        root
2423         |-- array_map_field: list (nullable = false)
2424         |    |-- item: map (nullable = false)
2425         |    |    |-- key: utf8 (nullable = false)
2426         |    |    |-- value: utf8 (nullable = false)
2427        ");
2428    }
2429
2430    #[test]
2431    fn test_print_schema_complex_type_combinations() {
2432        // Test various combinations of list, struct, and map types
2433
2434        // List of structs
2435        let list_of_structs = Field::new(
2436            "list_of_structs",
2437            DataType::List(Arc::new(Field::new(
2438                "item",
2439                DataType::Struct(Fields::from(vec![
2440                    Field::new("id", DataType::Int32, false),
2441                    Field::new("name", DataType::Utf8, true),
2442                    Field::new("score", DataType::Float64, true),
2443                ])),
2444                true,
2445            ))),
2446            true,
2447        );
2448
2449        // Struct containing lists
2450        let struct_with_lists = Field::new(
2451            "struct_with_lists",
2452            DataType::Struct(Fields::from(vec![
2453                Field::new(
2454                    "tags",
2455                    DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
2456                    true,
2457                ),
2458                Field::new(
2459                    "scores",
2460                    DataType::List(Arc::new(Field::new("item", DataType::Int32, true))),
2461                    false,
2462                ),
2463                Field::new("metadata", DataType::Utf8, true),
2464            ])),
2465            false,
2466        );
2467
2468        // Map with struct values
2469        let map_with_struct_values = Field::new(
2470            "map_with_struct_values",
2471            DataType::Map(
2472                Arc::new(Field::new(
2473                    "entries",
2474                    DataType::Struct(Fields::from(vec![
2475                        Field::new("key", DataType::Utf8, false),
2476                        Field::new(
2477                            "value",
2478                            DataType::Struct(Fields::from(vec![
2479                                Field::new("count", DataType::Int64, false),
2480                                Field::new("active", DataType::Boolean, true),
2481                            ])),
2482                            true,
2483                        ),
2484                    ])),
2485                    false,
2486                )),
2487                false,
2488            ),
2489            true,
2490        );
2491
2492        // List of maps
2493        let list_of_maps = Field::new(
2494            "list_of_maps",
2495            DataType::List(Arc::new(Field::new(
2496                "item",
2497                DataType::Map(
2498                    Arc::new(Field::new(
2499                        "entries",
2500                        DataType::Struct(Fields::from(vec![
2501                            Field::new("key", DataType::Utf8, false),
2502                            Field::new("value", DataType::Int32, true),
2503                        ])),
2504                        false,
2505                    )),
2506                    false,
2507                ),
2508                true,
2509            ))),
2510            true,
2511        );
2512
2513        // Deeply nested: struct containing list of structs containing maps
2514        let deeply_nested = Field::new(
2515            "deeply_nested",
2516            DataType::Struct(Fields::from(vec![
2517                Field::new("level1", DataType::Utf8, true),
2518                Field::new(
2519                    "level2",
2520                    DataType::List(Arc::new(Field::new(
2521                        "item",
2522                        DataType::Struct(Fields::from(vec![
2523                            Field::new("id", DataType::Int32, false),
2524                            Field::new(
2525                                "properties",
2526                                DataType::Map(
2527                                    Arc::new(Field::new(
2528                                        "entries",
2529                                        DataType::Struct(Fields::from(vec![
2530                                            Field::new("key", DataType::Utf8, false),
2531                                            Field::new("value", DataType::Float64, true),
2532                                        ])),
2533                                        false,
2534                                    )),
2535                                    false,
2536                                ),
2537                                true,
2538                            ),
2539                        ])),
2540                        true,
2541                    ))),
2542                    false,
2543                ),
2544            ])),
2545            true,
2546        );
2547
2548        let schema = DFSchema::from_unqualified_fields(
2549            vec![
2550                list_of_structs,
2551                struct_with_lists,
2552                map_with_struct_values,
2553                list_of_maps,
2554                deeply_nested,
2555            ]
2556            .into(),
2557            HashMap::new(),
2558        )
2559        .unwrap();
2560
2561        let output = schema.tree_string();
2562
2563        insta::assert_snapshot!(output, @r"
2564        root
2565         |-- list_of_structs: list (nullable = true)
2566         |    |-- item: struct (nullable = true)
2567         |    |    |-- id: int32 (nullable = false)
2568         |    |    |-- name: utf8 (nullable = true)
2569         |    |    |-- score: float64 (nullable = true)
2570         |-- struct_with_lists: struct (nullable = false)
2571         |    |-- tags: list (nullable = true)
2572         |    |    |-- item: utf8 (nullable = true)
2573         |    |-- scores: list (nullable = false)
2574         |    |    |-- item: int32 (nullable = true)
2575         |    |-- metadata: utf8 (nullable = true)
2576         |-- map_with_struct_values: map (nullable = true)
2577         |    |-- key: utf8 (nullable = false)
2578         |    |-- value: struct (nullable = true)
2579         |    |    |-- count: int64 (nullable = false)
2580         |    |    |-- active: boolean (nullable = true)
2581         |-- list_of_maps: list (nullable = true)
2582         |    |-- item: map (nullable = true)
2583         |    |    |-- key: utf8 (nullable = false)
2584         |    |    |-- value: int32 (nullable = false)
2585         |-- deeply_nested: struct (nullable = true)
2586         |    |-- level1: utf8 (nullable = true)
2587         |    |-- level2: list (nullable = false)
2588         |    |    |-- item: struct (nullable = true)
2589         |    |    |    |-- id: int32 (nullable = false)
2590         |    |    |    |-- properties: map (nullable = true)
2591         |    |    |    |    |-- key: utf8 (nullable = false)
2592         |    |    |    |    |-- value: float64 (nullable = false)
2593        ");
2594    }
2595
2596    #[test]
2597    fn test_print_schema_edge_case_types() {
2598        // Test edge cases and special types
2599        let schema = DFSchema::from_unqualified_fields(
2600            vec![
2601                Field::new("null_field", DataType::Null, true),
2602                Field::new("binary_field", DataType::Binary, false),
2603                Field::new("large_binary", DataType::LargeBinary, true),
2604                Field::new("large_utf8", DataType::LargeUtf8, false),
2605                Field::new("fixed_size_binary", DataType::FixedSizeBinary(16), true),
2606                Field::new(
2607                    "fixed_size_list",
2608                    DataType::FixedSizeList(
2609                        Arc::new(Field::new("item", DataType::Int32, true)),
2610                        5,
2611                    ),
2612                    false,
2613                ),
2614                Field::new("decimal32", DataType::Decimal32(9, 4), true),
2615                Field::new("decimal64", DataType::Decimal64(9, 4), true),
2616                Field::new("decimal128", DataType::Decimal128(18, 4), true),
2617                Field::new("decimal256", DataType::Decimal256(38, 10), false),
2618                Field::new("date32", DataType::Date32, true),
2619                Field::new("date64", DataType::Date64, false),
2620                Field::new(
2621                    "time32_seconds",
2622                    DataType::Time32(arrow::datatypes::TimeUnit::Second),
2623                    true,
2624                ),
2625                Field::new(
2626                    "time64_nanoseconds",
2627                    DataType::Time64(arrow::datatypes::TimeUnit::Nanosecond),
2628                    false,
2629                ),
2630            ]
2631            .into(),
2632            HashMap::new(),
2633        )
2634        .unwrap();
2635
2636        let output = schema.tree_string();
2637
2638        insta::assert_snapshot!(output, @r"
2639        root
2640         |-- null_field: null (nullable = true)
2641         |-- binary_field: binary (nullable = false)
2642         |-- large_binary: large_binary (nullable = true)
2643         |-- large_utf8: large_utf8 (nullable = false)
2644         |-- fixed_size_binary: fixed_size_binary (nullable = true)
2645         |-- fixed_size_list: fixed size list (nullable = false)
2646         |    |-- item: int32 (nullable = true)
2647         |-- decimal32: decimal32(9, 4) (nullable = true)
2648         |-- decimal64: decimal64(9, 4) (nullable = true)
2649         |-- decimal128: decimal128(18, 4) (nullable = true)
2650         |-- decimal256: decimal256(38, 10) (nullable = false)
2651         |-- date32: date32 (nullable = true)
2652         |-- date64: date64 (nullable = false)
2653         |-- time32_seconds: time32 (nullable = true)
2654         |-- time64_nanoseconds: time64 (nullable = false)
2655        ");
2656    }
2657}